opencode-crosstalk 0.0.0-stage → 0.3.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 (132) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +539 -2
  3. package/assets/CursorGuard.png +0 -0
  4. package/assets/Wren.png +0 -0
  5. package/assets/avatars/ATTRIBUTION.md +18 -0
  6. package/assets/avatars/female/01-explorer-eeb4a4.png +0 -0
  7. package/assets/avatars/female/02-manager-b16a5b.png +0 -0
  8. package/assets/avatars/female/02-manager-e7a391.png +0 -0
  9. package/assets/avatars/female/03-coder-92594b.png +0 -0
  10. package/assets/avatars/female/03-coder-e5a07e.png +0 -0
  11. package/assets/avatars/female/05-analyst-b16a5b.png +0 -0
  12. package/assets/avatars/female/05-analyst-eeb4a4.png +0 -0
  13. package/assets/avatars/female/08-tester-d78774.png +0 -0
  14. package/assets/avatars/female/08-tester-eeb4a4.png +0 -0
  15. package/assets/avatars/female/10-builder-92594b.png +0 -0
  16. package/assets/avatars/female/10-builder-e5a07e.png +0 -0
  17. package/assets/avatars/female/13-researcher-92594b.png +0 -0
  18. package/assets/avatars/female/13-researcher-e7a391.png +0 -0
  19. package/assets/avatars/female/14-writer-623d36.png +0 -0
  20. package/assets/avatars/female/14-writer-e5a07e.png +0 -0
  21. package/assets/avatars/female/16-fixer-e7a391.png +0 -0
  22. package/assets/avatars/female/17-deployer-92594b.png +0 -0
  23. package/assets/avatars/female/17-deployer-e5a07e.png +0 -0
  24. package/assets/avatars/female/23-mentor-b16a5b.png +0 -0
  25. package/assets/avatars/female/23-mentor-e7a391.png +0 -0
  26. package/assets/avatars/female/25-pioneer-d78774.png +0 -0
  27. package/assets/avatars/female/26-strategist-b16a5b.png +0 -0
  28. package/assets/avatars/female/31-gardener-e5a07e.png +0 -0
  29. package/assets/avatars/female/33-simplifier-b16a5b.png +0 -0
  30. package/assets/avatars/female/33-simplifier-eeb4a4.png +0 -0
  31. package/assets/avatars/female/34-optimizer-92594b.png +0 -0
  32. package/assets/avatars/female/34-optimizer-e7a391.png +0 -0
  33. package/assets/avatars/female/36-integrator-d78774.png +0 -0
  34. package/assets/avatars/female/36-integrator-eeb4a4.png +0 -0
  35. package/assets/avatars/female/37-compiler-b16a5b.png +0 -0
  36. package/assets/avatars/female/37-compiler-e7a391.png +0 -0
  37. package/assets/avatars/female/40-formatter-b16a5b.png +0 -0
  38. package/assets/avatars/female/42-shipper-623d36.png +0 -0
  39. package/assets/avatars/female/46-steward-623d36.png +0 -0
  40. package/assets/avatars/female/46-steward-d78774.png +0 -0
  41. package/assets/avatars/female/47-shepherd-b16a5b.png +0 -0
  42. package/assets/avatars/female/47-shepherd-eeb4a4.png +0 -0
  43. package/assets/avatars/female/48-tinkerer-92594b.png +0 -0
  44. package/assets/avatars/female/50-wrangler-eeb4a4.png +0 -0
  45. package/assets/avatars/index.html +4 -0
  46. package/assets/avatars/male/01-explorer-d78774.png +0 -0
  47. package/assets/avatars/male/06-planner-92594b.png +0 -0
  48. package/assets/avatars/male/06-planner-e7a391.png +0 -0
  49. package/assets/avatars/male/07-reviewer-623d36.png +0 -0
  50. package/assets/avatars/male/07-reviewer-e5a07e.png +0 -0
  51. package/assets/avatars/male/09-migrator-b16a5b.png +0 -0
  52. package/assets/avatars/male/09-migrator-e7a391.png +0 -0
  53. package/assets/avatars/male/11-debugger-623d36.png +0 -0
  54. package/assets/avatars/male/11-debugger-d78774.png +0 -0
  55. package/assets/avatars/male/12-designer-b16a5b.png +0 -0
  56. package/assets/avatars/male/12-designer-eeb4a4.png +0 -0
  57. package/assets/avatars/male/15-editor-d78774.png +0 -0
  58. package/assets/avatars/male/15-editor-eeb4a4.png +0 -0
  59. package/assets/avatars/male/16-fixer-b16a5b.png +0 -0
  60. package/assets/avatars/male/18-scout-623d36.png +0 -0
  61. package/assets/avatars/male/18-scout-d78774.png +0 -0
  62. package/assets/avatars/male/19-architect-b16a5b.png +0 -0
  63. package/assets/avatars/male/19-architect-eeb4a4.png +0 -0
  64. package/assets/avatars/male/20-operator-92594b.png +0 -0
  65. package/assets/avatars/male/20-operator-e7a391.png +0 -0
  66. package/assets/avatars/male/21-coordinator-623d36.png +0 -0
  67. package/assets/avatars/male/21-coordinator-e5a07e.png +0 -0
  68. package/assets/avatars/male/22-auditor-d78774.png +0 -0
  69. package/assets/avatars/male/22-auditor-eeb4a4.png +0 -0
  70. package/assets/avatars/male/25-pioneer-623d36.png +0 -0
  71. package/assets/avatars/male/26-strategist-eeb4a4.png +0 -0
  72. package/assets/avatars/male/28-librarian-623d36.png +0 -0
  73. package/assets/avatars/male/28-librarian-e5a07e.png +0 -0
  74. package/assets/avatars/male/30-tracker-b16a5b.png +0 -0
  75. package/assets/avatars/male/30-tracker-e7a391.png +0 -0
  76. package/assets/avatars/male/31-gardener-92594b.png +0 -0
  77. package/assets/avatars/male/32-refactorer-623d36.png +0 -0
  78. package/assets/avatars/male/32-refactorer-d78774.png +0 -0
  79. package/assets/avatars/male/35-profiler-623d36.png +0 -0
  80. package/assets/avatars/male/35-profiler-e5a07e.png +0 -0
  81. package/assets/avatars/male/38-parser-92594b.png +0 -0
  82. package/assets/avatars/male/38-parser-e5a07e.png +0 -0
  83. package/assets/avatars/male/39-linter-623d36.png +0 -0
  84. package/assets/avatars/male/39-linter-d78774.png +0 -0
  85. package/assets/avatars/male/40-formatter-eeb4a4.png +0 -0
  86. package/assets/avatars/male/41-patcher-92594b.png +0 -0
  87. package/assets/avatars/male/41-patcher-e7a391.png +0 -0
  88. package/assets/avatars/male/42-shipper-e5a07e.png +0 -0
  89. package/assets/avatars/male/43-maintainer-d78774.png +0 -0
  90. package/assets/avatars/male/43-maintainer-eeb4a4.png +0 -0
  91. package/assets/avatars/male/44-guardian-b16a5b.png +0 -0
  92. package/assets/avatars/male/44-guardian-e7a391.png +0 -0
  93. package/assets/avatars/male/45-sentinel-92594b.png +0 -0
  94. package/assets/avatars/male/45-sentinel-e5a07e.png +0 -0
  95. package/assets/avatars/male/48-tinkerer-e7a391.png +0 -0
  96. package/assets/avatars/male/49-hacker-623d36.png +0 -0
  97. package/assets/avatars/male/49-hacker-e5a07e.png +0 -0
  98. package/assets/avatars/male/50-wrangler-d78774.png +0 -0
  99. package/assets/avatars/manifest.json +1202 -0
  100. package/index.ts +11 -0
  101. package/package.json +65 -4
  102. package/src/config.ts +180 -0
  103. package/src/core/avatar.ts +92 -0
  104. package/src/core/claims.ts +302 -0
  105. package/src/core/clock.ts +31 -0
  106. package/src/core/directory.ts +48 -0
  107. package/src/core/format.ts +409 -0
  108. package/src/core/mailbox.ts +245 -0
  109. package/src/core/mesh.ts +800 -0
  110. package/src/core/registry.ts +306 -0
  111. package/src/deliverer.ts +88 -0
  112. package/src/events.ts +66 -0
  113. package/src/index.ts +323 -0
  114. package/src/rpc.ts +52 -0
  115. package/src/storage.ts +105 -0
  116. package/src/tools/args.ts +132 -0
  117. package/src/tools/claim.ts +87 -0
  118. package/src/tools/continue.ts +68 -0
  119. package/src/tools/heartbeat.ts +152 -0
  120. package/src/tools/inbox.ts +76 -0
  121. package/src/tools/index.ts +96 -0
  122. package/src/tools/peers.ts +101 -0
  123. package/src/tools/reply.ts +73 -0
  124. package/src/tools/send.ts +102 -0
  125. package/src/tools/status.ts +148 -0
  126. package/src/tools/types.ts +72 -0
  127. package/src/tools/wait.ts +96 -0
  128. package/src/tui/avatar.ts +188 -0
  129. package/src/tui/focus.ts +34 -0
  130. package/src/tui/index.tsx +219 -0
  131. package/src/types.ts +147 -0
  132. package/tui.ts +8 -0
