@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.
- package/docs/commands.md +123 -65
- package/docs/dependencies.md +189 -4
- package/docs/index.md +56 -12
- package/docs/install-steps.md +20 -17
- package/docs/jobs.md +43 -16
- package/docs/mod.md +43 -27
- package/docs/options.md +2 -2
- package/docs/session.md +58 -32
- package/docs/testing.md +88 -24
- package/docs/ui.md +128 -58
- package/installer.d.ts +2 -2
- package/jobs/context.js +1 -1
- package/jobs/program.d.ts +4 -1
- package/jobs/program.d.ts.map +1 -1
- package/jobs/program.js +79 -20
- package/mod.d.ts +59 -9
- package/mod.d.ts.map +1 -1
- package/mod.js +5 -3
- package/package.json +1 -1
- package/records.d.ts +15 -2
- package/records.d.ts.map +1 -1
- package/records.js +24 -10
- package/register.d.ts.map +1 -1
- package/register.js +7 -4
- package/rpc.d.ts +7 -0
- package/rpc.d.ts.map +1 -0
- package/rpc.js +59 -0
- package/runtime/bound.d.ts +1 -0
- package/runtime/bound.d.ts.map +1 -1
- package/runtime/bound.js +10 -0
- package/runtime/bun.d.ts +20 -0
- package/runtime/bun.d.ts.map +1 -0
- package/runtime/bun.js +20 -0
- package/runtime/claude.d.ts +1 -0
- package/runtime/claude.d.ts.map +1 -1
- package/runtime/conversations.d.ts +12 -1
- package/runtime/conversations.d.ts.map +1 -1
- package/runtime/conversations.js +472 -362
- package/runtime/deadline.d.ts +4 -3
- package/runtime/deadline.d.ts.map +1 -1
- package/runtime/deadline.js +10 -4
- package/runtime/engine.d.ts +5 -4
- package/runtime/engine.d.ts.map +1 -1
- package/runtime/installer.d.ts +3 -3
- package/runtime/installer.d.ts.map +1 -1
- package/runtime/installer.js +10 -9
- package/runtime/interfaces.d.ts +262 -0
- package/runtime/interfaces.d.ts.map +1 -0
- package/runtime/interfaces.js +935 -0
- package/runtime/lifecycle.d.ts +3 -3
- package/runtime/lifecycle.d.ts.map +1 -1
- package/runtime/lifecycle.js +83 -52
- package/runtime/options.d.ts.map +1 -1
- package/runtime/options.js +2 -6
- package/runtime/parts.d.ts +64 -1
- package/runtime/parts.d.ts.map +1 -1
- package/runtime/parts.js +311 -4
- package/runtime/programs.d.ts +1 -0
- package/runtime/programs.d.ts.map +1 -1
- package/runtime/programs.js +5 -3
- package/runtime/rpc.d.ts +111 -0
- package/runtime/rpc.d.ts.map +1 -0
- package/runtime/rpc.js +387 -0
- package/runtime/sessions.d.ts +6 -4
- package/runtime/sessions.d.ts.map +1 -1
- package/runtime/sessions.js +59 -80
- package/runtime/toaster.js +1 -1
- package/runtime/ui.d.ts +23 -10
- package/runtime/ui.d.ts.map +1 -1
- package/runtime/ui.js +63 -52
- package/runtime/web.d.ts +0 -73
- package/runtime/web.d.ts.map +1 -1
- package/runtime/web.js +9 -5
- package/runtime/widgets.d.ts +4 -2
- package/runtime/widgets.d.ts.map +1 -1
- package/runtime/widgets.js +17 -16
- package/session/conversation.d.ts +7 -1
- package/session/conversation.d.ts.map +1 -1
- package/session/session.d.ts +31 -7
- package/session/session.d.ts.map +1 -1
- package/session/session.js +1 -0
- package/src/installer.ts +2 -2
- package/src/jobs/context.ts +1 -1
- package/src/jobs/program.ts +76 -21
- package/src/mod.ts +51 -10
- package/src/records.ts +33 -9
- package/src/register.ts +7 -4
- package/src/rpc.ts +67 -0
- package/src/runtime/bound.ts +10 -0
- package/src/runtime/bun.ts +40 -0
- package/src/runtime/claude.ts +1 -0
- package/src/runtime/conversations.ts +470 -352
- package/src/runtime/deadline.ts +13 -6
- package/src/runtime/engine.ts +5 -4
- package/src/runtime/installer.ts +13 -12
- package/src/runtime/interfaces.ts +1161 -0
- package/src/runtime/lifecycle.ts +102 -59
- package/src/runtime/options.ts +2 -5
- package/src/runtime/parts.ts +364 -5
- package/src/runtime/programs.ts +6 -3
- package/src/runtime/rpc.ts +457 -0
- package/src/runtime/sessions.ts +63 -83
- package/src/runtime/toaster.ts +1 -1
- package/src/runtime/ui.ts +82 -61
- package/src/runtime/web.ts +10 -39
- package/src/runtime/widgets.ts +20 -18
- package/src/session/conversation.ts +7 -1
- package/src/session/session.ts +22 -7
- package/src/testing/fake-claude.ts +38 -7
- package/src/testing/fake-serve.ts +144 -0
- package/src/testing/fake-sessions.ts +21 -6
- package/src/testing.ts +156 -68
- package/src/ui/areas.ts +2 -2
- package/src/ui/elements.ts +21 -16
- package/src/ui/panes.ts +14 -7
- package/testing/fake-claude.d.ts +6 -0
- package/testing/fake-claude.d.ts.map +1 -1
- package/testing/fake-claude.js +34 -7
- package/testing/fake-serve.d.ts +39 -0
- package/testing/fake-serve.d.ts.map +1 -0
- package/testing/fake-serve.js +110 -0
- package/testing/fake-sessions.d.ts.map +1 -1
- package/testing/fake-sessions.js +22 -6
- package/testing.d.ts +21 -4
- package/testing.d.ts.map +1 -1
- package/testing.js +138 -56
- package/ui/areas.d.ts +3 -1
- package/ui/areas.d.ts.map +1 -1
- package/ui/elements.d.ts +18 -9
- package/ui/elements.d.ts.map +1 -1
- package/ui/elements.js +9 -8
- package/ui/panes.d.ts +10 -6
- package/ui/panes.d.ts.map +1 -1
- package/ui/panes.js +5 -3
- package/runtime/pages.d.ts +0 -32
- package/runtime/pages.d.ts.map +0 -1
- package/runtime/pages.js +0 -142
- package/src/runtime/pages.ts +0 -183
|
@@ -0,0 +1,1161 @@
|
|
|
1
|
+
import { interfaceName, isObject, type ProgramInstance } from '../records.js'
|
|
2
|
+
import type { Device } from '../session/context/turn/device.js'
|
|
3
|
+
import type { SessionData } from '../session/conversation.js'
|
|
4
|
+
import { matches, receivedMatcher, sentMatcher, type SentMatcher } from '../utils/matcher.js'
|
|
5
|
+
import type { Subscription } from '../utils/subscription.js'
|
|
6
|
+
import { messageOf } from '../utils/text.js'
|
|
7
|
+
import type { Claude } from './claude.js'
|
|
8
|
+
import { beforeDeadline, callDeadline, hookMs, listenerMs, listenerOf } from './deadline.js'
|
|
9
|
+
import { cmodPluginName } from './dependencies.js'
|
|
10
|
+
import { unaborted } from './router.js'
|
|
11
|
+
import { addressCall, connectRpc, isConnectionGone, RpcError, rpcCodes, rpcRoutes, RpcUnreached, type HttpFetch, type Peer, type RpcClient, type RpcConnection, type RpcHandler, type RpcMessage, type RpcRoutes } from './rpc.js'
|
|
12
|
+
|
|
13
|
+
export type InterfaceName = `${string}/${string}`
|
|
14
|
+
|
|
15
|
+
export const listenMethod = '$/listen'
|
|
16
|
+
|
|
17
|
+
export const unlistenMethod = '$/unlisten'
|
|
18
|
+
|
|
19
|
+
export const onMethod = '$/on'
|
|
20
|
+
|
|
21
|
+
export const beforeMethod = '$/before'
|
|
22
|
+
|
|
23
|
+
export const sessionsInterface = 'cmod/Sessions'
|
|
24
|
+
|
|
25
|
+
export const devicesInterface = 'cmod/Devices'
|
|
26
|
+
|
|
27
|
+
export const styleInterface = 'cmod/Style'
|
|
28
|
+
|
|
29
|
+
export const uiInterface = 'cmod/UI'
|
|
30
|
+
|
|
31
|
+
export const uiMethods = ['widgets', 'views', 'pages', 'draw', 'press', 'open', 'close'] as const
|
|
32
|
+
|
|
33
|
+
export const uiEvents: readonly string[] = ['Change', 'Redraw', 'Open', 'Close']
|
|
34
|
+
|
|
35
|
+
export const sessionActs = {
|
|
36
|
+
hold: '$/hold',
|
|
37
|
+
act: '$/act',
|
|
38
|
+
changed: '$/changed',
|
|
39
|
+
status: '$/status',
|
|
40
|
+
ui: '$/ui',
|
|
41
|
+
uiEvent: '$/uiEvent',
|
|
42
|
+
} as const
|
|
43
|
+
|
|
44
|
+
export type HeldSession = { readonly session: string; readonly project: string; readonly cwd: string }
|
|
45
|
+
|
|
46
|
+
export type HeldStatus = Pick<SessionData, 'status' | 'waitingFor' | 'contextPercent' | 'lastTurn'>
|
|
47
|
+
|
|
48
|
+
export type VisitedAt = Readonly<Record<string, string>>
|
|
49
|
+
|
|
50
|
+
export type StoreChange = { readonly session: string; readonly part: 'visit' | 'running' | 'tasks' | 'goal' | 'status' | 'deleted' }
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
export type ListenKind = 'on' | 'before'
|
|
54
|
+
|
|
55
|
+
export type Listening = {
|
|
56
|
+
readonly id: string
|
|
57
|
+
readonly interface: string
|
|
58
|
+
readonly event: string
|
|
59
|
+
readonly kind: ListenKind
|
|
60
|
+
readonly args?: readonly unknown[]
|
|
61
|
+
readonly matcher?: SentMatcher
|
|
62
|
+
readonly timeoutMs?: number
|
|
63
|
+
readonly onFailure?: 'pass' | 'refuse'
|
|
64
|
+
readonly after?: string
|
|
65
|
+
readonly provider?: ProviderIdentity
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type Heard = { readonly id: string; readonly payload: unknown; readonly cursor?: string }
|
|
69
|
+
|
|
70
|
+
export type ListenOptions = { readonly timeoutMs?: number; readonly onFailure?: 'pass' | 'refuse' }
|
|
71
|
+
|
|
72
|
+
export type Provider = { readonly mod: string; readonly program: string; readonly address: string; readonly provides: readonly string[] }
|
|
73
|
+
|
|
74
|
+
export const interfaceMethods = { providers: 'cmod:providers', provider: 'cmod:provider', provided: 'cmod:provided', listen: 'cmod:listenProvided', unlisten: 'cmod:unlistenProvided', tell: 'cmod:tellProvided', ask: 'cmod:askProvided', heard: 'cmod:heard' } as const
|
|
75
|
+
|
|
76
|
+
export const providerActs = { provide: '$/provide', unprovide: '$/unprovide', providers: '$/providers', provider: '$/provider', call: '$/call', link: '$/link' } as const
|
|
77
|
+
|
|
78
|
+
export const providerHoldMs = hookMs / 4
|
|
79
|
+
|
|
80
|
+
export type ProvidedCall = { readonly interface: string; readonly method: string; readonly args: readonly unknown[] } & Partial<ProviderIdentity>
|
|
81
|
+
|
|
82
|
+
export type InstanceFiles = {
|
|
83
|
+
list(folder: string): Promise<readonly { readonly name: string; readonly kind: string }[]>
|
|
84
|
+
read(path: string): Promise<string | undefined>
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function readProviders(files: InstanceFiles, store: string, name: string): Promise<Provider[]> {
|
|
88
|
+
const folder = `${store}/instances`
|
|
89
|
+
const mods = (await files.list(folder)).filter((entry) => entry.kind === 'dir')
|
|
90
|
+
const records = await Promise.all(
|
|
91
|
+
mods.map(async (mod) =>
|
|
92
|
+
Promise.all(
|
|
93
|
+
(await files.list(`${folder}/${mod.name}`))
|
|
94
|
+
.filter((file) => file.name.endsWith('.json'))
|
|
95
|
+
.map(async (file) => ({ mod: mod.name, program: file.name.slice(0, -'.json'.length), instance: JSON.parse((await files.read(`${folder}/${mod.name}/${file.name}`)) ?? 'null') as unknown })),
|
|
96
|
+
),
|
|
97
|
+
),
|
|
98
|
+
)
|
|
99
|
+
return providersIn(records.flat(), name)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function providersIn(records: readonly { readonly mod: string; readonly program: string; readonly instance: unknown }[], name: string): Provider[] {
|
|
103
|
+
return records.flatMap(({ mod, program, instance }) => {
|
|
104
|
+
if (!isObject(instance) || typeof instance['address'] !== 'string' || !Array.isArray(instance['provides'])) return []
|
|
105
|
+
const provides = (instance as ProgramInstance).provides ?? []
|
|
106
|
+
return provides.includes(name) ? [{ mod, program, address: instance['address'], provides }] : []
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function checkInterfaceName(name: string): void {
|
|
111
|
+
if (!interfaceName.test(name)) throw new Error(`${name} is no interface name, such as demo/Platform.`)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function methodName(name: string, method: string): string {
|
|
115
|
+
return `${name}.${method}`
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function isHeardAt(listening: Pick<Listening, 'args' | 'matcher'>, args: readonly unknown[], payload: unknown): boolean {
|
|
119
|
+
const wanted = listening.args ?? []
|
|
120
|
+
if (wanted.some((each, index) => each !== undefined && each !== '*' && each !== args[index])) return false
|
|
121
|
+
return listening.matcher === undefined || matches(payload, receivedMatcher(listening.matcher))
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export type Implementation = Readonly<Record<string, (...args: never[]) => unknown>>
|
|
125
|
+
|
|
126
|
+
export type InterfaceServer = {
|
|
127
|
+
handler(connection: Pick<Peer, 'request' | 'notify'>): RpcHandler
|
|
128
|
+
emit(name: string, event: string, payload: unknown, args?: readonly unknown[]): void
|
|
129
|
+
listeners(name: string, event?: string): readonly (Listening & { readonly connection: Pick<Peer, 'request' | 'notify'> })[]
|
|
130
|
+
closed(connection: Pick<Peer, 'request' | 'notify'>): void
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const keptEvents = 500
|
|
134
|
+
|
|
135
|
+
export function interfaceServer({
|
|
136
|
+
implementations,
|
|
137
|
+
onListen,
|
|
138
|
+
extraMethod,
|
|
139
|
+
}: {
|
|
140
|
+
readonly implementations: Readonly<Record<string, Implementation>>
|
|
141
|
+
readonly onListen?: (connection: Pick<Peer, 'request' | 'notify'>, listening: Listening) => void | Promise<void>
|
|
142
|
+
readonly extraMethod?: (connection: Pick<Peer, 'request' | 'notify'>, method: string, params: unknown, signal: AbortSignal) => { readonly result: unknown } | undefined | Promise<{ readonly result: unknown } | undefined>
|
|
143
|
+
}): InterfaceServer {
|
|
144
|
+
const held = new Map<Pick<Peer, 'request' | 'notify'>, Map<string, Listening>>()
|
|
145
|
+
const recent = new Map<string, { cursor: number; readonly kept: { readonly cursor: number; readonly args: readonly unknown[]; readonly payload: unknown }[] }>()
|
|
146
|
+
|
|
147
|
+
const keyOf = (name: string, event: string) => `${name}\n${event}`
|
|
148
|
+
|
|
149
|
+
const listeningOf = (params: unknown): Listening => {
|
|
150
|
+
if (!isObject(params) || typeof params['id'] !== 'string' || typeof params['interface'] !== 'string' || typeof params['event'] !== 'string' || (params['kind'] !== 'on' && params['kind'] !== 'before')) throw new RpcError(rpcCodes.invalidParams, `${listenMethod} takes { id, interface, event, kind }.`)
|
|
151
|
+
if (implementations[params['interface']] === undefined) throw new RpcError(rpcCodes.methodNotFound, `This program provides no ${params['interface']}.`)
|
|
152
|
+
return params as Listening
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const replay = (connection: Pick<Peer, 'request' | 'notify'>, listening: Listening) => {
|
|
156
|
+
if (listening.kind !== 'on' || listening.after === undefined) return
|
|
157
|
+
const after = Number(listening.after)
|
|
158
|
+
for (const each of recent.get(keyOf(listening.interface, listening.event))?.kept ?? []) {
|
|
159
|
+
if (each.cursor > after && isHeardAt(listening, each.args, each.payload)) connection.notify(onMethod, { id: listening.id, payload: each.payload, cursor: String(each.cursor) } satisfies Heard)
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const server: InterfaceServer = {
|
|
164
|
+
handler: (connection) => async (method, params, signal) => {
|
|
165
|
+
if (method === listenMethod) {
|
|
166
|
+
const listening = listeningOf(params)
|
|
167
|
+
await onListen?.(connection, listening)
|
|
168
|
+
const list = held.get(connection) ?? new Map<string, Listening>()
|
|
169
|
+
list.set(listening.id, listening)
|
|
170
|
+
held.set(connection, list)
|
|
171
|
+
replay(connection, listening)
|
|
172
|
+
return {}
|
|
173
|
+
}
|
|
174
|
+
if (method === unlistenMethod) {
|
|
175
|
+
const id = isObject(params) ? params['id'] : undefined
|
|
176
|
+
if (typeof id === 'string') held.get(connection)?.delete(id)
|
|
177
|
+
return {}
|
|
178
|
+
}
|
|
179
|
+
const extra = await extraMethod?.(connection, method, params, signal)
|
|
180
|
+
if (extra !== undefined) return extra.result
|
|
181
|
+
const dot = method.lastIndexOf('.')
|
|
182
|
+
const implementation = dot === -1 ? undefined : implementations[method.slice(0, dot)]
|
|
183
|
+
const run = implementation === undefined ? undefined : Object.hasOwn(implementation, method.slice(dot + 1)) ? implementation[method.slice(dot + 1)] : undefined
|
|
184
|
+
if (run === undefined) throw new RpcError(rpcCodes.methodNotFound, `This program answers no ${method}.`)
|
|
185
|
+
return (run as (...args: unknown[]) => unknown)(...(Array.isArray(params) ? params : []))
|
|
186
|
+
},
|
|
187
|
+
emit(name, event, payload, args = []) {
|
|
188
|
+
const key = keyOf(name, event)
|
|
189
|
+
const log = recent.get(key) ?? { cursor: 0, kept: [] }
|
|
190
|
+
log.cursor += 1
|
|
191
|
+
log.kept.push({ cursor: log.cursor, args, payload })
|
|
192
|
+
if (log.kept.length > keptEvents) log.kept.shift()
|
|
193
|
+
recent.set(key, log)
|
|
194
|
+
for (const listening of server.listeners(name, event)) {
|
|
195
|
+
if (listening.kind === 'on' && isHeardAt(listening, args, payload)) listening.connection.notify(onMethod, { id: listening.id, payload, cursor: String(log.cursor) } satisfies Heard)
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
listeners: (name, event) => [...held].flatMap(([connection, list]) => [...list.values()].filter((each) => each.interface === name && (event === undefined || each.event === event)).map((each) => ({ ...each, connection }))),
|
|
199
|
+
closed(connection) {
|
|
200
|
+
held.delete(connection)
|
|
201
|
+
},
|
|
202
|
+
}
|
|
203
|
+
return server
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export type Listener = (payload: never, signal: AbortSignal) => unknown
|
|
207
|
+
|
|
208
|
+
type Registered = { readonly listening: Listening; readonly listener: Listener; cursor: string | undefined }
|
|
209
|
+
|
|
210
|
+
export type InterfaceListeners = {
|
|
211
|
+
listen(request: Pick<Peer, 'request'>, listening: Omit<Listening, 'id'>, listener: Listener): Subscription
|
|
212
|
+
handler(method: string, params: unknown, signal: AbortSignal): { readonly result: unknown } | undefined | Promise<{ readonly result: unknown }>
|
|
213
|
+
replay(request: Pick<Peer, 'request'>): Promise<void>
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function interfaceListeners({ report: reportAll }: { readonly report: (error: unknown) => void }): InterfaceListeners {
|
|
217
|
+
const registered = new Map<string, Registered>()
|
|
218
|
+
let next = 0
|
|
219
|
+
const report = (error: unknown) => {
|
|
220
|
+
if (!isConnectionGone(error)) reportAll(error)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const send = (request: Pick<Peer, 'request'>, each: Registered) =>
|
|
224
|
+
request.request(listenMethod, { ...each.listening, ...(each.cursor === undefined ? {} : { after: each.cursor }) } satisfies Listening)
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
listen(request, listening, listener) {
|
|
228
|
+
const id = `${(next += 1)}`
|
|
229
|
+
const each: Registered = { listening: { ...listening, id }, listener, cursor: undefined }
|
|
230
|
+
registered.set(id, each)
|
|
231
|
+
void send(request, each).catch(report)
|
|
232
|
+
return {
|
|
233
|
+
remove() {
|
|
234
|
+
if (!registered.delete(id)) return
|
|
235
|
+
void request.request(unlistenMethod, { id }).catch(report)
|
|
236
|
+
},
|
|
237
|
+
}
|
|
238
|
+
},
|
|
239
|
+
handler(method, params, signal) {
|
|
240
|
+
if (method !== onMethod && method !== beforeMethod) return undefined
|
|
241
|
+
const heard = params as Heard
|
|
242
|
+
const each = registered.get(heard.id)
|
|
243
|
+
if (each === undefined) return method === beforeMethod ? Promise.resolve({ result: null }) : undefined
|
|
244
|
+
if (heard.cursor !== undefined) each.cursor = heard.cursor
|
|
245
|
+
if (method === onMethod) {
|
|
246
|
+
void (async () => each.listener(heard.payload as never, signal))().catch(report)
|
|
247
|
+
return undefined
|
|
248
|
+
}
|
|
249
|
+
return (async () => ({ result: (await each.listener(heard.payload as never, signal)) ?? null }))()
|
|
250
|
+
},
|
|
251
|
+
async replay(request) {
|
|
252
|
+
await Promise.all([...registered.values()].map((each) => send(request, each).catch(report)))
|
|
253
|
+
},
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function listeningOf(name: string, kind: ListenKind, event: string, args: readonly unknown[], matcher: unknown, options: ListenOptions = {}): Omit<Listening, 'id'> {
|
|
258
|
+
return {
|
|
259
|
+
interface: name,
|
|
260
|
+
event,
|
|
261
|
+
kind,
|
|
262
|
+
...(args.length === 0 ? {} : { args }),
|
|
263
|
+
...(matcher === undefined ? {} : { matcher: sentMatcher(matcher) }),
|
|
264
|
+
...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
|
|
265
|
+
...(options.onFailure === undefined ? {} : { onFailure: options.onFailure }),
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export type ProviderIdentity = { readonly mod: string; readonly program?: string; readonly device?: Pick<Device, 'id' | 'name'> | undefined }
|
|
270
|
+
|
|
271
|
+
export type ListenTo = (kind: ListenKind, event: string, matcher: unknown, listener: Listener, options: ListenOptions) => Subscription
|
|
272
|
+
|
|
273
|
+
export function providerClient(name: string, identity: ProviderIdentity, call: (method: string, args: readonly unknown[]) => Promise<unknown>, listen: ListenTo): Readonly<Record<string, unknown>> {
|
|
274
|
+
return new Proxy(identity, {
|
|
275
|
+
get: (known, key) => {
|
|
276
|
+
if (typeof key !== 'string' || key === 'then') return undefined
|
|
277
|
+
if (key === 'mod' || key === 'program' || key === 'device') return known[key]
|
|
278
|
+
const event = /^(on|before)([A-Z]\w*)$/.exec(key)
|
|
279
|
+
if (event === null) return (...args: unknown[]) => call(key, args)
|
|
280
|
+
return (...args: unknown[]) => {
|
|
281
|
+
const { matcher, listener, options } = listenerOf<Listener>(name, key, args)
|
|
282
|
+
return listen(event[1] as ListenKind, event[2] ?? '', matcher, listener, options)
|
|
283
|
+
}
|
|
284
|
+
},
|
|
285
|
+
})
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export type SessionContext = Readonly<Record<string, unknown>>
|
|
289
|
+
|
|
290
|
+
export type HoldingOf = (session: string) => HeldSession | undefined
|
|
291
|
+
|
|
292
|
+
export type SessionComputer = {
|
|
293
|
+
sessions(scope: Readonly<Record<string, unknown>>, holding: HoldingOf, held: ReadonlySet<string>): readonly SessionData[] | Promise<readonly SessionData[]>
|
|
294
|
+
search(text: string, options: Readonly<Record<string, unknown>>): unknown
|
|
295
|
+
read(session: string, part: string, options: Readonly<Record<string, unknown>>, holding: HoldingOf): unknown
|
|
296
|
+
unheld(session: string, action: string, input: unknown, context: SessionContext, holding: HoldingOf): Promise<unknown>
|
|
297
|
+
visit(session: string, at: string): Promise<void>
|
|
298
|
+
remove(session: string, context: SessionContext, holding: HoldingOf): Promise<void>
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export type SessionRouting = {
|
|
302
|
+
readonly routes: RpcRoutes
|
|
303
|
+
readonly interfaces: InterfaceServer
|
|
304
|
+
readonly providers: Pick<ProviderRouting, 'list' | 'call'>
|
|
305
|
+
holding: HoldingOf
|
|
306
|
+
heldSessions(): readonly HeldSession[]
|
|
307
|
+
call<Result>(session: string, action: string, input: unknown, context?: SessionContext): Promise<Result>
|
|
308
|
+
changed(change: StoreChange): void
|
|
309
|
+
close(): void
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export const sessionActions = ['send', 'abort', 'end', 'fork', 'startTask', 'callTool', 'usage', 'surfaces', 'visit', 'delete'] as const
|
|
313
|
+
|
|
314
|
+
export const showLeaseMs = 16_000
|
|
315
|
+
|
|
316
|
+
export function routeSessions({
|
|
317
|
+
computer,
|
|
318
|
+
device,
|
|
319
|
+
now,
|
|
320
|
+
after,
|
|
321
|
+
report,
|
|
322
|
+
aliases = [],
|
|
323
|
+
programs,
|
|
324
|
+
}: {
|
|
325
|
+
readonly computer: SessionComputer
|
|
326
|
+
readonly device: () => Promise<Pick<Device, 'id' | 'name'>>
|
|
327
|
+
readonly now: () => number
|
|
328
|
+
readonly after: (ms: number, run: () => void) => unknown
|
|
329
|
+
readonly report: (error: unknown) => void
|
|
330
|
+
readonly aliases?: readonly string[]
|
|
331
|
+
readonly programs?: ProgramReach
|
|
332
|
+
}): SessionRouting {
|
|
333
|
+
type Holder = HeldSession & { readonly connection: Pick<Peer, 'request' | 'notify'>; readonly told: HeldStatus }
|
|
334
|
+
const holders = new Map<Pick<Peer, 'request' | 'notify'>, Holder>()
|
|
335
|
+
const holderOf = (session: string) => [...holders.values()].find((holder) => holder.session === session)
|
|
336
|
+
const holding: HoldingOf = (session) => {
|
|
337
|
+
const holder = holderOf(session)
|
|
338
|
+
return holder === undefined ? undefined : { session: holder.session, project: holder.project, cwd: holder.cwd }
|
|
339
|
+
}
|
|
340
|
+
const names = [sessionsInterface, ...aliases]
|
|
341
|
+
|
|
342
|
+
const changed = (change: StoreChange) => {
|
|
343
|
+
for (const name of names) interfaces.emit(name, 'Change', change, [change.session])
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const call = async (session: string, action: string, input: unknown, context: SessionContext = {}): Promise<unknown> => {
|
|
347
|
+
if (!(sessionActions as readonly string[]).includes(action)) throw new RpcError(rpcCodes.methodNotFound, `A session takes no ${action}.`)
|
|
348
|
+
if (action === 'visit') {
|
|
349
|
+
await computer.visit(session, typeof input === 'string' ? input : new Date(now()).toISOString())
|
|
350
|
+
changed({ session, part: 'visit' })
|
|
351
|
+
return null
|
|
352
|
+
}
|
|
353
|
+
if (action === 'delete') {
|
|
354
|
+
if (holderOf(session) !== undefined) throw new Error(`session ${session} runs, so it stays. End it first.`)
|
|
355
|
+
await computer.remove(session, context, holding)
|
|
356
|
+
changed({ session, part: 'deleted' })
|
|
357
|
+
return null
|
|
358
|
+
}
|
|
359
|
+
const holder = holderOf(session)
|
|
360
|
+
if (holder === undefined) return computer.unheld(session, action, input, context, holding)
|
|
361
|
+
return holder.connection.request(sessionActs.act, { action, input, ...context })
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const withStatus = (listed: SessionData, told: HeldStatus | undefined): SessionData => {
|
|
365
|
+
if (told === undefined) return listed
|
|
366
|
+
const status = listed.status ?? told.status
|
|
367
|
+
const recorded = listed.waitingFor
|
|
368
|
+
const waitingFor = status !== 'waiting' || told.waitingFor === undefined ? recorded : { ...told.waitingFor, ...(recorded === undefined ? {} : { dialog: recorded.dialog }) }
|
|
369
|
+
return { ...listed, ...(status === undefined ? {} : { status }), ...(waitingFor === undefined ? {} : { waitingFor }), ...(told.contextPercent === undefined ? {} : { contextPercent: told.contextPercent }), ...(told.lastTurn === undefined ? {} : { lastTurn: told.lastTurn }) }
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const implementation: Implementation = {
|
|
373
|
+
sessions: async (scope: Readonly<Record<string, unknown>> = {}) => {
|
|
374
|
+
const told = new Map([...holders.values()].map((holder) => [holder.session, holder.told]))
|
|
375
|
+
return (await computer.sessions(scope, holding, new Set(told.keys()))).map((listed) => withStatus(listed, told.get(listed.id)))
|
|
376
|
+
},
|
|
377
|
+
search: (text: string, options: Readonly<Record<string, unknown>> = {}) => computer.search(text, options),
|
|
378
|
+
read: (session: string, part: string, options: Readonly<Record<string, unknown>> = {}) => computer.read(session, part, options, holding),
|
|
379
|
+
...Object.fromEntries(sessionActions.map((action) => [action, (session: string, input?: unknown, context?: unknown) => call(session, action, input ?? null, isObject(context) ? context : {})])),
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const showing = (session: string) => {
|
|
383
|
+
const holder = holderOf(session)
|
|
384
|
+
if (holder === undefined) throw new RpcError(rpcCodes.notHeld, `No session ${session} runs on this computer, so it shows no UI.`)
|
|
385
|
+
return holder.connection
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
type ShownPart = { readonly mod: string; readonly id: string }
|
|
389
|
+
type ShownSet = { readonly parts: readonly ShownPart[]; readonly until: number }
|
|
390
|
+
const shownSets = new Map<string, Map<string, ShownSet>>()
|
|
391
|
+
const toldShown = new Map<string, string>()
|
|
392
|
+
|
|
393
|
+
const tellShown = (session: string) => {
|
|
394
|
+
const sets = shownSets.get(session) ?? new Map<string, ShownSet>()
|
|
395
|
+
for (const [client, set] of sets) if (set.until <= now()) sets.delete(client)
|
|
396
|
+
if (sets.size === 0) shownSets.delete(session)
|
|
397
|
+
const union = [...new Map([...sets.values()].flatMap(({ parts }) => parts).map(({ mod, id }) => [`${mod}/${id}`, { mod, id }])).values()].sort((first, second) => `${first.mod}/${first.id}`.localeCompare(`${second.mod}/${second.id}`))
|
|
398
|
+
const holder = holderOf(session)
|
|
399
|
+
const told = JSON.stringify(union)
|
|
400
|
+
if (holder === undefined || (toldShown.get(session) ?? '[]') === told) return
|
|
401
|
+
toldShown.set(session, told)
|
|
402
|
+
void holder.connection.request(sessionActs.ui, { method: 'shown', args: [session, union] }).catch((error: unknown) => {
|
|
403
|
+
if (!isConnectionGone(error)) report(error)
|
|
404
|
+
})
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const show = (session: string, client: unknown, parts: unknown) => {
|
|
408
|
+
showing(session)
|
|
409
|
+
if (typeof client !== 'string' || client === '') throw new RpcError(rpcCodes.invalidParams, `${uiInterface}.show takes the client that shows the parts, a name its app picks.`)
|
|
410
|
+
if (!Array.isArray(parts) || !parts.every((each) => isObject(each) && typeof each['mod'] === 'string' && typeof each['id'] === 'string')) throw new RpcError(rpcCodes.invalidParams, `${uiInterface}.show takes the parts it shows as { mod, id }[].`)
|
|
411
|
+
const sets = shownSets.get(session) ?? new Map<string, ShownSet>()
|
|
412
|
+
shownSets.set(session, sets)
|
|
413
|
+
if (parts.length === 0) sets.delete(client)
|
|
414
|
+
else sets.set(client, { parts: (parts as readonly ShownPart[]).map(({ mod, id }) => ({ mod, id })), until: now() + showLeaseMs })
|
|
415
|
+
after(showLeaseMs, () => tellShown(session))
|
|
416
|
+
tellShown(session)
|
|
417
|
+
return null
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const ui: Implementation = { ...Object.fromEntries(uiMethods.map((method) => [method, (session: string, ...args: unknown[]) => showing(session).request(sessionActs.ui, { method, args: [session, ...args] })])), show }
|
|
421
|
+
|
|
422
|
+
const interfaces = interfaceServer({
|
|
423
|
+
implementations: { ...Object.fromEntries(names.map((name) => [name, implementation])), [uiInterface]: ui },
|
|
424
|
+
onListen: (_connection, listening) => {
|
|
425
|
+
if (listening.interface === uiInterface) {
|
|
426
|
+
if (!uiEvents.includes(listening.event)) throw new RpcError(rpcCodes.methodNotFound, `${uiInterface} tells only Change, Redraw, Open, and Close.`)
|
|
427
|
+
return
|
|
428
|
+
}
|
|
429
|
+
if (listening.event !== 'Change') throw new RpcError(rpcCodes.methodNotFound, `${listening.interface} tells only Change, because a mod hears only the session it runs in.`)
|
|
430
|
+
},
|
|
431
|
+
extraMethod: (connection, method, params) => {
|
|
432
|
+
if (method === sessionActs.uiEvent) {
|
|
433
|
+
const holder = holders.get(connection)
|
|
434
|
+
const { event, payload } = (isObject(params) ? params : {}) as { readonly event?: unknown; readonly payload?: unknown }
|
|
435
|
+
if (holder !== undefined && typeof event === 'string' && uiEvents.includes(event)) interfaces.emit(uiInterface, event, { ...(isObject(payload) ? payload : {}), session: holder.session }, [holder.session])
|
|
436
|
+
return { result: null }
|
|
437
|
+
}
|
|
438
|
+
if (method === sessionActs.hold) {
|
|
439
|
+
const { session, project, cwd } = params as HeldSession
|
|
440
|
+
const known = holders.get(connection)
|
|
441
|
+
for (const [each, holder] of holders) if (holder.session === session && each !== connection) holders.delete(each)
|
|
442
|
+
holders.set(connection, { session, project, cwd, connection, told: known?.session === session ? known.told : {} })
|
|
443
|
+
changed({ session, part: 'running' })
|
|
444
|
+
toldShown.delete(session)
|
|
445
|
+
tellShown(session)
|
|
446
|
+
return { result: {} }
|
|
447
|
+
}
|
|
448
|
+
if (method === sessionActs.changed) {
|
|
449
|
+
changed(params as StoreChange)
|
|
450
|
+
return { result: null }
|
|
451
|
+
}
|
|
452
|
+
if (method === sessionActs.status) {
|
|
453
|
+
const holder = holders.get(connection)
|
|
454
|
+
const { session, ...told } = (isObject(params) ? params : {}) as HeldStatus & { readonly session?: unknown }
|
|
455
|
+
if (holder === undefined || holder.session !== session || JSON.stringify(told) === JSON.stringify(holder.told)) return { result: null }
|
|
456
|
+
holders.set(connection, { ...holder, told })
|
|
457
|
+
changed({ session: holder.session, part: 'status' })
|
|
458
|
+
return { result: null }
|
|
459
|
+
}
|
|
460
|
+
return undefined
|
|
461
|
+
},
|
|
462
|
+
})
|
|
463
|
+
|
|
464
|
+
const providers = routeProviders({ isOwn: (name) => names.includes(name) || name === uiInterface, own: (connection) => interfaces.handler(connection), device, report, channel: (send) => routes.channel(send), ...(programs === undefined ? {} : { programs }) })
|
|
465
|
+
|
|
466
|
+
const routes = rpcRoutes({
|
|
467
|
+
handle: (connection) => {
|
|
468
|
+
const own = interfaces.handler(connection)
|
|
469
|
+
return (method, params, signal) => providers.handler(connection, method, params, signal) ?? own(method, params, signal)
|
|
470
|
+
},
|
|
471
|
+
onClose: (connection) => {
|
|
472
|
+
const holder = holders.get(connection)
|
|
473
|
+
holders.delete(connection)
|
|
474
|
+
interfaces.closed(connection)
|
|
475
|
+
providers.closed(connection)
|
|
476
|
+
if (holder === undefined) return
|
|
477
|
+
toldShown.delete(holder.session)
|
|
478
|
+
changed({ session: holder.session, part: 'running' })
|
|
479
|
+
if (Object.keys(holder.told).length > 0) changed({ session: holder.session, part: 'status' })
|
|
480
|
+
},
|
|
481
|
+
now,
|
|
482
|
+
})
|
|
483
|
+
|
|
484
|
+
return {
|
|
485
|
+
routes,
|
|
486
|
+
interfaces,
|
|
487
|
+
providers,
|
|
488
|
+
holding,
|
|
489
|
+
heldSessions: () => [...holders.values()].map(({ session, project, cwd }) => ({ session, project, cwd })),
|
|
490
|
+
call: (session, action, input, context) => call(session, action, input, context) as never,
|
|
491
|
+
changed,
|
|
492
|
+
close: () => {
|
|
493
|
+
routes.close()
|
|
494
|
+
void providers.close()
|
|
495
|
+
},
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
export type ProgramReach = { readonly store: string; readonly files: InstanceFiles; readonly fetch: HttpFetch; readonly wait: (ms: number) => Promise<void> }
|
|
500
|
+
|
|
501
|
+
export type ProviderRouting = {
|
|
502
|
+
handler(connection: RpcConnection, method: string, params: unknown, signal: AbortSignal): Promise<unknown> | undefined
|
|
503
|
+
list(name: string): Promise<ProviderIdentity[]>
|
|
504
|
+
call(called: ProvidedCall, signal?: AbortSignal): Promise<unknown>
|
|
505
|
+
closed(connection: RpcConnection): void
|
|
506
|
+
close(): Promise<void>
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
type ProviderEnd = {
|
|
510
|
+
readonly identity: ProviderIdentity
|
|
511
|
+
readonly listeners: InterfaceListeners
|
|
512
|
+
readonly link: Pick<Peer, 'request'>
|
|
513
|
+
connection: RpcConnection | undefined
|
|
514
|
+
names: Set<string>
|
|
515
|
+
older: { readonly address: string; readonly client: RpcClient } | undefined
|
|
516
|
+
readonly awaited: Set<{ readonly name: string | undefined; readonly provided: () => void }>
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
type DeviceListed = Pick<Device, 'id' | 'name'> & { readonly address?: string; readonly carrier: ProviderEnd }
|
|
520
|
+
|
|
521
|
+
type AddressServe = { readonly name: string; readonly listeners: InterfaceListeners; readonly address: string; readonly client: RpcClient }
|
|
522
|
+
|
|
523
|
+
type MessageServe = { name: string; readonly listeners: InterfaceListeners; readonly carrier: ProviderEnd; link: RpcConnection; theirs: string | undefined }
|
|
524
|
+
|
|
525
|
+
type DeviceServe = AddressServe | MessageServe
|
|
526
|
+
|
|
527
|
+
type Hello = { readonly link: string; readonly answers?: string }
|
|
528
|
+
|
|
529
|
+
type Target = Pick<ProviderEnd, 'listeners' | 'link'> & { readonly provider?: ProviderIdentity }
|
|
530
|
+
|
|
531
|
+
export function providerPeer(serve: Pick<Peer, 'request'>, identity: ProviderIdentity): Pick<Peer, 'request'> {
|
|
532
|
+
return {
|
|
533
|
+
request: <Result>(method: string, params?: unknown, signal?: AbortSignal) => {
|
|
534
|
+
if (method.startsWith('$/')) return serve.request<Result>(method, params, signal)
|
|
535
|
+
const dot = method.lastIndexOf('.')
|
|
536
|
+
return serve.request<Result>(providerActs.call, { interface: method.slice(0, dot), method: method.slice(dot + 1), args: Array.isArray(params) ? params : [], ...identity } satisfies ProvidedCall, signal)
|
|
537
|
+
},
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
export function routeProviders({
|
|
542
|
+
isOwn,
|
|
543
|
+
own,
|
|
544
|
+
device,
|
|
545
|
+
report,
|
|
546
|
+
channel,
|
|
547
|
+
programs,
|
|
548
|
+
}: {
|
|
549
|
+
readonly isOwn: (name: string) => boolean
|
|
550
|
+
readonly own: (connection: RpcConnection) => RpcHandler
|
|
551
|
+
readonly device: () => Promise<Pick<Device, 'id' | 'name'>>
|
|
552
|
+
readonly report: (error: unknown) => void
|
|
553
|
+
readonly channel: RpcRoutes['channel']
|
|
554
|
+
readonly programs?: ProgramReach
|
|
555
|
+
}): ProviderRouting {
|
|
556
|
+
const ends = new Map<string, ProviderEnd>()
|
|
557
|
+
const forwarded = new Map<RpcConnection, Map<string, Subscription>>()
|
|
558
|
+
const devices = new Map<string, DeviceServe>()
|
|
559
|
+
const deviceListeners = new Map<string, InterfaceListeners>()
|
|
560
|
+
const followed = new WeakSet<ProviderEnd>()
|
|
561
|
+
let following: Promise<void> = Promise.resolve()
|
|
562
|
+
const keyOf = ({ mod, program }: ProviderIdentity) => `${mod}\n${program ?? ''}`
|
|
563
|
+
const named = ({ mod, program }: ProviderIdentity) => `${mod}'s ${program ?? mod} program`
|
|
564
|
+
const isSelf = ({ mod, program }: Partial<ProviderIdentity>) => mod === cmodPluginName && program === cmodPluginName
|
|
565
|
+
|
|
566
|
+
const endOf = (identity: ProviderIdentity): ProviderEnd => {
|
|
567
|
+
const known = ends.get(keyOf(identity))
|
|
568
|
+
if (known !== undefined) return known
|
|
569
|
+
const end: ProviderEnd = {
|
|
570
|
+
identity: { mod: identity.mod, ...(identity.program === undefined ? {} : { program: identity.program }) },
|
|
571
|
+
listeners: interfaceListeners({ report }),
|
|
572
|
+
link: {
|
|
573
|
+
request: <Result>(method: string, params?: unknown, signal?: AbortSignal) => {
|
|
574
|
+
const peer = end.connection ?? end.older?.client
|
|
575
|
+
return peer === undefined ? Promise.reject(new RpcUnreached(`${named(identity)} does not run.`)) : peer.request<Result>(method, params, signal)
|
|
576
|
+
},
|
|
577
|
+
},
|
|
578
|
+
connection: undefined,
|
|
579
|
+
names: new Set(),
|
|
580
|
+
older: undefined,
|
|
581
|
+
awaited: new Set(),
|
|
582
|
+
}
|
|
583
|
+
ends.set(keyOf(identity), end)
|
|
584
|
+
return end
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const heardBy = (listeners: InterfaceListeners, who: string) => async (method: string, params: unknown, signal: AbortSignal) => {
|
|
588
|
+
const answered = await listeners.handler(method, params, signal)
|
|
589
|
+
if (answered !== undefined) return answered.result
|
|
590
|
+
if (method === onMethod) return null
|
|
591
|
+
throw new RpcError(rpcCodes.methodNotFound, `cmod serve answers ${who} no ${method}.`)
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
const instances = async (name: string): Promise<Provider[]> => (programs === undefined ? [] : (await readProviders(programs.files, programs.store, name)).filter((each) => each.mod !== cmodPluginName))
|
|
595
|
+
|
|
596
|
+
const ownOf = async (name: string): Promise<ProviderIdentity[]> => {
|
|
597
|
+
const registered = [...ends.values()].filter((end) => end.connection !== undefined && end.names.has(name)).map((end) => end.identity)
|
|
598
|
+
const keys = new Set(registered.map(keyOf))
|
|
599
|
+
const older = (await instances(name)).filter((each) => !keys.has(keyOf(each))).map(({ mod, program }) => ({ mod, program }))
|
|
600
|
+
return [...registered, ...older]
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
const listed = async (name: string, asked: string | undefined): Promise<ProviderIdentity[]> => {
|
|
604
|
+
const here = await device()
|
|
605
|
+
const stamped = (identities: readonly ProviderIdentity[]) => identities.map((identity) => ({ ...identity, device: here }))
|
|
606
|
+
if (asked !== undefined) return asked === here.id ? stamped([...(await ownOf(name)), ...(isOwn(name) ? [{ mod: cmodPluginName, program: cmodPluginName }] : [])]) : []
|
|
607
|
+
await following
|
|
608
|
+
const carried = await Promise.all(
|
|
609
|
+
[...devices.entries()]
|
|
610
|
+
.filter(([, each]) => isReached(each))
|
|
611
|
+
.map(([id, each]) =>
|
|
612
|
+
peerOf(each).request<ProviderIdentity[]>(providerActs.providers, { interface: name, device: id }).catch((error: unknown) => {
|
|
613
|
+
report(new Error(`cmod serve lists no ${name} of ${each.name}: ${messageOf(error)}`))
|
|
614
|
+
return []
|
|
615
|
+
}),
|
|
616
|
+
),
|
|
617
|
+
)
|
|
618
|
+
return [...stamped(await ownOf(name)), ...carried.flat()]
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
const reachOlder = (end: ProviderEnd, address: string, reach: ProgramReach) => {
|
|
622
|
+
if (end.older?.address === address) return
|
|
623
|
+
void end.older?.client.close()
|
|
624
|
+
const client = connectRpc({ call: addressCall(reach.fetch, address), handle: heardBy(end.listeners, named(end.identity)), onConnect: (connected) => end.listeners.replay(connected), wait: reach.wait })
|
|
625
|
+
end.older = { address, client }
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
const isLinked = (each: DeviceServe): each is MessageServe => 'carrier' in each
|
|
629
|
+
|
|
630
|
+
const isReached = (each: DeviceServe) => (isLinked(each) ? each.theirs !== undefined : each.client.isConnected)
|
|
631
|
+
|
|
632
|
+
const peerOf = (each: DeviceServe): Pick<Peer, 'request'> =>
|
|
633
|
+
isLinked(each)
|
|
634
|
+
? { request: <Result>(method: string, params?: unknown, signal?: AbortSignal) => (each.theirs === undefined ? Promise.reject(new RpcUnreached(`The cmod serve of ${each.name} has not linked yet.`)) : each.link.request<Result>(method, params, signal)) }
|
|
635
|
+
: each.client
|
|
636
|
+
|
|
637
|
+
const listenersOf = (id: string) => {
|
|
638
|
+
const listeners = deviceListeners.get(id) ?? interfaceListeners({ report })
|
|
639
|
+
deviceListeners.set(id, listeners)
|
|
640
|
+
return listeners
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
const drop = (id: string, each: DeviceServe) => {
|
|
644
|
+
devices.delete(id)
|
|
645
|
+
if (!isLinked(each)) return each.client.close()
|
|
646
|
+
each.link.close(new Error(`cmod serve dropped ${each.name}`))
|
|
647
|
+
return undefined
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
const carry = (carrier: ProviderEnd, id: string, message: RpcMessage) => carrier.link.request(methodName(devicesInterface, 'send'), [id, message])
|
|
651
|
+
|
|
652
|
+
const linkTo = (id: string, name: string, carrier: ProviderEnd, theirs: string | undefined) => {
|
|
653
|
+
const link: RpcConnection = channel((message) => {
|
|
654
|
+
void carry(carrier, id, message).catch((error: unknown) => {
|
|
655
|
+
const failed = `${named(carrier.identity)} carried no message to ${name}: ${messageOf(error)}`
|
|
656
|
+
if ('method' in message && 'id' in message) link.receive({ jsonrpc: '2.0', id: message.id, error: { code: rpcCodes.closed, message: failed } })
|
|
657
|
+
else report(new Error(failed))
|
|
658
|
+
})
|
|
659
|
+
})
|
|
660
|
+
const each: MessageServe = { name, listeners: listenersOf(id), carrier, link, theirs }
|
|
661
|
+
devices.set(id, each)
|
|
662
|
+
link.notify(providerActs.link, { link: link.id, ...(theirs === undefined ? {} : { answers: theirs }) } satisfies Hello)
|
|
663
|
+
if (theirs !== undefined) void each.listeners.replay(peerOf(each))
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
const greeted = (id: string, known: MessageServe | undefined, carrier: ProviderEnd, hello: Hello) => {
|
|
667
|
+
if (known === undefined) return linkTo(id, id, carrier, hello.link)
|
|
668
|
+
if (known.theirs !== undefined && hello.answers !== known.link.id) {
|
|
669
|
+
known.link.close(new Error(`the cmod serve of ${known.name} linked again`))
|
|
670
|
+
return linkTo(id, known.name, carrier, hello.link)
|
|
671
|
+
}
|
|
672
|
+
if (known.theirs === hello.link) return
|
|
673
|
+
known.theirs = hello.link
|
|
674
|
+
if (hello.answers !== known.link.id) known.link.notify(providerActs.link, { link: known.link.id, answers: hello.link } satisfies Hello)
|
|
675
|
+
void known.listeners.replay(peerOf(known))
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const heardThrough = (carrier: ProviderEnd, told: unknown) => {
|
|
679
|
+
if (!isObject(told) || typeof told['device'] !== 'string' || !isObject(told['message'])) return
|
|
680
|
+
const id = told['device']
|
|
681
|
+
const message = told['message']
|
|
682
|
+
const known = devices.get(id)
|
|
683
|
+
if (known !== undefined && !(isLinked(known) && known.carrier === carrier)) return report(new Error(`${named(carrier.identity)} carried a message from device ${id}, which cmod serve reaches another way.`))
|
|
684
|
+
const params = message['params']
|
|
685
|
+
if (message['method'] === providerActs.link && isObject(params) && typeof params['link'] === 'string') return greeted(id, known, carrier, params as Hello)
|
|
686
|
+
if (known?.theirs !== undefined) return known.link.receive(message)
|
|
687
|
+
const asked = message['id']
|
|
688
|
+
if (known === undefined && typeof message['method'] === 'string' && (typeof asked === 'number' || typeof asked === 'string'))
|
|
689
|
+
void carry(carrier, id, { jsonrpc: '2.0', id: asked, error: { code: rpcCodes.closed, message: `This cmod serve holds no link to device ${id}, so it answers nothing from it.` } }).catch(report)
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
const reachDevice = async ({ id, name, address }: Pick<Device, 'id' | 'name'> & { readonly address: string }, reach: ProgramReach) => {
|
|
693
|
+
const listeners = listenersOf(id)
|
|
694
|
+
let reached: () => void = () => undefined
|
|
695
|
+
const isReached = new Promise<void>((resolve) => {
|
|
696
|
+
reached = resolve
|
|
697
|
+
})
|
|
698
|
+
const client = connectRpc({
|
|
699
|
+
call: addressCall(reach.fetch, address),
|
|
700
|
+
handle: heardBy(listeners, `the cmod serve of ${name}`),
|
|
701
|
+
onConnect: async (connected) => {
|
|
702
|
+
reached()
|
|
703
|
+
await listeners.replay(connected)
|
|
704
|
+
},
|
|
705
|
+
onError: () => reached(),
|
|
706
|
+
wait: reach.wait,
|
|
707
|
+
keepsConnecting: true,
|
|
708
|
+
})
|
|
709
|
+
devices.set(id, { name, address, client, listeners })
|
|
710
|
+
await isReached
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const connectDevices = async () => {
|
|
714
|
+
const here = await device()
|
|
715
|
+
const sources = [...ends.values()].filter((end) => end.connection !== undefined && end.names.has(devicesInterface))
|
|
716
|
+
const lists = await Promise.all(
|
|
717
|
+
sources.map((end) =>
|
|
718
|
+
end.link.request<Omit<DeviceListed, 'carrier'>[]>(methodName(devicesInterface, 'devices'), []).then(
|
|
719
|
+
(list): DeviceListed[] => list.map((each) => ({ ...each, carrier: end })),
|
|
720
|
+
(error: unknown) => {
|
|
721
|
+
report(new Error(`${named(end.identity)} lists no ${devicesInterface}: ${messageOf(error)}`))
|
|
722
|
+
return []
|
|
723
|
+
},
|
|
724
|
+
),
|
|
725
|
+
),
|
|
726
|
+
)
|
|
727
|
+
const wanted = new Map(lists.flat().filter((each) => each.id !== here.id).map((each) => [each.id, each]))
|
|
728
|
+
for (const [id, each] of devices) {
|
|
729
|
+
const kept = wanted.get(id)
|
|
730
|
+
if (kept === undefined || (isLinked(each) ? kept.address !== undefined || kept.carrier !== each.carrier : kept.address !== each.address)) void drop(id, each)
|
|
731
|
+
else if (isLinked(each)) each.name = kept.name
|
|
732
|
+
}
|
|
733
|
+
const added = [...wanted.values()].filter((each) => !devices.has(each.id))
|
|
734
|
+
for (const each of added) if (each.address === undefined) linkTo(each.id, each.name, each.carrier, undefined)
|
|
735
|
+
await Promise.all(added.map(({ address, ...each }) => (address === undefined || programs === undefined ? undefined : reachDevice({ ...each, address }, programs))))
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
const followDevices = () => {
|
|
739
|
+
following = following.then(connectDevices).catch(report)
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
const follow = (end: ProviderEnd) => {
|
|
743
|
+
if (!followed.has(end)) {
|
|
744
|
+
followed.add(end)
|
|
745
|
+
end.listeners.listen(end.link, listeningOf(devicesInterface, 'on', 'Change', [], undefined), () => followDevices())
|
|
746
|
+
end.listeners.listen(end.link, listeningOf(devicesInterface, 'on', 'Message', [], undefined), (told: unknown) => heardThrough(end, told))
|
|
747
|
+
}
|
|
748
|
+
followDevices()
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
const targetOf = async (name: string, asked: ProviderIdentity | undefined): Promise<Target | undefined> => {
|
|
752
|
+
if (asked === undefined) {
|
|
753
|
+
const found = await listed(name, undefined)
|
|
754
|
+
const [only] = found
|
|
755
|
+
if (only === undefined) throw new RpcError(rpcCodes.methodNotFound, `No program on this computer or the devices it reaches provides ${name}.`)
|
|
756
|
+
if (found.length > 1) throw new RpcError(rpcCodes.methodNotFound, `${found.map(named).join(' and ')} provide ${name}, so cmod serve picks none. Call one through providers('${name}').`)
|
|
757
|
+
return targetOf(name, only)
|
|
758
|
+
}
|
|
759
|
+
if (asked.device !== undefined && asked.device.id !== (await device()).id) {
|
|
760
|
+
const carrier = devices.get(asked.device.id)
|
|
761
|
+
if (carrier === undefined) throw new Error(`cmod serve reaches no device ${asked.device.name}, so ${named(asked)} there answers no ${name}.`)
|
|
762
|
+
return { listeners: carrier.listeners, link: providerPeer(peerOf(carrier), asked), provider: asked }
|
|
763
|
+
}
|
|
764
|
+
if (isSelf(asked)) return undefined
|
|
765
|
+
return providerOf(name, asked)
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
const providerOf = async (name: string, asked: ProviderIdentity): Promise<ProviderEnd> => {
|
|
769
|
+
const end = endOf(asked)
|
|
770
|
+
if (end.connection !== undefined && end.names.has(name)) return end
|
|
771
|
+
const older = programs === undefined ? undefined : (await instances(name)).find((each) => keyOf(each) === keyOf(asked))
|
|
772
|
+
if (older === undefined || programs === undefined) throw new Error(`${named(asked)} does not run, so it answers no ${name}.`)
|
|
773
|
+
reachOlder(end, older.address, programs)
|
|
774
|
+
return end
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
const provide = (connection: RpcConnection, params: unknown) => {
|
|
778
|
+
if (!isObject(params) || typeof params['interface'] !== 'string' || typeof params['mod'] !== 'string' || (params['program'] !== undefined && typeof params['program'] !== 'string')) throw new RpcError(rpcCodes.invalidParams, `${providerActs.provide} takes { interface, mod, program }.`)
|
|
779
|
+
checkInterfaceName(params['interface'])
|
|
780
|
+
const end = endOf({ mod: params['mod'], ...(typeof params['program'] === 'string' ? { program: params['program'] } : {}) })
|
|
781
|
+
if (end.connection !== connection) {
|
|
782
|
+
end.connection = connection
|
|
783
|
+
end.names = new Set()
|
|
784
|
+
void end.listeners.replay(end.link)
|
|
785
|
+
}
|
|
786
|
+
end.names.add(params['interface'])
|
|
787
|
+
for (const each of end.awaited) if (each.name === undefined || each.name === params['interface']) each.provided()
|
|
788
|
+
if (params['interface'] === devicesInterface) follow(end)
|
|
789
|
+
return {}
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
const provider = async (params: unknown, signal: AbortSignal): Promise<ProviderIdentity> => {
|
|
793
|
+
if (!isObject(params) || (params['interface'] !== undefined && typeof params['interface'] !== 'string') || typeof params['mod'] !== 'string' || typeof params['program'] !== 'string') throw new RpcError(rpcCodes.invalidParams, `${providerActs.provider} takes { interface, mod, program }, or { mod, program } for any interface.`)
|
|
794
|
+
const name = params['interface']
|
|
795
|
+
const end = endOf({ mod: params['mod'], program: params['program'] })
|
|
796
|
+
if (end.connection === undefined || (name === undefined ? end.names.size === 0 : !end.names.has(name))) {
|
|
797
|
+
await new Promise<void>((resolve, reject) => {
|
|
798
|
+
const each = {
|
|
799
|
+
name,
|
|
800
|
+
provided: () => {
|
|
801
|
+
end.awaited.delete(each)
|
|
802
|
+
resolve()
|
|
803
|
+
},
|
|
804
|
+
}
|
|
805
|
+
end.awaited.add(each)
|
|
806
|
+
signal.addEventListener(
|
|
807
|
+
'abort',
|
|
808
|
+
() => {
|
|
809
|
+
end.awaited.delete(each)
|
|
810
|
+
reject(signal.reason)
|
|
811
|
+
},
|
|
812
|
+
{ once: true },
|
|
813
|
+
)
|
|
814
|
+
})
|
|
815
|
+
}
|
|
816
|
+
return { ...end.identity, device: await device() }
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
const unprovide = (connection: RpcConnection, params: unknown) => {
|
|
820
|
+
const name = isObject(params) ? params['interface'] : undefined
|
|
821
|
+
for (const end of ends.values()) if (end.connection === connection && typeof name === 'string') end.names.delete(name)
|
|
822
|
+
if (name === devicesInterface) followDevices()
|
|
823
|
+
return {}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
const listen = async (caller: RpcConnection, { id, provider, ...listening }: Listening, signal: AbortSignal) => {
|
|
827
|
+
const target = await targetOf(listening.interface, provider)
|
|
828
|
+
if (target === undefined) return own(caller)(listenMethod, { ...listening, id }, signal)
|
|
829
|
+
const mine = forwarded.get(caller) ?? new Map<string, Subscription>()
|
|
830
|
+
mine.get(id)?.remove()
|
|
831
|
+
const sent = target.provider === undefined ? listening : { ...listening, provider: target.provider }
|
|
832
|
+
mine.set(id, target.listeners.listen(target.link, sent, (payload, heard) => (listening.kind === 'on' ? caller.notify(onMethod, { id, payload } satisfies Heard) : caller.request(beforeMethod, { id, payload } satisfies Heard, heard))))
|
|
833
|
+
forwarded.set(caller, mine)
|
|
834
|
+
return {}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
const call = async (caller: RpcConnection | undefined, { interface: name, method, args, ...asked }: ProvidedCall, signal: AbortSignal | undefined) => {
|
|
838
|
+
const target = await targetOf(name, asked.mod === undefined ? undefined : { ...asked, mod: asked.mod })
|
|
839
|
+
const sent = Array.isArray(args) ? args : []
|
|
840
|
+
if (target !== undefined) return target.link.request(methodName(name, method), sent, signal)
|
|
841
|
+
if (caller === undefined) throw new Error(`cmod serve answers its own ${name} on a connection.`)
|
|
842
|
+
return own(caller)(methodName(name, method), sent, signal ?? caller.signal)
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
return {
|
|
846
|
+
handler(connection, method, params, signal) {
|
|
847
|
+
if (method === providerActs.provide) return new Promise((resolve) => resolve(provide(connection, params)))
|
|
848
|
+
if (method === providerActs.unprovide) return Promise.resolve(unprovide(connection, params))
|
|
849
|
+
if (method === providerActs.provider) return provider(params, signal)
|
|
850
|
+
if (method === providerActs.providers) return listed(isObject(params) ? String(params['interface']) : '', isObject(params) && typeof params['device'] === 'string' ? params['device'] : undefined)
|
|
851
|
+
if (method === providerActs.call) return call(connection, (isObject(params) ? params : {}) as ProvidedCall, signal)
|
|
852
|
+
if (method === onMethod || method === beforeMethod) {
|
|
853
|
+
const end = [...ends.values()].find((each) => each.connection === connection)
|
|
854
|
+
if (end !== undefined) return heardBy(end.listeners, named(end.identity))(method, params, signal)
|
|
855
|
+
const linked = [...devices.values()].find((each) => isLinked(each) && each.link === connection)
|
|
856
|
+
return linked === undefined ? undefined : heardBy(linked.listeners, `the cmod serve of ${linked.name}`)(method, params, signal)
|
|
857
|
+
}
|
|
858
|
+
if (method === listenMethod) {
|
|
859
|
+
if (!isObject(params) || typeof params['interface'] !== 'string') return undefined
|
|
860
|
+
return params['provider'] === undefined && isOwn(params['interface']) ? undefined : listen(connection, params as Listening, signal)
|
|
861
|
+
}
|
|
862
|
+
if (method === unlistenMethod) {
|
|
863
|
+
const id = isObject(params) ? params['id'] : undefined
|
|
864
|
+
const mine = forwarded.get(connection)
|
|
865
|
+
const listener = typeof id === 'string' ? mine?.get(id) : undefined
|
|
866
|
+
if (listener === undefined) return undefined
|
|
867
|
+
listener.remove()
|
|
868
|
+
mine?.delete(String(id))
|
|
869
|
+
return Promise.resolve({})
|
|
870
|
+
}
|
|
871
|
+
const dot = method.lastIndexOf('.')
|
|
872
|
+
if (method.startsWith('$/') || dot === -1 || isOwn(method.slice(0, dot))) return undefined
|
|
873
|
+
return call(connection, { interface: method.slice(0, dot), method: method.slice(dot + 1), args: Array.isArray(params) ? params : [] }, signal)
|
|
874
|
+
},
|
|
875
|
+
list: (name) => listed(name, undefined),
|
|
876
|
+
call: (called, signal) => call(undefined, called, signal),
|
|
877
|
+
closed(connection) {
|
|
878
|
+
let listedDevices = false
|
|
879
|
+
for (const end of ends.values()) {
|
|
880
|
+
if (end.connection !== connection) continue
|
|
881
|
+
listedDevices ||= end.names.has(devicesInterface)
|
|
882
|
+
end.connection = undefined
|
|
883
|
+
end.names = new Set()
|
|
884
|
+
}
|
|
885
|
+
for (const listener of forwarded.get(connection)?.values() ?? []) listener.remove()
|
|
886
|
+
forwarded.delete(connection)
|
|
887
|
+
if (listedDevices) followDevices()
|
|
888
|
+
},
|
|
889
|
+
async close() {
|
|
890
|
+
await Promise.all([...[...ends.values()].map((end) => end.older?.client.close()), ...[...devices.entries()].map(([id, each]) => drop(id, each))])
|
|
891
|
+
},
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
export type ProviderList = { readonly mods: readonly string[]; readonly programs: readonly ProviderIdentity[]; readonly device?: Pick<Device, 'id' | 'name'> }
|
|
896
|
+
|
|
897
|
+
export type ProvidedListen = Omit<Listening, 'id' | 'args' | 'after' | 'provider'> & ProviderIdentity & { readonly id: string }
|
|
898
|
+
|
|
899
|
+
export type ProvidedHeard = { readonly id: string; readonly payload: unknown }
|
|
900
|
+
|
|
901
|
+
export type ProvidedTell = { readonly interface: string; readonly event: string; readonly payload: unknown }
|
|
902
|
+
|
|
903
|
+
type Asked = Pick<Listening, 'event' | 'timeoutMs' | 'onFailure'> & { readonly listener?: string; ask(signal: AbortSignal): Promise<unknown> }
|
|
904
|
+
|
|
905
|
+
async function askInTurn(asked: readonly Asked[], after: Claude['clock']['after'], report: (error: unknown) => void): Promise<unknown[]> {
|
|
906
|
+
const answers: unknown[] = []
|
|
907
|
+
for (const { event, timeoutMs = listenerMs, onFailure, listener, ask } of asked) {
|
|
908
|
+
const passed = new AbortController()
|
|
909
|
+
let timer: ReturnType<typeof after> | undefined
|
|
910
|
+
const answer = await new Promise<unknown>((resolve, reject) => {
|
|
911
|
+
timer = after(timeoutMs, () => {
|
|
912
|
+
passed.abort()
|
|
913
|
+
reject(new Error(`before${event} passed its ${timeoutMs / 1000} s timeout`))
|
|
914
|
+
})
|
|
915
|
+
ask(passed.signal).then(resolve, reject)
|
|
916
|
+
}).catch((error: unknown) => {
|
|
917
|
+
const failed = new Error(listener === undefined ? messageOf(error) : `${listener}: ${messageOf(error)}`)
|
|
918
|
+
report(failed)
|
|
919
|
+
return onFailure === 'refuse' ? { refuse: failed.message } : null
|
|
920
|
+
})
|
|
921
|
+
timer?.cancel()
|
|
922
|
+
if (answer === null || answer === undefined) continue
|
|
923
|
+
answers.push(answer)
|
|
924
|
+
if (isObject(answer) && typeof answer['refuse'] === 'string') break
|
|
925
|
+
}
|
|
926
|
+
return answers
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
type SessionCodeListeners = {
|
|
930
|
+
listen(caller: string, listening: ProvidedListen): null
|
|
931
|
+
unlisten(caller: string, id: string): null
|
|
932
|
+
tell(provider: string, told: ProvidedTell): null
|
|
933
|
+
ask(provider: string, asked: ProvidedTell): Promise<unknown[]>
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
function sessionCodeListeners(hear: (caller: string, heard: ProvidedHeard, signal: AbortSignal) => Promise<unknown>, after: Claude['clock']['after'], report: (error: unknown) => void): SessionCodeListeners {
|
|
937
|
+
const held = new Map<string, { readonly caller: string; readonly listening: ProvidedListen }>()
|
|
938
|
+
const heldFor = (provider: string, { interface: named, event, payload }: ProvidedTell, kind: ListenKind) =>
|
|
939
|
+
[...held.values()].filter(({ listening }) => listening.mod === provider && listening.interface === named && listening.event === event && listening.kind === kind && isHeardAt(listening, [], payload))
|
|
940
|
+
return {
|
|
941
|
+
listen(caller, listening) {
|
|
942
|
+
held.set(`${caller}\n${listening.id}`, { caller, listening })
|
|
943
|
+
return null
|
|
944
|
+
},
|
|
945
|
+
unlisten(caller, id) {
|
|
946
|
+
held.delete(`${caller}\n${id}`)
|
|
947
|
+
return null
|
|
948
|
+
},
|
|
949
|
+
tell(provider, told) {
|
|
950
|
+
for (const { caller, listening } of heldFor(provider, told, 'on')) void hear(caller, { id: listening.id, payload: told.payload }, unaborted).catch(report)
|
|
951
|
+
return null
|
|
952
|
+
},
|
|
953
|
+
ask: (provider, asked) => askInTurn(heldFor(provider, asked, 'before').map(({ caller, listening }) => ({ ...listening, listener: caller, ask: (signal: AbortSignal) => hear(caller, { id: listening.id, payload: asked.payload }, signal) })), after, report),
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
export type Provided = Subscription & { tell(event: string, payload: unknown): void; ask(event: string, payload: unknown): Promise<unknown[]> }
|
|
958
|
+
|
|
959
|
+
export type Providers = {
|
|
960
|
+
provided(): readonly string[]
|
|
961
|
+
provide(name: string, methods: Implementation): Provided
|
|
962
|
+
providers(name: string): Promise<Readonly<Record<string, unknown>>[]>
|
|
963
|
+
answer(method: string, input: unknown, caller: string, signal: AbortSignal): Promise<unknown> | undefined
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
export function createProviders({ name, call, changed, after, report }: { readonly name: string; readonly call: (to: string, method: string, input: unknown) => Promise<unknown>; readonly changed: () => void; readonly after: Claude['clock']['after']; readonly report: (error: unknown) => void }): Providers {
|
|
967
|
+
const provided = new Map<string, Implementation>()
|
|
968
|
+
const heard = new Map<string, Listener>()
|
|
969
|
+
let nextListener = 0
|
|
970
|
+
const run = async ({ interface: named, method, args }: ProvidedCall) => {
|
|
971
|
+
const runs = provided.get(named)?.[method] as ((...each: readonly unknown[]) => unknown) | undefined
|
|
972
|
+
if (runs === undefined) throw new Error(`${name} provides no ${named}.${method}.`)
|
|
973
|
+
return (await runs(...args)) ?? null
|
|
974
|
+
}
|
|
975
|
+
const answer = (method: string, asked: ProvidedCall & ProvidedHeard, caller: string, signal: AbortSignal): Promise<unknown> | undefined => {
|
|
976
|
+
if (method === interfaceMethods.heard && caller === cmodPluginName) return (async () => (await heard.get(asked.id)?.(asked.payload as never, signal)) ?? null)()
|
|
977
|
+
return method === interfaceMethods.provided && asked.program === undefined ? run(asked) : undefined
|
|
978
|
+
}
|
|
979
|
+
const client = (named: string, identity: ProviderIdentity) =>
|
|
980
|
+
providerClient(
|
|
981
|
+
named,
|
|
982
|
+
identity,
|
|
983
|
+
(method, args) => {
|
|
984
|
+
const asked: ProvidedCall = { interface: named, method, args, ...identity }
|
|
985
|
+
return beforeDeadline({ after }, callDeadline, methodName(named, method), () => identity.mod === name && identity.program === undefined ? run(asked) : call(identity.program === undefined ? identity.mod : cmodPluginName, interfaceMethods.provided, asked))
|
|
986
|
+
},
|
|
987
|
+
(kind, event, matcher, listener, options) => {
|
|
988
|
+
const id = `${named}#${(nextListener += 1)}`
|
|
989
|
+
heard.set(id, listener)
|
|
990
|
+
void call(cmodPluginName, interfaceMethods.listen, { id, interface: named, kind, event, ...identity, ...(matcher === undefined ? {} : { matcher: sentMatcher(matcher) }), ...options } satisfies ProvidedListen).catch((error: unknown) => {
|
|
991
|
+
heard.delete(id)
|
|
992
|
+
report(error)
|
|
993
|
+
})
|
|
994
|
+
return {
|
|
995
|
+
remove() {
|
|
996
|
+
if (heard.delete(id)) void call(cmodPluginName, interfaceMethods.unlisten, { id }).catch(report)
|
|
997
|
+
},
|
|
998
|
+
}
|
|
999
|
+
},
|
|
1000
|
+
)
|
|
1001
|
+
return {
|
|
1002
|
+
provided: () => [...provided.keys()],
|
|
1003
|
+
provide(named, methods) {
|
|
1004
|
+
checkInterfaceName(named)
|
|
1005
|
+
provided.set(named, methods)
|
|
1006
|
+
changed()
|
|
1007
|
+
const send = (method: string, event: string, payload: unknown) => new Promise<unknown>((resolve) => after(0, () => resolve(call(cmodPluginName, method, { interface: named, event, payload } satisfies ProvidedTell))))
|
|
1008
|
+
return {
|
|
1009
|
+
remove() {
|
|
1010
|
+
if (provided.get(named) === methods && provided.delete(named)) changed()
|
|
1011
|
+
},
|
|
1012
|
+
tell: (event, payload) => void send(interfaceMethods.tell, event, payload).catch(report),
|
|
1013
|
+
ask: (event, payload) => send(interfaceMethods.ask, event, payload) as Promise<unknown[]>,
|
|
1014
|
+
}
|
|
1015
|
+
},
|
|
1016
|
+
async providers(named) {
|
|
1017
|
+
const listed = (await call(cmodPluginName, interfaceMethods.providers, { name: named })) as ProviderList
|
|
1018
|
+
return [...listed.mods.map((mod) => client(named, { mod, device: listed.device })), ...listed.programs.map((identity) => client(named, identity))]
|
|
1019
|
+
},
|
|
1020
|
+
answer,
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
export type ServedProviders = {
|
|
1025
|
+
answer(method: string, input: unknown, caller: string | undefined): Promise<unknown> | undefined
|
|
1026
|
+
provide(name: string, methods: Implementation): Provided
|
|
1027
|
+
tell(name: string, event: string, payload: unknown): void
|
|
1028
|
+
ask(name: string, event: string, payload: unknown): Promise<unknown[]>
|
|
1029
|
+
handler(method: string, params: unknown, signal: AbortSignal): Promise<unknown> | undefined
|
|
1030
|
+
replay(): Promise<void>
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
export function serveProviders({
|
|
1034
|
+
serve,
|
|
1035
|
+
listeners,
|
|
1036
|
+
provider,
|
|
1037
|
+
tell,
|
|
1038
|
+
sessionCode,
|
|
1039
|
+
device,
|
|
1040
|
+
after,
|
|
1041
|
+
report,
|
|
1042
|
+
}: {
|
|
1043
|
+
readonly serve: Pick<Peer, 'request' | 'notify'>
|
|
1044
|
+
readonly listeners: InterfaceListeners
|
|
1045
|
+
readonly provider?: ProviderIdentity
|
|
1046
|
+
readonly tell: (caller: string, heard: ProvidedHeard, signal: AbortSignal) => Promise<unknown>
|
|
1047
|
+
readonly sessionCode: (name: string) => readonly string[]
|
|
1048
|
+
readonly device?: () => Promise<Pick<Device, 'id' | 'name'>>
|
|
1049
|
+
readonly after: Claude['clock']['after']
|
|
1050
|
+
readonly report: (error: unknown) => void
|
|
1051
|
+
}): ServedProviders {
|
|
1052
|
+
const implementations: Record<string, Implementation> = {}
|
|
1053
|
+
const server = interfaceServer({ implementations })
|
|
1054
|
+
const handle = server.handler(serve)
|
|
1055
|
+
const held = new Map<string, Subscription>()
|
|
1056
|
+
const reported = (error: unknown) => {
|
|
1057
|
+
if (!isConnectionGone(error)) report(error)
|
|
1058
|
+
}
|
|
1059
|
+
const register = (name: string) => serve.request(providerActs.provide, { interface: name, ...provider }).catch(reported)
|
|
1060
|
+
const listen = (caller: string | undefined, { id, interface: named, kind, event, matcher, timeoutMs, onFailure, mod, program, device: on }: ProvidedListen) => {
|
|
1061
|
+
if (caller === undefined) throw new Error('cmod hears no caller for this listener.')
|
|
1062
|
+
const key = `${caller}\n${id}`
|
|
1063
|
+
held.get(key)?.remove()
|
|
1064
|
+
const listening = { interface: named, kind, event, ...(matcher === undefined ? {} : { matcher }), ...(timeoutMs === undefined ? {} : { timeoutMs }), ...(onFailure === undefined ? {} : { onFailure }), provider: { mod, ...(program === undefined ? {} : { program }), ...(on === undefined ? {} : { device: on }) } }
|
|
1065
|
+
held.set(key, listeners.listen(serve, listening, (payload: unknown, signal) => tell(caller, { id, payload }, signal)))
|
|
1066
|
+
return null
|
|
1067
|
+
}
|
|
1068
|
+
const unlisten = (caller: string | undefined, id: string) => {
|
|
1069
|
+
const key = `${caller}\n${id}`
|
|
1070
|
+
held.get(key)?.remove()
|
|
1071
|
+
held.delete(key)
|
|
1072
|
+
return null
|
|
1073
|
+
}
|
|
1074
|
+
const sessionListeners = sessionCodeListeners(tell, after, report)
|
|
1075
|
+
const ask = (name: string, event: string, payload: unknown) =>
|
|
1076
|
+
askInTurn(
|
|
1077
|
+
server.listeners(name, event).filter((listening) => listening.kind === 'before' && isHeardAt(listening, [], payload)).map((listening) => ({ ...listening, ask: (signal: AbortSignal) => listening.connection.request(beforeMethod, { id: listening.id, payload } satisfies Heard, signal) })),
|
|
1078
|
+
after,
|
|
1079
|
+
report,
|
|
1080
|
+
)
|
|
1081
|
+
const listed = async (named: string): Promise<ProviderList> => {
|
|
1082
|
+
const mods = sessionCode(named)
|
|
1083
|
+
const programs = await serve.request<ProviderIdentity[]>(providerActs.providers, { interface: named })
|
|
1084
|
+
return { mods, programs, ...(mods.length === 0 || device === undefined ? {} : { device: await device() }) }
|
|
1085
|
+
}
|
|
1086
|
+
const waitForProvider = async ({ interface: named, mod, program }: Readonly<Record<string, unknown>>): Promise<ProviderIdentity | null> => {
|
|
1087
|
+
const held = new AbortController()
|
|
1088
|
+
const timer = after(providerHoldMs, () => held.abort())
|
|
1089
|
+
try {
|
|
1090
|
+
return await serve.request<ProviderIdentity>(providerActs.provider, { interface: named, mod, program }, held.signal)
|
|
1091
|
+
} catch (error) {
|
|
1092
|
+
if (!held.signal.aborted && !isConnectionGone(error)) throw error
|
|
1093
|
+
await new Promise<void>((resolve) => (held.signal.aborted ? resolve() : held.signal.addEventListener('abort', () => resolve(), { once: true })))
|
|
1094
|
+
return null
|
|
1095
|
+
} finally {
|
|
1096
|
+
timer.cancel()
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
return {
|
|
1100
|
+
answer(method, input, caller) {
|
|
1101
|
+
const asked = isObject(input) ? input : {}
|
|
1102
|
+
if (method === interfaceMethods.providers) return listed(String(asked['name']))
|
|
1103
|
+
if (method === interfaceMethods.provider) return waitForProvider(asked)
|
|
1104
|
+
if (method === interfaceMethods.listen) return new Promise((resolve) => resolve(asked['program'] === undefined ? sessionListeners.listen(String(caller), input as ProvidedListen) : listen(caller, input as ProvidedListen)))
|
|
1105
|
+
if (method === interfaceMethods.unlisten) {
|
|
1106
|
+
sessionListeners.unlisten(String(caller), String(asked['id']))
|
|
1107
|
+
return Promise.resolve(unlisten(caller, String(asked['id'])))
|
|
1108
|
+
}
|
|
1109
|
+
if (method === interfaceMethods.tell) return Promise.resolve(sessionListeners.tell(String(caller), input as ProvidedTell))
|
|
1110
|
+
if (method === interfaceMethods.ask) return sessionListeners.ask(String(caller), input as ProvidedTell)
|
|
1111
|
+
const call = asked as Partial<ProvidedCall>
|
|
1112
|
+
if (method !== interfaceMethods.provided || call.program === undefined || call.mod === undefined) return undefined
|
|
1113
|
+
return beforeDeadline({ after }, callDeadline, methodName(String(call.interface), String(call.method)), (signal) => serve.request(providerActs.call, call, signal))
|
|
1114
|
+
},
|
|
1115
|
+
provide(name, methods) {
|
|
1116
|
+
checkInterfaceName(name)
|
|
1117
|
+
if (provider === undefined) throw new Error(`${name}: this connection to cmod serve provides nothing.`)
|
|
1118
|
+
implementations[name] = methods
|
|
1119
|
+
void register(name)
|
|
1120
|
+
return {
|
|
1121
|
+
remove() {
|
|
1122
|
+
if (implementations[name] !== methods) return
|
|
1123
|
+
delete implementations[name]
|
|
1124
|
+
void serve.request(providerActs.unprovide, { interface: name }).catch(reported)
|
|
1125
|
+
},
|
|
1126
|
+
tell: (event, payload) => server.emit(name, event, payload),
|
|
1127
|
+
ask: (event, payload) => ask(name, event, payload),
|
|
1128
|
+
}
|
|
1129
|
+
},
|
|
1130
|
+
tell: (name, event, payload) => server.emit(name, event, payload),
|
|
1131
|
+
ask,
|
|
1132
|
+
handler(method, params, signal) {
|
|
1133
|
+
const isProvided = method === listenMethod || method === unlistenMethod || (!method.startsWith('$/') && method.includes('.'))
|
|
1134
|
+
return isProvided ? Promise.resolve(handle(method, params, signal)) : undefined
|
|
1135
|
+
},
|
|
1136
|
+
async replay() {
|
|
1137
|
+
await Promise.all(Object.keys(implementations).map(register))
|
|
1138
|
+
},
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
export type Connection = {
|
|
1143
|
+
call(name: string, method: string, params: readonly unknown[]): Promise<unknown>
|
|
1144
|
+
listen(name: string, event: string, listener: (payload: unknown, signal: AbortSignal) => unknown): Subscription
|
|
1145
|
+
tell(name: string, event: string, payload: unknown): void
|
|
1146
|
+
ask(name: string, event: string, payload: unknown): Promise<unknown[]>
|
|
1147
|
+
close(): Promise<void>
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
export function programConnection({ client, listeners, served, after }: { readonly client: RpcClient; readonly listeners: InterfaceListeners; readonly served: ServedProviders; readonly after: Claude['clock']['after'] }): Connection {
|
|
1151
|
+
return {
|
|
1152
|
+
call: (name, method, params) => {
|
|
1153
|
+
const called = methodName(name, method)
|
|
1154
|
+
return beforeDeadline({ after }, callDeadline, called, (signal) => client.request(called, params, signal))
|
|
1155
|
+
},
|
|
1156
|
+
listen: (name, event, listener) => listeners.listen(client, listeningOf(name, 'on', event, [], undefined), listener),
|
|
1157
|
+
tell: (name, event, payload) => served.tell(name, event, payload),
|
|
1158
|
+
ask: (name, event, payload) => served.ask(name, event, payload),
|
|
1159
|
+
close: () => client.close(),
|
|
1160
|
+
}
|
|
1161
|
+
}
|