@cmodjs/core 6.3.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/docs/commands.md +123 -65
  2. package/docs/dependencies.md +189 -4
  3. package/docs/index.md +56 -12
  4. package/docs/install-steps.md +20 -17
  5. package/docs/jobs.md +43 -16
  6. package/docs/mod.md +43 -27
  7. package/docs/options.md +2 -2
  8. package/docs/session.md +58 -32
  9. package/docs/testing.md +88 -24
  10. package/docs/ui.md +128 -58
  11. package/installer.d.ts +2 -2
  12. package/jobs/context.js +1 -1
  13. package/jobs/program.d.ts +4 -1
  14. package/jobs/program.d.ts.map +1 -1
  15. package/jobs/program.js +79 -20
  16. package/mod.d.ts +59 -9
  17. package/mod.d.ts.map +1 -1
  18. package/mod.js +5 -3
  19. package/package.json +1 -1
  20. package/records.d.ts +15 -2
  21. package/records.d.ts.map +1 -1
  22. package/records.js +24 -10
  23. package/register.d.ts.map +1 -1
  24. package/register.js +7 -4
  25. package/rpc.d.ts +7 -0
  26. package/rpc.d.ts.map +1 -0
  27. package/rpc.js +59 -0
  28. package/runtime/bound.d.ts +1 -0
  29. package/runtime/bound.d.ts.map +1 -1
  30. package/runtime/bound.js +10 -0
  31. package/runtime/bun.d.ts +20 -0
  32. package/runtime/bun.d.ts.map +1 -0
  33. package/runtime/bun.js +20 -0
  34. package/runtime/claude.d.ts +1 -0
  35. package/runtime/claude.d.ts.map +1 -1
  36. package/runtime/conversations.d.ts +12 -1
  37. package/runtime/conversations.d.ts.map +1 -1
  38. package/runtime/conversations.js +472 -362
  39. package/runtime/deadline.d.ts +4 -3
  40. package/runtime/deadline.d.ts.map +1 -1
  41. package/runtime/deadline.js +10 -4
  42. package/runtime/engine.d.ts +5 -4
  43. package/runtime/engine.d.ts.map +1 -1
  44. package/runtime/installer.d.ts +3 -3
  45. package/runtime/installer.d.ts.map +1 -1
  46. package/runtime/installer.js +10 -9
  47. package/runtime/interfaces.d.ts +262 -0
  48. package/runtime/interfaces.d.ts.map +1 -0
  49. package/runtime/interfaces.js +935 -0
  50. package/runtime/lifecycle.d.ts +3 -3
  51. package/runtime/lifecycle.d.ts.map +1 -1
  52. package/runtime/lifecycle.js +83 -52
  53. package/runtime/options.d.ts.map +1 -1
  54. package/runtime/options.js +2 -6
  55. package/runtime/parts.d.ts +64 -1
  56. package/runtime/parts.d.ts.map +1 -1
  57. package/runtime/parts.js +311 -4
  58. package/runtime/programs.d.ts +1 -0
  59. package/runtime/programs.d.ts.map +1 -1
  60. package/runtime/programs.js +5 -3
  61. package/runtime/rpc.d.ts +111 -0
  62. package/runtime/rpc.d.ts.map +1 -0
  63. package/runtime/rpc.js +387 -0
  64. package/runtime/sessions.d.ts +6 -4
  65. package/runtime/sessions.d.ts.map +1 -1
  66. package/runtime/sessions.js +59 -80
  67. package/runtime/toaster.js +1 -1
  68. package/runtime/ui.d.ts +23 -10
  69. package/runtime/ui.d.ts.map +1 -1
  70. package/runtime/ui.js +63 -52
  71. package/runtime/web.d.ts +0 -73
  72. package/runtime/web.d.ts.map +1 -1
  73. package/runtime/web.js +9 -5
  74. package/runtime/widgets.d.ts +4 -2
  75. package/runtime/widgets.d.ts.map +1 -1
  76. package/runtime/widgets.js +17 -16
  77. package/session/conversation.d.ts +7 -1
  78. package/session/conversation.d.ts.map +1 -1
  79. package/session/session.d.ts +31 -7
  80. package/session/session.d.ts.map +1 -1
  81. package/session/session.js +1 -0
  82. package/src/installer.ts +2 -2
  83. package/src/jobs/context.ts +1 -1
  84. package/src/jobs/program.ts +76 -21
  85. package/src/mod.ts +51 -10
  86. package/src/records.ts +33 -9
  87. package/src/register.ts +7 -4
  88. package/src/rpc.ts +67 -0
  89. package/src/runtime/bound.ts +10 -0
  90. package/src/runtime/bun.ts +40 -0
  91. package/src/runtime/claude.ts +1 -0
  92. package/src/runtime/conversations.ts +470 -352
  93. package/src/runtime/deadline.ts +13 -6
  94. package/src/runtime/engine.ts +5 -4
  95. package/src/runtime/installer.ts +13 -12
  96. package/src/runtime/interfaces.ts +1161 -0
  97. package/src/runtime/lifecycle.ts +102 -59
  98. package/src/runtime/options.ts +2 -5
  99. package/src/runtime/parts.ts +364 -5
  100. package/src/runtime/programs.ts +6 -3
  101. package/src/runtime/rpc.ts +457 -0
  102. package/src/runtime/sessions.ts +63 -83
  103. package/src/runtime/toaster.ts +1 -1
  104. package/src/runtime/ui.ts +82 -61
  105. package/src/runtime/web.ts +10 -39
  106. package/src/runtime/widgets.ts +20 -18
  107. package/src/session/conversation.ts +7 -1
  108. package/src/session/session.ts +22 -7
  109. package/src/testing/fake-claude.ts +38 -7
  110. package/src/testing/fake-serve.ts +144 -0
  111. package/src/testing/fake-sessions.ts +21 -6
  112. package/src/testing.ts +156 -68
  113. package/src/ui/areas.ts +2 -2
  114. package/src/ui/elements.ts +21 -16
  115. package/src/ui/panes.ts +14 -7
  116. package/testing/fake-claude.d.ts +6 -0
  117. package/testing/fake-claude.d.ts.map +1 -1
  118. package/testing/fake-claude.js +34 -7
  119. package/testing/fake-serve.d.ts +39 -0
  120. package/testing/fake-serve.d.ts.map +1 -0
  121. package/testing/fake-serve.js +110 -0
  122. package/testing/fake-sessions.d.ts.map +1 -1
  123. package/testing/fake-sessions.js +22 -6
  124. package/testing.d.ts +21 -4
  125. package/testing.d.ts.map +1 -1
  126. package/testing.js +138 -56
  127. package/ui/areas.d.ts +3 -1
  128. package/ui/areas.d.ts.map +1 -1
  129. package/ui/elements.d.ts +18 -9
  130. package/ui/elements.d.ts.map +1 -1
  131. package/ui/elements.js +9 -8
  132. package/ui/panes.d.ts +10 -6
  133. package/ui/panes.d.ts.map +1 -1
  134. package/ui/panes.js +5 -3
  135. package/runtime/pages.d.ts +0 -32
  136. package/runtime/pages.d.ts.map +0 -1
  137. package/runtime/pages.js +0 -142
  138. package/src/runtime/pages.ts +0 -183
@@ -1,5 +1,5 @@
1
1
  import type { Args, EventResult, Frozen } from 'claude-code'
2
- import { coreVersion, dataFolder, isObject } from '../records.js'
2
+ import { coreVersion, dataFolder, isObject, serveSocketPath } from '../records.js'
3
3
  import { Message, rowOfAppend, type Row } from '../session/context/turn/message/message.js'
4
4
  import { modNote, Note } from '../session/context/turn/message/note.js'
5
5
  import { Person } from '../session/context/turn/message/sender.js'
