@cmodjs/core 8.10.3 → 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.
@@ -1,10 +1,10 @@
1
- import { interfaceName, isObject, type ProgramInstance } from '../records.js'
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'
@@ -40,6 +40,7 @@ export const uiParts = ['widgets', 'views', 'pages'] as const
40
40
 
41
41
  export const sessionActs = {
42
42
  hold: '$/hold',
43
+ stop: '$/stop',
43
44
  act: '$/act',
44
45
  changed: '$/changed',
45
46
  status: '$/status',
@@ -70,11 +71,11 @@ export type SessionTerminals = {
70
71
 
71
72
  export type HeldSession = { readonly session: string; readonly project: string; readonly cwd: string }
72
73
 
73
- export type HeldStatus = Pick<SessionData, 'status' | 'waitingFor' | 'contextPercent' | 'lastTurn'>
74
+ export type HeldStatus = Pick<SessionData, 'status' | 'waitingFor' | 'contextPercent' | 'lastTurn' | 'openCall'>
74
75
 
75
76
  export type VisitedAt = Readonly<Record<string, string>>
76
77
 
77
- 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' }
78
79
 
79
80
  export const storeInterface = 'cmod/Store'
80
81
 
@@ -130,21 +131,29 @@ export async function readProviders(files: InstanceFiles, store: string, name: s
130
131
  Promise.all(
131
132
  (await files.list(`${folder}/${mod.name}`))
132
133
  .filter((file) => file.name.endsWith('.json'))
133
- .map(async (file) => ({ mod: mod.name, program: file.name.slice(0, -'.json'.length), instance: JSON.parse((await files.read(`${folder}/${mod.name}/${file.name}`)) ?? 'null') as unknown })),
134
+ .map(async (file) => ({ mod: mod.name, program: file.name.slice(0, -'.json'.length), instance: await instanceAt(files, `${folder}/${mod.name}/${file.name}`) })),
134
135
  ),
135
136
  ),
136
137
  )
137
138
  return providersIn(records.flat(), name)
138
139
  }
139
140
 
141
+ async function instanceAt(files: InstanceFiles, path: string): Promise<unknown> {
142
+ return JSON.parse((await files.read(path)) ?? 'null') as unknown
143
+ }
144
+
140
145
  export function providersIn(records: readonly { readonly mod: string; readonly program: string; readonly instance: unknown }[], name: string): Provider[] {
141
146
  return records.flatMap(({ mod, program, instance }) => {
142
- if (!isObject(instance) || typeof instance['address'] !== 'string' || !Array.isArray(instance['provides'])) return []
143
- const provides = (instance as ProgramInstance).provides ?? []
144
- return provides.includes(name) ? [{ mod, program, address: instance['address'], provides }] : []
147
+ const provided = providesOf(instance)
148
+ return provided.provides.includes(name) ? [{ mod, program, ...provided }] : []
145
149
  })
146
150
  }
147
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
+
148
157
  export function checkInterfaceName(name: string): void {
149
158
  if (!interfaceName.test(name)) throw new Error(`${name} is no interface name, such as demo/Platform.`)
150
159
  }
@@ -159,6 +168,11 @@ export function isHeardAt(listening: Pick<Listening, 'args' | 'matcher'>, args:
159
168
  return listening.matcher === undefined || matches(payload, receivedMatcher(listening.matcher))
160
169
  }
161
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
+
162
176
  export type Implementation = Readonly<Record<string, (...args: never[]) => unknown>>
163
177
 
