@cmodjs/core 7.0.0 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/commands.md +104 -70
- package/docs/dependencies.md +153 -23
- package/docs/index.md +54 -10
- package/docs/install-steps.md +20 -17
- package/docs/jobs.md +42 -17
- package/docs/mod.md +37 -30
- package/docs/options.md +2 -2
- package/docs/session.md +39 -29
- package/docs/testing.md +84 -23
- package/docs/ui.md +128 -58
- package/installer.d.ts +2 -2
- package/jobs/context.js +1 -1
- package/jobs/program.d.ts +2 -3
- package/jobs/program.d.ts.map +1 -1
- package/jobs/program.js +72 -23
- package/mod.d.ts +23 -8
- package/mod.d.ts.map +1 -1
- package/mod.js +3 -3
- package/package.json +1 -1
- package/records.d.ts +5 -3
- package/records.d.ts.map +1 -1
- package/records.js +18 -9
- package/register.d.ts.map +1 -1
- package/register.js +7 -15
- 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 +9 -2
- package/runtime/conversations.d.ts.map +1 -1
- package/runtime/conversations.js +244 -185
- 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 +4 -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 +108 -42
- package/runtime/interfaces.d.ts.map +1 -1
- package/runtime/interfaces.js +639 -143
- package/runtime/lifecycle.d.ts +3 -5
- package/runtime/lifecycle.d.ts.map +1 -1
- package/runtime/lifecycle.js +74 -63
- 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 +2 -0
- package/runtime/rpc.d.ts.map +1 -1
- package/runtime/rpc.js +30 -5
- package/runtime/sessions.d.ts +3 -3
- package/runtime/sessions.d.ts.map +1 -1
- package/runtime/sessions.js +38 -73
- package/runtime/toaster.js +1 -1
- package/runtime/ui.d.ts +19 -8
- package/runtime/ui.d.ts.map +1 -1
- package/runtime/ui.js +51 -47
- 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 +6 -2
- package/session/conversation.d.ts.map +1 -1
- package/session/session.d.ts +22 -6
- 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 +63 -23
- package/src/mod.ts +22 -11
- package/src/records.ts +21 -9
- package/src/register.ts +7 -15
- 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 +247 -182
- package/src/runtime/deadline.ts +13 -6
- package/src/runtime/engine.ts +4 -4
- package/src/runtime/installer.ts +13 -12
- package/src/runtime/interfaces.ts +753 -172
- package/src/runtime/lifecycle.ts +93 -67
- 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 +32 -5
- package/src/runtime/sessions.ts +39 -73
- package/src/runtime/toaster.ts +1 -1
- package/src/runtime/ui.ts +67 -55
- package/src/runtime/web.ts +10 -39
- package/src/runtime/widgets.ts +20 -18
- package/src/session/conversation.ts +7 -2
- package/src/session/session.ts +14 -6
- package/src/testing/fake-claude.ts +10 -4
- package/src/testing/fake-serve.ts +106 -6
- package/src/testing/fake-sessions.ts +6 -5
- package/src/testing.ts +149 -67
- 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 +2 -0
- package/testing/fake-claude.d.ts.map +1 -1
- package/testing/fake-claude.js +10 -4
- package/testing/fake-serve.d.ts +32 -2
- package/testing/fake-serve.d.ts.map +1 -1
- package/testing/fake-serve.js +81 -6
- package/testing/fake-sessions.d.ts.map +1 -1
- package/testing/fake-sessions.js +6 -5
- package/testing.d.ts +21 -4
- package/testing.d.ts.map +1 -1
- package/testing.js +131 -55
- 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 -34
- package/runtime/pages.d.ts.map +0 -1
- package/runtime/pages.js +0 -157
- package/src/runtime/pages.ts +0 -198
|
@@ -1,8 +1,14 @@
|
|
|
1
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'
|
|
2
4
|
import { matches, receivedMatcher, sentMatcher, type SentMatcher } from '../utils/matcher.js'
|
|
3
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'
|
|
4
9
|
import { cmodPluginName } from './dependencies.js'
|
|
5
|
-
import {
|
|
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'
|
|
6
12
|
|
|
7
13
|
export type InterfaceName = `${string}/${string}`
|
|
8
14
|
|
|
@@ -14,30 +20,34 @@ export const onMethod = '$/on'
|
|
|
14
20
|
|
|
15
21
|
export const beforeMethod = '$/before'
|
|
16
22
|
|
|
17
|
-
export const
|
|
23
|
+
export const sessionsInterface = 'cmod/Sessions'
|
|
18
24
|
|
|
19
|
-
export const
|
|
20
|
-
|
|
21
|
-
export const terminalInterface = 'cmod/Terminal'
|
|
25
|
+
export const devicesInterface = 'cmod/Devices'
|
|
22
26
|
|
|
23
27
|
export const styleInterface = 'cmod/Style'
|
|
24
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
|
+
|
|
25
35
|
export const sessionActs = {
|
|
26
36
|
hold: '$/hold',
|
|
27
|
-
listeners: '$/listeners',
|
|
28
37
|
act: '$/act',
|
|
29
|
-
emit: '$/emit',
|
|
30
|
-
ask: '$/ask',
|
|
31
38
|
changed: '$/changed',
|
|
39
|
+
status: '$/status',
|
|
40
|
+
ui: '$/ui',
|
|
41
|
+
uiEvent: '$/uiEvent',
|
|
32
42
|
} as const
|
|
33
43
|
|
|
34
44
|
export type HeldSession = { readonly session: string; readonly project: string; readonly cwd: string }
|
|
35
45
|
|
|
36
|
-
export type
|
|
46
|
+
export type HeldStatus = Pick<SessionData, 'status' | 'waitingFor' | 'contextPercent' | 'lastTurn'>
|
|
37
47
|
|
|
38
48
|
export type VisitedAt = Readonly<Record<string, string>>
|
|
39
49
|
|
|
40
|
-
export type StoreChange = { readonly session: string; readonly part: 'visit' | 'running' | 'tasks' | 'goal' | 'deleted' }
|
|
50
|
+
export type StoreChange = { readonly session: string; readonly part: 'visit' | 'running' | 'tasks' | 'goal' | 'status' | 'deleted' }
|
|
41
51
|
|
|
42
52
|
|
|
43
53
|
export type ListenKind = 'on' | 'before'
|
|
@@ -52,7 +62,7 @@ export type Listening = {
|
|
|
52
62
|
readonly timeoutMs?: number
|
|
53
63
|
readonly onFailure?: 'pass' | 'refuse'
|
|
54
64
|
readonly after?: string
|
|
55
|
-
readonly
|
|
65
|
+
readonly provider?: ProviderIdentity
|
|
56
66
|
}
|
|
57
67
|
|
|
58
68
|
export type Heard = { readonly id: string; readonly payload: unknown; readonly cursor?: string }
|
|
@@ -61,7 +71,11 @@ export type ListenOptions = { readonly timeoutMs?: number; readonly onFailure?:
|
|
|
61
71
|
|
|
62
72
|
export type Provider = { readonly mod: string; readonly program: string; readonly address: string; readonly provides: readonly string[] }
|
|
63
73
|
|
|
64
|
-
export const interfaceMethods = { providers: 'cmod:providers', provided: 'cmod:provided', listen: 'cmod:listenProvided', unlisten: 'cmod:unlistenProvided', heard: 'cmod:heard' } as const
|
|
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
|
|
65
79
|
|
|
66
80
|
export type ProvidedCall = { readonly interface: string; readonly method: string; readonly args: readonly unknown[] } & Partial<ProviderIdentity>
|
|
67
81
|
|
|
@@ -94,7 +108,7 @@ export function providersIn(records: readonly { readonly mod: string; readonly p
|
|
|
94
108
|
}
|
|
95
109
|
|
|
96
110
|
export function checkInterfaceName(name: string): void {
|
|
97
|
-
if (!interfaceName.test(name)) throw new Error(`${name} is no interface name, such as
|
|
111
|
+
if (!interfaceName.test(name)) throw new Error(`${name} is no interface name, such as demo/Platform.`)
|
|
98
112
|
}
|
|
99
113
|
|
|
100
114
|
export function methodName(name: string, method: string): string {
|
|
@@ -110,11 +124,10 @@ export function isHeardAt(listening: Pick<Listening, 'args' | 'matcher'>, args:
|
|
|
110
124
|
export type Implementation = Readonly<Record<string, (...args: never[]) => unknown>>
|
|
111
125
|
|
|
112
126
|
export type InterfaceServer = {
|
|
113
|
-
handler(connection:
|
|
127
|
+
handler(connection: Pick<Peer, 'request' | 'notify'>): RpcHandler
|
|
114
128
|
emit(name: string, event: string, payload: unknown, args?: readonly unknown[]): void
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
closed(connection: RpcConnection): void
|
|
129
|
+
listeners(name: string, event?: string): readonly (Listening & { readonly connection: Pick<Peer, 'request' | 'notify'> })[]
|
|
130
|
+
closed(connection: Pick<Peer, 'request' | 'notify'>): void
|
|
118
131
|
}
|
|
119
132
|
|
|
120
133
|
const keptEvents = 500
|
|
@@ -122,15 +135,13 @@ const keptEvents = 500
|
|
|
122
135
|
export function interfaceServer({
|
|
123
136
|
implementations,
|
|
124
137
|
onListen,
|
|
125
|
-
onUnlisten,
|
|
126
138
|
extraMethod,
|
|
127
139
|
}: {
|
|
128
140
|
readonly implementations: Readonly<Record<string, Implementation>>
|
|
129
|
-
readonly onListen?: (connection:
|
|
130
|
-
readonly
|
|
131
|
-
readonly extraMethod?: (connection: RpcConnection, method: string, params: unknown, signal: AbortSignal) => { readonly result: unknown } | undefined | Promise<{ readonly result: unknown } | undefined>
|
|
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>
|
|
132
143
|
}): InterfaceServer {
|
|
133
|
-
const held = new Map<
|
|
144
|
+
const held = new Map<Pick<Peer, 'request' | 'notify'>, Map<string, Listening>>()
|
|
134
145
|
const recent = new Map<string, { cursor: number; readonly kept: { readonly cursor: number; readonly args: readonly unknown[]; readonly payload: unknown }[] }>()
|
|
135
146
|
|
|
136
147
|
const keyOf = (name: string, event: string) => `${name}\n${event}`
|
|
@@ -141,7 +152,7 @@ export function interfaceServer({
|
|
|
141
152
|
return params as Listening
|
|
142
153
|
}
|
|
143
154
|
|
|
144
|
-
const replay = (connection:
|
|
155
|
+
const replay = (connection: Pick<Peer, 'request' | 'notify'>, listening: Listening) => {
|
|
145
156
|
if (listening.kind !== 'on' || listening.after === undefined) return
|
|
146
157
|
const after = Number(listening.after)
|
|
147
158
|
for (const each of recent.get(keyOf(listening.interface, listening.event))?.kept ?? []) {
|
|
@@ -153,19 +164,16 @@ export function interfaceServer({
|
|
|
153
164
|
handler: (connection) => async (method, params, signal) => {
|
|
154
165
|
if (method === listenMethod) {
|
|
155
166
|
const listening = listeningOf(params)
|
|
167
|
+
await onListen?.(connection, listening)
|
|
156
168
|
const list = held.get(connection) ?? new Map<string, Listening>()
|
|
157
169
|
list.set(listening.id, listening)
|
|
158
170
|
held.set(connection, list)
|
|
159
|
-
await onListen?.(connection, listening)
|
|
160
171
|
replay(connection, listening)
|
|
161
172
|
return {}
|
|
162
173
|
}
|
|
163
174
|
if (method === unlistenMethod) {
|
|
164
175
|
const id = isObject(params) ? params['id'] : undefined
|
|
165
|
-
|
|
166
|
-
if (listening === undefined) return {}
|
|
167
|
-
held.get(connection)?.delete(listening.id)
|
|
168
|
-
onUnlisten?.(connection, listening)
|
|
176
|
+
if (typeof id === 'string') held.get(connection)?.delete(id)
|
|
169
177
|
return {}
|
|
170
178
|
}
|
|
171
179
|
const extra = await extraMethod?.(connection, method, params, signal)
|
|
@@ -187,21 +195,9 @@ export function interfaceServer({
|
|
|
187
195
|
if (listening.kind === 'on' && isHeardAt(listening, args, payload)) listening.connection.notify(onMethod, { id: listening.id, payload, cursor: String(log.cursor) } satisfies Heard)
|
|
188
196
|
}
|
|
189
197
|
},
|
|
190
|
-
async ask(name, event, payload, args = [], signal) {
|
|
191
|
-
const answers: { readonly listening: Listening; readonly answer: unknown }[] = []
|
|
192
|
-
for (const listening of server.listeners(name, event)) {
|
|
193
|
-
if (listening.kind !== 'before' || !isHeardAt(listening, args, payload)) continue
|
|
194
|
-
const answer = await listening.connection.request(beforeMethod, { id: listening.id, payload } satisfies Heard, signal)
|
|
195
|
-
answers.push({ listening, answer })
|
|
196
|
-
if (isObject(answer) && typeof answer['refuse'] === 'string') break
|
|
197
|
-
}
|
|
198
|
-
return answers
|
|
199
|
-
},
|
|
200
198
|
listeners: (name, event) => [...held].flatMap(([connection, list]) => [...list.values()].filter((each) => each.interface === name && (event === undefined || each.event === event)).map((each) => ({ ...each, connection }))),
|
|
201
199
|
closed(connection) {
|
|
202
|
-
const list = held.get(connection)
|
|
203
200
|
held.delete(connection)
|
|
204
|
-
for (const listening of list?.values() ?? []) onUnlisten?.(connection, listening)
|
|
205
201
|
},
|
|
206
202
|
}
|
|
207
203
|
return server
|
|
@@ -221,7 +217,7 @@ export function interfaceListeners({ report: reportAll }: { readonly report: (er
|
|
|
221
217
|
const registered = new Map<string, Registered>()
|
|
222
218
|
let next = 0
|
|
223
219
|
const report = (error: unknown) => {
|
|
224
|
-
if (!(error
|
|
220
|
+
if (!isConnectionGone(error)) reportAll(error)
|
|
225
221
|
}
|
|
226
222
|
|
|
227
223
|
const send = (request: Pick<Peer, 'request'>, each: Registered) =>
|
|
@@ -270,7 +266,7 @@ export function listeningOf(name: string, kind: ListenKind, event: string, args:
|
|
|
270
266
|
}
|
|
271
267
|
}
|
|
272
268
|
|
|
273
|
-
export type ProviderIdentity = { readonly mod: string; readonly program?: string }
|
|
269
|
+
export type ProviderIdentity = { readonly mod: string; readonly program?: string; readonly device?: Pick<Device, 'id' | 'name'> | undefined }
|
|
274
270
|
|
|
275
271
|
export type ListenTo = (kind: ListenKind, event: string, matcher: unknown, listener: Listener, options: ListenOptions) => Subscription
|
|
276
272
|
|
|
@@ -278,34 +274,23 @@ export function providerClient(name: string, identity: ProviderIdentity, call: (
|
|
|
278
274
|
return new Proxy(identity, {
|
|
279
275
|
get: (known, key) => {
|
|
280
276
|
if (typeof key !== 'string' || key === 'then') return undefined
|
|
281
|
-
if (key === 'mod' || key === 'program') return known[key]
|
|
277
|
+
if (key === 'mod' || key === 'program' || key === 'device') return known[key]
|
|
282
278
|
const event = /^(on|before)([A-Z]\w*)$/.exec(key)
|
|
283
279
|
if (event === null) return (...args: unknown[]) => call(key, args)
|
|
284
280
|
return (...args: unknown[]) => {
|
|
285
|
-
const
|
|
286
|
-
|
|
287
|
-
if (typeof listener !== 'function') throw new Error(`${name}: ${key} takes a listener.`)
|
|
288
|
-
return listen(event[1] as ListenKind, event[2] ?? '', hasMatcher ? args[0] : undefined, listener, ((hasMatcher ? args[2] : args[1]) ?? {}))
|
|
281
|
+
const { matcher, listener, options } = listenerOf<Listener>(name, key, args)
|
|
282
|
+
return listen(event[1] as ListenKind, event[2] ?? '', matcher, listener, options)
|
|
289
283
|
}
|
|
290
284
|
},
|
|
291
285
|
})
|
|
292
286
|
}
|
|
293
287
|
|
|
294
|
-
export function interfaceClient(name: string, request: Pick<Peer, 'request'>, listeners: InterfaceListeners, identity: ProviderIdentity = { mod: '' }): Readonly<Record<string, unknown>> {
|
|
295
|
-
return providerClient(
|
|
296
|
-
name,
|
|
297
|
-
identity,
|
|
298
|
-
(method, args) => request.request(methodName(name, method), args),
|
|
299
|
-
(kind, event, matcher, listener, options) => listeners.listen(request, listeningOf(name, kind, event, [], matcher, options), listener),
|
|
300
|
-
)
|
|
301
|
-
}
|
|
302
|
-
|
|
303
288
|
export type SessionContext = Readonly<Record<string, unknown>>
|
|
304
289
|
|
|
305
290
|
export type HoldingOf = (session: string) => HeldSession | undefined
|
|
306
291
|
|
|
307
292
|
export type SessionComputer = {
|
|
308
|
-
sessions(scope: Readonly<Record<string, unknown>>, holding: HoldingOf, held: ReadonlySet<string>):
|
|
293
|
+
sessions(scope: Readonly<Record<string, unknown>>, holding: HoldingOf, held: ReadonlySet<string>): readonly SessionData[] | Promise<readonly SessionData[]>
|
|
309
294
|
search(text: string, options: Readonly<Record<string, unknown>>): unknown
|
|
310
295
|
read(session: string, part: string, options: Readonly<Record<string, unknown>>, holding: HoldingOf): unknown
|
|
311
296
|
unheld(session: string, action: string, input: unknown, context: SessionContext, holding: HoldingOf): Promise<unknown>
|
|
@@ -316,6 +301,7 @@ export type SessionComputer = {
|
|
|
316
301
|
export type SessionRouting = {
|
|
317
302
|
readonly routes: RpcRoutes
|
|
318
303
|
readonly interfaces: InterfaceServer
|
|
304
|
+
readonly providers: Pick<ProviderRouting, 'list' | 'call'>
|
|
319
305
|
holding: HoldingOf
|
|
320
306
|
heldSessions(): readonly HeldSession[]
|
|
321
307
|
call<Result>(session: string, action: string, input: unknown, context?: SessionContext): Promise<Result>
|
|
@@ -325,33 +311,37 @@ export type SessionRouting = {
|
|
|
325
311
|
|
|
326
312
|
export const sessionActions = ['send', 'abort', 'end', 'fork', 'startTask', 'callTool', 'usage', 'surfaces', 'visit', 'delete'] as const
|
|
327
313
|
|
|
328
|
-
export
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
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>()
|
|
333
335
|
const holderOf = (session: string) => [...holders.values()].find((holder) => holder.session === session)
|
|
334
336
|
const holding: HoldingOf = (session) => {
|
|
335
337
|
const holder = holderOf(session)
|
|
336
338
|
return holder === undefined ? undefined : { session: holder.session, project: holder.project, cwd: holder.cwd }
|
|
337
339
|
}
|
|
340
|
+
const names = [sessionsInterface, ...aliases]
|
|
338
341
|
|
|
339
|
-
const
|
|
340
|
-
|
|
341
|
-
const [target] = listening.args ?? []
|
|
342
|
-
const extra = listening.extra ?? {}
|
|
343
|
-
const isEvery = target === undefined || target === '*'
|
|
344
|
-
if (listening.connection === holder.connection) return []
|
|
345
|
-
if (!isEvery && target !== holder.session) return []
|
|
346
|
-
if (isEvery && typeof extra['project'] === 'string' && extra['project'] !== holder.project && extra['everyProject'] !== true) return []
|
|
347
|
-
return [{ id: globalId(listening.connection, listening.id), event: listening.event, kind: listening.kind, ...(listening.matcher === undefined ? {} : { matcher: listening.matcher }), ...(listening.timeoutMs === undefined ? {} : { timeoutMs: listening.timeoutMs }), ...(listening.onFailure === undefined ? {} : { onFailure: listening.onFailure }), isEvery, extra }]
|
|
348
|
-
})
|
|
349
|
-
|
|
350
|
-
const tell = (holder: Holder) => holder.connection.notify(sessionActs.listeners, { session: holder.session, list: sessionListeners(holder) })
|
|
351
|
-
const tellAll = () => {
|
|
352
|
-
for (const holder of holders.values()) tell(holder)
|
|
342
|
+
const changed = (change: StoreChange) => {
|
|
343
|
+
for (const name of names) interfaces.emit(name, 'Change', change, [change.session])
|
|
353
344
|
}
|
|
354
|
-
const changed = (change: StoreChange) => interfaces.emit(sessionStore, 'Change', change, [change.session])
|
|
355
345
|
|
|
356
346
|
const call = async (session: string, action: string, input: unknown, context: SessionContext = {}): Promise<unknown> => {
|
|
357
347
|
if (!(sessionActions as readonly string[]).includes(action)) throw new RpcError(rpcCodes.methodNotFound, `A session takes no ${action}.`)
|
|
@@ -371,62 +361,122 @@ export function routeSessions({ computer, now }: { readonly computer: SessionCom
|
|
|
371
361
|
return holder.connection.request(sessionActs.act, { action, input, ...context })
|
|
372
362
|
}
|
|
373
363
|
|
|
374
|
-
const
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
tellAll()
|
|
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)))
|
|
387
376
|
},
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
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.`)
|
|
392
430
|
},
|
|
393
|
-
extraMethod:
|
|
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
|
+
}
|
|
394
438
|
if (method === sessionActs.hold) {
|
|
395
439
|
const { session, project, cwd } = params as HeldSession
|
|
440
|
+
const known = holders.get(connection)
|
|
396
441
|
for (const [each, holder] of holders) if (holder.session === session && each !== connection) holders.delete(each)
|
|
397
|
-
|
|
398
|
-
holders.set(connection, holder)
|
|
399
|
-
tell(holder)
|
|
442
|
+
holders.set(connection, { session, project, cwd, connection, told: known?.session === session ? known.told : {} })
|
|
400
443
|
changed({ session, part: 'running' })
|
|
444
|
+
toldShown.delete(session)
|
|
445
|
+
tellShown(session)
|
|
401
446
|
return { result: {} }
|
|
402
447
|
}
|
|
403
448
|
if (method === sessionActs.changed) {
|
|
404
449
|
changed(params as StoreChange)
|
|
405
450
|
return { result: null }
|
|
406
451
|
}
|
|
407
|
-
if (method === sessionActs.
|
|
408
|
-
const
|
|
409
|
-
const
|
|
410
|
-
|
|
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' })
|
|
411
458
|
return { result: null }
|
|
412
459
|
}
|
|
413
|
-
if (method === sessionActs.ask) {
|
|
414
|
-
const { id, payload } = params as { readonly id: string; readonly payload: unknown }
|
|
415
|
-
const asked = listened.get(id)
|
|
416
|
-
if (asked === undefined) return { result: null }
|
|
417
|
-
return { result: await asked.connection.request(beforeMethod, { id: asked.listening.id, payload }) }
|
|
418
|
-
}
|
|
419
460
|
return undefined
|
|
420
461
|
},
|
|
421
462
|
})
|
|
422
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
|
+
|
|
423
466
|
const routes = rpcRoutes({
|
|
424
|
-
handle: (connection) =>
|
|
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
|
+
},
|
|
425
471
|
onClose: (connection) => {
|
|
426
472
|
const holder = holders.get(connection)
|
|
427
473
|
holders.delete(connection)
|
|
428
474
|
interfaces.closed(connection)
|
|
429
|
-
|
|
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' })
|
|
430
480
|
},
|
|
431
481
|
now,
|
|
432
482
|
})
|
|
@@ -434,48 +484,510 @@ export function routeSessions({ computer, now }: { readonly computer: SessionCom
|
|
|
434
484
|
return {
|
|
435
485
|
routes,
|
|
436
486
|
interfaces,
|
|
487
|
+
providers,
|
|
437
488
|
holding,
|
|
438
489
|
heldSessions: () => [...holders.values()].map(({ session, project, cwd }) => ({ session, project, cwd })),
|
|
439
490
|
call: (session, action, input, context) => call(session, action, input, context) as never,
|
|
440
491
|
changed,
|
|
441
|
-
close: () =>
|
|
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
|
+
},
|
|
442
538
|
}
|
|
443
539
|
}
|
|
444
540
|
|
|
445
|
-
export
|
|
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
|
+
}
|
|
446
649
|
|
|
447
|
-
|
|
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 }
|
|
448
898
|
|
|
449
899
|
export type ProvidedHeard = { readonly id: string; readonly payload: unknown }
|
|
450
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
|
+
|
|
451
959
|
export type Providers = {
|
|
452
960
|
provided(): readonly string[]
|
|
453
|
-
provide(name: string, methods: Implementation):
|
|
961
|
+
provide(name: string, methods: Implementation): Provided
|
|
454
962
|
providers(name: string): Promise<Readonly<Record<string, unknown>>[]>
|
|
455
|
-
answer(
|
|
456
|
-
heard(heard: ProvidedHeard, signal: AbortSignal): Promise<unknown>
|
|
963
|
+
answer(method: string, input: unknown, caller: string, signal: AbortSignal): Promise<unknown> | undefined
|
|
457
964
|
}
|
|
458
965
|
|
|
459
|
-
export function createProviders({ name, call, changed, report }: { readonly name: string; readonly call: (to: string, method: string, input: unknown) => Promise<unknown>; readonly changed: () => void; readonly report: (error: unknown) => void }): Providers {
|
|
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 {
|
|
460
967
|
const provided = new Map<string, Implementation>()
|
|
461
968
|
const heard = new Map<string, Listener>()
|
|
462
969
|
let nextListener = 0
|
|
463
|
-
const
|
|
464
|
-
const
|
|
465
|
-
if (
|
|
466
|
-
return (await
|
|
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
|
|
467
978
|
}
|
|
468
979
|
const client = (named: string, identity: ProviderIdentity) =>
|
|
469
980
|
providerClient(
|
|
470
981
|
named,
|
|
471
982
|
identity,
|
|
472
|
-
(method, args) =>
|
|
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
|
+
},
|
|
473
987
|
(kind, event, matcher, listener, options) => {
|
|
474
|
-
if (identity.program === undefined) throw new Error(`${identity.mod} tells ${named} events only from a program.`)
|
|
475
988
|
const id = `${named}#${(nextListener += 1)}`
|
|
476
989
|
heard.set(id, listener)
|
|
477
|
-
|
|
478
|
-
void call(cmodPluginName, interfaceMethods.listen, listening).catch((error: unknown) => {
|
|
990
|
+
void call(cmodPluginName, interfaceMethods.listen, { id, interface: named, kind, event, ...identity, ...(matcher === undefined ? {} : { matcher: sentMatcher(matcher) }), ...options } satisfies ProvidedListen).catch((error: unknown) => {
|
|
479
991
|
heard.delete(id)
|
|
480
992
|
report(error)
|
|
481
993
|
})
|
|
@@ -492,89 +1004,158 @@ export function createProviders({ name, call, changed, report }: { readonly name
|
|
|
492
1004
|
checkInterfaceName(named)
|
|
493
1005
|
provided.set(named, methods)
|
|
494
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))))
|
|
495
1008
|
return {
|
|
496
1009
|
remove() {
|
|
497
1010
|
if (provided.get(named) === methods && provided.delete(named)) changed()
|
|
498
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[]>,
|
|
499
1014
|
}
|
|
500
1015
|
},
|
|
501
1016
|
async providers(named) {
|
|
502
1017
|
const listed = (await call(cmodPluginName, interfaceMethods.providers, { name: named })) as ProviderList
|
|
503
|
-
return [...listed.mods.map((mod) => client(named, { mod })), ...listed.programs.map((identity) => client(named, identity))]
|
|
1018
|
+
return [...listed.mods.map((mod) => client(named, { mod, device: listed.device })), ...listed.programs.map((identity) => client(named, identity))]
|
|
504
1019
|
},
|
|
505
1020
|
answer,
|
|
506
|
-
async heard({ id, payload }, signal) {
|
|
507
|
-
const listener = heard.get(id)
|
|
508
|
-
return listener === undefined ? null : ((await listener(payload as never, signal)) ?? null)
|
|
509
|
-
},
|
|
510
1021
|
}
|
|
511
1022
|
}
|
|
512
1023
|
|
|
513
|
-
export type
|
|
514
|
-
answer(method: string, input: unknown, caller: string): Promise<unknown> | undefined
|
|
515
|
-
|
|
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>
|
|
516
1031
|
}
|
|
517
1032
|
|
|
518
|
-
export function
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
wait,
|
|
523
|
-
report,
|
|
1033
|
+
export function serveProviders({
|
|
1034
|
+
serve,
|
|
1035
|
+
listeners,
|
|
1036
|
+
provider,
|
|
524
1037
|
tell,
|
|
525
1038
|
sessionCode,
|
|
1039
|
+
device,
|
|
1040
|
+
after,
|
|
1041
|
+
report,
|
|
526
1042
|
}: {
|
|
527
|
-
readonly
|
|
528
|
-
readonly
|
|
529
|
-
readonly
|
|
530
|
-
readonly wait: (ms: number) => Promise<void>
|
|
531
|
-
readonly report: (error: unknown) => void
|
|
1043
|
+
readonly serve: Pick<Peer, 'request' | 'notify'>
|
|
1044
|
+
readonly listeners: InterfaceListeners
|
|
1045
|
+
readonly provider?: ProviderIdentity
|
|
532
1046
|
readonly tell: (caller: string, heard: ProvidedHeard, signal: AbortSignal) => Promise<unknown>
|
|
533
1047
|
readonly sessionCode: (name: string) => readonly string[]
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
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)
|
|
537
1055
|
const held = new Map<string, Subscription>()
|
|
538
|
-
const
|
|
539
|
-
|
|
540
|
-
if (answered === undefined) throw new RpcError(rpcCodes.methodNotFound, `The cmod plugin answers no ${method}.`)
|
|
541
|
-
return answered.result
|
|
542
|
-
}
|
|
543
|
-
const clientOf = async (named: string, { mod, program }: ProviderIdentity) => {
|
|
544
|
-
const found = (await readProviders(files, store, named)).find((each) => each.mod === mod && each.program === program)
|
|
545
|
-
if (found === undefined) throw new Error(`${mod}'s ${program ?? mod} program does not run, so it answers no ${named}.`)
|
|
546
|
-
const known = clients.get(found.address)
|
|
547
|
-
if (known !== undefined) return known
|
|
548
|
-
const client = connectRpc({ call: addressCall(fetch, found.address), handle, onConnect: (connected) => listeners.replay(connected), wait })
|
|
549
|
-
clients.set(found.address, client)
|
|
550
|
-
return client
|
|
1056
|
+
const reported = (error: unknown) => {
|
|
1057
|
+
if (!isConnectionGone(error)) report(error)
|
|
551
1058
|
}
|
|
552
|
-
const
|
|
553
|
-
|
|
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.')
|
|
554
1062
|
const key = `${caller}\n${id}`
|
|
555
1063
|
held.get(key)?.remove()
|
|
556
|
-
|
|
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)))
|
|
557
1066
|
return null
|
|
558
1067
|
}
|
|
559
|
-
const unlisten = (caller: string, id: string) => {
|
|
1068
|
+
const unlisten = (caller: string | undefined, id: string) => {
|
|
560
1069
|
const key = `${caller}\n${id}`
|
|
561
1070
|
held.get(key)?.remove()
|
|
562
1071
|
held.delete(key)
|
|
563
1072
|
return null
|
|
564
1073
|
}
|
|
565
|
-
const
|
|
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
|
+
}
|
|
566
1099
|
return {
|
|
567
1100
|
answer(method, input, caller) {
|
|
568
|
-
const asked = input
|
|
1101
|
+
const asked = isObject(input) ? input : {}
|
|
569
1102
|
if (method === interfaceMethods.providers) return listed(String(asked['name']))
|
|
570
|
-
if (method === interfaceMethods.
|
|
571
|
-
if (method === interfaceMethods.
|
|
572
|
-
|
|
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>
|
|
573
1112
|
if (method !== interfaceMethods.provided || call.program === undefined || call.mod === undefined) return undefined
|
|
574
|
-
return
|
|
1113
|
+
return beforeDeadline({ after }, callDeadline, methodName(String(call.interface), String(call.method)), (signal) => serve.request(providerActs.call, call, signal))
|
|
575
1114
|
},
|
|
576
|
-
|
|
577
|
-
|
|
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))
|
|
578
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(),
|
|
579
1160
|
}
|
|
580
1161
|
}
|