@@ -0,0 +1,800 @@
1
+ /**
2
+ * @fileoverview The mesh: presence, mailboxes, and leases behind one façade.
3
+ *
4
+ * `Mesh` owns no I/O beyond the injected clock and an optional `Deliverer`, so
5
+ * every behaviour here is exercised directly in tests. `src/index.ts` supplies
6
+ * the real deliverer (OpenCode's `session.synthetic`) and the real event
7
+ * stream.
8
+ */
9
+
10
+ import type {
11
+ Claim,
12
+ ClaimOutcome,
13
+ CrosstalkMessage,
14
+ Declared,
15
+ Delivery,
16
+ MeshSnapshot,
17
+ MessageKind,
18
+ Peer,
19
+ PeerView,
20
+ Scope,
21
+ } from "../types.ts"
22
+ import { hasTask, portraitFor, type AvatarEntry } from "./avatar.ts"
23
+ import { delay, systemClock, type Clock } from "./clock.ts"
24
+ import { ClaimTable } from "./claims.ts"
25
+ import { Mailbox, type ListOptions, type WaitResult } from "./mailbox.ts"
26
+ import { Registry, type CrosstalkEvent, type ListFilter } from "./registry.ts"
27
+
28
+ export interface MeshOptions {
29
+ scope: Scope
30
+ staleAfterMs: number
31
+ evictAfterMs: number
32
+ maxMessages: number
33
+ messageTtlMs: number
34
+ claimTtlMs: number
35
+ maxWaitMs: number
36
+ pollMs: number
37
+ }
38
+
39
+ export interface Deliverer {
40
+ deliver(message: CrosstalkMessage): Promise<{ delivered: boolean; reason?: string }>
41
+ }
42
+
43
+ export interface MeshDeps {
44
+ options: MeshOptions
45
+ clock?: Clock
46
+ deliverer?: Deliverer
47
+ /** Plugin location, used when a peer record carries no project or directory. */
48
+ defaults?: { projectID?: string; directory?: string }
49
+ /** Bundled Personas; when present, each session freezes one portrait per task. */
50
+ avatars?: readonly AvatarEntry[]
51
+ idFactory?(seq: number): string
52
+ }
53
+
54
+ export interface SendInput {
55
+ to?: string
56
+ role?: string
57
+ all?: boolean
58
+ topic?: string
59
+ text: string
60
+ kind?: MessageKind
61
+ delivery?: Delivery
62
+ /** Set when the caller is answering another message. */
63
+ replyTo?: string
64
+ /** Exact files the task may edit; carried into `meta.task` for the recipient. */
65
+ writeScope?: string[]
66
+ /** Command that decides whether the task landed green. */
67
+ validation?: string
68
+ /** What the reporter must show to prove completion. */
69
+ evidence?: string
70
+ }
71
+
72
+ export interface SendOutcome {
73
+ recipients: Array<{ sessionID: string; delivered: boolean; reason?: string }>
74
+ skipped: Array<{ target: string; reason: string }>
75
+ messages: CrosstalkMessage[]
76
+ }
77
+
78
+ export interface InboxInput extends ListOptions {
79
+ waitMs?: number
80
+ markRead?: boolean
81
+ }
82
+
83
+ export interface InboxOutcome {
84
+ messages: CrosstalkMessage[]
85
+ reason: "immediate" | WaitResult["reason"]
86
+ marked: number
87
+ /** Unread remaining after this call. */
88
+ unread: number
89
+ /** Unread as it stood before this call acknowledged anything. */
90
+ unreadBefore: number
91
+ }
92
+
93
+ export interface ClaimInput {
94
+ action: "claim" | "release" | "renew" | "list"
95
+ resources?: readonly string[]
96
+ ttlMs?: number
97
+ note?: string
98
+ force?: boolean
99
+ atomic?: boolean
100
+ includeExpired?: boolean
101
+ }
102
+
103
+ export interface ClaimResult {
104
+ outcome: ClaimOutcome
105
+ held: Claim[]
106
+ ttlMs: number
107
+ }
108
+
109
+ export interface PeerIdleResult {
110
+ reason: "done" | "timeout" | "aborted" | "gone" | "outside"
111
+ elapsedMs: number
112
+ status?: Peer["status"]
113
+ }
114
+
115
+ export interface ClaimFreeResult {
116
+ reason: "done" | "timeout" | "aborted"
117
+ elapsedMs: number
118
+ holder?: string
119
+ }
120
+
121
+ export interface DeclareResult {
122
+ view: PeerView
123
+ /**
124
+ * The requested name is already used by another visible session; nothing was
125
+ * changed. `holder` is the session that owns the name.
126
+ */
127
+ nameConflict?: { name: string; holder: string }
128
+ }
129
+
130
+ /**
131
+ * Bumped to 2 when twin plugin instances could each persist to the same key
132
+ * and clobber each other's records. v1 is still migrated rather than dropped:
133
+ * its peer records were written under the same freeze contract, so a long-run
134
+ * session carries its declarations and frozen portrait across the upgrade —
135
+ * discarding them would change art the user already sees, breaking the never-
136
+ * change rule. Only v1's claims are discarded, because the lease table is what
137
+ * the twins corrupted; a snapshot from any other era is ignored whole.
138
+ */
139
+ export const SNAPSHOT_VERSION = 2
140
+
141
+ /** The one older format whose peer records `restore` still carries forward. */
142
+ export const LEGACY_SNAPSHOT_VERSION = 1
143
+
144
+ export class Mesh {
145
+ readonly registry: Registry
146
+ readonly mailbox: Mailbox
147
+ readonly claims: ClaimTable
148
+ readonly options: MeshOptions
149
+
150
+ readonly #clock: Clock
151
+ readonly #deliverer: Deliverer | undefined
152
+ readonly #defaults: { projectID?: string; directory?: string }
153
+ readonly #avatars: readonly AvatarEntry[]
154
+ readonly #idFactory: ((seq: number) => string) | undefined
155
+ /**
156
+ * Messages that are in a mailbox but were never injected into the live
157
+ * session, keyed by the session that should receive them. A `synthetic` call
158
+ * can fail across locations; without this the recipient would only ever find
159
+ * the message by polling, so every tool call retries them first.
160
+ */
161
+ readonly #pendingInjection = new Map<string, CrosstalkMessage[]>()
162
+
163
+ /** Mesh-mutation observers (the RPC bridge); a listener must never throw. */
164
+ readonly #listeners = new Set<() => void>()
165
+
166
+ constructor(deps: MeshDeps) {
167
+ this.options = deps.options
168
+ this.#clock = deps.clock ?? systemClock
169
+ this.#deliverer = deps.deliverer
170
+ this.#defaults = deps.defaults ?? {}
171
+ this.#avatars = deps.avatars ?? []
172
+ this.#idFactory = deps.idFactory
173
+ this.registry = new Registry({
174
+ now: () => this.#clock.now(),
175
+ staleAfterMs: deps.options.staleAfterMs,
176
+ evictAfterMs: deps.options.evictAfterMs,
177
+ })
178
+ this.mailbox = new Mailbox({
179
+ now: () => this.#clock.now(),
180
+ maxPerSession: deps.options.maxMessages,
181
+ ttlMs: deps.options.messageTtlMs,
182
+ ...(this.#idFactory ? { idFactory: this.#idFactory } : {}),
183
+ })
184
+ this.claims = new ClaimTable({ now: () => this.#clock.now(), defaultTtlMs: deps.options.claimTtlMs })
185
+ }
186
+
187
+ now(): number {
188
+ return this.#clock.now()
189
+ }
190
+
191
+ /**
192
+ * Observe declarations and presence changes. The RPC bridge subscribes so it
193
+ * can push directory updates without polling.
194
+ */
195
+ subscribe(listener: () => void): () => void {
196
+ this.#listeners.add(listener)
197
+ return () => {
198
+ this.#listeners.delete(listener)
199
+ }
200
+ }
201
+
202
+ #notify(): void {
203
+ for (const listener of this.#listeners) {
204
+ try {
205
+ listener()
206
+ } catch {
207
+ // A broken observer must never break a tool call.
208
+ }
209
+ }
210
+ }
211
+
212
+ /** Fold a server event in and evict lapsed peers. */
213
+ applyEvent(event: CrosstalkEvent): boolean {
214
+ const applied = this.registry.apply(event)
215
+ if (applied) {
216
+ this.registry.prune(this.#clock.now())
217
+ this.#notify()
218
+ }
219
+ return applied
220
+ }
221
+
222
+ /**
223
+ * Guarantee a record for the calling session. A session that started before
224
+ * the plugin loaded may never emit `session.created` at us.
225
+ */
226
+ ensureSelf(sessionID: string, agent?: string): Peer {
227
+ return this.registry.ensure(sessionID, {
228
+ projectID: this.#defaults.projectID,
229
+ directory: this.#defaults.directory,
230
+ ...(agent ? { agent } : {}),
231
+ })
232
+ }
233
+
234
+ /** The directory claims and relative paths resolve against for a session. */
235
+ directoryOf(sessionID: string): string | undefined {
236
+ return this.registry.get(sessionID)?.directory ?? this.#defaults.directory
237
+ }
238
+
239
+ #filter(selfID: string, overrides: Partial<ListFilter> = {}): ListFilter {
240
+ return {
241
+ selfID,
242
+ scope: this.options.scope,
243
+ selfProjectID: this.#defaults.projectID,
244
+ selfDirectory: this.#defaults.directory,
245
+ ...overrides,
246
+ }
247
+ }
248
+
249
+ /** Peer records visible to `selfID`, decorated with mesh state. */
250
+ peers(selfID: string, filter: Partial<ListFilter> = {}): PeerView[] {
251
+ this.ensureSelf(selfID)
252
+ const now = this.#clock.now()
253
+ return this.registry.list(this.#filter(selfID, filter)).map((peer) =>
254
+ this.registry.view(
255
+ peer,
256
+ {
257
+ isSelf: peer.sessionID === selfID,
258
+ unread: this.mailbox.unreadCount(peer.sessionID),
259
+ claims: this.claims.heldBy(peer.sessionID),
260
+ addressable: this.#inScope(selfID, peer),
261
+ },
262
+ now,
263
+ ),
264
+ )
265
+ }
266
+
267
+ view(selfID: string): PeerView {
268
+ const self = this.ensureSelf(selfID)
269
+ return this.registry.view(
270
+ self,
271
+ { isSelf: true, unread: this.mailbox.unreadCount(selfID), claims: this.claims.heldBy(selfID), addressable: true },
272
+ this.#clock.now(),
273
+ )
274
+ }
275
+
276
+ /** Record what a session says it is doing. Returns the updated self view. */
277
+ declare(sessionID: string, declared: Declared): DeclareResult {
278
+ const id = sessionIDOrThrow(sessionID)
279
+ const peer = this.ensureSelf(id)
280
+ // A name is a nickname, not identity: it must be unique among the peers
281
+ // the session can see, and a taken name is refused without touching the
282
+ // rest of the declaration.
283
+ if (declared.name !== undefined && declared.name !== peer.declared?.name) {
284
+ const holder = this.#nameHolder(declared.name, id)
285
+ if (holder) return { view: this.view(id), nameConflict: { name: declared.name, holder } }
286
+ }
287
+ const previous = peer.declared
288
+ const merged: Declared = {
289
+ name: declared.name ?? previous?.name,
290
+ role: declared.role ?? previous?.role,
291
+ goal: declared.goal ?? previous?.goal,
292
+ summary: declared.summary ?? previous?.summary,
293
+ summaryAt: declared.summary !== undefined ? this.#clock.now() : previous?.summaryAt,
294
+ note: declared.note ?? previous?.note,
295
+ avatar: declared.avatar ?? previous?.avatar,
296
+ workingOn: declared.workingOn ?? previous?.workingOn,
297
+ updatedAt: this.#clock.now(),
298
+ }
299
+ peer.declared = merged
300
+ peer.lastSeen = this.#clock.now()
301
+ // The portrait is a one-shot decision: it is assigned when a task first
302
+ // shows up and frozen afterwards, so no later declaration — different
303
+ // role, name, or avatar hint — can move the artwork.
304
+ if (peer.portrait === undefined && hasTask(merged)) {
305
+ const portrait = portraitFor(this.#avatars, {
306
+ sessionID: id,
307
+ name: merged.name,
308
+ role: merged.role,
309
+ avatar: merged.avatar,
310
+ })
311
+ if (portrait !== undefined) peer.portrait = portrait
312
+ }
313
+ this.#notify()
314
+ return { view: this.view(id) }
315
+ }
316
+
317
+ /** The visible session that already declared `name`, if any. */
318
+ #nameHolder(name: string, selfID: string): string | undefined {
319
+ const wanted = name.toLowerCase()
320
+ for (const peer of this.registry.list(this.#filter(selfID))) {
321
+ if (peer.sessionID === selfID) continue
322
+ if (peer.declared?.name?.toLowerCase() === wanted) return peer.sessionID
323
+ }
324
+ return undefined
325
+ }
326
+
327
+ /**
328
+ * Freeze portraits for sessions that already carry a task but have no
329
+ * portrait — the ones that declared before the portrait existed, or records
330
+ * restored from an older snapshot. One pass at startup; returns how many
331
+ * were assigned.
332
+ */
333
+ assignPortraits(): number {
334
+ let assigned = 0
335
+ for (const peer of this.registry.list({ scope: "server" })) {
336
+ if (peer.portrait !== undefined || !hasTask(peer.declared)) continue
337
+ const portrait = portraitFor(this.#avatars, {
338
+ sessionID: peer.sessionID,
339
+ name: peer.declared?.name,
340
+ role: peer.declared?.role,
341
+ avatar: peer.declared?.avatar,
342
+ })
343
+ if (portrait !== undefined) {
344
+ peer.portrait = portrait
345
+ assigned += 1
346
+ }
347
+ }
348
+ if (assigned > 0) this.#notify()
349
+ return assigned
350
+ }
351
+
352
+ /**
353
+ * Send a message to peers, then try to inject it into each recipient's live
354
+ * session. A failed injection is not an error: the message stays in the
355
+ * recipient's mailbox and surfaces on their next `crosstalk_inbox`.
356
+ */
357
+ async send(selfID: string, input: SendInput, signal?: AbortSignal): Promise<SendOutcome> {
358
+ const sender = this.ensureSelf(selfID)
359
+ const targets = this.#resolveTargets(selfID, input)
360
+ if (targets.recipients.length === 0) {
361
+ return { recipients: [], skipped: targets.skipped, messages: [] }
362
+ }
363
+
364
+ const meta: Record<string, unknown> = {}
365
+ if (input.replyTo) meta.replyTo = input.replyTo
366
+ meta.requested = sender.declared?.role
367
+ if (input.writeScope || input.validation || input.evidence) {
368
+ meta.task = {
369
+ ...(input.writeScope && input.writeScope.length > 0 ? { writeScope: input.writeScope } : {}),
370
+ ...(input.validation ? { validation: input.validation } : {}),
371
+ ...(input.evidence ? { evidence: input.evidence } : {}),
372
+ }
373
+ }
374
+
375
+ const messages = this.mailbox.send({
376
+ from: selfID,
377
+ ...(sender.declared?.name ? { fromName: sender.declared.name } : {}),
378
+ ...(sender.declared?.role ? { fromRole: sender.declared.role } : {}),
379
+ to: targets.recipients,
380
+ text: input.text,
381
+ ...(input.topic ? { topic: input.topic } : {}),
382
+ kind: input.kind ?? "message",
383
+ delivery: input.delivery ?? "steer",
384
+ meta,
385
+ })
386
+
387
+ const recipients: SendOutcome["recipients"] = []
388
+ for (const message of messages) {
389
+ if (signal?.aborted) {
390
+ recipients.push({ sessionID: message.to, delivered: false, reason: "cancelled" })
391
+ continue
392
+ }
393
+ const peer = this.registry.get(message.to)
394
+ if (!peer) {
395
+ recipients.push({ sessionID: message.to, delivered: false, reason: "session not known to the mesh" })
396
+ continue
397
+ }
398
+ // Defense in depth: the targets were resolved inside the wall, but a
399
+ // session whose location changed between resolution and delivery must
400
+ // not receive mail across it.
401
+ if (!this.#inScope(selfID, peer)) {
402
+ recipients.push({ sessionID: message.to, delivered: false, reason: `outside the ${this.options.scope} scope` })
403
+ continue
404
+ }
405
+ // `session.synthetic` on a foreign location may throw; the mailbox copy
406
+ // is the durable path, so a failure only downgrades delivery and is
407
+ // retried the next time the recipient touches a crosstalk tool.
408
+ const result = this.#deliverer
409
+ ? await this.#deliverer.deliver(message)
410
+ : { delivered: false, reason: "no deliverer configured" }
411
+ if (!result.delivered) this.#queuePending(message)
412
+ recipients.push({ sessionID: message.to, delivered: result.delivered, reason: result.reason })
413
+ }
414
+
415
+ return { recipients, skipped: targets.skipped, messages }
416
+ }
417
+
418
+ /**
419
+ * Retry injecting messages that were queued for `sessionID` but never made it
420
+ * into its live turn. Called before every tool execution, so a peer recovers
421
+ * from a failed injection as soon as it does anything at all. Returns how
422
+ * many were delivered by this attempt.
423
+ */
424
+ async flushPendingInjection(sessionID: string, signal?: AbortSignal): Promise<number> {
425
+ const queue = this.#pendingInjection.get(sessionID)
426
+ if (!queue || queue.length === 0) return 0
427
+
428
+ const cutoff = this.#clock.now() - this.options.messageTtlMs
429
+ const remaining: CrosstalkMessage[] = []
430
+ let delivered = 0
431
+
432
+ for (const message of queue) {
433
+ if (message.created < cutoff) continue
434
+ const peer = this.registry.get(message.to)
435
+ if (signal?.aborted || !peer) {
436
+ remaining.push(message)
437
+ continue
438
+ }
439
+ // The wall holds on retries too: a session that moved out of this
440
+ // location's project must not receive cross-project mail. The message
441
+ // stays queued in case the record catches up; it can never be injected.
442
+ if (!this.#deliverable(peer)) {
443
+ remaining.push(message)
444
+ continue
445
+ }
446
+ const result = this.#deliverer ? await this.#deliverer.deliver(message) : { delivered: false }
447
+ if (result.delivered) delivered += 1
448
+ else remaining.push(message)
449
+ }
450
+
451
+ if (remaining.length === 0) this.#pendingInjection.delete(sessionID)
452
+ else this.#pendingInjection.set(sessionID, remaining)
453
+ return delivered
454
+ }
455
+
456
+ /**
457
+ * A queued injection may only reach a session that is still provably inside
458
+ * this location's scope. Unknown locations pass (they were in scope when the
459
+ * message was queued, and an event may simply be missing); a provably
460
+ * different project or directory is refused.
461
+ */
462
+ #deliverable(target: Peer): boolean {
463
+ if (this.options.scope === "server") return true
464
+ if (this.options.scope === "project") {
465
+ const selfProject = this.#defaults.projectID
466
+ return selfProject === undefined || target.projectID === undefined || target.projectID === selfProject
467
+ }
468
+ const selfDirectory = this.#defaults.directory
469
+ return selfDirectory === undefined || target.directory === undefined || target.directory === selfDirectory
470
+ }
471
+
472
+ /** Messages still waiting to be injected into a session's live turn. */
473
+ pendingInjectionCount(sessionID: string): number {
474
+ return this.#pendingInjection.get(sessionID)?.length ?? 0
475
+ }
476
+
477
+ #queuePending(message: CrosstalkMessage): void {
478
+ const queue = this.#pendingInjection.get(message.to) ?? []
479
+ // Bounded: a recipient that never opens a tool call must not grow the
480
+ // server's memory without limit. Oldest queued injection goes first.
481
+ while (queue.length >= 50) queue.shift()
482
+ queue.push(message)
483
+ this.#pendingInjection.set(message.to, queue)
484
+ }
485
+
486
+ #resolveTargets(selfID: string, input: SendInput): { recipients: string[]; skipped: SendOutcome["skipped"] } {
487
+ const skipped: SendOutcome["skipped"] = []
488
+ if (input.all) {
489
+ // `all` reaches every peer inside the communication wall; a session
490
+ // whose project cannot be proven is never on the distribution list.
491
+ return {
492
+ recipients: this.registry.list(this.#filter(selfID, { strict: true })).map((p) => p.sessionID),
493
+ skipped,
494
+ }
495
+ }
496
+ if (input.to) {
497
+ const target = input.to.trim()
498
+ if (target === "") {
499
+ skipped.push({ target: "(empty)", reason: "no session id given" })
500
+ return { recipients: [], skipped }
501
+ }
502
+ if (target === selfID) {
503
+ skipped.push({ target, reason: "that is you" })
504
+ return { recipients: [], skipped }
505
+ }
506
+ if (this.registry.get(target)) {
507
+ if (!this.#visible(selfID, target)) {
508
+ skipped.push({ target, reason: `outside the ${this.options.scope} scope` })
509
+ return { recipients: [], skipped }
510
+ }
511
+ return { recipients: [target], skipped }
512
+ }
513
+ // Not a session id: try a declared human name, case-insensitively,
514
+ // among addressable peers only — names never cross the wall.
515
+ const wanted = target.toLowerCase()
516
+ const byName = this.registry
517
+ .list(this.#filter(selfID, { strict: true }))
518
+ .filter((peer) => peer.declared?.name?.toLowerCase() === wanted)
519
+ .map((peer) => peer.sessionID)
520
+ if (byName.length === 1) return { recipients: [byName[0] as string], skipped }
521
+ if (byName.length > 1) {
522
+ skipped.push({ target, reason: `"${target}" is claimed by ${byName.length} sessions; use a session id` })
523
+ return { recipients: [], skipped }
524
+ }
525
+ skipped.push({ target, reason: "session unknown; check crosstalk_peers for session ids and names" })
526
+ return { recipients: [], skipped }
527
+ }
528
+ if (input.role) {
529
+ const wanted = input.role.trim().toLowerCase()
530
+ const matches = this.registry
531
+ .list(this.#filter(selfID, { strict: true }))
532
+ .filter((peer) => peer.declared?.role?.toLowerCase() === wanted)
533
+ .map((peer) => peer.sessionID)
534
+ if (matches.length === 0) skipped.push({ target: `role:${input.role}`, reason: "no peer declared that role" })
535
+ return { recipients: matches, skipped }
536
+ }
537
+ skipped.push({ target: "(none)", reason: "give to, role, or all" })
538
+ return { recipients: [], skipped }
539
+ }
540
+
541
+ /**
542
+ * True when `target` is a peer this session may address: provably within the
543
+ * configured scope. An unknown location is a refusal, not a maybe.
544
+ */
545
+ #visible(selfID: string, target: string): boolean {
546
+ const peer = this.registry.get(target)
547
+ return peer !== undefined && this.#inScope(selfID, peer)
548
+ }
549
+
550
+ /**
551
+ * The communication wall. `scope: "server"` has no wall; otherwise the peer
552
+ * must carry a location that provably equals the caller's — a session whose
553
+ * project (or directory) is unknown cannot be messaged or waited on.
554
+ */
555
+ #inScope(selfID: string, peer: Peer): boolean {
556
+ const scope = this.options.scope
557
+ if (peer.sessionID === selfID || scope === "server") return true
558
+ const projectID = this.registry.get(selfID)?.projectID ?? this.#defaults.projectID
559
+ if (scope === "project") return projectID !== undefined && peer.projectID === projectID
560
+ const directory = this.registry.get(selfID)?.directory ?? this.#defaults.directory
561
+ return directory !== undefined && peer.directory === directory
562
+ }
563
+
564
+ /** Read, optionally block for, and optionally ack the caller's mail. */
565
+ async inbox(selfID: string, input: InboxInput, signal?: AbortSignal): Promise<InboxOutcome> {
566
+ this.ensureSelf(selfID)
567
+ const waitMs = Math.min(Math.max(0, input.waitMs ?? 0), this.options.maxWaitMs)
568
+
569
+ let messages: CrosstalkMessage[]
570
+ let reason: InboxOutcome["reason"] = "immediate"
571
+ if (waitMs > 0) {
572
+ const result = await this.mailbox.wait(selfID, waitMs, signal)
573
+ messages = result.messages
574
+ reason = result.reason
575
+ if (reason === "messages") {
576
+ // Re-read through the caller's filters; `wait` only filtered unread.
577
+ messages = this.mailbox.list(selfID, input)
578
+ }
579
+ } else {
580
+ messages = this.mailbox.list(selfID, input)
581
+ }
582
+
583
+ // Counted before acknowledging, so the header can say how much was unread
584
+ // even though this call is about to mark it read.
585
+ const unreadBefore = messages.filter((message) => message.readAt === undefined).length
586
+ const marked = input.markRead === false ? 0 : this.mailbox.markRead(selfID, messages.map((m) => m.id))
587
+ return {
588
+ messages,
589
+ reason,
590
+ marked,
591
+ unread: this.mailbox.unreadCount(selfID),
592
+ unreadBefore,
593
+ }
594
+ }
595
+
596
+ /** Resolve a message by id for reply-by-id; only the recipient's own mail counts. */
597
+ findMessage(selfID: string, id: string): CrosstalkMessage | undefined {
598
+ this.ensureSelf(selfID)
599
+ return this.mailbox.find(selfID, id)
600
+ }
601
+
602
+ /** Lease bookkeeping for the caller's session. */
603
+ claims_for(selfID: string): ClaimResult {
604
+ return { outcome: emptyOutcome(), held: this.claims.list({ holder: selfID }), ttlMs: this.#claimsExpiry(selfID) }
605
+ }
606
+
607
+ claim(selfID: string, input: ClaimInput): ClaimResult {
608
+ this.ensureSelf(selfID)
609
+ const baseDir = this.directoryOf(selfID)
610
+ const ttlMs = Math.min(Math.max(1, input.ttlMs ?? this.options.claimTtlMs), 86_400_000)
611
+ const resources = (input.resources ?? []).filter((r) => r.trim() !== "")
612
+
613
+ let outcome: ClaimOutcome
614
+ switch (input.action) {
615
+ case "claim":
616
+ outcome = this.claims.claim({
617
+ holder: selfID,
618
+ resources,
619
+ ttlMs,
620
+ baseDir,
621
+ ...(input.note ? { note: input.note } : {}),
622
+ ...(input.force !== undefined ? { force: input.force } : {}),
623
+ ...(input.atomic !== undefined ? { atomic: input.atomic } : {}),
624
+ })
625
+ break
626
+ case "renew":
627
+ outcome = this.claims.renew({
628
+ holder: selfID,
629
+ resources,
630
+ ttlMs,
631
+ baseDir,
632
+ ...(input.note ? { note: input.note } : {}),
633
+ ...(input.atomic !== undefined ? { atomic: input.atomic } : {}),
634
+ })
635
+ break
636
+ case "release":
637
+ outcome = this.claims.release({
638
+ holder: selfID,
639
+ resources,
640
+ baseDir,
641
+ ...(input.force !== undefined ? { force: input.force } : {}),
642
+ })
643
+ break
644
+ case "list": {
645
+ const held = this.claims.list({
646
+ holder: selfID,
647
+ baseDir,
648
+ ...(input.includeExpired ? { includeExpired: true } : {}),
649
+ })
650
+ return { outcome: emptyOutcome(), held, ttlMs }
651
+ }
652
+ }
653
+
654
+ return { outcome, held: this.claims.list({ holder: selfID }), ttlMs }
655
+ }
656
+
657
+ #claimsExpiry(selfID: string): number {
658
+ const held = this.claims.list({ holder: selfID })
659
+ const soonest = held.reduce((min, claim) => Math.min(min, claim.expires), Number.POSITIVE_INFINITY)
660
+ return Number.isFinite(soonest) ? Math.max(0, soonest - this.#clock.now()) : this.options.claimTtlMs
661
+ }
662
+
663
+ /** Block until a peer stops being busy, disappears, or the wait expires. */
664
+ async waitForPeerIdle(
665
+ selfID: string,
666
+ target: string,
667
+ timeoutMs: number,
668
+ signal?: AbortSignal,
669
+ ): Promise<PeerIdleResult> {
670
+ const start = this.#clock.now()
671
+ const limit = Math.min(Math.max(0, timeoutMs), this.options.maxWaitMs)
672
+ if (target === selfID) return { reason: "gone", elapsedMs: 0 }
673
+
674
+ const peer = this.registry.get(target)
675
+ if (!peer) return { reason: "gone", elapsedMs: 0 }
676
+ // Waiting on a peer is communication: the wall applies. A session outside
677
+ // the scope resolves at once instead of blocking until the timeout.
678
+ if (!this.#inScope(selfID, peer)) return { reason: "outside", elapsedMs: 0, status: peer.status }
679
+
680
+ for (;;) {
681
+ if (peer.status === "idle" || peer.status === "unknown") {
682
+ return { reason: "done", elapsedMs: this.#clock.now() - start, status: peer.status }
683
+ }
684
+ if (this.#clock.now() - start >= limit) {
685
+ return { reason: signal?.aborted ? "aborted" : "timeout", elapsedMs: this.#clock.now() - start, status: peer.status }
686
+ }
687
+ await delay(this.options.pollMs, signal)
688
+ if (signal?.aborted) return { reason: "aborted", elapsedMs: this.#clock.now() - start }
689
+ const current = this.registry.get(target)
690
+ if (!current) return { reason: "gone", elapsedMs: this.#clock.now() - start }
691
+ if (!this.#inScope(selfID, current)) return { reason: "outside", elapsedMs: this.#clock.now() - start, status: current.status }
692
+ if (current.status === "idle" || current.status === "unknown") {
693
+ return { reason: "done", elapsedMs: this.#clock.now() - start, status: current.status }
694
+ }
695
+ }
696
+ }
697
+
698
+ /** Block until a resource has no live lease. */
699
+ async waitForClaimFree(
700
+ _selfID: string,
701
+ resource: string,
702
+ timeoutMs: number,
703
+ baseDir?: string,
704
+ signal?: AbortSignal,
705
+ ): Promise<ClaimFreeResult> {
706
+ const start = this.#clock.now()
707
+ const limit = Math.min(Math.max(0, timeoutMs), this.options.maxWaitMs)
708
+ const key = this.claims.normalize(resource, baseDir)
709
+ const holderOf = (): string | undefined => {
710
+ const claim = this.claims.list({ resource: key, includeExpired: true })[0]
711
+ if (!claim || claim.expires <= this.#clock.now()) return undefined
712
+ return claim.holder
713
+ }
714
+
715
+ for (;;) {
716
+ const holder = holderOf()
717
+ if (holder === undefined) return { reason: "done", elapsedMs: this.#clock.now() - start }
718
+ if (this.#clock.now() - start >= limit) {
719
+ return {
720
+ reason: signal?.aborted ? "aborted" : "timeout",
721
+ elapsedMs: this.#clock.now() - start,
722
+ holder,
723
+ }
724
+ }
725
+ await delay(this.options.pollMs, signal)
726
+ if (signal?.aborted) return { reason: "aborted", elapsedMs: this.#clock.now() - start, holder }
727
+ }
728
+ }
729
+
730
+ /** Serializable state. Messages are intentionally left out. */
731
+ snapshot(): MeshSnapshot {
732
+ return {
733
+ version: SNAPSHOT_VERSION,
734
+ savedAt: this.#clock.now(),
735
+ peers: [...this.registry.list({ scope: "server" })].map((peer) => ({ ...peer })),
736
+ claims: this.claims.entries().map((claim) => ({ ...claim })),
737
+ }
738
+ }
739
+
740
+ /**
741
+ * Merge a snapshot back in. A session the live stream has already created
742
+ * keeps its freshness and only receives fields the stream never carried
743
+ * (declarations, project, directory); a session the registry has not seen is
744
+ * restored wholesale. Restored claims are dropped when the same key is
745
+ * already held. A v1 snapshot is migrated rather than rejected: peers (with
746
+ * their declarations and frozen portraits) are carried forward, but none of
747
+ * its claims are adopted — that lease table is exactly what the twin
748
+ * instances corrupted, and a resurrected ghost lease would harm live peers.
749
+ */
750
+ restore(snapshot: MeshSnapshot): void {
751
+ const legacy = snapshot.version === LEGACY_SNAPSHOT_VERSION
752
+ if (!legacy && snapshot.version !== SNAPSHOT_VERSION) return
753
+ for (const peer of snapshot.peers) {
754
+ if (!peer || typeof peer.sessionID !== "string") continue
755
+ const live = this.registry.get(peer.sessionID)
756
+ if (live) {
757
+ if (live.title === undefined && peer.title !== undefined) live.title = peer.title
758
+ if (live.agent === undefined && peer.agent !== undefined) live.agent = peer.agent
759
+ if (live.model === undefined && peer.model !== undefined) live.model = peer.model
760
+ if (live.parentID === undefined && peer.parentID !== undefined) live.parentID = peer.parentID
761
+ if (live.projectID === undefined && peer.projectID !== undefined) live.projectID = peer.projectID
762
+ if (live.directory === undefined && peer.directory !== undefined) live.directory = peer.directory
763
+ if (live.created === undefined && peer.created !== undefined) live.created = peer.created
764
+ if (live.declared === undefined && peer.declared !== undefined) live.declared = peer.declared
765
+ if (live.portrait === undefined && peer.portrait !== undefined) live.portrait = peer.portrait
766
+ continue
767
+ }
768
+ const restored = this.registry.ensure(peer.sessionID)
769
+ restored.status = peer.status ?? "unknown"
770
+ restored.lastSeen = typeof peer.lastSeen === "number" ? peer.lastSeen : this.#clock.now()
771
+ if (peer.title !== undefined) restored.title = peer.title
772
+ if (peer.agent !== undefined) restored.agent = peer.agent
773
+ if (peer.model !== undefined) restored.model = peer.model
774
+ if (peer.parentID !== undefined) restored.parentID = peer.parentID
775
+ if (peer.projectID !== undefined) restored.projectID = peer.projectID
776
+ if (peer.directory !== undefined) restored.directory = peer.directory
777
+ if (peer.created !== undefined) restored.created = peer.created
778
+ if (peer.declared !== undefined) restored.declared = peer.declared
779
+ if (peer.portrait !== undefined) restored.portrait = peer.portrait
780
+ }
781
+ if (legacy) return
782
+ const held = new Set(this.claims.entries().map((claim) => claim.key))
783
+ for (const claim of snapshot.claims) {
784
+ if (!claim || typeof claim.key !== "string" || held.has(claim.key)) continue
785
+ if (claim.expires <= this.#clock.now()) continue
786
+ this.claims.adopt(claim)
787
+ }
788
+ }
789
+ }
790
+
791
+ function emptyOutcome(): ClaimOutcome {
792
+ return { claimed: [], renewed: [], released: [], stolen: [], conflicts: [], rolledBack: false }
793
+ }
794
+
795
+ function sessionIDOrThrow(sessionID: string): string {
796
+ if (typeof sessionID !== "string" || sessionID === "") {
797
+ throw new Error("crosstalk: session id is required")
798
+ }
799
+ return sessionID
800
+ }