@cmodjs/core 8.10.4 → 8.11.1

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'
@@ -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: 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}`) })),
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
- if (!isObject(instance) || typeof instance['address'] !== 'string' || !Array.isArray(instance['provides'])) return []
144
- const provides = (instance as ProgramInstance).provides ?? []
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 && 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)
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 (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)
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; cursor: string | undefined; isPending: boolean }
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 id = `${(next += 1)}`
275
- const each: Registered = { listening: { ...listening, id }, listener, cursor: undefined, isPending: false }
276
- registered.set(id, each)
277
- 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
+ }
278
302
  return {
279
303
  remove() {
280
- if (!registered.delete(id)) return
281
- 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)
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
- void (async () => each.listener(heard.payload as never, signal))().catch(report)
319
+ for (const answer of answers) void answer.catch(report)
293
320
  return undefined
294
321
  }
295
- return (async () => ({ result: (await each.listener(heard.payload as never, signal)) ?? null }))()
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 ask = (method: string, args: readonly unknown[]) => providers.call({ interface: sessionsInterface, method, args, ...other })
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 (isObject(found) && found['isRunning'] === true) return other.device?.name ?? other.mod
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
- peerOf(each).request<ProviderIdentity[]>(providerActs.providers, { interface: name, device: id }).catch((error: unknown) => {
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', [], undefined), (told: unknown) => {
923
- 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']) })
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) {
@@ -733,7 +733,7 @@ export function createLifecycle<State extends object, Declared extends Options =
733
733
  }
734
734
  if (event === 'classic.UserPromptSubmit' && phase === 'active' && !hasHeardSessionStart) {
735
735
  const { session_id, transcript_path, cwd } = e as Frozen<Args<'classic.UserPromptSubmit'>>
736
- await replaySessionStart({ session_id, transcript_path, cwd, hook_event_name: 'SessionStart', source: 'resume' })
736
+ if (session_id === (await claude().session.id())) await replaySessionStart({ session_id, transcript_path, cwd, hook_event_name: 'SessionStart', source: 'resume' })
737
737
  }
738
738
  const answer = router.dispatch(event, e, next, signal)
739
739
  const render = e as Frozen<Args<'ui.render'>>
@@ -1149,6 +1149,7 @@ async function createMod<State extends object, Declared extends Options>(definit
1149
1149
  router.add('classic.UserPromptSubmit', async (e, next) => {
1150
1150
  staleCwd = undefined
1151
1151
  await followSession()
1152
+ if (e.session_id !== (await claude.session.id())) return next(e)
1152
1153
  const isPerson = e.source === undefined || e.source === 'user' || e.source === 'sdk'
1153
1154
  await followCurrent(e.session_id, e.session_title || (isPerson && !hasEarlierPrompts && client.sessions.current.title === '' ? firstLine(e.prompt) : undefined)).catch((error: unknown) => report({ id: 'cmod:current', message: 'Kept the details of the session from before', error }))
1154
1155
  return next(e)
@@ -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[]>
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
  }
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
  }