@cmodjs/core 8.10.4 → 8.11.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 +1 -1
- package/docs/session.md +5 -3
- package/mod.d.ts +11 -1
- package/mod.d.ts.map +1 -1
- package/package.json +1 -1
- package/records.d.ts +1 -1
- package/records.js +1 -1
- package/runtime/conversations.d.ts.map +1 -1
- package/runtime/conversations.js +91 -74
- package/runtime/interfaces.d.ts +7 -3
- package/runtime/interfaces.d.ts.map +1 -1
- package/runtime/interfaces.js +94 -30
- package/runtime/sessions.js +1 -1
- package/session/conversation.d.ts +1 -0
- package/session/conversation.d.ts.map +1 -1
- package/session/session.d.ts +5 -0
- package/session/session.d.ts.map +1 -1
- package/src/mod.ts +3 -3
- package/src/records.ts +1 -1
- package/src/runtime/conversations.ts +86 -73
- package/src/runtime/interfaces.ts +93 -29
- package/src/runtime/sessions.ts +1 -1
- package/src/session/conversation.ts +1 -0
- package/src/session/session.ts +2 -1
- package/src/utils/text.ts +12 -0
- package/utils/text.d.ts +2 -0
- package/utils/text.d.ts.map +1 -1
- package/utils/text.js +9 -0
|
@@ -11,12 +11,12 @@ import { TaskEnd, TaskStart } from '../session/goal/task.js'
|
|
|
11
11
|
import { receivedMatcher } from '../utils/matcher.js'
|
|
12
12
|
import { resolve } from '../vendor.js'
|
|
13
13
|
import { ifMissing } from '../utils/paths.js'
|
|
14
|
-
import { messageOf } from '../utils/text.js'
|
|
14
|
+
import { callSummary, firstLine, messageOf, questionOf } from '../utils/text.js'
|
|
15
15
|
import { beforeAnswerKeys, foldBefore, installBefore, relayOf, type Decide, type Place } from './before.js'
|
|
16
16
|
import type { Claude } from './claude.js'
|
|
17
17
|
import { cmodPluginName, isNotInstalled } from './dependencies.js'
|
|
18
18
|
import { MissingMachineId } from './device.js'
|
|
19
|
-
import { interfaceListeners, interfaceMethods, providerActs, providerPeer, serveProviders, sessionActs, sessionsInterface, uiInterface, type HeldStatus, type Implementation, type Provided, type KeptListen, type ProvidedHeard, type ProviderIdentity, type SessionsChange, type HeldSession, storeInterface, methodName, listeningOf, type StoreChange, type StorePart } from './interfaces.js'
|
|
19
|
+
import { findSession, interfaceListeners, interfaceMethods, providerActs, providerPeer, serveProviders, sessionActs, sessionsInterface, uiInterface, type HeldStatus, type Implementation, type Provided, type KeptListen, type ProvidedHeard, type ProviderIdentity, type SessionsChange, type HeldSession, storeInterface, methodName, listeningOf, type StoreChange, type StorePart } from './interfaces.js'
|
|
20
20
|
import { runCmod } from './programs.js'
|
|
21
21
|
import { addressCall, connectRpc, isConnectionGone, RpcError, rpcCodes, type RpcClient } from './rpc.js'
|
|
22
22
|
import type { RoutedHook, Router } from './router.js'
|
|
@@ -75,7 +75,7 @@ const noneKept: Kept = { subscribed: {}, watched: {}, provided: [] }
|
|
|
75
75
|
|
|
76
76
|
type Registered = { remove(): void }
|
|
77
77
|
|
|
78
|
-
type OtherProvider = { readonly identity: ProviderIdentity; readonly peer: Pick<RpcClient, 'request'
|
|
78
|
+
type OtherProvider = { readonly identity: ProviderIdentity; readonly peer: Pick<RpcClient, 'request'> }
|
|
79
79
|
|
|
80
80
|
export function serveConversations({
|
|
81
81
|
claude,
|
|
@@ -125,16 +125,19 @@ export function serveConversations({
|
|
|
125
125
|
let contextPercent: number | undefined
|
|
126
126
|
let endedTurn: HeldStatus['lastTurn']
|
|
127
127
|
let failedWith: string | undefined
|
|
128
|
+
let repliedWith: string | undefined
|
|
128
129
|
const openCalls = new Map<string, ToolCallArgs>()
|
|
129
130
|
const tellStatus = () => {
|
|
130
131
|
if (session === '') return
|
|
131
|
-
|
|
132
|
+
const open = [...openCalls.values()].at(-1)
|
|
133
|
+
const openCall = open === undefined ? undefined : { tool: open.name, summary: callSummary(open.input) }
|
|
134
|
+
local.client.notify(sessionActs.status, { session, status: waitingFor !== undefined ? 'waiting' : isWorking ? 'busy' : 'idle', ...(waitingFor === undefined ? {} : { waitingFor }), ...(contextPercent === undefined ? {} : { contextPercent }), ...(endedTurn === undefined ? {} : { lastTurn: endedTurn }), ...(openCall === undefined ? {} : { openCall }) } satisfies HeldStatus & { readonly session: string })
|
|
132
135
|
}
|
|
133
136
|
const waitFor = (callId: string) => {
|
|
134
137
|
const call = openCalls.get(callId)
|
|
135
138
|
if (call === undefined) return
|
|
136
|
-
const question = call.name === questionTool ? (call.input
|
|
137
|
-
waitingFor =
|
|
139
|
+
const question = call.name === questionTool ? questionOf(call.input) : undefined
|
|
140
|
+
waitingFor = question !== undefined ? { dialog: permissionPrompt, question } : { dialog: permissionPrompt, tool: call.name, input: call.input }
|
|
138
141
|
waitingOn = callId
|
|
139
142
|
tellStatus()
|
|
140
143
|
}
|
|
@@ -143,6 +146,7 @@ export function serveConversations({
|
|
|
143
146
|
if (isStarted) {
|
|
144
147
|
endedTurn = undefined
|
|
145
148
|
failedWith = undefined
|
|
149
|
+
repliedWith = undefined
|
|
146
150
|
}
|
|
147
151
|
waitingFor = undefined
|
|
148
152
|
waitingOn = undefined
|
|
@@ -160,7 +164,7 @@ export function serveConversations({
|
|
|
160
164
|
if (e.agentId !== undefined) return completed
|
|
161
165
|
const reason = e.reason === 'answer' ? 'answered' : e.reason === 'aborted' ? 'stopped' : 'failed'
|
|
162
166
|
const failure = e.reason === 'refusal' ? (e.refusal.explanation ?? e.refusal.category ?? 'Claude refused to answer.') : failedWith
|
|
163
|
-
endedTurn = { reason, at: new Date().toISOString(), ...(reason === 'failed' && failure !== undefined ? { failure } : {}) }
|
|
167
|
+
endedTurn = { reason, at: new Date().toISOString(), ...(reason === 'failed' && failure !== undefined ? { failure } : {}), ...(reason === 'answered' && repliedWith !== undefined ? { reply: repliedWith } : {}) }
|
|
164
168
|
turnMoved(false)
|
|
165
169
|
return completed
|
|
166
170
|
})
|
|
@@ -168,6 +172,7 @@ export function serveConversations({
|
|
|
168
172
|
if (e.agentId !== undefined) return next(e)
|
|
169
173
|
openCalls.set(e.tool_use_id, { name: e.tool, input: toolInputOf(e) })
|
|
170
174
|
if (e.tool === questionTool) waitFor(e.tool_use_id)
|
|
175
|
+
else tellStatus()
|
|
171
176
|
try {
|
|
172
177
|
return await next(e)
|
|
173
178
|
} finally {
|
|
@@ -175,8 +180,8 @@ export function serveConversations({
|
|
|
175
180
|
if (waitingOn === e.tool_use_id) {
|
|
176
181
|
waitingFor = undefined
|
|
177
182
|
waitingOn = undefined
|
|
178
|
-
tellStatus()
|
|
179
183
|
}
|
|
184
|
+
tellStatus()
|
|
180
185
|
}
|
|
181
186
|
})
|
|
182
187
|
router.add('classic.Notification', async (e, next) => {
|
|
@@ -216,7 +221,10 @@ export function serveConversations({
|
|
|
216
221
|
router.add('classic.SubagentStop', async (e, next) => endTurn({ reason: 'answer', ...(e.last_assistant_message === undefined ? {} : { answer: e.last_assistant_message }) }, e.agent_id)(await next(e), next.signal.aborted))
|
|
217
222
|
router.add('classic.Stop', async (e, next) => {
|
|
218
223
|
const below = await next(e)
|
|
219
|
-
if (below.block === undefined && !next.signal.aborted)
|
|
224
|
+
if (below.block === undefined && !next.signal.aborted) {
|
|
225
|
+
repliedWith = firstLine(e.last_assistant_message ?? '') || undefined
|
|
226
|
+
void answerTask().catch((error: unknown) => report('task', 'Could not record that this session answered its task', error))
|
|
227
|
+
}
|
|
220
228
|
return below
|
|
221
229
|
})
|
|
222
230
|
|
|
@@ -283,7 +291,7 @@ export function serveConversations({
|
|
|
283
291
|
await served.replay()
|
|
284
292
|
await held.replay(client)
|
|
285
293
|
storeChanged(undefined)
|
|
286
|
-
await reconcileTasks()
|
|
294
|
+
await reconcileTasks({ atConnect: true })
|
|
287
295
|
},
|
|
288
296
|
onError: (error) => {
|
|
289
297
|
if (!isUnreached) claude.ui.warn('serve:connect', `cmod: this session waits for cmod serve: ${messageOf(error)}`)
|
|
@@ -315,47 +323,41 @@ export function serveConversations({
|
|
|
315
323
|
changed: () => void saveListeners().catch((error: unknown) => report('listeners', 'Could not keep the provider listeners of this session', error)),
|
|
316
324
|
})
|
|
317
325
|
|
|
318
|
-
const
|
|
319
|
-
const keyOf = ({ mod, program, device }: ProviderIdentity) => `${device?.id ?? ''}\n${mod}\n${program ?? ''}`
|
|
320
|
-
const otherProviders = async () => {
|
|
321
|
-
const found = await local.client.request<ProviderIdentity[]>(providerActs.providers, { interface: sessionsInterface })
|
|
322
|
-
const keys = new Set(found.map(keyOf))
|
|
323
|
-
for (const [key, other] of others) {
|
|
324
|
-
if (keys.has(key)) continue
|
|
325
|
-
others.delete(key)
|
|
326
|
-
other.change.remove()
|
|
327
|
-
}
|
|
328
|
-
for (const identity of found) if (!others.has(keyOf(identity))) others.set(keyOf(identity), followProvider(identity))
|
|
329
|
-
return [...others.values()]
|
|
330
|
-
}
|
|
326
|
+
const otherProviders = async (): Promise<OtherProvider[]> => (await local.client.request<ProviderIdentity[]>(providerActs.providers, { interface: sessionsInterface })).map((identity) => ({ identity, peer: providerPeer(local.client, identity) }))
|
|
331
327
|
|
|
332
|
-
const
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
})
|
|
337
|
-
|
|
328
|
+
const taskWatches = new Map<string, { readonly runner: OtherProvider; readonly watch: Registered }>()
|
|
329
|
+
const watchTask = (task: string, runner: OtherProvider) => {
|
|
330
|
+
if (taskWatches.has(task)) return
|
|
331
|
+
const listening = { ...listeningOf(sessionsInterface, 'on', 'Change', [task], { part: 'running' }), provider: runner.identity }
|
|
332
|
+
taskWatches.set(task, { runner, watch: held.listen(local.client, listening, () => followTask(runner, task)) })
|
|
333
|
+
void followTask(runner, task)
|
|
334
|
+
}
|
|
335
|
+
const unwatchTask = (task: string) => {
|
|
336
|
+
taskWatches.get(task)?.watch.remove()
|
|
337
|
+
taskWatches.delete(task)
|
|
338
338
|
}
|
|
339
339
|
|
|
340
340
|
const providers = async () => [local.client, ...(await otherProviders()).map((other) => other.peer)]
|
|
341
341
|
|
|
342
|
-
const isNotHeld = (error: unknown) => error instanceof RpcError && error.code === rpcCodes.notHeld
|
|
342
|
+
const isNotHeld = (error: unknown): error is RpcError => error instanceof RpcError && error.code === rpcCodes.notHeld
|
|
343
|
+
|
|
344
|
+
const sessionsAsk = (client: Pick<RpcClient, 'request'>) => (method: string, args: readonly unknown[]) => client.request(`${sessionsInterface}.${method}`, args)
|
|
343
345
|
|
|
344
|
-
const firstHolding = async <Value>(ask: (
|
|
345
|
-
let last
|
|
346
|
-
for (const
|
|
346
|
+
const firstHolding = async <Item, Value>(items: readonly Item[], ask: (item: Item) => Promise<Value>): Promise<Value> => {
|
|
347
|
+
let last = new RpcError(rpcCodes.notHeld, 'No sessions provider answers.')
|
|
348
|
+
for (const item of items) {
|
|
347
349
|
try {
|
|
348
|
-
return await ask(
|
|
350
|
+
return await ask(item)
|
|
349
351
|
} catch (error) {
|
|
350
352
|
if (!isNotHeld(error)) throw error
|
|
351
353
|
last = error
|
|
352
354
|
}
|
|
353
355
|
}
|
|
354
|
-
throw last
|
|
356
|
+
throw last
|
|
355
357
|
}
|
|
356
358
|
|
|
357
|
-
const read = <Value>(id: string, part: string, options: Request = {}): Promise<Value> =>
|
|
358
|
-
firstHolding((client) => client.request<Value>(`${sessionsInterface}.read`, [id, part, { project: project(), ...options }])).catch((error: unknown) => {
|
|
359
|
+
const read = async <Value>(id: string, part: string, options: Request = {}): Promise<Value> =>
|
|
360
|
+
firstHolding(await providers(), (client) => client.request<Value>(`${sessionsInterface}.read`, [id, part, { project: project(), ...options }])).catch((error: unknown) => {
|
|
359
361
|
throw isNotHeld(error) ? new Error(`no session ${id} on any of your devices.`) : error
|
|
360
362
|
})
|
|
361
363
|
|
|
@@ -365,7 +367,7 @@ export function serveConversations({
|
|
|
365
367
|
return lists.flat().filter((each) => !seen.has(each.id) && Boolean(seen.add(each.id)))
|
|
366
368
|
}
|
|
367
369
|
|
|
368
|
-
const actOn = (target: string, action: Act, input: unknown, context: Request) => firstHolding((client) => client.request(`${sessionsInterface}.${action}`, [target, input, { project: project(), ...context }]))
|
|
370
|
+
const actOn = async (target: string, action: Act, input: unknown, context: Request) => firstHolding(await providers(), (client) => client.request(`${sessionsInterface}.${action}`, [target, input, { project: project(), ...context }]))
|
|
369
371
|
|
|
370
372
|
let color: SessionColor = { session: '' }
|
|
371
373
|
let onColor: (told: SessionColor) => void = () => undefined
|
|
@@ -400,6 +402,7 @@ export function serveConversations({
|
|
|
400
402
|
const dispatch = (changes: readonly SessionChange[]) => {
|
|
401
403
|
if (session !== '' && changes.some((change) => change.type === TaskStart || change.type === TaskEnd)) local.client.notify(sessionActs.changed, { session, part: 'tasks' })
|
|
402
404
|
for (const change of changes) {
|
|
405
|
+
if (change.type === TaskEnd) unwatchTask(change.task.id)
|
|
403
406
|
if ((change.type === TurnStart || change.type === TurnEnd) && change.turn.prompt.task === undefined) lastTurn = change.turn
|
|
404
407
|
if (change.type === Message && !liveIds.has(change.message.id)) {
|
|
405
408
|
live.push(change.message)
|
|
@@ -553,7 +556,7 @@ export function serveConversations({
|
|
|
553
556
|
|
|
554
557
|
const listenToServe = () => {
|
|
555
558
|
serveChanges?.remove()
|
|
556
|
-
serveChanges = held.listen(local.client,
|
|
559
|
+
serveChanges = held.listen(local.client, listeningOf(sessionsInterface, 'on', 'Change', [session], { part: ['tasks', 'goal'] }), (change: SessionsChange) => {
|
|
557
560
|
if (change.part === 'tasks') void reconcileTasks()
|
|
558
561
|
if (change.part === 'goal') void rereadGoal()
|
|
559
562
|
})
|
|
@@ -563,6 +566,7 @@ export function serveConversations({
|
|
|
563
566
|
if (id === session) return
|
|
564
567
|
const previous = session
|
|
565
568
|
session = id
|
|
569
|
+
for (const task of taskWatches.keys()) unwatchTask(task)
|
|
566
570
|
live = []
|
|
567
571
|
liveIds.clear()
|
|
568
572
|
waitingRows.clear()
|
|
@@ -595,40 +599,53 @@ export function serveConversations({
|
|
|
595
599
|
)
|
|
596
600
|
listening = Promise.all([restored, holding]).then(() => undefined)
|
|
597
601
|
listenToServe()
|
|
598
|
-
void starting.then(reconcileTasks)
|
|
602
|
+
void starting.then(() => reconcileTasks())
|
|
599
603
|
if (heard.size === 0 && watched.size === 0 && served.listened().length === 0) return
|
|
600
604
|
void Promise.all([previous === '' ? undefined : onListenerFiles(() => claude.fs.write(`${listeners}/${previous}.json`, JSON.stringify(noneKept))), saveListeners()]).catch((error: unknown) => report('follow', 'Kept telling the mods about the session from before', error))
|
|
601
605
|
}
|
|
602
606
|
|
|
603
|
-
const
|
|
607
|
+
const openTasks = () => liveTasks().filter((task) => task.isBackground === true && task.closedAt === undefined)
|
|
608
|
+
const openTask = (id: string) => openTasks().find((task) => task.id === id)
|
|
609
|
+
|
|
610
|
+
const reconcileTasks = async ({ atConnect = false } = {}) => {
|
|
604
611
|
if (session === '') return
|
|
605
612
|
await starting
|
|
606
|
-
|
|
607
|
-
if (open.length === 0) return
|
|
613
|
+
if (openTasks().length === 0) return
|
|
608
614
|
const saved = await read<TaskData[]>(session, 'tasks').catch((error: unknown) => (report('tasks', 'Could not read whether its background tasks ended', error), []))
|
|
609
|
-
for (const task of saved)
|
|
610
|
-
|
|
611
|
-
|
|
615
|
+
for (const task of saved) if (task.closedAt !== undefined && openTask(task.id) !== undefined) dispatch(conversation.endTask(task, task.closedAt))
|
|
616
|
+
const open = openTasks().filter((task) => atConnect || !taskWatches.has(task.id))
|
|
617
|
+
const others = open.every((task) => taskWatches.has(task.id)) ? [] : await otherProviders()
|
|
618
|
+
for (const task of open) {
|
|
619
|
+
const watched = taskWatches.get(task.id)
|
|
620
|
+
if (watched !== undefined) await followTask(watched.runner, task.id)
|
|
621
|
+
else await findTask(task.id, others).catch((error: unknown) => report('tasks', 'Could not read whether its tasks on another device ended', error))
|
|
612
622
|
}
|
|
613
|
-
for (const { peer } of await otherProviders()) await closeEndedOn(peer, open.map((task) => task.id)).catch((error: unknown) => report('tasks', 'Could not read whether its tasks on another device ended', error))
|
|
614
623
|
}
|
|
615
624
|
|
|
616
|
-
const
|
|
617
|
-
await
|
|
618
|
-
const
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
return
|
|
622
|
-
})
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
625
|
+
const findTask = async (id: string, others: readonly OtherProvider[]) => {
|
|
626
|
+
if ((await findSession(sessionsAsk(local.client), id)) !== undefined) return
|
|
627
|
+
for (const runner of others) {
|
|
628
|
+
const found = await findSession(sessionsAsk(runner.peer), id).catch((error: unknown) => {
|
|
629
|
+
report('tasks', `Could not ask ${runner.identity.mod} whether it runs task ${id}`, error)
|
|
630
|
+
return undefined
|
|
631
|
+
})
|
|
632
|
+
if (found !== undefined) return watchTask(id, runner)
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const followTask = async (runner: OtherProvider, id: string) => {
|
|
637
|
+
try {
|
|
638
|
+
await starting
|
|
639
|
+
if (openTask(id) === undefined) return
|
|
640
|
+
const found = await findSession(sessionsAsk(runner.peer), id)
|
|
641
|
+
if (found === undefined) return unwatchTask(id)
|
|
642
|
+
const task = openTask(id)
|
|
643
|
+
if (task === undefined || found.isRunning) return
|
|
629
644
|
const closedAt = new Date().toISOString()
|
|
630
645
|
await claude.fs.write(`${backgroundTasks}/${session}/${task.id}.json`, JSON.stringify({ ...task, closedAt } satisfies TaskData))
|
|
631
646
|
dispatch(conversation.endTask(task, closedAt))
|
|
647
|
+
} catch (error) {
|
|
648
|
+
report('tasks', `Could not read whether a task ${runner.identity.mod} runs ended`, error)
|
|
632
649
|
}
|
|
633
650
|
}
|
|
634
651
|
|
|
@@ -825,12 +842,14 @@ export function serveConversations({
|
|
|
825
842
|
const elsewhere: TaskStartArgs = { ...task, ...owner, title: answer?.title ?? task.title, prompt: answer?.prompt ?? task.prompt }
|
|
826
843
|
const others = await otherProviders()
|
|
827
844
|
const onDevice = others.filter(({ identity }) => identity.device !== undefined && (identity.device.name === task.device || identity.device.id === task.device))
|
|
828
|
-
const
|
|
829
|
-
|
|
845
|
+
const candidates = onDevice.length > 0 ? onDevice : others
|
|
846
|
+
const { opened, runner } = await firstHolding(candidates, async (runner) => ({ opened: await runner.peer.request<TaskData>(`${sessionsInterface}.startTask`, [session, elsewhere, { project: project() }]), runner })).catch((error: unknown) => {
|
|
847
|
+
throw isNotHeld(error) ? new Error(`no mod starts sessions on ${task.device}, so the task did not start. Leave device out to start it on ${here.name}.`) : error
|
|
830
848
|
})
|
|
831
849
|
const started: TaskData = { ...asked, id: opened.id, title: elsewhere.title }
|
|
832
850
|
await claude.fs.write(`${backgroundTasks}/${session}/${started.id}.json`, JSON.stringify(started))
|
|
833
851
|
dispatch(conversation.startTask(started))
|
|
852
|
+
watchTask(started.id, runner)
|
|
834
853
|
return started
|
|
835
854
|
}
|
|
836
855
|
}
|
|
@@ -910,17 +929,11 @@ export function serveConversations({
|
|
|
910
929
|
const fields = (request: Request, keys: readonly string[]) => Object.fromEntries(keys.flatMap((key) => (request[key] === undefined ? [] : [[key, request[key]]])))
|
|
911
930
|
|
|
912
931
|
const sessionNamed = async (id: string): Promise<SessionData> => {
|
|
913
|
-
const
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
return listed
|
|
919
|
-
})
|
|
920
|
-
const found = await firstHolding(lookedUp).catch((error: unknown) => {
|
|
921
|
-
throw isNotHeld(error) ? new Error(`no session ${id} on any of your devices.`) : error
|
|
922
|
-
})
|
|
923
|
-
return found.id === session ? { ...found, isRunning: true } : found
|
|
932
|
+
for (const client of await providers()) {
|
|
933
|
+
const found = await findSession(sessionsAsk(client), id)
|
|
934
|
+
if (found !== undefined) return found.id === session ? { ...found, isRunning: true } : found
|
|
935
|
+
}
|
|
936
|
+
throw new Error(`no session ${id} on any of your devices.`)
|
|
924
937
|
}
|
|
925
938
|
|
|
926
939
|
const methods: Readonly<Record<string, (request: Request, caller: string | undefined) => Promise<unknown>>> = {
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { interfaceName, isObject
|
|
1
|
+
import { instanceFolder, interfaceName, isObject } from '../records.js'
|
|
2
2
|
import type { Device } from '../session/context/turn/device.js'
|
|
3
3
|
import type { SessionData } from '../session/conversation.js'
|
|
4
4
|
import { Note } from '../session/context/turn/message/note.js'
|
|
5
5
|
import { Prompt } from '../session/context/turn/message/prompt.js'
|
|
6
6
|
import { Person } from '../session/context/turn/message/sender.js'
|
|
7
|
-
import type { SendReceipt } from '../session/session.js'
|
|
7
|
+
import type { SendReceipt, SessionScope } from '../session/session.js'
|
|
8
8
|
import { matches, receivedMatcher, sentMatcher, type SentMatcher } from '../utils/matcher.js'
|
|
9
9
|
import type { Subscription } from '../utils/subscription.js'
|
|
10
10
|
import { messageOf } from '../utils/text.js'
|
|
@@ -71,11 +71,11 @@ export type SessionTerminals = {
|
|
|
71
71
|
|
|
72
72
|
export type HeldSession = { readonly session: string; readonly project: string; readonly cwd: string }
|
|
73
73
|
|
|
74
|
-
export type HeldStatus = Pick<SessionData, 'status' | 'waitingFor' | 'contextPercent' | 'lastTurn'>
|
|
74
|
+
export type HeldStatus = Pick<SessionData, 'status' | 'waitingFor' | 'contextPercent' | 'lastTurn' | 'openCall'>
|
|
75
75
|
|
|
76
76
|
export type VisitedAt = Readonly<Record<string, string>>
|
|
77
77
|
|
|
78
|
-
export type SessionsChange = { readonly session: string; readonly part: 'visit' | 'running' | 'tasks' | 'goal' | 'status' | 'deleted' | 'messages' | 'mail' }
|
|
78
|
+
export type SessionsChange = { readonly session: string; readonly part: 'visit' | 'running' | 'tasks' | 'goal' | 'status' | 'title' | 'deleted' | 'messages' | 'mail' }
|
|
79
79
|
|
|
80
80
|
export const storeInterface = 'cmod/Store'
|
|
81
81
|
|
|
@@ -131,21 +131,29 @@ export async function readProviders(files: InstanceFiles, store: string, name: s
|
|
|
131
131
|
Promise.all(
|
|
132
132
|
(await files.list(`${folder}/${mod.name}`))
|
|
133
133
|
.filter((file) => file.name.endsWith('.json'))
|
|
134
|
-
.map(async (file) => ({ mod: mod.name, program: file.name.slice(0, -'.json'.length), instance:
|
|
134
|
+
.map(async (file) => ({ mod: mod.name, program: file.name.slice(0, -'.json'.length), instance: await instanceAt(files, `${folder}/${mod.name}/${file.name}`) })),
|
|
135
135
|
),
|
|
136
136
|
),
|
|
137
137
|
)
|
|
138
138
|
return providersIn(records.flat(), name)
|
|
139
139
|
}
|
|
140
140
|
|
|
141
|
+
async function instanceAt(files: InstanceFiles, path: string): Promise<unknown> {
|
|
142
|
+
return JSON.parse((await files.read(path)) ?? 'null') as unknown
|
|
143
|
+
}
|
|
144
|
+
|
|
141
145
|
export function providersIn(records: readonly { readonly mod: string; readonly program: string; readonly instance: unknown }[], name: string): Provider[] {
|
|
142
146
|
return records.flatMap(({ mod, program, instance }) => {
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
return provides.includes(name) ? [{ mod, program, address: instance['address'], provides }] : []
|
|
147
|
+
const provided = providesOf(instance)
|
|
148
|
+
return provided.provides.includes(name) ? [{ mod, program, ...provided }] : []
|
|
146
149
|
})
|
|
147
150
|
}
|
|
148
151
|
|
|
152
|
+
function providesOf(instance: unknown): Pick<Provider, 'address' | 'provides'> {
|
|
153
|
+
if (!isObject(instance) || typeof instance['address'] !== 'string' || !Array.isArray(instance['provides'])) return { address: '', provides: [] }
|
|
154
|
+
return { address: instance['address'], provides: instance['provides'].filter((each): each is string => typeof each === 'string') }
|
|
155
|
+
}
|
|
156
|
+
|
|
149
157
|
export function checkInterfaceName(name: string): void {
|
|
150
158
|
if (!interfaceName.test(name)) throw new Error(`${name} is no interface name, such as demo/Platform.`)
|
|
151
159
|
}
|
|
@@ -160,6 +168,11 @@ export function isHeardAt(listening: Pick<Listening, 'args' | 'matcher'>, args:
|
|
|
160
168
|
return listening.matcher === undefined || matches(payload, receivedMatcher(listening.matcher))
|
|
161
169
|
}
|
|
162
170
|
|
|
171
|
+
export function wantsMessages({ matcher }: Pick<Listening, 'matcher'>): boolean {
|
|
172
|
+
const part = isObject(matcher) && 'part' in matcher ? matcher['part'] : undefined
|
|
173
|
+
return part === 'messages' || (Array.isArray(part) && part.includes('messages'))
|
|
174
|
+
}
|
|
175
|
+
|
|
163
176
|
export type Implementation = Readonly<Record<string, (...args: never[]) => unknown>>
|
|
164
177
|
|
|
165
178
|
export type InterfaceServer = {
|
|
@@ -175,16 +188,20 @@ export function interfaceServer({
|
|
|
175
188
|
implementations,
|
|
176
189
|
onListen,
|
|
177
190
|
extraMethod,
|
|
191
|
+
hears = () => true,
|
|
178
192
|
}: {
|
|
179
193
|
readonly implementations: Readonly<Record<string, Implementation>>
|
|
180
194
|
readonly onListen?: (connection: Pick<Peer, 'request' | 'notify'>, listening: Listening) => void | Promise<void>
|
|
181
195
|
readonly extraMethod?: (connection: Pick<Peer, 'request' | 'notify'>, method: string, params: unknown, signal: AbortSignal) => { readonly result: unknown } | undefined | Promise<{ readonly result: unknown } | undefined>
|
|
196
|
+
readonly hears?: (listening: Listening, payload: unknown) => boolean
|
|
182
197
|
}): InterfaceServer {
|
|
183
198
|
const held = new Map<Pick<Peer, 'request' | 'notify'>, Map<string, Listening>>()
|
|
184
199
|
const recent = new Map<string, { cursor: number; readonly kept: { readonly cursor: number; readonly args: readonly unknown[]; readonly payload: unknown }[] }>()
|
|
185
200
|
|
|
186
201
|
const keyOf = (name: string, event: string) => `${name}\n${event}`
|
|
187
202
|
|
|
203
|
+
const isHeard = (listening: Listening, args: readonly unknown[], payload: unknown) => listening.kind === 'on' && isHeardAt(listening, args, payload) && hears(listening, payload)
|
|
204
|
+
|
|
188
205
|
const listeningOf = (params: unknown): Listening => {
|
|
189
206
|
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 }.`)
|
|
190
207
|
if (implementations[params['interface']] === undefined) throw new RpcError(rpcCodes.methodNotFound, `This program provides no ${params['interface']}.`)
|
|
@@ -195,7 +212,7 @@ export function interfaceServer({
|
|
|
195
212
|
if (listening.kind !== 'on' || listening.after === undefined) return
|
|
196
213
|
const after = Number(listening.after)
|
|
197
214
|
for (const each of recent.get(keyOf(listening.interface, listening.event))?.kept ?? []) {
|
|
198
|
-
if (each.cursor > after &&
|
|
215
|
+
if (each.cursor > after && isHeard(listening, each.args, each.payload)) connection.notify(onMethod, { id: listening.id, payload: each.payload, cursor: String(each.cursor) } satisfies Heard)
|
|
199
216
|
}
|
|
200
217
|
}
|
|
201
218
|
|
|
@@ -231,7 +248,7 @@ export function interfaceServer({
|
|
|
231
248
|
if (log.kept.length > keptEvents) log.kept.shift()
|
|
232
249
|
recent.set(key, log)
|
|
233
250
|
for (const listening of server.listeners(name, event)) {
|
|
234
|
-
if (
|
|
251
|
+
if (isHeard(listening, args, payload)) listening.connection.notify(onMethod, { id: listening.id, payload, cursor: String(log.cursor) } satisfies Heard)
|
|
235
252
|
}
|
|
236
253
|
},
|
|
237
254
|
listeners: (name, event) => [...held].flatMap(([connection, list]) => [...list.values()].filter((each) => each.interface === name && (event === undefined || each.event === event)).map((each) => ({ ...each, connection }))),
|
|
@@ -244,7 +261,7 @@ export function interfaceServer({
|
|
|
244
261
|
|
|
245
262
|
export type Listener = (payload: never, signal: AbortSignal) => unknown
|
|
246
263
|
|
|
247
|
-
type Registered = { readonly listening: Listening; readonly listener: Listener
|
|
264
|
+
type Registered = { readonly listening: Listening; readonly joined: Set<{ readonly listener: Listener }>; cursor: string | undefined; isPending: boolean }
|
|
248
265
|
|
|
249
266
|
export type InterfaceListeners = {
|
|
250
267
|
listen(request: Pick<Peer, 'request'>, listening: Omit<Listening, 'id'>, listener: Listener): Subscription
|
|
@@ -255,7 +272,9 @@ export type InterfaceListeners = {
|
|
|
255
272
|
|
|
256
273
|
export function interfaceListeners({ report: reportAll }: { readonly report: (error: unknown) => void }): InterfaceListeners {
|
|
257
274
|
const registered = new Map<string, Registered>()
|
|
275
|
+
const shared = new Map<string, Registered>()
|
|
258
276
|
let next = 0
|
|
277
|
+
const sharedKey = ({ interface: name, event, args, matcher, provider }: Omit<Listening, 'id'>) => JSON.stringify([name, event, args ?? [], matcher ?? null, provider ?? null],(_key, value: unknown) => (isObject(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : 1))) : value))
|
|
259
278
|
const report = (error: unknown) => {
|
|
260
279
|
if (!isConnectionGone(error)) reportAll(error)
|
|
261
280
|
}
|
|
@@ -271,14 +290,21 @@ export function interfaceListeners({ report: reportAll }: { readonly report: (er
|
|
|
271
290
|
|
|
272
291
|
const listeners: InterfaceListeners = {
|
|
273
292
|
listen(request, listening, listener) {
|
|
274
|
-
const
|
|
275
|
-
const each: Registered = { listening: { ...listening, id },
|
|
276
|
-
|
|
277
|
-
|
|
293
|
+
const key = listening.kind === 'on' ? sharedKey(listening) : undefined
|
|
294
|
+
const each: Registered = (key === undefined ? undefined : shared.get(key)) ?? { listening: { ...listening, id: `${(next += 1)}` }, joined: new Set(), cursor: undefined, isPending: false }
|
|
295
|
+
const mine = { listener }
|
|
296
|
+
each.joined.add(mine)
|
|
297
|
+
if (!registered.has(each.listening.id)) {
|
|
298
|
+
registered.set(each.listening.id, each)
|
|
299
|
+
if (key !== undefined) shared.set(key, each)
|
|
300
|
+
void send(request, each)
|
|
301
|
+
}
|
|
278
302
|
return {
|
|
279
303
|
remove() {
|
|
280
|
-
if (!
|
|
281
|
-
|
|
304
|
+
if (!each.joined.delete(mine) || each.joined.size > 0) return
|
|
305
|
+
registered.delete(each.listening.id)
|
|
306
|
+
if (key !== undefined) shared.delete(key)
|
|
307
|
+
void request.request(unlistenMethod, { id: each.listening.id }).catch(report)
|
|
282
308
|
},
|
|
283
309
|
}
|
|
284
310
|
},
|
|
@@ -288,11 +314,12 @@ export function interfaceListeners({ report: reportAll }: { readonly report: (er
|
|
|
288
314
|
const each = registered.get(heard.id)
|
|
289
315
|
if (each === undefined) return method === beforeMethod ? Promise.resolve({ result: null }) : undefined
|
|
290
316
|
if (heard.cursor !== undefined) each.cursor = heard.cursor
|
|
317
|
+
const answers = [...each.joined].map(({ listener }) => (async () => listener(heard.payload as never, signal))())
|
|
291
318
|
if (method === onMethod) {
|
|
292
|
-
|
|
319
|
+
for (const answer of answers) void answer.catch(report)
|
|
293
320
|
return undefined
|
|
294
321
|
}
|
|
295
|
-
return (
|
|
322
|
+
return Promise.all(answers).then(([result]) => ({ result: result ?? null }))
|
|
296
323
|
},
|
|
297
324
|
async replay(request) {
|
|
298
325
|
await Promise.all([...registered.values()].map((each) => send(request, each)))
|
|
@@ -386,6 +413,17 @@ export const sessionActions = ['send', 'abort', 'end', 'fork', 'startTask', 'cal
|
|
|
386
413
|
|
|
387
414
|
export const showLeaseMs = 16_000
|
|
388
415
|
|
|
416
|
+
export async function findSession(ask: (method: string, args: readonly unknown[]) => Promise<unknown>, id: string, scope: SessionScope = {}): Promise<SessionData | undefined> {
|
|
417
|
+
const isAnswer = (error: unknown, code: number) => error instanceof RpcError && error.code === code
|
|
418
|
+
try {
|
|
419
|
+
return (await ask('session', [id])) as SessionData
|
|
420
|
+
} catch (error) {
|
|
421
|
+
if (isAnswer(error, rpcCodes.notHeld)) return undefined
|
|
422
|
+
if (!isAnswer(error, rpcCodes.methodNotFound)) throw error
|
|
423
|
+
}
|
|
424
|
+
return ((await ask('sessions', [{ everyProject: true, ...scope }])) as readonly SessionData[]).find((each) => each.id === id)
|
|
425
|
+
}
|
|
426
|
+
|
|
389
427
|
export function routeSessions({
|
|
390
428
|
computer,
|
|
391
429
|
device,
|
|
@@ -463,14 +501,10 @@ export function routeSessions({
|
|
|
463
501
|
|
|
464
502
|
const runnerElsewhere = async (session: string): Promise<string | undefined> => {
|
|
465
503
|
for (const other of await providers.list(sessionsInterface)) {
|
|
466
|
-
const
|
|
467
|
-
const isAnswer = (error: unknown, code: number) => error instanceof RpcError && error.code === code
|
|
468
|
-
const found = await ask('session', [session]).catch(async (error: unknown) => {
|
|
469
|
-
if (isAnswer(error, rpcCodes.notHeld)) return undefined
|
|
470
|
-
if (isAnswer(error, rpcCodes.methodNotFound)) return ((await ask('sessions', [{ everyProject: true, running: true }])) as readonly SessionData[]).find((each) => each.id === session)
|
|
504
|
+
const found = await findSession((method, args) => providers.call({ interface: sessionsInterface, method, args, ...other }), session, { running: true }).catch((error: unknown) => {
|
|
471
505
|
throw new Error(`cmod could not ask ${other.device?.name ?? other.mod} whether it runs session ${session}, so it starts no copy of it here: ${messageOf(error)}`)
|
|
472
506
|
})
|
|
473
|
-
if (
|
|
507
|
+
if (found?.isRunning === true) return other.device?.name ?? other.mod
|
|
474
508
|
}
|
|
475
509
|
return undefined
|
|
476
510
|
}
|
|
@@ -536,7 +570,7 @@ export function routeSessions({
|
|
|
536
570
|
const status = listed.status ?? told.status
|
|
537
571
|
const recorded = listed.waitingFor
|
|
538
572
|
const waitingFor = status !== 'waiting' || told.waitingFor === undefined ? recorded : { ...told.waitingFor, ...(recorded === undefined ? {} : { dialog: recorded.dialog }) }
|
|
539
|
-
return { ...listed, ...(status === undefined ? {} : { status }), ...(waitingFor === undefined ? {} : { waitingFor }), ...(told.contextPercent === undefined ? {} : { contextPercent: told.contextPercent }), ...(told.lastTurn === undefined ? {} : { lastTurn: told.lastTurn }) }
|
|
573
|
+
return { ...listed, ...(status === undefined ? {} : { status }), ...(waitingFor === undefined ? {} : { waitingFor }), ...(told.contextPercent === undefined ? {} : { contextPercent: told.contextPercent }), ...(told.lastTurn === undefined ? {} : { lastTurn: told.lastTurn }), ...(told.openCall === undefined || status === 'idle' ? {} : { openCall: told.openCall }) }
|
|
540
574
|
}
|
|
541
575
|
|
|
542
576
|
const implementation: Implementation = {
|
|
@@ -637,6 +671,7 @@ export function routeSessions({
|
|
|
637
671
|
}
|
|
638
672
|
|
|
639
673
|
const interfaces = interfaceServer({
|
|
674
|
+
hears: (listening, payload) => !isObject(payload) || payload['part'] !== 'messages' || wantsMessages(listening),
|
|
640
675
|
implementations: { ...Object.fromEntries(names.map((name) => [name, implementation])), [uiInterface]: ui, [providersInterface]: {}, [storeInterface]: store, [programsInterface]: programChanges, ...(terminal === undefined ? {} : { [terminalInterface]: terminal }) },
|
|
641
676
|
onListen: (_connection, listening) => {
|
|
642
677
|
if (listening.interface === uiInterface) {
|
|
@@ -824,6 +859,7 @@ export function routeProviders({
|
|
|
824
859
|
const forwarded = new Map<RpcConnection, Map<string, Subscription>>()
|
|
825
860
|
const devices = new Map<string, DeviceServe>()
|
|
826
861
|
const deviceListeners = new Map<string, InterfaceListeners>()
|
|
862
|
+
const deviceProviders = new Map<string, Map<string, Promise<ProviderIdentity[]>>>()
|
|
827
863
|
const followed = new WeakSet<ProviderEnd>()
|
|
828
864
|
let following: Promise<void> = Promise.resolve()
|
|
829
865
|
const keyOf = ({ mod, program }: ProviderIdentity) => `${mod}\n${program ?? ''}`
|
|
@@ -864,6 +900,12 @@ export function routeProviders({
|
|
|
864
900
|
throw new RpcError(rpcCodes.methodNotFound, `cmod serve answers ${who} no ${method}.`)
|
|
865
901
|
}
|
|
866
902
|
|
|
903
|
+
const instanceNames = new Map<string, readonly string[]>()
|
|
904
|
+
const instanceNamesOf = async (mod: string, program: string): Promise<readonly string[]> => {
|
|
905
|
+
if (programs === undefined || mod === cmodPluginName) return []
|
|
906
|
+
return providesOf(await instanceAt(programs.files, `${instanceFolder(programs.store, mod)}/${program}.json`)).provides
|
|
907
|
+
}
|
|
908
|
+
|
|
867
909
|
const instances = async (name: string): Promise<Provider[]> => (programs === undefined ? [] : (await readProviders(programs.files, programs.store, name)).filter((each) => each.mod !== cmodPluginName))
|
|
868
910
|
|
|
869
911
|
const ownOf = async (name: string): Promise<ProviderIdentity[]> => {
|
|
@@ -883,7 +925,7 @@ export function routeProviders({
|
|
|
883
925
|
[...devices.entries()]
|
|
884
926
|
.filter(([, each]) => isReached(each))
|
|
885
927
|
.map(([id, each]) =>
|
|
886
|
-
|
|
928
|
+
providersOn(id, each, name).catch((error: unknown) => {
|
|
887
929
|
report(new Error(`cmod serve lists no ${name} of ${each.name}: ${messageOf(error)}`))
|
|
888
930
|
return []
|
|
889
931
|
}),
|
|
@@ -908,6 +950,17 @@ export function routeProviders({
|
|
|
908
950
|
? { 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)) }
|
|
909
951
|
: each.client
|
|
910
952
|
|
|
953
|
+
const providersOn = (id: string, each: DeviceServe, name: string): Promise<ProviderIdentity[]> => {
|
|
954
|
+
const known = deviceProviders.get(id) ?? new Map<string, Promise<ProviderIdentity[]>>()
|
|
955
|
+
deviceProviders.set(id, known)
|
|
956
|
+
const kept = known.get(name)
|
|
957
|
+
if (kept !== undefined) return kept
|
|
958
|
+
const asked = peerOf(each).request<ProviderIdentity[]>(providerActs.providers, { interface: name, device: id })
|
|
959
|
+
known.set(name, asked)
|
|
960
|
+
void asked.catch(() => known.get(name) === asked && known.delete(name))
|
|
961
|
+
return asked
|
|
962
|
+
}
|
|
963
|
+
|
|
911
964
|
const listenersOf = (id: string) => {
|
|
912
965
|
const listeners = deviceListeners.get(id) ?? interfaceListeners({ report })
|
|
913
966
|
deviceListeners.set(id, listeners)
|
|
@@ -919,13 +972,16 @@ export function routeProviders({
|
|
|
919
972
|
const forward = (id: string, peer: Pick<Peer, 'request'>) => {
|
|
920
973
|
if (followedDevices.has(id)) return
|
|
921
974
|
followedDevices.add(id)
|
|
922
|
-
listenersOf(id).listen(peer, listeningOf(providersInterface, 'on', 'Change', [],
|
|
923
|
-
if (isObject(told)
|
|
975
|
+
listenersOf(id).listen(peer, listeningOf(providersInterface, 'on', 'Change', [], { device: { id } }), (told: unknown) => {
|
|
976
|
+
if (!isObject(told) || typeof told['interface'] !== 'string' || !isObject(told['device'])) return
|
|
977
|
+
deviceProviders.get(id)?.delete(told['interface'])
|
|
978
|
+
changed(told['interface'], { id, name: String(told['device']['name']) })
|
|
924
979
|
})
|
|
925
980
|
}
|
|
926
981
|
|
|
927
982
|
const drop = (id: string, each: DeviceServe) => {
|
|
928
983
|
devices.delete(id)
|
|
984
|
+
deviceProviders.delete(id)
|
|
929
985
|
changed(undefined, { id, name: each.name })
|
|
930
986
|
if (!isLinked(each)) return each.client.close()
|
|
931
987
|
each.link.close(new Error(`cmod serve dropped ${each.name}`))
|
|
@@ -944,6 +1000,7 @@ export function routeProviders({
|
|
|
944
1000
|
})
|
|
945
1001
|
const each: MessageServe = { name, listeners: listenersOf(id), carrier, link, theirs }
|
|
946
1002
|
devices.set(id, each)
|
|
1003
|
+
deviceProviders.delete(id)
|
|
947
1004
|
forward(id, peerOf(each))
|
|
948
1005
|
link.notify(providerActs.link, { link: link.id, ...(theirs === undefined ? {} : { answers: theirs }) } satisfies Hello)
|
|
949
1006
|
if (theirs === undefined) return
|
|
@@ -989,6 +1046,7 @@ export function routeProviders({
|
|
|
989
1046
|
handle: heardBy(listeners, `the cmod serve of ${name}`),
|
|
990
1047
|
onConnect: async (connected) => {
|
|
991
1048
|
reached()
|
|
1049
|
+
deviceProviders.delete(id)
|
|
992
1050
|
changed(undefined, { id, name })
|
|
993
1051
|
await listeners.replay(connected)
|
|
994
1052
|
},
|
|
@@ -1177,6 +1235,12 @@ export function routeProviders({
|
|
|
1177
1235
|
if (end !== undefined) void closeIfExited(end, connection).catch(report)
|
|
1178
1236
|
},
|
|
1179
1237
|
async programChanged(mod, program) {
|
|
1238
|
+
const key = keyOf({ mod, program })
|
|
1239
|
+
await instanceNamesOf(mod, program).then((named) => {
|
|
1240
|
+
for (const name of new Set([...(instanceNames.get(key) ?? []), ...named])) changed(name, undefined)
|
|
1241
|
+
if (named.length === 0) instanceNames.delete(key)
|
|
1242
|
+
else instanceNames.set(key, named)
|
|
1243
|
+
}, report)
|
|
1180
1244
|
await Promise.all([...ends.values()].flatMap((end) => (end.connection !== undefined && end.identity.mod === mod && (end.identity.program ?? mod) === program ? [closeIfExited(end, end.connection)] : [])))
|
|
1181
1245
|
},
|
|
1182
1246
|
closed(connection) {
|