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,87 @@
1
+ /**
2
+ * @fileoverview `crosstalk_claim` — exclusive, expiring leases on files.
3
+ *
4
+ * This is the tool that makes two agents safe on one repository: a claim is a
5
+ * hard lease, not a note in the conversation, and the default atomic behaviour
6
+ * means a batch request that touches one busy file takes nothing at all.
7
+ */
8
+
9
+ import { formatClaims } from "../core/format.ts"
10
+ import { readBoolean, readEnum, readNumber, readString, readStringArray } from "./args.ts"
11
+ import { jsonSchema, run, type CrosstalkToolInfo, type ToolDeps } from "./types.ts"
12
+
13
+ export function claimTool(deps: ToolDeps): CrosstalkToolInfo {
14
+ return {
15
+ name: "claim",
16
+ description: [
17
+ "Take an exclusive, expiring lease on files or named resources so another session does not",
18
+ "edit them at the same time. Claim before you edit, release when you are done, renew if you",
19
+ "work longer than the lease. If a file is already leased the request is refused and tells you",
20
+ "who holds it — signal them with crosstalk_send, wait with crosstalk_wait, or pass force: true.",
21
+ "Paths are normalized, and relative paths resolve against this session's directory.",
22
+ "Claim keys are exact: there is no glob expansion, and leasing a directory",
23
+ "does not cover the files inside it — claim each file you edit.",
24
+ ].join(" "),
25
+ input: jsonSchema({
26
+ type: "object",
27
+ properties: {
28
+ action: {
29
+ type: "string",
30
+ enum: ["claim", "renew", "release", "list"],
31
+ description: "Operation. 'list' reports the leases you hold and needs no resources.",
32
+ },
33
+ resources: {
34
+ type: "array",
35
+ items: { type: "string" },
36
+ description: "Exact normalized file paths (src/a.ts, src/auth/login.ts) or named resources (db:migrate). No globs: '**' is an ordinary path segment, not a pattern",
37
+ },
38
+ ttlSeconds: { type: "number", description: "Lease duration in seconds (default 300, max 86400)" },
39
+ note: { type: "string", description: "Why you hold it — shown to the peer you block" },
40
+ force: { type: "boolean", description: "Steal a lease held by another session" },
41
+ atomic: {
42
+ type: "boolean",
43
+ description: "On conflict take nothing (default true). false claims whatever is free",
44
+ },
45
+ includeExpired: { type: "boolean", description: "Include lapsed leases in list output" },
46
+ },
47
+ required: ["action"],
48
+ additionalProperties: false,
49
+ }),
50
+ async execute(input, context) {
51
+ return run(() => {
52
+ const action = readEnum(input, "action", ["claim", "renew", "release", "list"] as const, undefined)
53
+ if (action === undefined) {
54
+ return 'crosstalk: "action" is required (claim, renew, release, or list)'
55
+ }
56
+ const resources = readStringArray(input, "resources", { max: 64, maxLength: 400 })
57
+ const ttlSeconds = readNumber(input, "ttlSeconds", { min: 1, max: 86_400 })
58
+ const note = readString(input, "note", { max: 200 })
59
+ const force = readBoolean(input, "force", false)
60
+ const atomic = readBoolean(input, "atomic", true)
61
+ const includeExpired = readBoolean(input, "includeExpired", false)
62
+
63
+ if (action !== "list" && (resources === undefined || resources.length === 0)) {
64
+ return `crosstalk: action "${action}" needs "resources" (use action "list" to see what you hold)`
65
+ }
66
+
67
+ const result = deps.mesh.claim(context.sessionID, {
68
+ action,
69
+ ...(resources ? { resources } : {}),
70
+ ...(ttlSeconds !== undefined ? { ttlMs: ttlSeconds * 1000 } : {}),
71
+ ...(note ? { note } : {}),
72
+ force,
73
+ atomic,
74
+ includeExpired,
75
+ })
76
+
77
+ return formatClaims({
78
+ self: deps.mesh.view(context.sessionID),
79
+ outcome: result.outcome,
80
+ ttlMs: result.ttlMs,
81
+ now: deps.mesh.now(),
82
+ held: result.held,
83
+ })
84
+ })
85
+ },
86
+ }
87
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @fileoverview `crosstalk_continue` — steer an existing session by exact id.
3
+ *
4
+ * Continuation reuses the peer's context instead of spawning a new lane. It is
5
+ * a thin, explicit spelling of `send { to: <exact session id> }` with queued
6
+ * delivery, so the intent is visible in a report and the target cannot be a
7
+ * name that another session now claims.
8
+ */
9
+
10
+ import { formatSend } from "../core/format.ts"
11
+ import { readEnum, readString } from "./args.ts"
12
+ import { jsonSchema, run, type CrosstalkToolInfo, type ToolDeps } from "./types.ts"
13
+
14
+ export function continueTool(deps: ToolDeps): CrosstalkToolInfo {
15
+ return {
16
+ name: "continue",
17
+ description: [
18
+ "Continue an existing session by its exact session ID (see crosstalk_peers), preserving its",
19
+ "context instead of starting a new task. Defaults to queued delivery. The communication wall",
20
+ "still applies: out-of-scope and unknown sessions are refused.",
21
+ ].join(" "),
22
+ input: jsonSchema({
23
+ type: "object",
24
+ properties: {
25
+ sessionID: { type: "string", description: "Exact session ID to continue" },
26
+ prompt: { type: "string", description: "What the peer should do next" },
27
+ topic: { type: "string", description: "Optional thread label" },
28
+ delivery: {
29
+ type: "string",
30
+ enum: ["steer", "queue"],
31
+ description: "'queue' (default) waits for the peer's turn to end; 'steer' folds into it now",
32
+ },
33
+ },
34
+ required: ["sessionID", "prompt"],
35
+ additionalProperties: false,
36
+ }),
37
+ async execute(input, context) {
38
+ return run(async () => {
39
+ const sessionID = readString(input, "sessionID", { required: true, max: 200 })
40
+ const prompt = readString(input, "prompt", { required: true, max: 8_000 })
41
+ const topic = readString(input, "topic", { max: 80 })
42
+ const delivery = readEnum(input, "delivery", ["steer", "queue"] as const, "queue")
43
+
44
+ const outcome = await deps.mesh.send(
45
+ context.sessionID,
46
+ {
47
+ to: sessionID,
48
+ text: prompt,
49
+ kind: "request",
50
+ delivery,
51
+ ...(topic ? { topic } : {}),
52
+ },
53
+ context.signal,
54
+ )
55
+ if (outcome.skipped.some((skip) => /session unknown/.test(skip.reason))) {
56
+ return `crosstalk continue: ${sessionID} is not on this channel — check crosstalk_peers for session ids`
57
+ }
58
+ return formatSend({
59
+ self: deps.mesh.view(context.sessionID),
60
+ recipients: outcome.recipients,
61
+ skipped: outcome.skipped,
62
+ text: prompt,
63
+ now: deps.mesh.now(),
64
+ })
65
+ })
66
+ },
67
+ }
68
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * @fileoverview `crosstalk_heartbeat` — send a message to a peer on an interval.
3
+ *
4
+ * Useful for "check in every 30 s" coordination without the caller having to
5
+ * poll. Each started heartbeat is tracked per sender session and can be stopped
6
+ * or listed. Timers are unref'd so they never keep the process alive.
7
+ */
8
+
9
+ import { readBoolean, readEnum, readNumber, readString } from "./args.ts"
10
+ import { jsonSchema, run, type CrosstalkToolInfo, type ToolDeps } from "./types.ts"
11
+
12
+ interface Heartbeat {
13
+ id: string
14
+ sessionID: string
15
+ to?: string
16
+ role?: string
17
+ all?: boolean
18
+ text: string
19
+ topic?: string
20
+ kind?: "message" | "status" | "request" | "answer" | "system"
21
+ intervalMs: number
22
+ count: number // 0 = forever
23
+ sent: number
24
+ timer: ReturnType<typeof setInterval>
25
+ }
26
+
27
+ const heartbeats = new Map<string, Heartbeat>()
28
+ let seq = 0
29
+
30
+ export function heartbeatTool(deps: ToolDeps): CrosstalkToolInfo {
31
+ return {
32
+ name: "heartbeat",
33
+ description: [
34
+ "Send a message to another session on a repeating interval. Use this for periodic",
35
+ "check-ins (e.g. \"report status every 30 s\") without polling. Actions: 'start' begins a",
36
+ "heartbeat, 'stop' cancels one by id, 'list' shows this session's active heartbeats.",
37
+ "Timers are unref'd and stop automatically when the session ends.",
38
+ ].join(" "),
39
+ input: jsonSchema({
40
+ type: "object",
41
+ properties: {
42
+ action: {
43
+ type: "string",
44
+ enum: ["start", "stop", "list"],
45
+ description: "What to do. Defaults to 'start'.",
46
+ },
47
+ id: { type: "string", description: "Heartbeat id (for 'stop')." },
48
+ to: { type: "string", description: "Recipient session id or declared name." },
49
+ role: { type: "string", description: "Send to every peer with this role." },
50
+ all: { type: "boolean", description: "Send to every peer." },
51
+ text: { type: "string", description: "Message body." },
52
+ topic: { type: "string", description: "Optional thread label." },
53
+ kind: {
54
+ type: "string",
55
+ enum: ["message", "status", "request", "answer", "system"],
56
+ description: "Intent.",
57
+ },
58
+ intervalSeconds: {
59
+ type: "number",
60
+ description: "Seconds between sends. Min 5, max 3600. Defaults to 30.",
61
+ },
62
+ count: {
63
+ type: "number",
64
+ description: "How many times to send. 0 = forever (until stopped). Defaults to 0.",
65
+ },
66
+ },
67
+ required: [],
68
+ additionalProperties: false,
69
+ }),
70
+ async execute(input, context) {
71
+ return run(async () => {
72
+ const action = readEnum(input, "action", ["start", "stop", "list"] as const, "start")
73
+ const sessionID = context.sessionID
74
+
75
+ if (action === "list") {
76
+ const mine = [...heartbeats.values()].filter((h) => h.sessionID === sessionID)
77
+ if (mine.length === 0) return "crosstalk: no active heartbeats"
78
+ return "crosstalk: active heartbeats:\n" + mine
79
+ .map((h) => ` ${h.id} every ${h.intervalMs / 1000}s sent ${h.sent}/${h.count || "∞"} to=${h.to ?? h.role ?? (h.all ? "all" : "?")}`)
80
+ .join("\n")
81
+ }
82
+
83
+ if (action === "stop") {
84
+ const id = readString(input, "id", { required: true, max: 64 })
85
+ const h = heartbeats.get(id)
86
+ if (!h || h.sessionID !== sessionID)
87
+ return `crosstalk: no heartbeat '${id}' owned by this session`
88
+ clearInterval(h.timer)
89
+ heartbeats.delete(id)
90
+ return `crosstalk: stopped heartbeat ${id} (sent ${h.sent})`
91
+ }
92
+
93
+ // start
94
+ const text = readString(input, "text", { required: true, max: 8_000 })
95
+ const to = readString(input, "to", { max: 200 })
96
+ const role = readString(input, "role", { max: 64 })
97
+ const all = readBoolean(input, "all", false)
98
+ const topic = readString(input, "topic", { max: 80 })
99
+ const kind = readEnum(input, "kind", ["message", "status", "request", "answer", "system"] as const, "message")
100
+ if (!to && !role && !all)
101
+ return 'crosstalk: give one of "to", "role", or "all": true'
102
+ const intervalSeconds = Math.max(5, Math.min(3600, readNumber(input, "intervalSeconds", { fallback: 30 }) ?? 30))
103
+ const count = Math.max(0, Math.floor(readNumber(input, "count", { fallback: 0 }) ?? 0))
104
+ const intervalMs = intervalSeconds * 1000
105
+
106
+ const id = `hb-${++seq}`
107
+ let sent = 0
108
+
109
+ const sendOne = async () => {
110
+ sent++
111
+ const h = heartbeats.get(id)
112
+ if (!h) return
113
+ try {
114
+ await deps.mesh.send(sessionID, {
115
+ text,
116
+ ...(to ? { to } : {}),
117
+ ...(role ? { role } : {}),
118
+ ...(all ? { all: true } : {}),
119
+ ...(topic ? { topic } : {}),
120
+ ...(kind ? { kind } : {}),
121
+ }, new AbortController().signal)
122
+ } catch {
123
+ // ignore delivery failures; the next tick retries
124
+ }
125
+ h.sent = sent
126
+ if (count > 0 && sent >= count) {
127
+ clearInterval(h.timer)
128
+ heartbeats.delete(id)
129
+ }
130
+ }
131
+
132
+ const timer = setInterval(() => { void sendOne() }, intervalMs)
133
+ timer.unref?.()
134
+
135
+ const h: Heartbeat = {
136
+ id, sessionID, text, intervalMs, count, sent: 0, timer,
137
+ ...(to ? { to } : {}),
138
+ ...(role ? { role } : {}),
139
+ ...(all ? { all: true } : {}),
140
+ ...(topic ? { topic } : {}),
141
+ ...(kind ? { kind } : {}),
142
+ }
143
+ heartbeats.set(id, h)
144
+
145
+ // Send the first one immediately.
146
+ void sendOne()
147
+
148
+ return `crosstalk: started heartbeat ${id} (every ${intervalSeconds}s, ${count || "∞"} sends) to ${to || role || "all"}`
149
+ })
150
+ },
151
+ }
152
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * @fileoverview `crosstalk_inbox` — read and acknowledge mail from peers.
3
+ */
4
+
5
+ import { formatInbox } from "../core/format.ts"
6
+ import { readBoolean, readNumber, readString } from "./args.ts"
7
+ import { clampWait, jsonSchema, run, startHeartbeat, type CrosstalkToolInfo, type ToolDeps } from "./types.ts"
8
+
9
+ export function inboxTool(deps: ToolDeps): CrosstalkToolInfo {
10
+ return {
11
+ name: "inbox",
12
+ description: [
13
+ "Read messages other sessions sent you. Set wait to block until something arrives (or the",
14
+ "timeout expires) instead of returning an empty inbox — useful when you are waiting on a peer",
15
+ "to finish. Messages are marked read unless you pass markRead: false.",
16
+ ].join(" "),
17
+ input: jsonSchema({
18
+ type: "object",
19
+ properties: {
20
+ wait: {
21
+ type: "number",
22
+ description: "Seconds to block for a new message. 0 returns immediately. Capped by plugin config.",
23
+ },
24
+ limit: { type: "number", description: "Maximum messages to return (most recent, default 20)" },
25
+ topic: { type: "string", description: "Only messages with this topic" },
26
+ unreadOnly: { type: "boolean", description: "Skip messages you already read" },
27
+ since: { type: "string", description: "Return only messages after this message ID" },
28
+ markRead: { type: "boolean", description: "Mark the returned messages read (default true)" },
29
+ },
30
+ additionalProperties: false,
31
+ }),
32
+ async execute(input, context) {
33
+ return run(async () => {
34
+ const waitSeconds = readNumber(input, "wait", { min: 0, max: 600, fallback: 0 })
35
+ const limit = readNumber(input, "limit", { min: 1, max: 200, fallback: 20 })
36
+ const topic = readString(input, "topic", { max: 80 })
37
+ const unreadOnly = readBoolean(input, "unreadOnly", false)
38
+ const since = readString(input, "since", { max: 80 })
39
+ const markRead = readBoolean(input, "markRead", true)
40
+ const waitMs = clampWait((waitSeconds ?? 0) * 1000, deps.options)
41
+
42
+ const stop = startHeartbeat(context, deps.options.heartbeatMs, () => ({
43
+ status: "waiting",
44
+ waitSeconds: Math.round(waitMs / 1000),
45
+ }))
46
+ let outcome
47
+ try {
48
+ outcome = await deps.mesh.inbox(
49
+ context.sessionID,
50
+ {
51
+ waitMs,
52
+ markRead,
53
+ limit,
54
+ ...(unreadOnly ? { unreadOnly: true } : {}),
55
+ ...(topic ? { topic } : {}),
56
+ ...(since ? { since } : {}),
57
+ },
58
+ context.signal,
59
+ )
60
+ } finally {
61
+ stop()
62
+ }
63
+
64
+ return formatInbox({
65
+ self: deps.mesh.view(context.sessionID),
66
+ messages: outcome.messages,
67
+ marked: outcome.marked,
68
+ unread: outcome.unreadBefore,
69
+ now: deps.mesh.now(),
70
+ reason: outcome.reason,
71
+ ...(limit !== undefined ? { limit } : {}),
72
+ })
73
+ })
74
+ },
75
+ }
76
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @fileoverview Tool registration.
3
+ *
4
+ * All seven tools share one namespace and one permission action, so a project can
5
+ * allow or deny coordination with a single rule.
6
+ */
7
+
8
+ import type { ToolEditor } from "@opencode/plugin/promise/tool"
9
+ import { claimTool } from "./claim.ts"
10
+ import { continueTool } from "./continue.ts"
11
+ import { heartbeatTool } from "./heartbeat.ts"
12
+ import { replyTool } from "./reply.ts"
13
+ import { inboxTool } from "./inbox.ts"
14
+ import { peersTool } from "./peers.ts"
15
+ import { sendTool } from "./send.ts"
16
+ import { statusTool } from "./status.ts"
17
+ import { waitTool } from "./wait.ts"
18
+ import type { CrosstalkToolInfo, ToolDeps } from "./types.ts"
19
+
20
+ export const NAMESPACE_DESCRIPTION =
21
+ "Coordinate with the other OpenCode sessions on this project: discover peers, exchange messages, " +
22
+ "and lease files so two agents never edit the same path at once. Start with status, then peers."
23
+
24
+ /** Tool factories in registration order. */
25
+ export const toolFactories: Array<(deps: ToolDeps) => CrosstalkToolInfo> = [
26
+ statusTool,
27
+ peersTool,
28
+ sendTool,
29
+ replyTool,
30
+ continueTool,
31
+ inboxTool,
32
+ claimTool,
33
+ heartbeatTool,
34
+ waitTool,
35
+ ]
36
+
37
+ /**
38
+ * Register the namespace and every tool. Must run inside
39
+ * `ctx.tool.transform`, whose callback has to stay synchronous and cheap.
40
+ *
41
+ * Every executor is wrapped to retry queued injections first, so a message
42
+ * whose delivery failed — most likely because the recipient's session belongs
43
+ * to another location — still reaches its turn the moment that session next
44
+ * calls any crosstalk tool.
45
+ */
46
+ export function registerTools(editor: ToolEditor, deps: ToolDeps): void {
47
+ editor.namespace({ name: deps.options.namespace, description: NAMESPACE_DESCRIPTION })
48
+ // The optional guard counts only calls whose input AND result are identical
49
+ // to the previous one, so a repeated read of changed mail never counts.
50
+ // `inbox`, leases, status and waits are exempt: blocking retrieval would
51
+ // deadlock the recovery path the guard is meant to protect.
52
+ const guarded = new Set(["send", "reply"])
53
+ const loopState = new Map<string, { key: string; result: string; count: number }>()
54
+ for (const factory of toolFactories) {
55
+ const tool = factory(deps)
56
+ const execute = tool.execute
57
+ editor.add({
58
+ ...tool,
59
+ execute: async (input, context) => {
60
+ await deps.mesh.flushPendingInjection(context.sessionID, context.signal)
61
+ const result = await execute(input, context)
62
+ if (!deps.options.loopGuard || !guarded.has(tool.name)) return result
63
+
64
+ const text = typeof result.content === "string" ? result.content : JSON.stringify(result.content)
65
+ const key = `${tool.name}\u0000${JSON.stringify(input ?? {})}`
66
+ const previous = loopState.get(context.sessionID)
67
+ const count = previous?.key === key && previous.result === text ? previous.count + 1 : 1
68
+ loopState.set(context.sessionID, { key, result: text, count })
69
+ if (count > 5) {
70
+ return { content: `crosstalk: repeated identical ${tool.name} call blocked — change the message or stop` }
71
+ }
72
+ if (count === 3) {
73
+ return { content: `${text}\n warning: repeated identical call — change the message or stop` }
74
+ }
75
+ return result
76
+ },
77
+ options: {
78
+ namespace: deps.options.namespace,
79
+ permission: deps.options.permission,
80
+ codemode: deps.options.codemode,
81
+ },
82
+ })
83
+ }
84
+ }
85
+
86
+ export {
87
+ claimTool,
88
+ continueTool,
89
+ heartbeatTool,
90
+ inboxTool,
91
+ peersTool,
92
+ replyTool,
93
+ sendTool,
94
+ statusTool,
95
+ waitTool,
96
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * @fileoverview `crosstalk_peers` — who else is running right now.
3
+ */
4
+
5
+ import { formatPeers } from "../core/format.ts"
6
+ import { normalizeResource } from "../core/claims.ts"
7
+ import type { PeerView } from "../types.ts"
8
+ import { readBoolean, readEnum, readNumber, readStringArray } from "./args.ts"
9
+ import { jsonSchema, run, type CrosstalkToolInfo, type ToolDeps } from "./types.ts"
10
+
11
+ /**
12
+ * Which peers touch any of `paths`: a session holding a lease on the exact key,
13
+ * or one that listed it in `workingOn`. Both sides are normalized to absolute
14
+ * keys — the caller's paths against the caller's directory, a peer's
15
+ * `workingOn` against the peer's own — so `src/auth.ts` typed by a session in
16
+ * another worktree does not match this one until it provably is the same file.
17
+ *
18
+ * Keys are exact, like every claim key: asking about a directory never matches
19
+ * the files inside it, and `**` is an ordinary path segment. An empty `paths`
20
+ * list matches every peer, which is "no filter" expressed as data.
21
+ */
22
+ export function overlappingPeers(
23
+ peers: readonly PeerView[],
24
+ paths: readonly string[],
25
+ baseDir?: string,
26
+ ): PeerView[] {
27
+ const wanted = paths.map((path) => normalizeResource(path, baseDir)).filter((key) => key !== "")
28
+ if (wanted.length === 0) return [...peers]
29
+ const claimed = new Set(wanted)
30
+ return peers.filter(
31
+ (peer) =>
32
+ peer.claims.some((claim) => claimed.has(claim)) ||
33
+ (peer.declared?.workingOn ?? []).some((entry) => claimed.has(normalizeResource(entry, peer.directory))),
34
+ )
35
+ }
36
+
37
+ export function peersTool(deps: ToolDeps): CrosstalkToolInfo {
38
+ return {
39
+ name: "peers",
40
+ description: [
41
+ "List the other OpenCode sessions on this channel with their liveness, what they declared",
42
+ "they are working on, unread mail counts, and the files they have leased.",
43
+ "Use this before editing shared code, and to find out which session to signal.",
44
+ 'Pass "overlap" with exact paths to see only the peers whose leases or workingOn cover them.',
45
+ ].join(" "),
46
+ input: jsonSchema({
47
+ type: "object",
48
+ properties: {
49
+ status: {
50
+ type: "string",
51
+ enum: ["all", "running", "idle"],
52
+ description: "Filter by liveness. 'all' (default) lists everyone the mesh knows.",
53
+ },
54
+ scope: {
55
+ type: "string",
56
+ enum: ["project", "location", "server"],
57
+ description: "Widen or narrow visibility for this call. Defaults to the configured scope.",
58
+ },
59
+ overlap: {
60
+ type: "array",
61
+ items: { type: "string" },
62
+ description:
63
+ "Only peers whose leases or workingOn cover one of these exact paths — no globs, relative paths resolve against your directory",
64
+ },
65
+ includeSelf: { type: "boolean", description: "Include this session in the list" },
66
+ limit: { type: "number", description: "Maximum peers to return (default 50)" },
67
+ },
68
+ additionalProperties: false,
69
+ }),
70
+ async execute(input, context) {
71
+ return run(() => {
72
+ const status = readEnum(input, "status", ["all", "running", "idle"] as const, "all")
73
+ const scope =
74
+ readEnum(input, "scope", ["project", "location", "server"] as const, deps.options.scope) ??
75
+ deps.options.scope
76
+ const overlap = readStringArray(input, "overlap", { max: 32, maxLength: 200 })
77
+ const includeSelf = readBoolean(input, "includeSelf", false)
78
+ const limit = readNumber(input, "limit", { min: 1, max: 500, fallback: 50 })
79
+
80
+ const known = deps.mesh.peers(context.sessionID, {
81
+ status,
82
+ scope,
83
+ includeSelf,
84
+ ...(limit !== undefined ? { limit } : {}),
85
+ })
86
+ // An empty list is "no filter", not "match nothing".
87
+ const asked = overlap && overlap.length > 0 ? overlap : undefined
88
+ const peers = asked
89
+ ? overlappingPeers(known, asked, deps.mesh.directoryOf(context.sessionID))
90
+ : known
91
+ return formatPeers({
92
+ self: deps.mesh.view(context.sessionID),
93
+ peers,
94
+ scope,
95
+ now: deps.mesh.now(),
96
+ ...(asked ? { overlap: { paths: asked, considered: known.length } } : {}),
97
+ })
98
+ })
99
+ },
100
+ }
101
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @fileoverview `crosstalk_reply` — answer a message by its id.
3
+ *
4
+ * Ownership comes from the caller's own inbox, not from a caller-chosen
5
+ * recipient: the original sender is resolved from the stored message, so a
6
+ * reply cannot be redirected at another session by mistake or by name reuse.
7
+ * The communication wall is still enforced by `mesh.send`.
8
+ */
9
+
10
+ import { formatSend } from "../core/format.ts"
11
+ import { readEnum, readString } from "./args.ts"
12
+ import { jsonSchema, run, type CrosstalkToolInfo, type ToolDeps } from "./types.ts"
13
+
14
+ export function replyTool(deps: ToolDeps): CrosstalkToolInfo {
15
+ return {
16
+ name: "reply",
17
+ description: [
18
+ "Reply to a specific message by its ID, as shown by crosstalk_inbox. The recipient is read",
19
+ "from that message, so you cannot accidentally reply to a different session. The thread topic",
20
+ "is inherited. Answer one request once, then continue your task — do not answer an ack.",
21
+ ].join(" "),
22
+ input: jsonSchema({
23
+ type: "object",
24
+ properties: {
25
+ messageId: { type: "string", description: "ID of the message in your inbox, e.g. msg-3" },
26
+ text: { type: "string", description: "Your reply. Be specific and keep it to one or two sentences." },
27
+ delivery: {
28
+ type: "string",
29
+ enum: ["steer", "queue"],
30
+ description: "'steer' (default) folds into the current turn; 'queue' waits for it to end",
31
+ },
32
+ },
33
+ required: ["messageId", "text"],
34
+ additionalProperties: false,
35
+ }),
36
+ async execute(input, context) {
37
+ return run(async () => {
38
+ const messageId = readString(input, "messageId", { required: true, max: 80 })
39
+ const text = readString(input, "text", { required: true, max: 8_000 })
40
+ const delivery = readEnum(input, "delivery", ["steer", "queue"] as const, "steer")
41
+
42
+ const original = deps.mesh.findMessage(context.sessionID, messageId)
43
+ if (original === undefined) {
44
+ return `crosstalk reply: message ${messageId} is not in your inbox — use crosstalk_inbox to find its id`
45
+ }
46
+
47
+ const outcome = await deps.mesh.send(
48
+ context.sessionID,
49
+ {
50
+ to: original.from,
51
+ text,
52
+ replyTo: messageId,
53
+ kind: "answer",
54
+ ...(delivery ? { delivery } : {}),
55
+ ...(original.topic ? { topic: original.topic } : {}),
56
+ },
57
+ context.signal,
58
+ )
59
+ const head = `crosstalk: in reply to ${messageId} from ${original.fromName ?? original.from}`
60
+ return [
61
+ head,
62
+ formatSend({
63
+ self: deps.mesh.view(context.sessionID),
64
+ recipients: outcome.recipients,
65
+ skipped: outcome.skipped,
66
+ text,
67
+ now: deps.mesh.now(),
68
+ }),
69
+ ].join("\n")
70
+ })
71
+ },
72
+ }
73
+ }