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,48 @@
1
+ /**
2
+ * @fileoverview The session directory the TUI plugin reads over RPC.
3
+ *
4
+ * Host-free: built straight from the mesh registry so it is unit-testable and
5
+ * stays in step with what `crosstalk_peers` sees.
6
+ */
7
+
8
+ import type { Mesh } from "./mesh.ts"
9
+
10
+ /** One session as the TUI needs it: identity, declared hints, location. */
11
+ export type DirectoryEntry = {
12
+ sessionID: string
13
+ status: "running" | "idle" | "unknown"
14
+ title?: string
15
+ name?: string
16
+ role?: string
17
+ goal?: string
18
+ /** Live status: 1-2 short sentences, refreshed as the session's work moves. */
19
+ summary?: string
20
+ /** When `summary` was declared, so a viewer can tell how current it is. */
21
+ summaryAt?: number
22
+ avatar?: string
23
+ directory?: string
24
+ projectID?: string
25
+ /** Frozen portrait (`pool/file` inside `assets/avatars/`); absent before the first task. */
26
+ portrait?: string
27
+ }
28
+
29
+ export type DirectoryPayload = { sessions: DirectoryEntry[] }
30
+
31
+ /** Every session the mesh has seen, with the fields a TUI needs. */
32
+ export function directoryPayload(mesh: Mesh): DirectoryPayload {
33
+ const sessions = mesh.registry.list().map((peer) => {
34
+ const entry: DirectoryEntry = { sessionID: peer.sessionID, status: peer.status }
35
+ if (peer.title !== undefined) entry.title = peer.title
36
+ if (peer.declared?.name !== undefined) entry.name = peer.declared.name
37
+ if (peer.declared?.role !== undefined) entry.role = peer.declared.role
38
+ if (peer.declared?.goal !== undefined) entry.goal = peer.declared.goal
39
+ if (peer.declared?.summary !== undefined) entry.summary = peer.declared.summary
40
+ if (peer.declared?.summaryAt !== undefined) entry.summaryAt = peer.declared.summaryAt
41
+ if (peer.declared?.avatar !== undefined) entry.avatar = peer.declared.avatar
42
+ if (peer.directory !== undefined) entry.directory = peer.directory
43
+ if (peer.projectID !== undefined) entry.projectID = peer.projectID
44
+ if (peer.portrait !== undefined) entry.portrait = peer.portrait
45
+ return entry
46
+ })
47
+ return { sessions }
48
+ }
@@ -0,0 +1,409 @@
1
+ /**
2
+ * @fileoverview Agent-facing rendering.
3
+ *
4
+ * Tool output is the only thing an agent sees, so these strings are part of
5
+ * the plugin's contract: compact, stable, and free of absolute paths the model
6
+ * cannot act on. Tests assert exact output, which is deliberate — a silent
7
+ * format change would degrade coordination without failing anything.
8
+ */
9
+
10
+ import type { ClaimOutcome, CrosstalkMessage, PeerView, Scope } from "../types.ts"
11
+
12
+ /** Compact relative age, e.g. `4s`, `12m`, `3h`. */
13
+ export function relativeAge(from: number, now: number): string {
14
+ const seconds = Math.max(0, Math.round((now - from) / 1000))
15
+ if (seconds < 60) return `${seconds}s`
16
+ const minutes = Math.round(seconds / 60)
17
+ if (minutes < 60) return `${minutes}m`
18
+ const hours = Math.round(minutes / 60)
19
+ if (hours < 48) return `${hours}h`
20
+ return `${Math.round(hours / 24)}d`
21
+ }
22
+
23
+ /** Trim a long value for one-line display. */
24
+ export function ellipsis(value: string, max: number): string {
25
+ const flat = value.replaceAll(/\s+/g, " ").trim()
26
+ if (flat.length <= max) return flat
27
+ return `${flat.slice(0, Math.max(0, max - 1))}…`
28
+ }
29
+
30
+ /**
31
+ * A summary younger than this is current. The peer line annotates its age only
32
+ * once a session has stopped refreshing it: a running session's live status
33
+ * needs no timestamp to be trusted, and every peer line paying for a clock it
34
+ * does not need is noise.
35
+ */
36
+ export const SUMMARY_FRESH_MS = 5 * 60_000
37
+
38
+ /**
39
+ * A summary older than this is *stale*: the sidebar already dims it (see
40
+ * `STALE_SUMMARY_MS` in `src/tui/avatar.ts`, which mirrors this value on
41
+ * purpose — the dim the user sees and the nudge the agent gets should land
42
+ * together), and the declaring session is told to refresh it.
43
+ */
44
+ export const SUMMARY_STALE_MS = 15 * 60_000
45
+
46
+ /**
47
+ * How long ago the peer declared its summary — ` (14m ago)`, or an empty
48
+ * string while it is fresh, missing (declared before the feature, or restored
49
+ * from a snapshot that predates it), or clock-skewed into the future. The
50
+ * window is closed at the boundary: exactly `SUMMARY_FRESH_MS` is still fresh,
51
+ * one millisecond past it is not — the same convention as the dim rule in
52
+ * `src/tui/avatar.ts`.
53
+ */
54
+ function summaryAge(peer: PeerView, now: number): string {
55
+ const at = peer.declared?.summaryAt
56
+ if (at === undefined || now - at <= SUMMARY_FRESH_MS) return ""
57
+ return ` (${relativeAge(at, now)} ago)`
58
+ }
59
+
60
+ function peerLine(peer: PeerView, now: number, scope: Scope): string {
61
+ const parts = [`- ${peer.sessionID}`]
62
+ if (peer.declared?.name) parts.push(`(${ellipsis(peer.declared.name, 32)})`)
63
+ if (peer.isSelf) parts.push("(you)")
64
+ parts.push(peer.stale ? `${peer.status}?` : peer.status)
65
+ if (peer.declared?.role) parts.push(`role=${ellipsis(peer.declared.role, 24)}`)
66
+ if (peer.declared?.goal) parts.push(`goal="${ellipsis(peer.declared.goal, 60)}"`)
67
+ // The self view prints role → goal → summary; keep a peer's line in the same
68
+ // order, with the summary's age once it stops being fresh.
69
+ if (peer.declared?.summary) {
70
+ parts.push(`summary="${ellipsis(peer.declared.summary, 60)}"${summaryAge(peer, now)}`)
71
+ }
72
+ if (peer.title) parts.push(`"${ellipsis(peer.title, 48)}"`)
73
+ if (peer.agent) parts.push(peer.agent)
74
+ parts.push(`active ${relativeAge(peer.lastSeen, now)} ago`)
75
+ if (peer.unread > 0) parts.push(`unread ${peer.unread}`)
76
+ if (peer.claims.length > 0) parts.push(`claims ${peer.claims.join(", ")}`)
77
+ if (!peer.addressable) parts.push(notAddressable(peer, scope))
78
+ return parts.join(" ")
79
+ }
80
+
81
+ /** Why a listed peer cannot be messaged, shown on its line. */
82
+ function notAddressable(peer: PeerView, scope: Scope): string {
83
+ return peer.projectID === undefined || peer.directory === undefined
84
+ ? "location unknown — not addressable"
85
+ : `outside the ${scope} scope — not addressable`
86
+ }
87
+
88
+ /**
89
+ * Plugin health for the calling location, rendered as one diagnostic line so
90
+ * install problems (double loads, lost snapshots) are visible to the model
91
+ * without spelunking logs.
92
+ */
93
+ export interface SelfCheck {
94
+ /** Communication wall in effect for this process. */
95
+ scope: Scope
96
+ /** Permission action that gates the whole tool namespace. */
97
+ permission: string
98
+ /** Whether the tools are exposed through Code Mode instead of directly. */
99
+ codemode: boolean
100
+ /** Messages whose injection is still pending for this session. */
101
+ pending?: number
102
+ /** Snapshot format this build writes and restores, e.g. `v2`. */
103
+ snapshot: string
104
+ /** Mesh storage key; only meaningful when `persist` is true. */
105
+ storageKey?: string
106
+ /** False when persistence is off: nothing survives a restart. */
107
+ persist: boolean
108
+ /** Locations the live plugin instances in this process own. Absent when unknown. */
109
+ locations?: number
110
+ /** Loads the location guard refused — more than zero means a duplicate install. */
111
+ refused?: number
112
+ }
113
+
114
+ export interface StatusViewInput {
115
+ self: PeerView
116
+ peers: PeerView[]
117
+ scope: Scope
118
+ now: number
119
+ hints?: string[]
120
+ selfCheck?: SelfCheck
121
+ }
122
+
123
+ export function formatStatus(input: StatusViewInput): string {
124
+ const { self, peers, now } = input
125
+ const lines: string[] = []
126
+ const header = [`crosstalk: you are ${self.sessionID}`]
127
+ if (self.declared?.name) header.push(`(${ellipsis(self.declared.name, 32)})`)
128
+ if (self.agent) header.push(`(${self.agent})`)
129
+ header.push(self.stale ? `${self.status}?` : self.status)
130
+ lines.push(header.join(" "))
131
+
132
+ if (self.title) lines.push(` session: ${ellipsis(self.title, 72)}`)
133
+ if (self.declared?.role) lines.push(` role: ${self.declared.role}`)
134
+ if (self.declared?.goal) lines.push(` goal: ${self.declared.goal}`)
135
+ // The own record annotates the summary by the same rule as a peer's line:
136
+ // silent while fresh, explicit once it is worth re-reading before trusting.
137
+ if (self.declared?.summary) {
138
+ lines.push(` summary: ${self.declared.summary}${summaryAge(self, now)}`)
139
+ }
140
+ if (self.declared?.workingOn && self.declared.workingOn.length > 0) {
141
+ lines.push(` working on: ${self.declared.workingOn.join(", ")}`)
142
+ }
143
+ if (self.claims.length > 0) lines.push(` your claims: ${self.claims.join(", ")}`)
144
+
145
+ if (input.selfCheck) {
146
+ const check = input.selfCheck
147
+ const parts = [
148
+ `snapshot ${check.snapshot}`,
149
+ `scope ${check.scope}`,
150
+ `action ${check.permission}`,
151
+ check.codemode ? "code mode" : "direct",
152
+ ]
153
+ if (check.pending !== undefined && check.pending > 0) parts.push(`${check.pending} pending injection`)
154
+ if (check.persist && check.storageKey !== undefined) parts.push(`storage ${check.storageKey}`)
155
+ if (!check.persist) parts.push("persistence off")
156
+ if (check.locations !== undefined) parts.push(`${check.locations} location${check.locations === 1 ? "" : "s"} owned`)
157
+ if (check.refused !== undefined && check.refused > 0) parts.push(`${check.refused} refused load${check.refused === 1 ? "" : "s"}`)
158
+ lines.push(` self-check: ${parts.join(" · ")}`)
159
+ }
160
+
161
+ const running = peers.filter((p) => p.status === "running").length
162
+ const idle = peers.filter((p) => p.status === "idle").length
163
+ const stale = peers.filter((p) => p.stale).length
164
+ const counts = [`${peers.length} peer${peers.length === 1 ? "" : "s"}`, `${running} running`, `${idle} idle`]
165
+ if (stale > 0) counts.push(`${stale} stale`)
166
+ lines.push(` peers on this channel (${input.scope}): ${counts.join(", ")}`)
167
+ for (const peer of peers) lines.push(` ${peerLine(peer, now, input.scope)}`)
168
+ if (peers.length === 0) {
169
+ lines.push(" (none — you are the only session here; crosstalk_wait will just time out)")
170
+ }
171
+ for (const hint of input.hints ?? []) lines.push(` ${hint}`)
172
+ return lines.join("\n")
173
+ }
174
+
175
+ export interface PeersViewInput {
176
+ self: PeerView
177
+ peers: PeerView[]
178
+ scope: Scope
179
+ now: number
180
+ /**
181
+ * Set when the caller asked for an overlap filter. The `paths` are echoed in
182
+ * the header and in the empty answer, so the model sees what the filter was
183
+ * about; `considered` is how many peers the channel held before the filter
184
+ * narrowed them, which distinguishes "nobody is here" from "nobody overlaps".
185
+ */
186
+ overlap?: { paths: readonly string[]; considered: number }
187
+ }
188
+
189
+ export function formatPeers(input: PeersViewInput): string {
190
+ const { peers, now } = input
191
+ const lines: string[] = []
192
+ // The paths are echoed so an empty answer still says what the filter was about.
193
+ const paths = input.overlap ? ellipsis(input.overlap.paths.join(", "), 120) : ""
194
+ if (peers.length === 0) {
195
+ if (input.overlap) {
196
+ const others = input.overlap.considered
197
+ return [
198
+ `crosstalk: no peers overlap ${paths} (scope ${input.scope}).`,
199
+ others > 0
200
+ ? `${others} other session${others === 1 ? "" : "s"} on this channel, but none leases or works on those exact` +
201
+ " paths — you do not need to claim anything."
202
+ : "Nobody else is on this channel, so nothing can overlap — you do not need to claim anything.",
203
+ ].join("\n")
204
+ }
205
+ return [
206
+ `crosstalk: no other sessions on this channel (scope ${input.scope}).`,
207
+ "Nobody is competing for files right now; you do not need to claim anything.",
208
+ ].join("\n")
209
+ }
210
+ const running = peers.filter((p) => p.status === "running").length
211
+ lines.push(
212
+ `crosstalk peers (scope ${input.scope}, ${peers.length} found, ${running} running${input.overlap ? `, overlap ${paths}` : ""}):`,
213
+ )
214
+ const you = [`you: ${input.self.sessionID}`]
215
+ if (input.self.declared?.name) you.push(`(${ellipsis(input.self.declared.name, 32)})`)
216
+ you.push(input.self.status)
217
+ you.push(input.self.declared?.role ? `role=${input.self.declared.role}` : "role=undeclared")
218
+ lines.push(` ${you.join(" ")}`)
219
+ for (const peer of peers) lines.push(` ${peerLine(peer, now, input.scope)}`)
220
+ return lines.join("\n")
221
+ }
222
+
223
+ export interface MessageViewInput {
224
+ message: CrosstalkMessage
225
+ now: number
226
+ }
227
+
228
+ export function formatMessage(input: MessageViewInput): string {
229
+ const { message, now } = input
230
+ const parts = [`from ${message.from}`]
231
+ if (message.fromName) parts.push(`(${message.fromName})`)
232
+ if (message.fromRole) parts.push(`(${message.fromRole})`)
233
+ parts.push(`· ${message.kind}`)
234
+ if (message.topic) parts.push(`· topic ${message.topic}`)
235
+ parts.push(`· ${relativeAge(message.created, now)} ago`)
236
+ return parts.join(" ")
237
+ }
238
+
239
+ export interface InboxViewInput {
240
+ self: PeerView
241
+ messages: CrosstalkMessage[]
242
+ marked: number
243
+ now: number
244
+ reason?: "messages" | "timeout" | "aborted" | "immediate"
245
+ limit?: number
246
+ /** Unread count observed *before* this call marked anything read. */
247
+ unread?: number
248
+ }
249
+
250
+ export function formatInbox(input: InboxViewInput): string {
251
+ const { messages, now } = input
252
+ const lines: string[] = []
253
+ const unread = input.unread ?? input.self.unread
254
+ const head = `crosstalk inbox for ${input.self.sessionID}: ${messages.length} message${messages.length === 1 ? "" : "s"}`
255
+ if (unread > 0) lines.push(`${head} (${unread} unread)`)
256
+ else lines.push(head)
257
+
258
+ if (messages.length === 0) {
259
+ if (input.reason === "timeout") lines.push(" nothing arrived before the wait expired")
260
+ else if (input.reason === "aborted") lines.push(" wait cancelled before a message arrived")
261
+ else lines.push(" empty")
262
+ return lines.join("\n")
263
+ }
264
+
265
+ for (const message of messages) {
266
+ lines.push(` [${message.id}] ${formatMessage({ message, now })}`)
267
+ for (const line of message.text.split("\n")) lines.push(` ${line}`)
268
+ if (message.kind === "request") {
269
+ lines.push(` ↳ answer with crosstalk_send to ${message.fromName ?? message.from}`)
270
+ } else if (message.kind === "decline") {
271
+ lines.push(" ↳ declined — no answer needed; reroute instead")
272
+ }
273
+ const task = (message.meta as { task?: Record<string, unknown> } | undefined)?.task
274
+ if (task) {
275
+ const parts: string[] = []
276
+ if (Array.isArray(task.writeScope) && task.writeScope.length > 0) parts.push(`files ${task.writeScope.join(", ")}`)
277
+ if (typeof task.validation === "string") parts.push(`gate ${task.validation}`)
278
+ if (typeof task.evidence === "string") parts.push(`evidence ${task.evidence}`)
279
+ if (parts.length > 0) lines.push(` brief: ${parts.join("; ")}`)
280
+ }
281
+ }
282
+ if (input.limit !== undefined && messages.length >= input.limit) {
283
+ lines.push(` (showing the most recent ${input.limit}; raise the limit for more)`)
284
+ }
285
+ if (input.marked > 0) lines.push(` marked ${input.marked} message${input.marked === 1 ? "" : "s"} read`)
286
+ return lines.join("\n")
287
+ }
288
+
289
+ export interface SendViewInput {
290
+ self: PeerView
291
+ recipients: Array<{ sessionID: string; delivered: boolean; reason?: string }>
292
+ skipped: Array<{ target: string; reason: string }>
293
+ text: string
294
+ now: number
295
+ }
296
+
297
+ export function formatSend(input: SendViewInput): string {
298
+ const lines: string[] = []
299
+ const delivered = input.recipients.filter((r) => r.delivered).length
300
+ const queued = input.recipients.length - delivered
301
+ const head = `crosstalk: signalled ${input.recipients.length} session${input.recipients.length === 1 ? "" : "s"}`
302
+ lines.push(`${head} (${delivered} delivered now, ${queued} queued in mailbox)`)
303
+
304
+ for (const recipient of input.recipients) {
305
+ lines.push(
306
+ recipient.delivered
307
+ ? ` ✓ ${recipient.sessionID}`
308
+ : ` · ${recipient.sessionID} — queued only${recipient.reason ? `: ${recipient.reason}` : ""}`,
309
+ )
310
+ }
311
+ for (const skip of input.skipped) {
312
+ const hint = skip.reason.startsWith("outside the") ? " — ask the user or a shared-scope peer to relay" : ""
313
+ lines.push(` - ${skip.target}: ${skip.reason}${hint}`)
314
+ }
315
+ if (input.skipped.length === 0 && input.recipients.length === 0) {
316
+ lines.push(" no matching peers — check crosstalk_peers, or send with all: true")
317
+ }
318
+ lines.push(` message: ${ellipsis(input.text, 160)}`)
319
+ return lines.join("\n")
320
+ }
321
+
322
+ export interface ClaimViewInput {
323
+ self: PeerView
324
+ outcome: ClaimOutcome
325
+ ttlMs: number
326
+ now: number
327
+ held: Array<{ key: string; expires: number; note?: string }>
328
+ }
329
+
330
+ export function formatClaims(input: ClaimViewInput): string {
331
+ const { outcome, now } = input
332
+ const lines: string[] = []
333
+
334
+ if (outcome.conflicts.length > 0) {
335
+ lines.push(
336
+ `crosstalk claim: refused — ${outcome.conflicts.length} resource${outcome.conflicts.length === 1 ? "" : "s"} already leased`,
337
+ )
338
+ for (const conflict of outcome.conflicts) {
339
+ const who = conflict.holder || "unknown"
340
+ const note = conflict.note ? ` (${conflict.note})` : ""
341
+ const expires = conflict.expires > 0 ? `, free in ${relativeAge(now, conflict.expires)}` : ""
342
+ lines.push(` - ${conflict.raw} held by ${who}${note}${expires}`)
343
+ }
344
+ lines.push(" wait for them with crosstalk_wait, signal them with crosstalk_send, or pass force: true to steal.")
345
+ if (outcome.rolledBack) lines.push(" nothing was claimed (atomic request).")
346
+ return lines.join("\n")
347
+ }
348
+
349
+ const acquired = outcome.claimed.length
350
+ const renewed = outcome.renewed.length
351
+ const released = outcome.released.length
352
+ const stolen = outcome.stolen.length
353
+ const parts: string[] = []
354
+ if (acquired > 0) parts.push(`${acquired} claimed`)
355
+ if (renewed > 0) parts.push(`${renewed} renewed`)
356
+ if (released > 0) parts.push(`${released} released`)
357
+ if (stolen > 0) parts.push(`${stolen} stolen from another session`)
358
+ lines.push(`crosstalk claim: ${parts.length > 0 ? parts.join(", ") : "nothing to do"}`)
359
+
360
+ for (const key of outcome.claimed) lines.push(` + ${key} (lease ${Math.round(input.ttlMs / 1000)}s)`)
361
+ for (const key of outcome.renewed) lines.push(` ~ ${key}`)
362
+ for (const key of outcome.released) lines.push(` - ${key} released`)
363
+
364
+ if (input.held.length > 0) {
365
+ lines.push(" you currently hold:")
366
+ for (const claim of input.held) {
367
+ const note = claim.note ? ` (${claim.note})` : ""
368
+ lines.push(` ${claim.key} expires in ${relativeAge(now, claim.expires)}${note}`)
369
+ }
370
+ } else {
371
+ lines.push(" you hold no leases")
372
+ }
373
+ return lines.join("\n")
374
+ }
375
+
376
+ export interface WaitViewInput {
377
+ forWhat: "peer_idle" | "claim_free"
378
+ reason: WaitReasonLike
379
+ elapsedMs: number
380
+ detail?: string
381
+ }
382
+
383
+ type WaitReasonLike = "done" | "timeout" | "aborted" | "gone" | "outside"
384
+
385
+ export function formatWait(input: WaitViewInput): string {
386
+ const lines: string[] = []
387
+ const what = input.forWhat === "peer_idle" ? "peer idle" : "claim free"
388
+ const seconds = Math.round(input.elapsedMs / 100) / 10
389
+ if (input.reason === "done") {
390
+ lines.push(`crosstalk wait: ${what} after ${seconds}s${input.detail ? ` — ${input.detail}` : ""}`)
391
+ return lines.join("\n")
392
+ }
393
+ if (input.reason === "gone") {
394
+ lines.push(`crosstalk wait: ${input.detail ?? "target is gone"} after ${seconds}s`)
395
+ return lines.join("\n")
396
+ }
397
+ if (input.reason === "outside") {
398
+ lines.push(`crosstalk wait: ${input.detail ?? "target is outside the communication scope"} after ${seconds}s`)
399
+ return lines.join("\n")
400
+ }
401
+ if (input.reason === "aborted") {
402
+ lines.push(`crosstalk wait: cancelled after ${seconds}s while waiting for ${what}`)
403
+ return lines.join("\n")
404
+ }
405
+ lines.push(
406
+ `crosstalk wait: timed out after ${seconds}s waiting for ${what}${input.detail ? ` — ${input.detail}` : ""}`,
407
+ )
408
+ return lines.join("\n")
409
+ }