164
178
  export type InterfaceServer = {
@@ -174,16 +188,20 @@ export function interfaceServer({
174
188
  implementations,
175
189
  onListen,
176
190
  extraMethod,
191
+ hears = () => true,
177
192
  }: {
178
193
  readonly implementations: Readonly<Record<string, Implementation>>
179
194
  readonly onListen?: (connection: Pick<Peer, 'request' | 'notify'>, listening: Listening) => void | Promise<void>
180
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
181
197
  }): InterfaceServer {
182
198
  const held = new Map<Pick<Peer, 'request' | 'notify'>, Map<string, Listening>>()
183
199
  const recent = new Map<string, { cursor: number; readonly kept: { readonly cursor: number; readonly args: readonly unknown[]; readonly payload: unknown }[] }>()
184
200
 
185
201
  const keyOf = (name: string, event: string) => `${name}\n${event}`
186
202
 
203
+ const isHeard = (listening: Listening, args: readonly unknown[], payload: unknown) => listening.kind === 'on' && isHeardAt(listening, args, payload) && hears(listening, payload)
204
+
187
205
  const listeningOf = (params: unknown): Listening => {
188
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 }.`)
189
207
  if (implementations[params['interface']] === undefined) throw new RpcError(rpcCodes.methodNotFound, `This program provides no ${params['interface']}.`)
@@ -194,7 +212,7 @@ export function interfaceServer({
194
212
  if (listening.kind !== 'on' || listening.after === undefined) return
195
213
  const after = Number(listening.after)
196
214
  for (const each of recent.get(keyOf(listening.interface, listening.event))?.kept ?? []) {
197
- if (each.cursor > after && isHeardAt(listening, each.args, each.payload)) connection.notify(onMethod, { id: listening.id, payload: each.payload, cursor: String(each.cursor) } satisfies Heard)
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)
198
216
  }
199
217
  }
200
218
 
@@ -230,7 +248,7 @@ export function interfaceServer({
230
248
  if (log.kept.length > keptEvents) log.kept.shift()
231
249
  recent.set(key, log)
232
250
  for (const listening of server.listeners(name, event)) {
233
- if (listening.kind === 'on' && isHeardAt(listening, args, payload)) listening.connection.notify(onMethod, { id: listening.id, payload, cursor: String(log.cursor) } satisfies Heard)
251
+ if (isHeard(listening, args, payload)) listening.connection.notify(onMethod, { id: listening.id, payload, cursor: String(log.cursor) } satisfies Heard)
234
252
  }
235
253
  },
236
254
  listeners: (name, event) => [...held].flatMap(([connection, list]) => [...list.values()].filter((each) => each.interface === name && (event === undefined || each.event === event)).map((each) => ({ ...each, connection }))),
@@ -243,7 +261,7 @@ export function interfaceServer({
243
261
 
244
262
  export type Listener = (payload: never, signal: AbortSignal) => unknown
245
263
 
246
- type Registered = { readonly listening: Listening; readonly listener: Listener; cursor: string | undefined; isPending: boolean }
264
+ type Registered = { readonly listening: Listening; readonly joined: Set<{ readonly listener: Listener }>; cursor: string | undefined; isPending: boolean }
247
265
 
248
266
  export type InterfaceListeners = {
249
267
  listen(request: Pick<Peer, 'request'>, listening: Omit<Listening, 'id'>, listener: Listener): Subscription
@@ -254,7 +272,9 @@ export type InterfaceListeners = {
254
272
 
255
273
  export function interfaceListeners({ report: reportAll }: { readonly report: (error: unknown) => void }): InterfaceListeners {
256
274
  const registered = new Map<string, Registered>()
275
+ const shared = new Map<string, Registered>()
257
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))
258
278
  const report = (error: unknown) => {
259
279
  if (!isConnectionGone(error)) reportAll(error)
260
280
  }
@@ -270,14 +290,21 @@ export function interfaceListeners({ report: reportAll }: { readonly report: (er
270
290
 
271
291
  const listeners: InterfaceListeners = {
272
292
  listen(request, listening, listener) {
273
- const id = `${(next += 1)}`
274
- const each: Registered = { listening: { ...listening, id }, listener, cursor: undefined, isPending: false }
275
- registered.set(id, each)
276
- void send(request, each)
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
+ }
277
302
  return {
278
303
  remove() {
279
- if (!registered.delete(id)) return
280
- void request.request(unlistenMethod, { id }).catch(report)
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)
281
308
  },
282
309
  }
283
310
  },
@@ -287,11 +314,12 @@ export function interfaceListeners({ report: reportAll }: { readonly report: (er
287
314
  const each = registered.get(heard.id)
288
315
  if (each === undefined) return method === beforeMethod ? Promise.resolve({ result: null }) : undefined
289
316
  if (heard.cursor !== undefined) each.cursor = heard.cursor
317
+ const answers = [...each.joined].map(({ listener }) => (async () => listener(heard.payload as never, signal))())
290
318
  if (method === onMethod) {
291
- void (async () => each.listener(heard.payload as never, signal))().catch(report)
319
+ for (const answer of answers) void answer.catch(report)
292
320
  return undefined
293
321
  }
294
- return (async () => ({ result: (await each.listener(heard.payload as never, signal)) ?? null }))()
322
+ return Promise.all(answers).then(([result]) => ({ result: result ?? null }))
295
323
  },
296
324
  async replay(request) {
297
325
  await Promise.all([...registered.values()].map((each) => send(request, each)))
@@ -363,6 +391,7 @@ export type SessionComputer = {
363
391
  unheld(session: string, action: string, input: unknown, context: SessionContext, holding: HoldingOf): Promise<unknown>
364
392
  visit(session: string, at: string, holding: HoldingOf): Promise<void>
365
393
  remove(session: string, context: SessionContext, holding: HoldingOf): Promise<void>
394
+ stop(session: string): Promise<boolean>
366
395
  queue(mail: Omit<Mail, 'id' | 'deliveredAt'>): Promise<number>
367
396
  queued(session: string): Promise<readonly Mail[]>
368
397
  delivered(id: number, at: string): Promise<void>
@@ -384,6 +413,17 @@ export const sessionActions = ['send', 'abort', 'end', 'fork', 'startTask', 'cal
384
413
 
385
414
  export const showLeaseMs = 16_000
386
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
+
387
427
  export function routeSessions({
388
428
  computer,
389
429
  device,
@@ -461,14 +501,10 @@ export function routeSessions({
461
501
 
462
502
  const runnerElsewhere = async (session: string): Promise<string | undefined> => {
463
503
  for (const other of await providers.list(sessionsInterface)) {
464
- const ask = (method: string, args: readonly unknown[]) => providers.call({ interface: sessionsInterface, method, args, ...other })
465
- const isAnswer = (error: unknown, code: number) => error instanceof RpcError && error.code === code
466
- const found = await ask('session', [session]).catch(async (error: unknown) => {
467
- if (isAnswer(error, rpcCodes.notHeld)) return undefined
468
- 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) => {
469
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)}`)
470
506
  })