@@ -11,65 +11,64 @@ import { 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 { formatExit, messageOf } from '../utils/text.js'
14
+ import { messageOf } 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
- import { newestCmodVersion, readLines, runCmod, spawnCmod } from './programs.js'
18
+ import { MissingMachineId } from './device.js'
19
+ import { interfaceListeners, interfaceMethods, providerActs, providerPeer, serveProviders, sessionActs, sessionsInterface, uiInterface, type HeldStatus, type Implementation, type Provided, type ProvidedHeard, type ProviderIdentity, type StoreChange } from './interfaces.js'
20
+ import { runCmod } from './programs.js'
21
+ import { addressCall, connectRpc, RpcError, rpcCodes, type RpcClient } from './rpc.js'
19
22
  import type { RoutedHook, Router } from './router.js'
20
- import { PassedTimeout } from './deadline.js'
23
+ import { toolInputOf } from './tool-calls.js'
21
24
  import { conversationMethods, everySession, isAct, isHeardBy, isInScope, pickedColor, resultOf, spawnTask, usageOf, type Act, type Listened, type SessionColor } from './sessions.js'
22
25
 
23
26
  type Request = Readonly<Record<string, unknown>>
24
27
 
25
28
  type Heard = { readonly event: Listened['event']; readonly matcher: unknown }
26
29
 
27
- type Watch = { readonly mod: string; readonly target: string; readonly project: string; readonly events: readonly string[]; readonly refusing?: readonly Listened[] }
28
-
29
- type Watcher = Watch & { readonly from: string }
30
-
31
- type Question =
32
- | { readonly kind: 'act'; readonly caller: string; readonly action: Act; readonly input: unknown; readonly task?: string }
33
- | { readonly kind: 'before'; readonly mod: string; readonly event: BeforeEvent; readonly change: SessionChange; readonly project: string }
30
+ type Watch = { readonly mod: string; readonly target: string; readonly list: readonly Listened[] }
34
31
 
35
32
  type Relay =
36
- | (Question & { readonly id: string; readonly from: string })
37
- | { readonly kind: 'answer'; readonly id: string; readonly value?: unknown; readonly deny?: string }
38
- | { readonly kind: 'watch' }
33
+ | { readonly kind: 'act'; readonly id: string; readonly from: string; readonly caller: string; readonly action: Act; readonly input: unknown; readonly task?: string }
39
34
  | { readonly kind: 'goal'; readonly task?: string; readonly text: string }
40
35
  | { readonly kind: 'taskEnd'; readonly task: TaskData }
41
36
 
42
- const relayKinds: ReadonlySet<unknown> = new Set(['act', 'before', 'answer', 'watch', 'goal', 'taskEnd'] satisfies Relay['kind'][])
37
+ const relayKinds: ReadonlySet<unknown> = new Set(['act', 'goal', 'taskEnd'] satisfies Relay['kind'][])
43
38
 
44
39
  const taskVariable = 'CMOD_TASK'
45
40
 
46
41
  const isRelay = (value: unknown): value is Relay => isObject(value) && relayKinds.has(value['kind'])
47
42
 
48
- type Asked = { resolve(value: unknown): void; reject(error: Error): void }
49
-
50
-
51
43
  const bufferedTaskRows = 200
52
44
 
53
- const beforeDeadlineMs = 5000
54
-
55
- const awayFoldMs = 8000
56
-
57
- const livenessMs = 5000
45
+ const questionTool = 'AskUserQuestion'
58
46
 
47
+ const permissionPrompt = 'permission prompt'
59
48
 
60
49
  export type Conversations = {
61
50
  answer(e: Frozen<Args<'cmod.call'>> & { readonly caller?: string }): Promise<EventResult<'cmod.call'> | undefined>
62
51
  moved(): void
63
52
  turnClosedBy(rowId: string): TurnData | undefined
53
+ onTurnClosed(listener: (turn: TurnData) => void): void
64
54
  color(): SessionColor
65
55
  onColor(listener: (told: SessionColor) => void): void
56
+ onUnreached(listener: () => void): void
57
+ serveUi(methods: Implementation): void
58
+ tellUi(event: string, payload: object): void
59
+ provide(name: string, methods: Implementation): Provided
60
+ close(): Promise<void>
66
61
  }
67
62
 
68
63
  const keptClosings = 200
69
64
 
70
65
  const keptMessages = 200
71
66
 
72
- const noWatches = '[]'
67
+ type Kept = { readonly subscribed: Readonly<Record<string, Readonly<Record<string, readonly Listened[]>>>>; readonly watched: Readonly<Record<string, Readonly<Record<string, readonly Listened[]>>>> }
68
+
69
+ type Registered = { remove(): void }
70
+
71
+ type OtherProvider = { readonly identity: ProviderIdentity; readonly peer: Pick<RpcClient, 'request'>; readonly change: Registered }
73
72
 
74
73
  export function serveConversations({
75
74
  claude,
@@ -78,6 +77,10 @@ export function serveConversations({
78
77
  project,
79
78
  report,
80
79
  clear,
80
+ keepsConnecting = true,
81
+ sessionCode = () => [],
82
+ provider,
83
+ tell = (caller, heard) => new Promise((resolve) => claude.clock.after(0, () => resolve(claude.cmod.call({ to: caller, method: interfaceMethods.heard, input: heard })))),
81
84
  }: {
82
85
  readonly claude: Claude
83
86
  readonly router: Router
@@ -85,45 +88,111 @@ export function serveConversations({
85
88
  readonly project: () => string
86
89
  readonly report: (id: string, message: string, error: unknown) => void
87
90
  readonly clear: (id: string) => void
91
+ readonly keepsConnecting?: boolean
92
+ readonly sessionCode?: (name: string) => readonly string[]
93
+ readonly provider?: ProviderIdentity
94
+ readonly tell?: (caller: string, heard: ProvidedHeard, signal: AbortSignal) => Promise<unknown>
88
95
  }): Conversations {
89
96
  const folder = dataFolder(store, cmodPluginName)
90
97
  const goals = `${folder}/goals`
91
98
  const backgroundTasks = `${folder}/tasks`
92
- const watches = `${folder}/before`
93
99
  const listeners = `${folder}/listeners`
94
100
  const heard = new Map<string, Map<string, readonly Heard[]>>()
95
101
  const subscribed = new Map<string, Map<string, readonly Listened[]>>()
102
+ const watched = new Map<string, Watch>()
96
103
  let listenerFiles: Promise<unknown> = Promise.resolve()
97
- const asked = new Map<string, Asked>()
98
- const ownWatches = new Map<string, Watch>()
99
- let watchers: readonly Watcher[] = []
100
- let watching: Promise<void> = Promise.resolve()
101
- let hasReadWatchers = false
102
- let published = new Set<string>()
103
- let publishing: Promise<unknown> = Promise.resolve()
104
104
  let session = ''
105
- const left = new Set<string>()
106
- let asks = 0
107
105
  let conversation: Conversation = createConversation(emptyConversation(''))
108
106
  let starting: Promise<void> = Promise.resolve()
107
+ let listening: Promise<void> = Promise.resolve()
108
+ let hasHeardListeners = false
109
109
  let live: Message[] = []
110
110
  const liveIds = new Set<string>()
111
111
  const waitingRows = new Map<string, Row[]>()
112
- let follower: { readonly sessions: string; stop(): void } | undefined
113
112
  const engineTurns = new Map<string, string>()
113
+ let endsAfterTurn = false
114
+ let isWorking = false
115
+ let waitingFor: HeldStatus['waitingFor']
116
+ let waitingOn: string | undefined
117
+ let contextPercent: number | undefined
118
+ let endedTurn: HeldStatus['lastTurn']
119
+ let failedWith: string | undefined
120
+ const openCalls = new Map<string, ToolCallArgs>()
121
+ const tellStatus = () => {
122
+ if (session === '') return
123
+ local.client.notify(sessionActs.status, { session, status: waitingFor !== undefined ? 'waiting' : isWorking ? 'busy' : 'idle', ...(waitingFor === undefined ? {} : { waitingFor }), ...(contextPercent === undefined ? {} : { contextPercent }), ...(endedTurn === undefined ? {} : { lastTurn: endedTurn }) } satisfies HeldStatus & { readonly session: string })
124
+ }
125
+ const waitFor = (callId: string) => {
126
+ const call = openCalls.get(callId)
127
+ if (call === undefined) return
128
+ const question = call.name === questionTool ? (call.input['questions'] as readonly { readonly question?: unknown }[] | undefined)?.[0]?.question : undefined
129
+ waitingFor = typeof question === 'string' ? { dialog: permissionPrompt, question } : { dialog: permissionPrompt, tool: call.name, input: call.input }
130
+ waitingOn = callId
131
+ tellStatus()
132
+ }
133
+ const turnMoved = (isStarted: boolean) => {
134
+ isWorking = isStarted
135
+ if (isStarted) {
136
+ endedTurn = undefined
137
+ failedWith = undefined
138
+ }
139
+ waitingFor = undefined
140
+ waitingOn = undefined
141
+ openCalls.clear()
142
+ tellStatus()
143
+ }
114
144
  router.add('turn.start', async (e, next) => {
115
145
  const agent = (e as typeof e & { readonly agentId?: string }).agentId ?? ''
116
146
  engineTurns.set(agent, e.turnId)
147
+ if (agent === '') turnMoved(true)
148
+ return next(e)
149
+ })
150
+ router.add('turn.complete', async (e, next) => {
151
+ const completed = await next(e)
152
+ if (e.agentId !== undefined) return completed
153
+ const reason = e.reason === 'answer' ? 'answered' : e.reason === 'aborted' ? 'stopped' : 'failed'
154
+ const failure = e.reason === 'refusal' ? (e.refusal.explanation ?? e.refusal.category ?? 'Claude refused to answer.') : failedWith
155
+ endedTurn = { reason, at: new Date().toISOString(), ...(reason === 'failed' && failure !== undefined ? { failure } : {}) }
156
+ turnMoved(false)
157
+ return completed
158
+ })
159
+ router.add('tool.call', async (e, next) => {
160
+ if (e.agentId !== undefined) return next(e)
161
+ openCalls.set(e.tool_use_id, { name: e.tool, input: toolInputOf(e) })
162
+ if (e.tool === questionTool) waitFor(e.tool_use_id)
163
+ try {
164
+ return await next(e)
165
+ } finally {
166
+ openCalls.delete(e.tool_use_id)
167
+ if (waitingOn === e.tool_use_id) {
168
+ waitingFor = undefined
169
+ waitingOn = undefined
170
+ tellStatus()
171
+ }
172
+ }
173
+ })
174
+ router.add('classic.Notification', async (e, next) => {
175
+ const last = [...openCalls.keys()].at(-1)
176
+ if (e.notification_type === 'permission_prompt' && last !== undefined) waitFor(last)
117
177
  return next(e)
118
178
  })
119
179
  const endTurn = (ending: TurnEnding, task?: string) => <Below extends { readonly block?: string }>(below: Below, isInterrupted = false): Below => {
120
180
  if (below.block !== undefined) return below
121
181
  engineTurns.delete(task ?? '')
122
- if (!isInterrupted) dispatch(session, conversation.endTurn(new Date().toISOString(), ending, task))
182
+ if (!isInterrupted) dispatch(conversation.endTurn(new Date().toISOString(), ending, task))
183
+ if (task === undefined && endsAfterTurn) claude.clock.after(0, () => void exitNow())
123
184
  return below
124
185
  }
125
186
  router.add('classic.Stop', async (e, next) => endTurn({ reason: 'answer', ...(e.last_assistant_message === undefined ? {} : { answer: e.last_assistant_message }) })(await next(e), next.signal.aborted))
126
- router.add('classic.StopFailure', async (e, next) => endTurn({ reason: 'error', failure: { type: String(e.error), text: e.error_details ?? e.last_assistant_message ?? String(e.error) } })(await next(e)))
187
+ router.add('classic.StopFailure', async (e, next) => {
188
+ const text = e.error_details ?? e.last_assistant_message ?? String(e.error)
189
+ failedWith = text
190
+ if (endedTurn?.reason === 'failed' && endedTurn.failure === undefined) {
191
+ endedTurn = { ...endedTurn, failure: text }
192
+ tellStatus()
193
+ }
194
+ return endTurn({ reason: 'error', failure: { type: String(e.error), text } })(await next(e))
195
+ })
127
196
  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))
128
197
  router.add('classic.Stop', async (e, next) => {
129
198
  const below = await next(e)
@@ -131,11 +200,129 @@ export function serveConversations({
131
200
  return below
132
201
  })
133
202
 
134
- const json = async <Value>(args: readonly string[]): Promise<Value> => JSON.parse(await runCmod(claude, [...args, '--json', '--project', project()], await claude.session.id())) as Value
135
-
136
203
  const ended = (id: string) => new Error(`session ${id} has ended`)
137
204
 
138
- const isRunning = async (id: string) => (await json<SessionData[]>(['history', 'sessions', '--running', '--all'])).some((each) => each.id === id)
205
+ const call = (address: string) => addressCall((url, init) => claude.http.fetch(url, init), address)
206
+
207
+ const held = interfaceListeners({ report: (error) => report('listen', 'Missed a change a sessions provider told', error) })
208
+
209
+ let ui: Implementation = {}
210
+
211
+ const handle = async (method: string, params: unknown, signal: AbortSignal): Promise<unknown> => {
212
+ const answered = await held.handler(method, params, signal)
213
+ if (answered !== undefined) return answered.result
214
+ if (method === sessionActs.act) {
215
+ const { action, input, caller, task } = params as { readonly action: string; readonly input: unknown; readonly caller?: string; readonly task?: string }
216
+ if (!isAct(action)) throw new RpcError(rpcCodes.methodNotFound, (await unknownTo(`"${action}" action`)).message)
217
+ return perform(caller ?? cmodPluginName, action, input, task)
218
+ }
219
+ if (method === sessionActs.ui) {
220
+ const { method: called, args } = params as { readonly method: string; readonly args: readonly unknown[] }
221
+ if (args[0] !== session) throw new RpcError(rpcCodes.notHeld, `The cmod plugin of session ${session} shows no UI of session ${String(args[0])}.`)
222
+ const run = Object.hasOwn(ui, called) ? (ui[called] as (...each: readonly unknown[]) => unknown) : undefined
223
+ if (run === undefined) throw new RpcError(rpcCodes.methodNotFound, `The cmod plugin of session ${session} answers no ${uiInterface}.${called}.`)
224
+ return run(...args)
225
+ }
226
+ const provided = served.handler(method, params, signal)
227
+ if (provided !== undefined) return provided
228
+ throw new RpcError(rpcCodes.methodNotFound, `The cmod plugin of session ${session} answers no ${method}.`)
229
+ }
230
+
231
+ const holdHere = async (client: RpcClient) => {
232
+ if (session === '') return
233
+ await client.request(sessionActs.hold, { session, project: project(), cwd: await claude.session.cwd() })
234
+ }
235
+
236
+ let serveChanges: Registered | undefined
237
+ let isUnreached = false
238
+ let unreached: () => void = () => undefined
239
+ const local: { readonly client: RpcClient } = {
240
+ client: connectRpc({
241
+ call: call(`unix:${serveSocketPath(store)}`),
242
+ handle,
243
+ onConnect: async (client) => {
244
+ isUnreached = false
245
+ await holdHere(client)
246
+ tellStatus()
247
+ await served.replay()
248
+ await held.replay(client)
249
+ await reconcileTasks()
250
+ },
251
+ onError: (error) => {
252
+ claude.ui.warn('serve:connect', `cmod: this session waits for cmod serve: ${messageOf(error)}`)
253
+ isUnreached = true
254
+ unreached()
255
+ },
256
+ wait: (ms) => new Promise<void>((resolve) => void claude.clock.after(ms, resolve)),
257
+ keepsConnecting,
258
+ }),
259
+ }
260
+
261
+ const served = serveProviders({
262
+ serve: local.client,
263
+ listeners: held,
264
+ ...(provider === undefined ? {} : { provider }),
265
+ tell,
266
+ sessionCode,
267
+ device: async () => {
268
+ const { id, name } = await claude.device.read().catch((error: unknown) => {
269
+ if (error instanceof MissingMachineId) return { id: '', name: '' }
270
+ throw error
271
+ })
272
+ return { id, name }
273
+ },
274
+ after: (ms, run) => claude.clock.after(ms, run),
275
+ report: (error) => report('providers', 'A provider listener failed', error),
276
+ })
277
+
278
+ const others = new Map<string, OtherProvider>()
279
+ const keyOf = ({ mod, program, device }: ProviderIdentity) => `${device?.id ?? ''}\n${mod}\n${program ?? ''}`
280
+ const otherProviders = async () => {
281
+ const found = await local.client.request<ProviderIdentity[]>(providerActs.providers, { interface: sessionsInterface })
282
+ const keys = new Set(found.map(keyOf))
283
+ for (const [key, other] of others) {
284
+ if (keys.has(key)) continue
285
+ others.delete(key)
286
+ other.change.remove()
287
+ }
288
+ for (const identity of found) if (!others.has(keyOf(identity))) others.set(keyOf(identity), followProvider(identity))
289
+ return [...others.values()]
290
+ }
291
+
292
+ const followProvider = (identity: ProviderIdentity): OtherProvider => {
293
+ const peer = providerPeer(local.client, identity)
294
+ const change = held.listen(local.client, { interface: sessionsInterface, event: 'Change', kind: 'on', provider: identity }, (told: StoreChange) => {
295
+ if (told.part === 'running') void closeEndedOn(peer, [told.session]).catch((error: unknown) => report('tasks', `Could not read whether a task ${identity.mod} runs ended`, error))
296
+ })
297
+ return { identity, peer, change }
298
+ }
299
+
300
+ const providers = async () => [local.client, ...(await otherProviders()).map((other) => other.peer)]
301
+
302
+ const isNotHeld = (error: unknown) => error instanceof RpcError && error.code === rpcCodes.notHeld
303
+
304
+ const firstHolding = async <Value>(ask: (client: Pick<RpcClient, 'request'>) => Promise<Value>, clients?: readonly Pick<RpcClient, 'request'>[]): Promise<Value> => {
305
+ let last: unknown
306
+ for (const client of clients ?? (await providers())) {
307
+ try {
308
+ return await ask(client)
309
+ } catch (error) {
310
+ if (!isNotHeld(error)) throw error
311
+ last = error
312
+ }
313
+ }
314
+ throw last instanceof Error ? last : new Error(String(last))
315
+ }
316
+
317
+ const read = <Value>(id: string, part: string, options: Request = {}): Promise<Value> => firstHolding((client) => client.request<Value>(`${sessionsInterface}.read`, [id, part, { project: project(), ...options }]))
318
+
319
+ const listAll = async (scope: Request): Promise<SessionData[]> => {
320
+ const lists = await Promise.all((await providers()).map((client) => client.request<SessionData[]>(`${sessionsInterface}.sessions`, [scope]).catch((error: unknown) => (client === local.client ? Promise.reject(error) : (report('store', 'Lists no sessions of another sessions provider', error), [])))))
321
+ const seen = new Set<string>()
322
+ return lists.flat().filter((each) => !seen.has(each.id) && Boolean(seen.add(each.id)))
323
+ }
324
+
325
+ const actOn = (target: string, action: Act, input: unknown, context: Request) => firstHolding((client) => client.request(`${sessionsInterface}.${action}`, [target, input, { project: project(), ...context }]))
139
326
 
140
327
  let color: SessionColor = { session: '' }
141
328
  let onColor: (told: SessionColor) => void = () => undefined
@@ -147,7 +334,7 @@ export function serveConversations({
147
334
  }
148
335
 
149
336
  const readColor = (id: string) =>
150
- void json<SessionData[]>(['history', 'sessions', '--running', '--all'])
337
+ void listAll({ project: project(), everyProject: true, running: true })
151
338
  .then((running) => recolor(id, running.find((each) => each.id === id)?.color))
152
339
  .catch((error: unknown) => report('color', `Could not read the color of session ${id}`, error))
153
340
 
@@ -159,138 +346,62 @@ export function serveConversations({
159
346
  return answer
160
347
  })
161
348
 
349
+ const isUnderHere = (task: string, ancestor: string) => {
350
+ for (let at: string | undefined = task, steps = 0; at !== undefined && steps < 64; at = conversation.state.tasks[at]?.parent, steps += 1) if (at === ancestor) return true
351
+ return false
352
+ }
353
+
162
354
  let lastTurn: TurnData | undefined
163
355
  const closings = new Map<string, TurnData>()
164
- const dispatch = (to: string, changes: readonly SessionChange[], isInProject = true) => {
356
+ let onTurnClosed: (turn: TurnData) => void = () => undefined
357
+ const dispatch = (changes: readonly SessionChange[]) => {
165
358
  for (const change of changes) {
166
- if (to === session && (change.type === TurnStart || change.type === TurnEnd) && change.turn.prompt.task === undefined) lastTurn = change.turn
167
- if (change.type === Message && !liveIds.has(change.message.id) && to === session) {
359
+ if ((change.type === TurnStart || change.type === TurnEnd) && change.turn.prompt.task === undefined) lastTurn = change.turn
360
+ if (change.type === Message && !liveIds.has(change.message.id)) {
168
361
  live.push(change.message)
169
362
  liveIds.add(change.message.id)
170
363
  if (live.length > keptMessages) liveIds.delete(live.shift()?.id ?? '')
171
364
  }
172
365
  for (const [mod, sessions] of heard) {
173
- const subscriptions = [...(sessions.get(to) ?? []), ...(isInProject ? (sessions.get(everySession) ?? []) : [])]
366
+ const subscriptions = [...(sessions.get(session) ?? []), ...(sessions.get(everySession) ?? [])]
174
367
  if (!subscriptions.some(({ event, matcher }) => isHeardBy(event, matcher, change))) continue
175
- void claude.cmod.call({ to: mod, method: conversationMethods.changed, input: { session: to, change, isInProject } }).then(
368
+ void claude.cmod.call({ to: mod, method: conversationMethods.changed, input: { session, change, isInProject: true } }).then(
176
369
  () => clear(`changed:${mod}`),
177
- (error: unknown) => (isNotInstalled(mod, error) ? forgetListeners(mod) : report(`changed:${mod}`, `Could not tell ${mod} about session ${to}`, error)),
370
+ (error: unknown) => (isNotInstalled(mod, error) ? forgetMod(mod) : report(`changed:${mod}`, `Could not tell ${mod} about session ${session}`, error)),
178
371
  )
179
372
  }
180
373
  }
181
374
  }
182
375
 
183
- const restartFollower = async () => {
184
- if (session === '') return
185
- const wantsEvery = [...heard.values()].some((sessions) => (sessions.get(everySession) ?? []).length > 0)
186
- const named = [...heard.values()].flatMap((sessions) => [...sessions].filter(([id, list]) => id !== session && id !== everySession && list.length > 0).map(([id]) => id))
187
- const others = [...new Set(named)].sort()
188
- const args = [...others, ...(wantsEvery ? ['--running'] : [])]
189
- const wanted = [session, project(), ...args].join(' ')
190
- if (follower?.sessions === wanted) return
191
- follower?.stop()
192
- follower = undefined
193
- if (args.length === 0) return
194
- const version = newestCmodVersion(claude)
195
- const stream = spawnCmod(claude, ['history', 'follow', ...args, '--json', '--project', project()], session)
196
- const started = { sessions: wanted, stop: () => void stream.return(undefined as never) }
197
- follower = started
198
- const followed = readLines(stream, (line) => {
199
- if (line.trim() === '') return
200
- const parsed = JSON.parse(line) as { readonly session: string; readonly isInProject: boolean; readonly change: SessionChange }
201
- dispatch(parsed.session, [parsed.change], parsed.isInProject)
202
- })
203
- void Promise.all([version, followed])
204
- .then(([, { code, lastError }]) => {
205
- if (follower === started) throw new Error(`cmod history follow ${formatExit(code, lastError)}`)
206
- })
207
- .catch(async (error: unknown) => {
208
- if (follower !== started) return
209
- follower = undefined
210
- started.stop()
211
- if ((await newestCmodVersion(claude)) === (await version)) throw error
212
- follow()
213
- })
214
- .catch((error: unknown) => report('follow', 'Stopped hearing the other sessions', error))
215
- }
216
-
217
- const follow = () => void restartFollower().catch((error: unknown) => report('follow', 'Stopped hearing the other sessions', error))
218
-
219
- const post = async (to: string, relay: Relay) => {
376
+ const post = async (to: string, relay: unknown) => {
220
377
  const sent = await claude.session.send({ to: { sessionId: to }, text: `<cmod-relay>${JSON.stringify(relay)}</cmod-relay>` })
221
378
  if (sent.isDelivered !== true) throw ended(to)
222
379
  }
223
380
 
224
- const waitingOn = new Map<Asked, string>()
225
- let liveness: { cancel(): void } | undefined
226
- let isChecking = false
227
- const checkLiveness = async () => {
228
- if (isChecking) return
229
- isChecking = true
230
- try {
231
- const waiting = [...waitingOn]
232
- const running = new Set((await json<SessionData[]>(['history', 'sessions', '--running', '--all'])).map((each) => each.id))
233
- for (const [settle, to] of waiting) if (!running.has(to)) settle.reject(ended(to))
234
- } finally {
235
- isChecking = false
236
- }
237
- }
238
- const watchLife = (settle: Asked, to: string) => {
239
- waitingOn.set(settle, to)
240
- liveness ??= claude.clock.every(livenessMs, () => void checkLiveness().catch((error: unknown) => report('liveness', 'Could not check which sessions still run', error)))
241
- return {
242
- cancel() {
243
- waitingOn.delete(settle)
244
- if (waitingOn.size > 0) return
245
- liveness?.cancel()
246
- liveness = undefined
247
- },
248
- }
381
+ const onListenerFiles = <Value>(work: () => Promise<Value>) => {
382
+ const next = listenerFiles.then(work)
383
+ listenerFiles = next.catch((error: unknown) => claude.ui.warn('listeners:files', `cmod: reading or writing the mods' listeners failed: ${messageOf(error)}`))
384
+ return next
249
385
  }
250
386
 
251
- const ask = (to: string, relay: Question, deadlineMs?: number) =>
252
- new Promise<unknown>((resolve, reject) => {
253
- const id = `${session}:${(asks += 1)}`
254
- const settle: Asked = {
255
- resolve(value) {
256
- if (asked.delete(id)) timer.cancel()
257
- resolve(value)
258
- },
259
- reject(error) {
260
- if (asked.delete(id)) timer.cancel()
261
- reject(error)
262
- },
263
- }
264
- const timer = deadlineMs === undefined ? watchLife(settle, to) : claude.clock.after(deadlineMs, () => settle.reject(new PassedTimeout(`session ${to} did not answer within ${deadlineMs / 1000} s`)))
265
- asked.set(id, settle)
266
- post(to, { ...relay, id, from: session }).catch((error: unknown) => settle.reject(error instanceof Error ? error : new Error(messageOf(error))))
267
- })
387
+ const keptOf = (): Kept => ({
388
+ subscribed: Object.fromEntries([...subscribed].map(([caller, lists]) => [caller, Object.fromEntries(lists)])),
389
+ watched: [...watched.values()].reduce<Record<string, Record<string, readonly Listened[]>>>((all, watch) => ({ ...all, [watch.mod]: { ...all[watch.mod], [watch.target]: watch.list } }), {}),
390
+ })
268
391
 
269
- const publishWatches = (isEnding = false) => {
270
- const next = publishing.then(() => publishNow(isEnding))
271
- publishing = next.catch((error: unknown) => claude.ui.warn('before:publish', `cmod: publishing before listeners failed: ${messageOf(error)}`))
272
- return next
392
+ const saveListeners = (isEnding = false) => {
393
+ const at = session
394
+ if (at === '') return Promise.resolve()
395
+ return onListenerFiles(() => claude.fs.write(`${listeners}/${at}.json`, JSON.stringify(isEnding ? ({ subscribed: {}, watched: {} } satisfies Kept) : keptOf())))
273
396
  }
274
397
 
275
- const publishNow = async (isEnding: boolean) => {
276
- if (session === '') return
398
+ const restoreListeners = () => {
277
399
  const at = session
278
- const list = await onListenerFiles(async () => {
279
- const kept = isEnding ? [] : [...ownWatches.values()].filter((watch) => watch.events.length > 0)
280
- await claude.fs.write(`${watches}/${at}.json`, JSON.stringify(kept))
281
- return kept
400
+ return onListenerFiles(async () => {
401
+ const read = JSON.parse(await claude.fs.read(`${listeners}/${at}.json`).catch(ifMissing('{}'))) as Partial<Kept>
402
+ for (const [caller, lists] of Object.entries(read.subscribed ?? {})) if (!subscribed.has(caller)) for (const [id, list] of Object.entries(lists)) hear(caller, id, list)
403
+ for (const [caller, targets] of Object.entries(read.watched ?? {})) for (const [target, list] of Object.entries(targets)) if (!watched.has(`${caller}\n${target}`)) watch(caller, target, list)
282
404
  })
283
- const targets = new Set([...published, ...list.map((watch) => watch.target)])
284
- published = new Set(list.map((watch) => watch.target))
285
- const running = targets.has(everySession) ? (await json<SessionData[]>(['history', 'sessions', '--running'])).map((each) => each.id) : []
286
- const told = new Set([...running, ...targets].filter((id) => id !== everySession && id !== session && !left.has(id)))
287
- await Promise.all(
288
- [...told].map((id) =>
289
- post(id, { kind: 'watch' }).catch((error: unknown) => {
290
- if (messageOf(error) !== ended(id).message) claude.ui.warn('before:tell', `cmod: session ${id} did not hear of a before listener: ${messageOf(error)}`)
291
- }),
292
- ),
293
- )
294
405
  }
295
406
 
296
407
  const hear = (caller: string, id: string, list: readonly Listened[]) => {
@@ -302,149 +413,65 @@ export function serveConversations({
302
413
  subscribed.set(caller, lists)
303
414
  }
304
415
 
305
- const forgetListeners = (mod: string) => {
306
- if (!heard.delete(mod)) return
307
- subscribed.delete(mod)
308
- clear(`changed:${mod}`)
309
- follow()
310
- void saveListeners().catch((error: unknown) => report('listeners', `Kept the listeners of ${mod}, which left this session`, error))
311
- }
312
-
313
- const onListenerFiles = <Value>(work: () => Promise<Value>) => {
314
- const next = listenerFiles.then(work)
315
- listenerFiles = next.catch((error: unknown) => claude.ui.warn('listeners:files', `cmod: reading or writing the mods' listeners failed: ${messageOf(error)}`))
316
- return next
416
+ const watch = (caller: string, target: string, list: readonly Listened[]) => {
417
+ const key = `${caller}\n${target}`
418
+ if (list.length === 0) watched.delete(key)
419
+ else watched.set(key, { mod: caller, target, list })
317
420
  }
318
421
 
319
- const clearListeners = (at: string) => onListenerFiles(() => claude.fs.write(`${listeners}/${at}.json`, '{}'))
320
-
321
- const clearWatches = (at: string) => onListenerFiles(() => claude.fs.write(`${watches}/${at}.json`, noWatches))
322
-
323
- const saveListeners = (isEnding = false) => {
324
- const at = session
325
- if (at === '') return Promise.resolve()
326
- if (isEnding) return clearListeners(at)
327
- return onListenerFiles(() => claude.fs.write(`${listeners}/${at}.json`, JSON.stringify(Object.fromEntries([...subscribed].map(([caller, lists]) => [caller, Object.fromEntries(lists)])))))
328
- }
329
-
330
- const restoreListeners = () => {
331
- const at = session
332
- return onListenerFiles(async () => {
333
- const kept = JSON.parse(await claude.fs.read(`${listeners}/${at}.json`).catch(ifMissing('{}'))) as Readonly<Record<string, Readonly<Record<string, readonly Listened[]>>>>
334
- for (const [caller, lists] of Object.entries(kept)) if (!subscribed.has(caller)) for (const [id, list] of Object.entries(lists)) hear(caller, id, list)
335
- })
422
+ const forgetMod = (mod: string) => {
423
+ const wasHeard = heard.delete(mod)
424
+ subscribed.delete(mod)
425
+ clear(`changed:${mod}`)
426
+ const wasWatching = [...watched.keys()].filter((key) => key.startsWith(`${mod}\n`))
427
+ for (const key of wasWatching) watched.delete(key)
428
+ if (wasHeard || wasWatching.length > 0) void saveListeners().catch((error: unknown) => report('listeners', `Kept the listeners of ${mod}, which left this session`, error))
336
429
  }
337
430
 
338
- const readWatchers = () =>
339
- onListenerFiles(async () => {
340
- const files = (await claude.fs.list(watches).catch(ifMissing([]))).filter((file) => file.name.endsWith('.json') && file.size !== noWatches.length)
341
- const texts = await Promise.all(files.map((file) => claude.fs.read(`${watches}/${file.name}`).catch(ifMissing(noWatches))))
342
- const found: Watcher[] = []
343
- for (const [index, file] of files.entries()) {
344
- const from = file.name.replace(/\.json$/, '')
345
- if (left.has(from)) continue
346
- const text = texts[index] ?? noWatches
347
- let list: readonly Watch[]
348
- try {
349
- list = JSON.parse(text) as readonly Watch[]
350
- } catch (error) {
351
- if (from === session || !(error instanceof SyntaxError)) throw error
352
- claude.ui.warn('before:read', `cmod: session ${from} was writing its before listeners, so it keeps the ones from before until it relays that it changed them`)
353
- found.push(...watchers.filter((watch) => watch.from === from))
354
- continue
355
- }
356
- if (from === session) {
357
- for (const watch of list) if (!ownWatches.has(`${watch.mod}\n${watch.target}`)) ownWatches.set(`${watch.mod}\n${watch.target}`, watch)
358
- continue
359
- }
360
- found.push(...list.filter((watch) => watch.target === session || (watch.target === everySession && watch.project === project())).map((watch) => ({ ...watch, from })))
361
- }
362
- watchers = found
363
- })
364
-
365
- const changeGoal = (task: string | undefined, text: string) => dispatch(session, task === undefined ? conversation.changeGoal(text) : [{ type: GoalChange, goal: { text, task } }])
366
-
367
- const reloadWatchers = () => {
368
- watching = readWatchers().catch((error: unknown) => report('before', 'Kept the other sessions’ before listeners from before', error))
369
- }
431
+ const changeGoal = (task: string | undefined, text: string) => dispatch(task === undefined ? conversation.changeGoal(text) : [{ type: GoalChange, goal: { text, task } }])
370
432
 
371
433
  const place = (): Place => {
372
434
  const { context, contextOpenedAt, turn, tasks, taskTurns, openCalls } = conversation.state
373
435
  return { session, context, contextOpenedAt, ...(turn === undefined ? {} : { turn }), tasks, taskTurns, ...(openCalls === undefined ? {} : { openCalls }) }
374
436
  }
375
437
 
376
- const deciders = (event: string): Watcher[] => {
377
- const all = [...[...ownWatches.values()].filter((watch) => watch.target === session || watch.target === everySession).map((watch) => ({ ...watch, from: session })), ...watchers]
378
- return [...new Map(all.filter((watcher) => watcher.events.includes(event)).map((watcher) => [`${watcher.from}\n${watcher.mod}`, watcher])).values()]
438
+ type Decider = { readonly mod: string; readonly list: readonly Listened[] }
439
+
440
+ const deciders = (event: string): Decider[] => {
441
+ const own = [...watched.values()].filter((each) => (each.target === session || each.target === everySession) && each.list.some((listened) => listened.event === event))
442
+ return [...new Map(own.map((each) => [each.mod, { mod: each.mod, list: each.list }])).values()]
379
443
  }
380
444
 
381
- const askHere = async (mod: string, event: BeforeEvent, change: SessionChange, from = session, isInProject = true) =>
382
- claude.cmod.call({ to: mod, method: conversationMethods.before, input: { session: from, event, change, isInProject } }).catch((error: unknown) => {
445
+ const askHere = async (mod: string, event: BeforeEvent, change: SessionChange) =>
446
+ claude.cmod.call({ to: mod, method: conversationMethods.before, input: { session, event, change, isInProject: true } }).catch((error: unknown) => {
383
447
  if (!isNotInstalled(mod, error)) throw error
384
- forgetWatches(mod)
448
+ forgetMod(mod)
385
449
  return undefined
386
450
  })
387
451
 
388
- const forgetWatches = (mod: string) => {
389
- const left = [...ownWatches].filter(([, watch]) => watch.mod === mod)
390
- if (left.length === 0) return
391
- for (const [key] of left) ownWatches.delete(key)
392
- void publishWatches().catch((error: unknown) => report('before', `Kept the before listeners of ${mod}, which left this session`, error))
393
- }
394
-
395
- const isUnderHere = (task: string, ancestor: string) => {
396
- for (let at: string | undefined = task, steps = 0; at !== undefined && steps < 64; at = conversation.state.tasks[at]?.parent, steps += 1) if (at === ancestor) return true
397
- return false
398
- }
399
-
400
- const refuses = (watcher: Watcher, event: BeforeEvent, change: SessionChange | undefined) =>
401
- beforeAnswerKeys[event].includes('refuse') && (watcher.refusing ?? []).some(({ event: heard, matcher, scope }) => (change === undefined ? heard === event : isInScope(scope ?? {}, session, change, isUnderHere) && isHeardBy(heard, matcher === undefined ? undefined : receivedMatcher(matcher), change)))
402
-
403
- const askAway = async (watcher: Watcher, event: BeforeEvent, change: SessionChange, endsAt: number) => {
404
- try {
405
- const leftMs = Math.min(beforeDeadlineMs, endsAt - (await claude.clock.now()))
406
- if (leftMs <= 0) throw new PassedTimeout(`the ${awayFoldMs / 1000} s cmod waits on other sessions ran out before session ${watcher.from} was asked`)
407
- return await ask(watcher.from, { kind: 'before', mod: watcher.mod, event, change, project: project() }, leftMs)
408
- } catch (error) {
409
- if (isNotInstalled(watcher.mod, error)) {
410
- watchers = watchers.filter((each) => each.from !== watcher.from || each.mod !== watcher.mod)
411
- return undefined
412
- }
413
- if (await isRunning(watcher.from)) {
414
- if (error instanceof PassedTimeout && refuses(watcher, event, change)) return { refuse: `${watcher.mod}: ${error.message}` }
415
- throw error
416
- }
417
- watchers = watchers.filter((each) => each.from !== watcher.from)
418
- claude.ui.warn('before:ended', `cmod: session ${watcher.from} ended without clearing its before listeners, so they are cleared now`)
419
- await clearWatches(watcher.from)
420
- return undefined
421
- }
452
+ const refuses = (decider: Decider, event: BeforeEvent, change: SessionChange | undefined) => {
453
+ if (!beforeAnswerKeys[event].includes('refuse')) return false
454
+ return decider.list.some(({ event: heardEvent, matcher, scope, onFailure }) => onFailure === 'refuse' && (change === undefined ? heardEvent === event : isInScope(scope ?? {}, session, change, isUnderHere) && isHeardBy(heardEvent, matcher === undefined ? undefined : receivedMatcher(matcher), change)))
422
455
  }
423
456
 
424
457
  const wants = async (event: BeforeEvent) => {
425
- await watching
458
+ await listening
426
459
  return deciders(event).length > 0
427
460
  }
428
461
 
429
462
  const failedBefore = (event: BeforeEvent, change: (where: Place) => SessionChange | undefined, error: Error) => {
430
- if (!hasReadWatchers) return { refuse: `${cmodPluginName}: ${error.message}` }
463
+ if (!hasHeardListeners) return { refuse: `${cmodPluginName}: ${error.message}` }
431
464
  const changed = change(place())
432
- const refusing = deciders(event).find((watcher) => refuses(watcher, event, changed))
465
+ const refusing = deciders(event).find((decider) => refuses(decider, event, changed))
433
466
  return refusing === undefined ? undefined : { refuse: `${refusing.mod}: ${error.message}` }
434
467
  }
435
468
 
436
469
  const decide = (cancel?: AbortSignal): Decide => {
437
- let endsAt: Promise<number> | undefined
438
470
  return (event, change) =>
439
471
  foldBefore(
440
472
  event,
441
473
  change,
442
- deciders(event).map((watcher) => async (latest: SessionChange) => {
443
- if (cancel?.aborted === true) return undefined
444
- if (watcher.from === session) return askHere(watcher.mod, event, latest)
445
- endsAt ??= claude.clock.now().then((now) => now + awayFoldMs)
446
- return askAway(watcher, event, latest, await endsAt)
447
- }),
474
+ deciders(event).map((decider) => async (latest: SessionChange) => (cancel?.aborted === true ? undefined : askHere(decider.mod, event, latest))),
448
475
  (error) => {
449
476
  if (cancel?.aborted !== true) report(`before:${event}`, `Passed the ${event} on without a mod's answer`, error)
450
477
  },
@@ -475,39 +502,89 @@ export function serveConversations({
475
502
  },
476
503
  })
477
504
 
505
+ const listenToServe = () => {
506
+ serveChanges?.remove()
507
+ serveChanges = held.listen(local.client, { interface: sessionsInterface, event: 'Change', kind: 'on', args: [session] }, (change: StoreChange) => {
508
+ if (change.part === 'tasks') void reconcileTasks()
509
+ if (change.part === 'goal') void rereadGoal()
510
+ })
511
+ }
512
+
478
513
  const start = (id: string, source: string) => {
479
514
  if (id === session) return
480
515
  const previous = session
481
- if (previous !== '') left.add(previous)
482
- left.delete(id)
483
516
  session = id
484
517
  live = []
485
518
  liveIds.clear()
486
519
  waitingRows.clear()
487
520
  conversation = createConversation(emptyConversation(id))
521
+ contextPercent = undefined
522
+ endedTurn = undefined
523
+ failedWith = undefined
524
+ turnMoved(false)
488
525
  const isNew = source === 'startup' || source === 'clear'
489
526
  if (!isNew) readColor(id)
490
- starting =
491
- isNew
492
- ? Promise.resolve(dispatch(id, conversation.startContext(new Date().toISOString())))
493
- : json<ConversationState>(['history', 'state', id]).then(
494
- (state) => {
495
- if (session === id) conversation = createConversation({ ...emptyConversation(id), ...state })
496
- },
497
- (error: unknown) => report('state', `Starts session ${id} without its earlier turns`, error),
498
- )
499
- const restored = restoreListeners()
500
- .catch((error: unknown) => report('listeners', "Could not read back the mods' listeners of this session", error))
501
- .then(follow)
527
+ starting = isNew
528
+ ? Promise.resolve(dispatch(conversation.startContext(new Date().toISOString())))
529
+ : read<ConversationState | null>(id, 'state').then(
530
+ (state) => {
531
+ if (session === id && state !== null) conversation = createConversation({ ...emptyConversation(id), ...state })
532
+ },
533
+ (error: unknown) => report('state', `Starts session ${id} without its earlier turns`, error),
534
+ )
535
+ const restored = restoreListeners().catch((error: unknown) => report('listeners', "Could not read back the mods' listeners of this session", error))
502
536
  starting = Promise.all([starting, restored]).then(() => undefined)
503
- reloadWatchers()
504
- hasReadWatchers = false
505
- void watching.then(() => {
506
- if (session === id) hasReadWatchers = true
507
- })
508
- if (subscribed.size > 0) void Promise.all([previous === '' ? undefined : clearListeners(previous), saveListeners()]).catch((error: unknown) => report('follow', 'Kept telling the mods about the session from before', error))
509
- if (ownWatches.size === 0) return
510
- void Promise.all([previous === '' ? undefined : clearWatches(previous), publishWatches()]).catch((error: unknown) => report('before', 'Kept its before listeners on the session from before', error))
537
+ hasHeardListeners = false
538
+ const holding = holdHere(local.client).then(
539
+ () => {
540
+ if (session !== id) return
541
+ hasHeardListeners = true
542
+ tellStatus()
543
+ },
544
+ (error: unknown) => claude.ui.warn('serve:hold', `cmod: other sessions reach session ${id} once cmod serve answers: ${messageOf(error)}`),
545
+ )
546
+ listening = Promise.all([restored, holding]).then(() => undefined)
547
+ listenToServe()
548
+ void starting.then(reconcileTasks)
549
+ if (heard.size === 0 && watched.size === 0) return
550
+ void Promise.all([previous === '' ? undefined : onListenerFiles(() => claude.fs.write(`${listeners}/${previous}.json`, JSON.stringify({ subscribed: {}, watched: {} } satisfies Kept))), saveListeners()]).catch((error: unknown) => report('follow', 'Kept telling the mods about the session from before', error))
551
+ }
552
+
553
+ const reconcileTasks = async () => {
554
+ if (session === '') return
555
+ await starting
556
+ const open = Object.values(conversation.state.tasks).filter((task) => task.isBackground === true && task.closedAt === undefined)
557
+ if (open.length === 0) return
558
+ const saved = await read<TaskData[]>(session, 'tasks').catch((error: unknown) => (report('tasks', 'Could not read whether its background tasks ended', error), []))
559
+ for (const task of saved) {
560
+ const running = conversation.state.tasks[task.id]
561
+ if (running !== undefined && running.closedAt === undefined && task.closedAt !== undefined) dispatch(conversation.endTask(task, task.closedAt))
562
+ }
563
+ 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))
564
+ }
565
+
566
+ const closeEndedOn = async (client: Pick<RpcClient, 'request'>, ids: readonly string[]) => {
567
+ await starting
568
+ const open = new Set(
569
+ ids.filter((id) => {
570
+ const task = conversation.state.tasks[id]
571
+ return task?.isBackground === true && task.closedAt === undefined
572
+ }),
573
+ )
574
+ if (open.size === 0) return
575
+ const listed = await client.request<SessionData[]>(`${sessionsInterface}.sessions`, [{ everyProject: true }])
576
+ for (const ended of listed.filter((each) => open.has(each.id) && !each.isRunning)) {
577
+ const task = liveTasks().find((each) => each.id === ended.id && each.closedAt === undefined)
578
+ if (task === undefined) continue
579
+ const closedAt = new Date().toISOString()
580
+ await claude.fs.write(`${backgroundTasks}/${session}/${task.id}.json`, JSON.stringify({ ...task, closedAt } satisfies TaskData))
581
+ dispatch(conversation.endTask(task, closedAt))
582
+ }
583
+ }
584
+
585
+ const rereadGoal = async () => {
586
+ const { text } = await read<{ readonly text: string }>(session, 'goal')
587
+ if (text !== conversation.state.goal) changeGoal(undefined, text)
511
588
  }
512
589
 
513
590
  const take = async (row: Row, task: string | undefined) => {
@@ -518,14 +595,15 @@ export function serveConversations({
518
595
  waitingRows.set(task, waiting)
519
596
  if (waiting.length < bufferedTaskRows) return
520
597
  waitingRows.delete(task)
521
- dispatch(session, conversation.startTask({ id: task, title: '', agentType: 'general-purpose', openedBy: '', openedAt: row.at }))
522
- for (const each of waiting) dispatch(session, conversation.add(each, task))
598
+ dispatch(conversation.startTask({ id: task, title: '', agentType: 'general-purpose', openedBy: '', openedAt: row.at }))
599
+ for (const each of waiting) dispatch(conversation.add(each, task))
523
600
  return
524
601
  }
525
- dispatch(session, conversation.add(row, task))
602
+ dispatch(conversation.add(row, task))
526
603
  if (task !== undefined || row.type !== 'system' || row.name !== 'turn_duration' || lastTurn === undefined) return
527
604
  closings.set(row.id, lastTurn)
528
605
  if (closings.size > keptClosings) closings.delete(closings.keys().next().value as string)
606
+ onTurnClosed(lastTurn)
529
607
  }
530
608
 
531
609
  router.add('classic.SessionStart', async (e, next) => {
@@ -533,8 +611,7 @@ export function serveConversations({
533
611
  return next(e)
534
612
  })
535
613
  router.add('classic.SessionEnd', async (e, next) => {
536
- if (ownWatches.size > 0) await publishWatches(true).catch((error: unknown) => report('before', 'Left its before listeners registered', error))
537
- if (subscribed.size > 0) await saveListeners(true).catch((error: unknown) => report('follow', 'Left its listeners registered', error))
614
+ if (subscribed.size > 0 || watched.size > 0) await saveListeners(true).catch((error: unknown) => report('follow', 'Left its listeners registered', error))
538
615
  return next(e)
539
616
  })
540
617
 
@@ -549,7 +626,13 @@ export function serveConversations({
549
626
 
550
627
  router.add('session.measure', async (e, next) => {
551
628
  const measured = await next(e)
552
- if (session !== '') dispatch(session, [{ type: UsageChange, usage: await usageOf(claude) }])
629
+ if (session === '') return measured
630
+ const usage = await usageOf(claude)
631
+ dispatch([{ type: UsageChange, usage }])
632
+ if (usage.contextWindow.percent !== contextPercent) {
633
+ contextPercent = usage.contextWindow.percent
634
+ tellStatus()
635
+ }
553
636
  return measured
554
637
  })
555
638
 
@@ -559,10 +642,10 @@ export function serveConversations({
559
642
  const id = spawned.agentId
560
643
  await starting
561
644
  const opened: TaskData = { id, title: e.description, ...ownerOfSpawn(e.subagentType, session), model: spawned.model, openedBy: e.tool_use_id, openedAt: new Date().toISOString(), ...(e.parentAgentId === undefined ? {} : { parent: e.parentAgentId }) }
562
- dispatch(session, conversation.startTask(opened))
645
+ dispatch(conversation.startTask(opened))
563
646
  const waiting = waitingRows.get(id) ?? []
564
647
  waitingRows.delete(id)
565
- for (const row of waiting) dispatch(session, conversation.add(row, id))
648
+ for (const row of waiting) dispatch(conversation.add(row, id))
566
649
  return spawned
567
650
  }
568
651
  router.add('agent.spawn', recordSpawn, (e, _error, next) => recordSpawn(e, next))
@@ -583,13 +666,6 @@ export function serveConversations({
583
666
  }
584
667
 
585
668
  const received = async (relay: Relay) => {
586
- if (relay.kind === 'answer') {
587
- const waiting = asked.get(relay.id)
588
- if (relay.deny === undefined) waiting?.resolve(relay.value)
589
- else waiting?.reject(new Error(relay.deny))
590
- return
591
- }
592
- if (relay.kind === 'watch') return readWatchers()
593
669
  if (relay.kind === 'goal') {
594
670
  await starting
595
671
  changeGoal(relay.task, relay.text)
@@ -597,18 +673,21 @@ export function serveConversations({
597
673
  }
598
674
  if (relay.kind === 'taskEnd') {
599
675
  await starting
600
- dispatch(session, conversation.endTask(relay.task, relay.task.closedAt ?? new Date().toISOString()))
676
+ dispatch(conversation.endTask(relay.task, relay.task.closedAt ?? new Date().toISOString()))
601
677
  return
602
678
  }
603
- const answered = async (run: () => Promise<unknown>) => {
604
- try {
605
- await post(relay.from, { kind: 'answer', id: relay.id, value: (await run()) ?? null })
606
- } catch (error) {
607
- await post(relay.from, { kind: 'answer', id: relay.id, deny: messageOf(error) })
608
- }
679
+ try {
680
+ if (!isAct(relay.action)) throw await unknownTo(`"${String(relay.action)}" action`)
681
+ const value = await perform(relay.caller, relay.action, relay.input, relay.task)
682
+ await post(relay.from, { kind: 'answer', id: relay.id, value: value ?? null })
683
+ } catch (error) {
684
+ await post(relay.from, { kind: 'answer', id: relay.id, deny: messageOf(error) })
609
685
  }
610
- if (relay.kind === 'act') return answered(async () => (isAct(relay.action) ? perform(relay.caller, relay.action, relay.input, relay.task) : Promise.reject(await unknownTo(`"${String(relay.action)}" action`))))
611
- return answered(() => askHere(relay.mod, relay.event, relay.change, relay.from, relay.project === project()))
686
+ }
687
+
688
+ const exitNow = async () => {
689
+ endsAfterTurn = false
690
+ await claude.command.run({ command: 'exit' })
612
691
  }
613
692
 
614
693
  const perform = async (caller: string, action: Act, input: unknown, task: string | undefined): Promise<unknown> => {
@@ -617,6 +696,11 @@ export function serveConversations({
617
696
  if (task !== undefined) return performInTask(caller, action, input, task)
618
697
  if (action === 'usage') return usageOf(claude)
619
698
  if (action === 'surfaces') return [...(await claude.session.surfaces())] satisfies Surface[]
699
+ if (action === 'end') {
700
+ if (engineTurns.has('')) endsAfterTurn = true
701
+ else claude.clock.after(0, () => void exitNow())
702
+ return null
703
+ }
620
704
  if (action === 'send') {
621
705
  const { type, text, as } = input as SessionSend
622
706
  if (as === Session) throw new Error(`session ${session} cannot send as itself to itself.`)
@@ -626,9 +710,14 @@ export function serveConversations({
626
710
  return null
627
711
  }
628
712
  if (action === 'startTask') return spawnTask(claude, input as TaskStartArgs)
629
- if (action === 'fork') return spawnTask(claude, input as TaskStartArgs, session)
630
- if (action === 'startBackgroundTask') return startBackground(input as TaskStartArgs)
631
- if (action === 'clone') return startBackground(input as TaskStartArgs, session)
713
+ if (action === 'startBackgroundTask') return startBackground(taskStartArgsOf(input))
714
+ if (action === 'fork' || action === 'clone') {
715
+ const fork = input as TaskStartArgs & { readonly at?: string }
716
+ if (action === 'clone' || fork.isBackground === true) return startBackground(fork, session, fork.at)
717
+ if (fork.at !== undefined) throw new Error('a fork through a message runs as a background session. Add isBackground: true.')
718
+ return spawnTask(claude, fork, session)
719
+ }
720
+ if (action === 'visit' || action === 'delete') return actOn(session, action, input, { caller })
632
721
  const { name, input: toolInput } = input as ToolCallArgs
633
722
  return resultOf(place(), { name, input: toolInput, cwd: await claude.session.cwd() }, await claude.tool.call({ ...toolInput, tool: name } as never))
634
723
  }
@@ -638,14 +727,14 @@ export function serveConversations({
638
727
  if (turnId === undefined) throw new Error(`no turn is running in ${task === undefined ? `session ${session}` : `task ${task}`}.`)
639
728
  const asked = isObject(input) ? input['turn'] : undefined
640
729
  const open = task === undefined ? conversation.state.turn : conversation.state.taskTurns[task]
641
- if (open?.prompt.id !== asked) throw new Error(`turn ${String(asked)} has ended, so there is nothing to abort.`)
730
+ if (asked !== undefined && open?.prompt.id !== asked) throw new Error(`turn ${String(asked)} has ended, so there is nothing to abort.`)
642
731
  await claude.turn.abort({ turnId })
643
732
  return null
644
733
  }
645
734
 
646
735
  const performInTask = async (caller: string, action: Act, input: unknown, task: string): Promise<unknown> => {
647
736
  const running = conversation.state.tasks[task]
648
- if (action === 'usage') return json(['history', 'usage', session, '--task', task])
737
+ if (action === 'usage') return read(session, 'usage', { task })
649
738
  if (action === 'surfaces') return running === undefined || running.closedAt !== undefined ? [] : [...(await claude.session.surfaces())]
650
739
  if (action !== 'send') throw new Error(`cmod: ${action} runs only on a session's own main loop.`)
651
740
  if (running === undefined || running.closedAt !== undefined) throw ended(task)
@@ -655,7 +744,7 @@ export function serveConversations({
655
744
  return null
656
745
  }
657
746
 
658
- const startBackground = async (task: TaskStartArgs, forkedFrom?: string): Promise<TaskData> => {
747
+ const startBackground = async (task: TaskStartArgs, forkedFrom?: string, at?: string): Promise<TaskData> => {
659
748
  if (task.title.trim() === '') throw new Error('a task needs a title.')
660
749
  if (task.name !== undefined) throw new Error('a background task takes no name.')
661
750
  const fresh: Partial<TaskStartArgs> = forkedFrom === undefined ? task : {}
@@ -663,6 +752,21 @@ export function serveConversations({
663
752
  const answer = (await wants(TaskStart)) ? await decide()(TaskStart, { type: TaskStart, task: { ...asked, context: conversation.state.context } }) : undefined
664
753
  if (answer?.refuse !== undefined) throw new Error(`a beforeTaskStart listener refused the task: ${answer.refuse}`)
665
754
  const owner = forkedFrom === undefined ? (answer?.owner ?? {}) : {}
755
+ if (task.device !== undefined) {
756
+ const here = await claude.device.read()
757
+ if (task.device !== here.name && task.device !== here.id) {
758
+ const elsewhere: TaskStartArgs = { ...task, ...owner, title: answer?.title ?? task.title, prompt: answer?.prompt ?? task.prompt }
759
+ const others = await otherProviders()
760
+ const onDevice = others.filter(({ identity }) => identity.device !== undefined && (identity.device.name === task.device || identity.device.id === task.device))
761
+ const opened = await firstHolding((client) => client.request<TaskData>(`${sessionsInterface}.startTask`, [session, elsewhere, { project: project() }]), (onDevice.length > 0 ? onDevice : others).map((other) => other.peer)).catch((error: unknown) => {
762
+ throw others.length === 0 || 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
763
+ })
764
+ const started: TaskData = { ...asked, id: opened.id, title: elsewhere.title }
765
+ await claude.fs.write(`${backgroundTasks}/${session}/${started.id}.json`, JSON.stringify(started))
766
+ dispatch(conversation.startTask(started))
767
+ return started
768
+ }
769
+ }
666
770
  const folder = owner.cwd ?? fresh.cwd
667
771
  const here = await claude.session.cwd()
668
772
  const args = [
@@ -671,6 +775,7 @@ export function serveConversations({
671
775
  '--title',
672
776
  answer?.title ?? task.title,
673
777
  ...(forkedFrom === undefined ? [] : ['--clone']),
778
+ ...(at === undefined ? [] : ['--at', at]),
674
779
  ...textArg('--agent', owner.agentType ?? fresh.agentType),
675
780
  ...textArg('--model', owner.model ?? fresh.model),
676
781
  '--cwd',
@@ -680,7 +785,7 @@ export function serveConversations({
680
785
  answer?.prompt ?? task.prompt,
681
786
  ]
682
787
  const started = JSON.parse(await runCmod(claude, args, session)) as TaskData
683
- dispatch(session, conversation.startTask(started))
788
+ dispatch(conversation.startTask(started))
684
789
  return started
685
790
  }
686
791
 
@@ -692,22 +797,19 @@ export function serveConversations({
692
797
  if ((await claude.store.get(answered)) === true) return
693
798
  await claude.store.set(answered, true)
694
799
  const { session: from, ...task } = JSON.parse(asked) as TaskData & { readonly session: string }
695
- const ended: TaskData = { ...task, id: session, closedAt: new Date().toISOString() }
696
- await claude.fs.write(`${backgroundTasks}/${from}/${session}.json`, JSON.stringify(ended))
697
- await post(from, { kind: 'taskEnd', task: ended }).catch((error: unknown) => claude.ui.warn('task:answered', `cmod: session ${from} did not hear that its task ${session} answered: ${messageOf(error)}`))
800
+ const closed: TaskData = { ...task, id: session, closedAt: new Date().toISOString() }
801
+ await claude.fs.write(`${backgroundTasks}/${from}/${session}.json`, JSON.stringify(closed))
802
+ local.client.notify(sessionActs.changed, { session: from, part: 'tasks' })
698
803
  }
699
804
 
700
805
  const actElsewhere = async (caller: string, target: string, action: Act, input: unknown, task: string | undefined): Promise<unknown> => {
701
- const isLive = await isRunning(target)
702
- if (!isLive && action === 'usage') return json(['history', 'usage', target, ...(task === undefined ? [] : ['--task', task])])
703
- if (!isLive && action === 'surfaces') return []
704
- if (!isLive) throw ended(task ?? target)
705
806
  if (action === 'send' && task === undefined && (input as SessionSend).as === Session) {
706
- const sent = await claude.session.send({ to: { sessionId: target }, text: (input as SessionSend).text })
707
- if (sent.isDelivered !== true) throw ended(target)
708
- return null
807
+ const { type, text } = input as SessionSend
808
+ const sent = await claude.session.send({ to: { sessionId: target }, text })
809
+ if (sent.isDelivered === true) return null
810
+ return actOn(target, action, { type, text }, { caller })
709
811
  }
710
- return ask(target, { kind: 'act', caller, action, input, ...(task === undefined ? {} : { task }) })
812
+ return actOn(target, action, input, { caller, ...(task === undefined ? {} : { task }) })
711
813
  }
712
814
 
713
815
  const merged = <Item>(saved: readonly Item[], kept: readonly Item[], key: (item: Item) => string): Item[] => {
@@ -747,20 +849,28 @@ export function serveConversations({
747
849
 
748
850
  const isHeld = (kept: readonly unknown[], last: unknown) => typeof last === 'number' && kept.length >= last
749
851
 
852
+ const fields = (request: Request, keys: readonly string[]) => Object.fromEntries(keys.flatMap((key) => (request[key] === undefined ? [] : [[key, request[key]]])))
853
+
750
854
  const methods: Readonly<Record<string, (request: Request, caller: string | undefined) => Promise<unknown>>> = {
751
855
  async [conversationMethods.sessions](request) {
752
- const found = await json<SessionData[]>(['history', 'sessions', ...scopeArgs(request), ...(request['running'] === true ? ['--running'] : [])])
856
+ const found = await listAll({ project: project(), ...fields(request, ['since', 'everyProject', 'running']) })
753
857
  return found.map((each) => (each.id === session ? { ...each, isRunning: true } : each))
754
858
  },
859
+ async [conversationMethods.session](request) {
860
+ const id = String(request['session'])
861
+ const found = (await listAll({ project: project(), everyProject: true })).find((each) => each.id === id)
862
+ if (found === undefined) throw new Error(`no session ${id} on any of your devices.`)
863
+ return found.id === session ? { ...found, isRunning: true } : found
864
+ },
755
865
  async [conversationMethods.search](request) {
756
- const before = isObject(request['before']) ? request['before'] : undefined
757
- const record = [...textArg('--session', request['session']), ...textArg('--task', request['task']), ...textArg('--turn', request['turn']), ...countArg('--context', request['context']), ...(request['isAgent'] === true ? ['--agent'] : [])]
758
- return json(['history', 'search', String(request['text']), ...scopeArgs(request), ...record, ...(request['running'] === true ? ['--running'] : []), ...(before === undefined ? [] : ['--before', `${String(before['session'])}:${String(before['id'])}`])])
866
+ const record = fields(request, ['session', 'task', 'turn', 'context', 'isAgent'])
867
+ const options = { project: project(), ...fields(request, ['since', 'everyProject', 'running', 'before']), record }
868
+ const pages = await Promise.all((await providers()).map((client) => client.request<Message[]>(`${sessionsInterface}.search`, [String(request['text']), options]).catch((error: unknown) => (client === local.client ? Promise.reject(error) : []))))
869
+ return pages.flat().sort((first, second) => second.at.localeCompare(first.at))
759
870
  },
760
871
  async [conversationMethods.messages](request) {
761
872
  const id = String(request['session'])
762
- const filters = [...textArg('--turn', request['turn']), ...textArg('--task', request['task']), ...textArg('--after', request['after'])]
763
- const saved = () => json<Message[]>(['history', 'messages', id, ...filters, ...countArg('--last', request['last'])])
873
+ const saved = () => read<Message[]>(id, 'messages', fields(request, ['turn', 'task', 'after', 'last']))
764
874
  if (id !== session) return saved()
765
875
  await starting
766
876
  const fits = (message: Message) => (request['turn'] === undefined || message.turn === request['turn']) && message.task === request['task']
@@ -771,7 +881,7 @@ export function serveConversations({
771
881
  },
772
882
  async [conversationMethods.turns](request) {
773
883
  const id = String(request['session'])
774
- const saved = () => json<TurnData[]>(['history', 'turns', id, ...textArg('--task', request['task']), ...countArg('--context', request['context']), ...countArg('--last', request['last'])])
884
+ const saved = () => read<TurnData[]>(id, 'turns', fields(request, ['task', 'context', 'last']))
775
885
  if (id !== session) return saved()
776
886
  await starting
777
887
  const kept = liveTurns(request['task']).filter((turn) => request['context'] === undefined || turn.context === request['context'])
@@ -780,7 +890,7 @@ export function serveConversations({
780
890
  },
781
891
  async [conversationMethods.contexts](request) {
782
892
  const id = String(request['session'])
783
- const saved = await json<ContextData[]>(['history', 'contexts', id, ...textArg('--task', request['task'])]).catch((error: unknown) => {
893
+ const saved = await read<ContextData[]>(id, 'contexts', fields(request, ['task'])).catch((error: unknown) => {
784
894
  if (id === session && typeof request['task'] === 'string') return []
785
895
  throw error
786
896
  })
@@ -791,7 +901,7 @@ export function serveConversations({
791
901
  async [conversationMethods.tasks](request) {
792
902
  const id = String(request['session'])
793
903
  const isNested = request['all'] === true
794
- const saved = await json<TaskData[]>(['history', 'tasks', id, ...(isNested ? ['--nested'] : textArg('--task', request['task']))])
904
+ const saved = await read<TaskData[]>(id, 'tasks', isNested ? { all: true } : fields(request, ['task']))
795
905
  if (id !== session) return saved
796
906
  await starting
797
907
  const kept = liveTasks().filter((task) => isNested || task.parent === request['task'])
@@ -807,7 +917,7 @@ export function serveConversations({
807
917
  const text = conversation.state.goal
808
918
  if (text !== undefined) return { text }
809
919
  }
810
- return json(['history', 'goal', id, ...textArg('--task', task)])
920
+ return read(id, 'goal', task === undefined ? {} : { task })
811
921
  },
812
922
  async [conversationMethods.updateGoal](request) {
813
923
  const id = String(request['session'])
@@ -816,10 +926,7 @@ export function serveConversations({
816
926
  await claude.fs.write(`${goals}/${task ?? id}.txt`, text)
817
927
  await starting
818
928
  if (id === session) changeGoal(task, text)
819
- else {
820
- dispatch(id, [{ type: GoalChange, goal: { text, ...(task === undefined ? {} : { task }) } }])
821
- await post(id, { kind: 'goal', ...(task === undefined ? {} : { task }), text }).catch((error: unknown) => claude.ui.warn('goal:tell', `cmod: session ${id} keeps its goal until it starts again: ${messageOf(error)}`))
822
- }
929
+ else local.client.notify(sessionActs.changed, { session: id, part: 'goal' })
823
930
  return null
824
931
  },
825
932
  async [conversationMethods.subscribe](request, caller) {
@@ -827,7 +934,6 @@ export function serveConversations({
827
934
  const id = String(request['session'])
828
935
  const list = Array.isArray(request['subscriptions']) ? (request['subscriptions'] as readonly Listened[]) : []
829
936
  hear(caller, id, list)
830
- follow()
831
937
  await saveListeners()
832
938
  return null
833
939
  },
@@ -835,8 +941,8 @@ export function serveConversations({
835
941
  if (caller === undefined) throw new Error('cmod hears no caller for this before listener.')
836
942
  const target = String(request['session'])
837
943
  const list = Array.isArray(request['subscriptions']) ? (request['subscriptions'] as readonly Listened[]) : []
838
- ownWatches.set(`${caller}\n${target}`, { mod: caller, target, project: project(), events: [...new Set(list.map(({ event }) => event))], refusing: list.filter((each) => each.onFailure === 'refuse') })
839
- await publishWatches()
944
+ watch(caller, target, list)
945
+ await saveListeners()
840
946
  return null
841
947
  },
842
948
  async [conversationMethods.act](request, caller) {
@@ -851,23 +957,38 @@ export function serveConversations({
851
957
  }
852
958
 
853
959
  return {
960
+ onUnreached(listener) {
961
+ unreached = listener
962
+ if (isUnreached) listener()
963
+ },
964
+ async close() {
965
+ serveChanges?.remove()
966
+ await local.client.close()
967
+ },
854
968
  turnClosedBy: (rowId) => closings.get(rowId),
969
+ onTurnClosed(listener) {
970
+ onTurnClosed = listener
971
+ },
855
972
  color: () => color,
856
973
  onColor(listener) {
857
974
  onColor = listener
858
975
  },
859
976
  moved() {
860
- for (const [key, watch] of ownWatches) ownWatches.set(key, { ...watch, project: project() })
861
- void publishWatches().catch((error: unknown) => report('before', 'Kept its before listeners on the project from before', error))
862
- reloadWatchers()
863
- follow()
977
+ void holdHere(local.client).catch((error: unknown) => report('hold', 'Other sessions see this session in its old project until cmod serve answers', error))
978
+ },
979
+ serveUi(methods) {
980
+ ui = methods
981
+ },
982
+ tellUi(event, payload) {
983
+ if (session !== '') local.client.notify(sessionActs.uiEvent, { event, payload })
864
984
  },
985
+ provide: (name, methods) => served.provide(name, methods),
865
986
  async answer(e) {
866
987
  const method = methods[e.method]
867
- if (method === undefined) return undefined
868
- const input = isObject(e.input) ? e.input : {}
988
+ const forProviders = method === undefined ? served.answer(e.method, e.input, e.caller) : undefined
989
+ if (method === undefined && forProviders === undefined) return undefined
869
990
  try {
870
- return { value: await method(input, e.caller) }
991
+ return { value: method === undefined ? await forProviders : await method(isObject(e.input) ? e.input : {}, e.caller) }
871
992
  } catch (error) {
872
993
  return { deny: messageOf(error) }
873
994
  }
@@ -875,12 +996,9 @@ export function serveConversations({
875
996
  }
876
997
  }
877
998
 
878
- function scopeArgs(request: Request): string[] {
879
- return [...(typeof request['since'] === 'string' ? ['--since', request['since']] : []), ...(request['everyProject'] === true ? ['--all'] : [])]
880
- }
881
-
882
- function countArg(flag: string, value: unknown): string[] {
883
- return typeof value === 'number' ? [flag, String(value)] : []
999
+ function taskStartArgsOf(sent: unknown): TaskStartArgs {
1000
+ const { machine, ...task } = sent as TaskStartArgs & { readonly machine?: string }
1001
+ return machine === undefined || task.device !== undefined ? task : { ...task, device: machine }
884
1002
  }
885
1003
 
886
1004
  function textArg(flag: string, value: unknown): string[] {