471
- if (isObject(found) && found['isRunning'] === true) return other.device?.name ?? other.mod
507
+ if (found?.isRunning === true) return other.device?.name ?? other.mod
472
508
  }
473
509
  return undefined
474
510
  }
@@ -534,7 +570,7 @@ export function routeSessions({
534
570
  const status = listed.status ?? told.status
535
571
  const recorded = listed.waitingFor
536
572
  const waitingFor = status !== 'waiting' || told.waitingFor === undefined ? recorded : { ...told.waitingFor, ...(recorded === undefined ? {} : { dialog: recorded.dialog }) }
537
- 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 }) }
538
574
  }
539
575
 
540
576
  const implementation: Implementation = {
@@ -635,6 +671,7 @@ export function routeSessions({
635
671
  }
636
672
 
637
673
  const interfaces = interfaceServer({
674
+ hears: (listening, payload) => !isObject(payload) || payload['part'] !== 'messages' || wantsMessages(listening),
638
675
  implementations: { ...Object.fromEntries(names.map((name) => [name, implementation])), [uiInterface]: ui, [providersInterface]: {}, [storeInterface]: store, [programsInterface]: programChanges, ...(terminal === undefined ? {} : { [terminalInterface]: terminal }) },
639
676
  onListen: (_connection, listening) => {
640
677
  if (listening.interface === uiInterface) {
@@ -648,7 +685,7 @@ export function routeSessions({
648
685
  if (listening.event !== 'Change') throw new RpcError(rpcCodes.methodNotFound, listening.interface === providersInterface || isServed(listening.interface) ? `${listening.interface} tells only Change.` : `${listening.interface} tells only Change, because a mod hears only the session it runs in.`)
649
686
  after(0, () => onListen(listening))
650
687
  },
651
- extraMethod: (connection, method, params) => {
688
+ extraMethod: async (connection, method, params) => {
652
689
  if (method === sessionActs.uiEvent) {
653
690
  const holder = holders.get(connection)
654
691
  const { event, payload } = (isObject(params) ? params : {}) as { readonly event?: unknown; readonly payload?: unknown }
@@ -671,6 +708,11 @@ export function routeSessions({
671
708
  changed(params as SessionsChange)
672
709
  return { result: null }
673
710
  }
711
+ if (method === sessionActs.stop) {
712
+ const holder = holders.get(connection)
713
+ if (holder === undefined) throw new RpcError(rpcCodes.notHeld, `${sessionActs.stop} stops the session this connection holds, and it holds none.`)
714
+ return { result: { isStopped: await computer.stop(holder.session) } }
715
+ }
674
716
  if (method === sessionActs.status) {
675
717
  const holder = holders.get(connection)
676
718
  const { session, ...told } = (isObject(params) ? params : {}) as HeldStatus & { readonly session?: unknown }
@@ -817,6 +859,7 @@ export function routeProviders({
817
859
  const forwarded = new Map<RpcConnection, Map<string, Subscription>>()
818
860
  const devices = new Map<string, DeviceServe>()
819
861
  const deviceListeners = new Map<string, InterfaceListeners>()
862
+ const deviceProviders = new Map<string, Map<string, Promise<ProviderIdentity[]>>>()
820
863
  const followed = new WeakSet<ProviderEnd>()
821
864
  let following: Promise<void> = Promise.resolve()
822
865
  const keyOf = ({ mod, program }: ProviderIdentity) => `${mod}\n${program ?? ''}`
@@ -857,6 +900,12 @@ export function routeProviders({
857
900
  throw new RpcError(rpcCodes.methodNotFound, `cmod serve answers ${who} no ${method}.`)
858
901
  }
859
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
+
860
909
  const instances = async (name: string): Promise<Provider[]> => (programs === undefined ? [] : (await readProviders(programs.files, programs.store, name)).filter((each) => each.mod !== cmodPluginName))
861
910
 
862
911
  const ownOf = async (name: string): Promise<ProviderIdentity[]> => {
@@ -876,7 +925,7 @@ export function routeProviders({
876
925
  [...devices.entries()]
877
926
  .filter(([, each]) => isReached(each))
878
927
  .map(([id, each]) =>
879
- peerOf(each).request<ProviderIdentity[]>(providerActs.providers, { interface: name, device: id }).catch((error: unknown) => {
928
+ providersOn(id, each, name).catch((error: unknown) => {
880
929
  report(new Error(`cmod serve lists no ${name} of ${each.name}: ${messageOf(error)}`))
881
930
  return []
882
931
  }),
@@ -901,6 +950,17 @@ export function routeProviders({
901
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)) }
902
951
  : each.client
903
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
+
904
964
  const listenersOf = (id: string) => {
905
965
  const listeners = deviceListeners.get(id) ?? interfaceListeners({ report })
906
966
  deviceListeners.set(id, listeners)
@@ -912,13 +972,16 @@ export function routeProviders({
912
972
  const forward = (id: string, peer: Pick<Peer, 'request'>) => {
913
973
  if (followedDevices.has(id)) return
914
974
  followedDevices.add(id)
915
- listenersOf(id).listen(peer, listeningOf(providersInterface, 'on', 'Change', [], undefined), (told: unknown) => {
916
- if (isObject(told) && typeof told['interface'] === 'string' && isObject(told['device']) && told['device']['id'] === id) changed(told['interface'], { id, name: String(told['device']['name']) })
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']) })
917
979
  })
918
980
  }
919
981
 
920
982
  const drop = (id: string, each: DeviceServe) => {
921
983
  devices.delete(id)
984
+ deviceProviders.delete(id)
922
985
  changed(undefined, { id, name: each.name })
923
986
  if (!isLinked(each)) return each.client.close()
924
987
  each.link.close(new Error(`cmod serve dropped ${each.name}`))
@@ -937,6 +1000,7 @@ export function routeProviders({
937
1000
  })
938
1001
  const each: MessageServe = { name, listeners: listenersOf(id), carrier, link, theirs }
939
1002
  devices.set(id, each)
1003
+ deviceProviders.delete(id)
940
1004
  forward(id, peerOf(each))
941
1005
  link.notify(providerActs.link, { link: link.id, ...(theirs === undefined ? {} : { answers: theirs }) } satisfies Hello)
942
1006
  if (theirs === undefined) return
@@ -982,6 +1046,7 @@ export function routeProviders({
982
1046
  handle: heardBy(listeners, `the cmod serve of ${name}`),
983
1047
  onConnect: async (connected) => {
984
1048
  reached()
1049
+ deviceProviders.delete(id)
985
1050
  changed(undefined, { id, name })
986
1051
  await listeners.replay(connected)
987
1052
  },
@@ -1170,6 +1235,12 @@ export function routeProviders({
1170
1235
  if (end !== undefined) void closeIfExited(end, connection).catch(report)
1171
1236
  },
1172
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)
1173
1244
  await Promise.all([...ends.values()].flatMap((end) => (end.connection !== undefined && end.identity.mod === mod && (end.identity.program ?? mod) === program ? [closeIfExited(end, end.connection)] : [])))
1174
1245
  },
1175
1246
  closed(connection) {
@@ -51,7 +51,7 @@ export function subagentTranscript(sessionTranscript: string | undefined, task:
51
51
  return sessionTranscript?.endsWith('.jsonl') === true ? `${sessionTranscript.slice(0, -'.jsonl'.length)}/subagents/agent-${task}.jsonl` : undefined
52
52
  }
53
53
 
54
- const sessionFields: Readonly<Record<keyof SessionData, true>> = { id: true, title: true, color: true, project: true, cwd: true, transcriptPath: true, model: true, startedAt: true, lastAt: true, forkedFrom: true, isRunning: true, agentType: true, visitedAt: true, device: true, status: true, waitingFor: true, contextPercent: true, lastTurn: true }
54
+ const sessionFields: Readonly<Record<keyof SessionData, true>> = { id: true, title: true, color: true, project: true, cwd: true, transcriptPath: true, model: true, startedAt: true, lastAt: true, forkedFrom: true, isRunning: true, agentType: true, visitedAt: true, device: true, status: true, waitingFor: true, contextPercent: true, lastTurn: true, openCall: true }
55
55
 
56
56
  export function pickedColor(args: string): string | undefined {
57
57
  const picked = args.trim().toLowerCase()
@@ -29,6 +29,7 @@ export type SessionData = {
29
29
  readonly waitingFor?: Session['waitingFor']
30
30
  readonly contextPercent?: number
31
31
  readonly lastTurn?: Session['lastTurn']
32
+ readonly openCall?: Session['openCall']
32
33
  }
33
34
 
34
35
  export type ContextData = Pick<Context, 'number' | 'openedAt' | 'closedAt' | 'task'>
@@ -177,7 +177,8 @@ export type Session = Pick<RecordPart, 'search'> & {
177
177
  readonly status?: 'busy' | 'shell' | 'idle' | 'waiting'
178
178
  readonly waitingFor?: { readonly dialog: string; readonly tool?: string; readonly input?: Readonly<Record<string, unknown>>; readonly question?: string }
179
179
  readonly contextPercent?: number
180
- readonly lastTurn?: { readonly reason: 'answered' | 'stopped' | 'failed'; readonly at: string; readonly failure?: string }
180
+ readonly lastTurn?: { readonly reason: 'answered' | 'stopped' | 'failed'; readonly at: string; readonly failure?: string; readonly reply?: string }
181
+ readonly openCall?: { readonly tool: string; readonly summary: string }
181
182
  readonly goal: Goal
182
183
  context(): Promise<Context>
183
184
  contexts(): Promise<Context[]>
@@ -80,6 +80,7 @@ const unfaked: Omit<SessionComputer, keyof Mailbox> = {
80
80
  unheld: (session) => Promise.reject(notHere(session)),
81
81
  visit: async () => undefined,
82
82
  remove: async () => undefined,
83
+ stop: async () => false,
83
84
  }
84
85
 
85
86
  const deviceLink: ProviderIdentity = { mod: 'testMod', program: 'devices' }
@@ -122,6 +123,7 @@ export function fakeServe(
122
123
  unheld: (...args) => answer('unheld')(...args),
123
124
  visit: (...args) => answer('visit')(...args),
124
125
  remove: (...args) => answer('remove')(...args),
126
+ stop: (...args) => answer('stop')(...args),
125
127
  queue: (...args) => answer('queue')(...args),
126
128
  queued: (...args) => answer('queued')(...args),
127
129
  delivered: (...args) => answer('delivered')(...args),
package/src/utils/text.ts CHANGED
@@ -7,6 +7,18 @@ export function firstLine(text: string): string {
7
7
  return text.split('\n').find((line) => line.trim() !== '')?.trim() ?? ''
8
8
  }
9
9
 
10
+ const summaryChars = 200
11
+
12
+ export function questionOf(input: Readonly<Record<string, unknown>>): string | undefined {
13
+ const question = (input['questions'] as readonly { readonly question?: unknown }[] | undefined)?.[0]?.question
14
+ return typeof question === 'string' ? question : undefined
15
+ }
16
+
17
+ export function callSummary(input: Readonly<Record<string, unknown>>): string {
18
+ const named = [input['command'], input['file_path'], input['path'], input['pattern'], input['url'], input['query'], questionOf(input), input['description'], input['prompt']].find((value) => typeof value === 'string')
19
+ return firstLine(typeof named === 'string' ? named : JSON.stringify(input)).slice(0, summaryChars)
20
+ }
21
+
10
22
  export function messageOf(error: unknown): string {
11
23
  return error instanceof Error ? error.message : String(error)
12
24
  }
@@ -1 +1 @@
1
- {"version":3,"file":"fake-serve.d.ts","sourceRoot":"","sources":["../src/testing/fake-serve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AACzD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAA;AAElD,OAAO,EAAqF,KAAK,cAAc,EAAa,KAAK,YAAY,EAAE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Q,CAAC,KAAK,CAAC,EAAE,UAAU,CAAA;CAAE,GACxJ,SAAS,CAyFX"}
@@ -42,6 +42,7 @@ const unfaked = {
42
42
  unheld: (session) => Promise.reject(notHere(session)),
43
43
  visit: async () => undefined,
44
44
  remove: async () => undefined,
45
+ stop: async () => false,
45
46
  };
46
47
  const deviceLink = { mod: 'testMod', program: 'devices' };
47
48
  const socketOf = (device) => `/test/devices/${device}/serve.sock`;
@@ -79,6 +80,7 @@ export function fakeServe(fakes, { device, programs, clock = realClock }) {
79
80
  unheld: (...args) => answer('unheld')(...args),
80
81
  visit: (...args) => answer('visit')(...args),
81
82
  remove: (...args) => answer('remove')(...args),
83
+ stop: (...args) => answer('stop')(...args),
82
84
  queue: (...args) => answer('queue')(...args),
83
85
  queued: (...args) => answer('queued')(...args),
84
86
  delivered: (...args) => answer('delivered')(...args),
package/utils/text.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export declare function listed(items: readonly string[]): string;
2
2
  export declare function firstLine(text: string): string;
3
+ export declare function questionOf(input: Readonly<Record<string, unknown>>): string | undefined;
4
+ export declare function callSummary(input: Readonly<Record<string, unknown>>): string;
3
5
  export declare function messageOf(error: unknown): string;
4
6
  export declare function formatExit(code: number | null, reason: string): string;
5
7
  //# sourceMappingURL=text.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"text.d.ts","sourceRoot":"","sources":["../src/utils/text.ts"],"names":[],"mappings":"AAAA,wBAAgB,MAAM,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAGvD;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE9C;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEhD;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAItE"}
1
+ {"version":3,"file":"text.d.ts","sourceRoot":"","sources":["../src/utils/text.ts"],"names":[],"mappings":"AAAA,wBAAgB,MAAM,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAGvD;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE9C;AAID,wBAAgB,UAAU,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,MAAM,GAAG,SAAS,CAGvF;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,MAAM,CAG5E;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEhD;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAItE"}
package/utils/text.js CHANGED
@@ -6,6 +6,15 @@ export function listed(items) {
6
6
  export function firstLine(text) {
7
7
  return text.split('\n').find((line) => line.trim() !== '')?.trim() ?? '';
8
8
  }
9
+ const summaryChars = 200;
10
+ export function questionOf(input) {
11
+ const question = input['questions']?.[0]?.question;
12
+ return typeof question === 'string' ? question : undefined;
13
+ }
14
+ export function callSummary(input) {
15
+ const named = [input['command'], input['file_path'], input['path'], input['pattern'], input['url'], input['query'], questionOf(input), input['description'], input['prompt']].find((value) => typeof value === 'string');
16
+ return firstLine(typeof named === 'string' ? named : JSON.stringify(input)).slice(0, summaryChars);
17
+ }
9
18
  export function messageOf(error) {
10
19
  return error instanceof Error ? error.message : String(error);
11
20
  }