opencode-crosstalk 0.2.0 → 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.
package/README.md CHANGED
@@ -7,20 +7,22 @@ Two agents in the same repository cannot discover each other, cannot say "I'm in
7
7
  `src/auth/` right now", and — most expensively — cannot stop each other from
8
8
  writing the same file at the same time. Which means the second agent usually
9
9
  discovers the first one's work by reading a half-applied diff during the
10
- postmortem. This plugin adds seven tools that make all three ordinary.
10
+ postmortem. This plugin adds nine tools that make all three ordinary.
11
11
 
12
12
  ```
13
- crosstalk_status declare your role and see who else is here
14
- crosstalk_peers who is running, what they declared, what they hold
15
- crosstalk_send message a peer, a role, or everyone
16
- crosstalk_inbox read replies, optionally blocking until one arrives
17
- crosstalk_claim take an exclusive, expiring lease on a file
18
- crosstalk_wait block until a peer is idle or a file is released
13
+ crosstalk_status declare your role and see who else is here
14
+ crosstalk_peers who is running, what they declared, what they hold
15
+ crosstalk_send message a peer, a role, or everyone; attach a task brief
16
+ crosstalk_reply answer a message by its id, addressed to its actual sender
17
+ crosstalk_continue steer an existing session by exact id, preserving context
18
+ crosstalk_inbox read replies, optionally blocking until one arrives
19
+ crosstalk_claim take an exclusive, expiring lease on a file
20
+ crosstalk_wait block until a peer is idle or a file is released
19
21
  crosstalk_heartbeat send a message to a peer on a repeating interval
20
22
  ```
21
23
 
22
- All seven share one namespace and one permission action (`crosstalk`), so a
23
- project can allow or deny coordination with a single rule instead of seven.
24
+ All nine share one namespace and one permission action (`crosstalk`), so a
25
+ project can allow or deny coordination with a single rule instead of nine.
24
26
 
25
27
  ## In action
26
28
 
@@ -74,6 +76,11 @@ exists to prevent. `npm run setup` uses `~/.opencode/plugins/`; the root the V2
74
76
  docs name, `<config>/plugins/` (`~/.config/opencode/plugins/`), is honored as
75
77
  well. Set `CROSSTALK_PLUGINS_DIR` to target another directory.
76
78
 
79
+ The package is also published to npm as
80
+ [`opencode-crosstalk`](https://www.npmjs.com/package/opencode-crosstalk); release
81
+ tags track that version. The symlink install above stays the recommended path
82
+ for a checkout you edit, because your edits are live after a reload.
83
+
77
84
  ### One specific project
78
85
 
79
86
  Point a project at it:
@@ -96,7 +103,7 @@ your-project/.opencode/plugins/crosstalk/ → symlink or copy this package he
96
103
 
97
104
  No permission rule is needed to *use* the tools: OpenCode's base policy allows
98
105
  every action, so `crosstalk` already resolves to allow. Add a rule when you want
99
- to control the plugin rather than enable it — one rule covers all seven tools:
106
+ to control the plugin rather than enable it — one rule covers all nine tools:
100
107
 
101
108
  ```jsonc title="opencode.jsonc"
102
109
  {
@@ -247,6 +254,22 @@ payload — it is confidently and loudly wrong. On a kitty-graphics terminal,
247
254
  switching `protocol` in `src/tui/index.tsx` from `blocks` to `auto` gives crisp
248
255
  pixels.
249
256
 
257
+ ### Task briefs and replies
258
+
259
+ An assignment is one message with an optional evidence contract: `writeScope`
260
+ (exact files one owner may edit), `validation` (the gate command) and `evidence`
261
+ (what must be shown to prove completion). They ride in the message's `meta.task`
262
+ and appear in the recipient's `crosstalk_inbox` as a `brief:` line. A session
263
+ that cannot take the work replies with `kind: "decline"` — no answer is demanded
264
+ and the coordinator reroutes instead of resending it unchanged.
265
+
266
+ Use `crosstalk_reply { messageId, text }` to answer a specific message: the
267
+ recipient is read from that message, not chosen by the caller, and the thread
268
+ topic is inherited. Use `crosstalk_continue { sessionID, prompt }` to reuse an
269
+ existing session's context instead of starting a new lane. With `loopGuard`
270
+ enabled, the third byte-identical `send`/`reply` warns and the sixth is blocked;
271
+ `inbox`, leases, status and waits are never blocked.
272
+
250
273
  ### Drop-in AGENTS.md snippet
251
274
 
252
275
  Copy this block into a project's `AGENTS.md` to teach its sessions how to
@@ -260,8 +283,8 @@ archaeological dig.
260
283
 
261
284
  Other OpenCode sessions in this workspace are reachable through the
262
285
  `opencode-crosstalk` plugin: `crosstalk_status`, `crosstalk_peers`,
263
- `crosstalk_send`, `crosstalk_inbox`, `crosstalk_claim`, `crosstalk_heartbeat`,
264
- `crosstalk_wait`.
286
+ `crosstalk_send`, `crosstalk_reply`, `crosstalk_continue`, `crosstalk_inbox`,
287
+ `crosstalk_claim`, `crosstalk_heartbeat`, `crosstalk_wait`.
265
288
  Write in **English only** and keep everything token-tight: one short sentence
266
289
  per status, message, or claim note (who, what, where) — no reports, no
267
290
  summaries, no pleasantries. Keep working; only stop for coordination that
@@ -279,6 +302,9 @@ prevents a real collision.
279
302
  peer holds, `crosstalk_send` one short precise sentence (`to: "George"` or a
280
303
  session id) and continue elsewhere; replies are injected into live turns (use
281
304
  `crosstalk_inbox` to catch up). Never force a claim.
305
+ - **Answer by message id, continue by session id.** `crosstalk_reply { messageId, text }`
306
+ addresses the real sender; `crosstalk_continue { sessionID, prompt }` reuses a
307
+ peer's context. Send `kind: "decline"` with a reason when work is outside your lane.
282
308
  - **Lease what you are editing now.** `crosstalk_claim` takes an exclusive
283
309
  expiring lease on exact paths — no globs (`resources`, `note`, `ttlSeconds`);
284
310
  keep the note to a few words. `renew` if the work runs long, `release` when
@@ -372,7 +398,7 @@ All optional; set them with the object form of `plugins`:
372
398
  | Option | Default | Meaning |
373
399
  | --- | --- | --- |
374
400
  | `namespace` | `crosstalk` | Tool namespace. Dots are rejected: the host rewrites them to `_`. |
375
- | `permission` | `crosstalk` | Permission action for all seven tools. |
401
+ | `permission` | `crosstalk` | Permission action for all nine tools. |
376
402
  | `codemode` | `false` | Expose the tools through Code Mode instead of directly. |
377
403
  | `scope` | `project` | Peer visibility: `project`, `location`, or `server`. |
378
404
  | `staleAfterMs` | `600000` | Silence after which a peer is flagged stale. |
@@ -386,6 +412,7 @@ All optional; set them with the object form of `plugins`:
386
412
  | `persist` | `true` | Persist peers and leases through `ctx.storage`. |
387
413
  | `storageKey` | `crosstalk` | Storage key prefix. |
388
414
  | `announce` | `true` | Brief every session in the system prompt; compact while the session is alone. |
415
+ | `loopGuard` | `false` | Warn on the 3rd and block the 6th byte-identical `send`/`reply` call; other tools never blocked. |
389
416
 
390
417
  Bad values degrade to the default with a warning; a typo never costs an agent
391
418
  its tools mid-session. `parseOptions` never throws — a missing bracket is a log
@@ -399,9 +426,9 @@ Both were confirmed against the host's own tool snapshot, which reads roughly
399
426
  and splits tools on `options.codemode === false` (direct) versus everything else
400
427
  (Code Mode catalog). So:
401
428
 
402
- - `permission: "crosstalk"` makes the action that gates all seven tools. Without
429
+ - `permission: "crosstalk"` makes the action that gates all nine tools. Without
403
430
  it, the action would fall back to the effective tool name — `crosstalk_status`,
404
- `crosstalk_claim`, and so on — needing seven rules instead of one.
431
+ `crosstalk_claim`, and so on — needing nine rules instead of one.
405
432
  - `codemode: false` is what makes the tools directly callable. Setting it to
406
433
  `true` moves them into the Code Mode catalog only, where they are reached
407
434
  through `execute` rather than called by name. That adds a second gate: the
@@ -415,7 +442,7 @@ and splits tools on `options.codemode === false` (direct) versus everything else
415
442
 
416
443
  ```sh
417
444
  npm install
418
- npm run check # the gate: typecheck + 279 unit tests, both always run
445
+ npm run check # the gate: typecheck + 280 unit tests, both always run
419
446
  npm run test:e2e # live smoke test, needs OPENCODE_E2E=1 and a usable model
420
447
  npm run setup # link the plugin in globally
421
448
  ```
@@ -439,22 +466,74 @@ host; `src/rpc.ts` is the shared contract and imports only types. `scripts/setup
439
466
  and `scripts/check.mjs` are plain JavaScript sitting outside `tsconfig.json`,
440
467
  so neither is part of the typecheck.
441
468
 
469
+ ### Releasing
470
+
471
+ Release publishing is staged by CI and approved by a human, using npm
472
+ **trusted publishing** — no long-lived token, and no terminal 2FA prompt:
473
+
474
+ ```sh
475
+ npm version minor # bumps package.json + package-lock.json
476
+ git push --follow-tags # the tag triggers .github/workflows/publish.yml
477
+ ```
478
+
479
+ The workflow installs npm 12, runs `npm run check`, verifies that the tag
480
+ matches `package.json`, and runs `npm stage publish` with an OIDC token.
481
+ Approve the staged version in the npm web UI (2FA in the browser). Staging never
482
+ needs 2FA; approving always does.
483
+
484
+ One-time setup on [npmjs.com](https://www.npmjs.com/package/opencode-crosstalk):
485
+ package **Settings → Trusted publishing → GitHub Actions**, with
486
+ `MrDoe` / `opencode-crosstalk` / `publish.yml`. Staged publishing is always
487
+ allowed for a trusted publisher; direct `npm publish` is a separate opt-in.
488
+ A new trusted publisher must complete its first publish within **2 days** or the
489
+ configuration expires.
490
+
491
+ `workflow_dispatch` stages whatever version is in `package.json`, without a tag.
492
+ `npm stage list` and `npm stage approve` require interactive authentication, so
493
+ they cannot run from the workflow — use them locally only where an OTP works.
494
+
442
495
  ## Skills
443
496
 
444
- `.opencode/skills/` carries four project skills OpenCode advertises to every
497
+ `.opencode/skills/` carries the project skills OpenCode advertises to every
445
498
  session here; load one with the `skill` tool when it fits:
446
499
 
447
500
  | Skill | Use it for |
448
501
  | --- | --- |
449
502
  | `crosstalk-coordination` | running several sessions — assigning phases, relaying findings, push waves |
450
503
  | `crosstalk-team-workflow` | executing an assignment — leases, a green gate, honest landing reports |
504
+ | `crosstalk-doctor` | diagnosing tool visibility, scope and a refused twin install from `crosstalk_status` |
505
+ | `crosstalk-tester` | focused verification without editing source; findings with file:line |
506
+ | `crosstalk-reviewer` | reading landed commits before the next phase opens; never edits |
507
+ | `crosstalk-scout` | read-only reconnaissance; returns findings, takes no leases |
508
+ | `crosstalk-integrator` | the one owner of shared files (`README.md`, `AGENTS.md`, config) |
451
509
  | `test-driven-development` | any new code: failing test first, watch it fail, then minimal code |
452
510
  | `requesting-code-review` | dispatching a reviewer on a commit range before merging |
453
511
 
454
- The first two are written for this repository. The last two are vendored from
455
- [obra/superpowers](https://github.com/obra/superpowers) under MIT; each file
456
- carries its attribution footer and any edits made while vendoring.
457
- `.opencode/skills/README.md` is the index.
512
+ The `crosstalk-*` skills are written for this repository. The last two are
513
+ vendored from [obra/superpowers](https://github.com/obra/superpowers) under MIT;
514
+ each file carries its attribution footer and any edits made while vendoring.
515
+ `.opencode/skills/roles.md` is the roster with the canonical lowercase role
516
+ labels used by `crosstalk_send { role: "tester" }`; `.opencode/skills/brief-format.md`
517
+ is the shared assignment card. `.opencode/skills/README.md` is the index.
518
+
519
+ ## Release notes
520
+
521
+ ### 0.3.0
522
+
523
+ - **Two new tools:** `crosstalk_reply` (answer a message by id, addressed to its
524
+ real sender) and `crosstalk_continue` (reuse a session by exact id).
525
+ - **Task briefs:** `send` carries `writeScope`, `validation` and `evidence`;
526
+ recipients see them as a `brief:` line in their inbox. `kind: "decline"` asks
527
+ for no answer.
528
+ - **Self-check:** `crosstalk_status` reports scope, permission action,
529
+ direct/Code Mode and pending injections; a `crosstalk-doctor` skill explains
530
+ how to read it.
531
+ - **Optional `loopGuard`** warns on repeated identical sends and blocks the
532
+ sixth (default off); retrieval tools are never blocked.
533
+ - **Click-to-focus:** named peers in this TUI's place can be focused from the
534
+ sidebar avatar.
535
+ - **Role kit:** `roles.md`, `brief-format.md` and skills for tester, reviewer,
536
+ scout, integrator and doctor.
458
537
 
459
538
  ## License
460
539
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-crosstalk",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "OpenCode plugin that lets sessions on the same server see each other, talk to each other, and lease the files they are editing",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/config.ts CHANGED
@@ -40,6 +40,8 @@ export interface CrosstalkOptions {
40
40
  storageKey: string
41
41
  /** Append a short briefing to the agent's system prompt. */
42
42
  announce: boolean
43
+ /** Warn then block repeated identical coordination calls (opt-in). */
44
+ loopGuard: boolean
43
45
  }
44
46
 
45
47
  export const DEFAULTS: CrosstalkOptions = {
@@ -58,6 +60,7 @@ export const DEFAULTS: CrosstalkOptions = {
58
60
  persist: true,
59
61
  storageKey: "crosstalk",
60
62
  announce: true,
63
+ loopGuard: false,
61
64
  }
62
65
 
63
66
  const SCOPES: readonly Scope[] = ["project", "location", "server"]
@@ -171,6 +174,7 @@ export function parseOptions(raw: unknown): ParsedOptions {
171
174
  persist: booleanOption(input, "persist", DEFAULTS.persist, warnings),
172
175
  storageKey: stringOption(input, "storageKey", DEFAULTS.storageKey, /^[A-Za-z0-9_./-]+$/, warnings),
173
176
  announce: booleanOption(input, "announce", DEFAULTS.announce, warnings),
177
+ loopGuard: booleanOption(input, "loopGuard", DEFAULTS.loopGuard, warnings),
174
178
  },
175
179
  }
176
180
  }
@@ -91,6 +91,14 @@ function notAddressable(peer: PeerView, scope: Scope): string {
91
91
  * without spelunking logs.
92
92
  */
93
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
94
102
  /** Snapshot format this build writes and restores, e.g. `v2`. */
95
103
  snapshot: string
96
104
  /** Mesh storage key; only meaningful when `persist` is true. */
@@ -136,7 +144,13 @@ export function formatStatus(input: StatusViewInput): string {
136
144
 
137
145
  if (input.selfCheck) {
138
146
  const check = input.selfCheck
139
- const parts = [`snapshot ${check.snapshot}`]
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`)
140
154
  if (check.persist && check.storageKey !== undefined) parts.push(`storage ${check.storageKey}`)
141
155
  if (!check.persist) parts.push("persistence off")
142
156
  if (check.locations !== undefined) parts.push(`${check.locations} location${check.locations === 1 ? "" : "s"} owned`)
@@ -253,6 +267,16 @@ export function formatInbox(input: InboxViewInput): string {
253
267
  for (const line of message.text.split("\n")) lines.push(` ${line}`)
254
268
  if (message.kind === "request") {
255
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("; ")}`)
256
280
  }
257
281
  }
258
282
  if (input.limit !== undefined && messages.length >= input.limit) {
@@ -284,7 +308,10 @@ export function formatSend(input: SendViewInput): string {
284
308
  : ` · ${recipient.sessionID} — queued only${recipient.reason ? `: ${recipient.reason}` : ""}`,
285
309
  )
286
310
  }
287
- for (const skip of input.skipped) lines.push(` - ${skip.target}: ${skip.reason}`)
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
+ }
288
315
  if (input.skipped.length === 0 && input.recipients.length === 0) {
289
316
  lines.push(" no matching peers — check crosstalk_peers, or send with all: true")
290
317
  }
@@ -120,6 +120,12 @@ export class Mailbox {
120
120
  return messages
121
121
  }
122
122
 
123
+ /** Resolve one message by id in a session's own mailbox, for reply-by-id. */
124
+ find(sessionID: string, id: string): CrosstalkMessage | undefined {
125
+ this.#pruneBox(sessionID)
126
+ return (this.#boxes.get(sessionID) ?? []).find((message) => message.id === id)
127
+ }
128
+
123
129
  unreadCount(sessionID: string): number {
124
130
  this.#pruneBox(sessionID)
125
131
  return (this.#boxes.get(sessionID) ?? []).filter((m) => m.readAt === undefined).length
package/src/core/mesh.ts CHANGED
@@ -61,6 +61,12 @@ export interface SendInput {
61
61
  delivery?: Delivery
62
62
  /** Set when the caller is answering another message. */
63
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
64
70
  }
65
71
 
66
72
  export interface SendOutcome {
@@ -358,6 +364,13 @@ export class Mesh {
358
364
  const meta: Record<string, unknown> = {}
359
365
  if (input.replyTo) meta.replyTo = input.replyTo
360
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
+ }
361
374
 
362
375
  const messages = this.mailbox.send({
363
376
  from: selfID,
@@ -580,6 +593,12 @@ export class Mesh {
580
593
  }
581
594
  }
582
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
+
583
602
  /** Lease bookkeeping for the caller's session. */
584
603
  claims_for(selfID: string): ClaimResult {
585
604
  return { outcome: emptyOutcome(), held: this.claims.list({ holder: selfID }), ttlMs: this.#claimsExpiry(selfID) }
package/src/deliverer.ts CHANGED
@@ -50,6 +50,8 @@ export function renderDelivery(message: CrosstalkMessage): string {
50
50
  lines.push(
51
51
  `This is a request: answer with crosstalk_send addressed to ${message.fromName ?? message.from}, then continue your task.`,
52
52
  )
53
+ } else if (message.kind === "decline") {
54
+ lines.push("This is a decline: no answer is needed; reroute the work instead of resending it unchanged.")
53
55
  } else {
54
56
  lines.push("Read it with crosstalk_inbox when convenient; reply only if a reply is warranted.")
55
57
  }
@@ -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
+ }
@@ -7,7 +7,9 @@
7
7
 
8
8
  import type { ToolEditor } from "@opencode/plugin/promise/tool"
9
9
  import { claimTool } from "./claim.ts"
10
+ import { continueTool } from "./continue.ts"
10
11
  import { heartbeatTool } from "./heartbeat.ts"
12
+ import { replyTool } from "./reply.ts"
11
13
  import { inboxTool } from "./inbox.ts"
12
14
  import { peersTool } from "./peers.ts"
13
15
  import { sendTool } from "./send.ts"
@@ -24,6 +26,8 @@ export const toolFactories: Array<(deps: ToolDeps) => CrosstalkToolInfo> = [
24
26
  statusTool,
25
27
  peersTool,
26
28
  sendTool,
29
+ replyTool,
30
+ continueTool,
27
31
  inboxTool,
28
32
  claimTool,
29
33
  heartbeatTool,
@@ -41,6 +45,12 @@ export const toolFactories: Array<(deps: ToolDeps) => CrosstalkToolInfo> = [
41
45
  */
42
46
  export function registerTools(editor: ToolEditor, deps: ToolDeps): void {
43
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 }>()
44
54
  for (const factory of toolFactories) {
45
55
  const tool = factory(deps)
46
56
  const execute = tool.execute
@@ -48,7 +58,21 @@ export function registerTools(editor: ToolEditor, deps: ToolDeps): void {
48
58
  ...tool,
49
59
  execute: async (input, context) => {
50
60
  await deps.mesh.flushPendingInjection(context.sessionID, context.signal)
51
- return execute(input, context)
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
52
76
  },
53
77
  options: {
54
78
  namespace: deps.options.namespace,
@@ -59,4 +83,14 @@ export function registerTools(editor: ToolEditor, deps: ToolDeps): void {
59
83
  }
60
84
  }
61
85
 
62
- export { claimTool, heartbeatTool, inboxTool, peersTool, sendTool, statusTool, waitTool }
86
+ export {
87
+ claimTool,
88
+ continueTool,
89
+ heartbeatTool,
90
+ inboxTool,
91
+ peersTool,
92
+ replyTool,
93
+ sendTool,
94
+ statusTool,
95
+ waitTool,
96
+ }
@@ -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
+ }
package/src/tools/send.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import { formatSend } from "../core/format.ts"
6
- import { readBoolean, readEnum, readString } from "./args.ts"
6
+ import { readBoolean, readEnum, readString, readStringArray } from "./args.ts"
7
7
  import { jsonSchema, run, type CrosstalkToolInfo, type ToolDeps } from "./types.ts"
8
8
 
9
9
  export function sendTool(deps: ToolDeps): CrosstalkToolInfo {
@@ -27,8 +27,8 @@ export function sendTool(deps: ToolDeps): CrosstalkToolInfo {
27
27
  topic: { type: "string", description: "Optional thread label, e.g. auth-refactor" },
28
28
  kind: {
29
29
  type: "string",
30
- enum: ["message", "status", "request", "answer", "system"],
31
- description: "Intent. 'request' expects a reply; 'answer' is a response to one.",
30
+ enum: ["message", "status", "request", "answer", "decline", "system"],
31
+ description: "Intent. 'request' expects a reply; 'answer' responds to one; 'decline' asks for no reply.",
32
32
  },
33
33
  delivery: {
34
34
  type: "string",
@@ -36,6 +36,13 @@ export function sendTool(deps: ToolDeps): CrosstalkToolInfo {
36
36
  description: "'steer' (default) folds into the recipient's current turn; 'queue' waits for it to end",
37
37
  },
38
38
  replyTo: { type: "string", description: "Message ID this answers" },
39
+ writeScope: {
40
+ type: "array",
41
+ items: { type: "string" },
42
+ description: "Exact files the task may edit (one owner per file per phase)",
43
+ },
44
+ validation: { type: "string", description: "Gate command that decides whether the work landed green" },
45
+ evidence: { type: "string", description: "What must be shown to prove completion, e.g. hash + gate result" },
39
46
  },
40
47
  required: ["text"],
41
48
  additionalProperties: false,
@@ -47,9 +54,17 @@ export function sendTool(deps: ToolDeps): CrosstalkToolInfo {
47
54
  const role = readString(input, "role", { max: 64 })
48
55
  const all = readBoolean(input, "all", false)
49
56
  const topic = readString(input, "topic", { max: 80 })
50
- const kind = readEnum(input, "kind", ["message", "status", "request", "answer", "system"] as const, "message")
57
+ const kind = readEnum(
58
+ input,
59
+ "kind",
60
+ ["message", "status", "request", "answer", "decline", "system"] as const,
61
+ "message",
62
+ )
51
63
  const delivery = readEnum(input, "delivery", ["steer", "queue"] as const, "steer")
52
64
  const replyTo = readString(input, "replyTo", { max: 80 })
65
+ const writeScope = readStringArray(input, "writeScope", { max: 32, maxLength: 200 })
66
+ const validation = readString(input, "validation", { max: 400 })
67
+ const evidence = readString(input, "evidence", { max: 800 })
53
68
 
54
69
  // `all` defaults to false rather than undefined, so test the values.
55
70
  if (!to && !role && !all) {
@@ -67,6 +82,9 @@ export function sendTool(deps: ToolDeps): CrosstalkToolInfo {
67
82
  ...(kind ? { kind } : {}),
68
83
  ...(delivery ? { delivery } : {}),
69
84
  ...(replyTo ? { replyTo } : {}),
85
+ ...(validation ? { validation } : {}),
86
+ ...(evidence ? { evidence } : {}),
87
+ ...(writeScope ? { writeScope } : {}),
70
88
  },
71
89
  context.signal,
72
90
  )
@@ -97,6 +97,9 @@ export function statusTool(deps: ToolDeps): CrosstalkToolInfo {
97
97
  const peers = deps.mesh.peers(selfID)
98
98
  const claimsHeld = self.claims.length
99
99
  const now = deps.mesh.now()
100
+ // Diagnostics for the calling location, read once so both the hint and
101
+ // the self-check line agree about a refused twin install.
102
+ const health = guardHealth()
100
103
  const hints: string[] = []
101
104
  if (peers.some((peer) => peer.claims.length > 0)) {
102
105
  hints.push("some peers hold leases — use crosstalk_claim before editing their files")
@@ -119,12 +122,20 @@ export function statusTool(deps: ToolDeps): CrosstalkToolInfo {
119
122
  `your summary is ${relativeAge(self.declared.summaryAt, now)} old — refresh it: crosstalk_status { summary: … }`,
120
123
  )
121
124
  }
125
+ const pending = deps.mesh.pendingInjectionCount(selfID)
126
+ if (pending > 0) hints.push(`${pending} message injection(s) still pending — they retry on your next crosstalk call`)
127
+ if (health?.refused !== undefined && health.refused > 0) {
128
+ hints.push("a duplicate plugin load was refused (twin install) — check ~/.opencode/plugins")
129
+ }
122
130
 
123
- // Diagnostics for the calling location, through the store's own key
124
- // formula so the line can never name a key state does not live under.
125
- const health = guardHealth()
131
+ // The storage key comes from the store's own formula, so the line can
132
+ // never name a key state does not live under.
126
133
  const selfCheck = {
127
134
  snapshot: `v${SNAPSHOT_VERSION}`,
135
+ scope: deps.options.scope,
136
+ permission: deps.options.permission,
137
+ codemode: deps.options.codemode,
138
+ pending,
128
139
  persist: deps.options.persist,
129
140
  ...(deps.options.persist ? { storageKey: meshStorageKey(deps.options.storageKey, self.projectID) } : {}),
130
141
  ...(health ? { locations: health.locations, refused: health.refused } : {}),
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @fileoverview Pure click-to-focus policy for peer avatars.
3
+ *
4
+ * The TUI plugin asks the host to focus a tab only for a peer this sidebar is
5
+ * allowed to touch: one that declared a name and sits in this TUI's directory
6
+ * or below it, compared with the same normalisation claims use so a Windows
7
+ * worktree does not look like a different place because of a separator.
8
+ */
9
+
10
+ import type { DirectoryEntry } from "../core/directory.ts"
11
+ import { normalizeResource } from "../core/claims.ts"
12
+
13
+ export interface TabsLike {
14
+ focus(sessionID: string): boolean
15
+ }
16
+
17
+ /** Whether a session sits in `home` or below it. */
18
+ export function inPlace(candidate: string | undefined, home: string | undefined): boolean {
19
+ if (candidate === undefined || home === undefined) return false
20
+ const base = normalizeResource(home)
21
+ const other = normalizeResource(candidate)
22
+ return other === base || other.startsWith(`${base}/`)
23
+ }
24
+
25
+ /** Focus a declared peer in this TUI's place; false means "not ours to focus". */
26
+ export function focusPeer(
27
+ tabs: TabsLike,
28
+ sessionID: string,
29
+ home: string | undefined,
30
+ entry: DirectoryEntry | undefined,
31
+ ): boolean {
32
+ if (entry === undefined || entry.name === undefined || !inPlace(entry.directory, home)) return false
33
+ return tabs.focus(sessionID)
34
+ }
package/src/tui/index.tsx CHANGED
@@ -12,8 +12,8 @@ import { Plugin, usePlugin } from "@opencode/plugin/tui"
12
12
  import { Show, createMemo, createSignal } from "solid-js"
13
13
  import { TextAttributes } from "@opentui/core"
14
14
  import type { DirectoryEntry, DirectoryPayload } from "../core/directory.ts"
15
- import { normalizeResource } from "../core/claims.ts"
16
15
  import { CrosstalkRpc } from "../rpc.ts"
16
+ import { focusPeer, inPlace } from "./focus.ts"
17
17
  import { emoticonFor, entryForPortrait, isSummaryStale, summaryText, titleWithEmoticon, type AvatarEntry } from "./avatar.ts"
18
18
 
19
19
  const manifestUrl = new URL("../../assets/avatars/manifest.json", import.meta.url)
@@ -54,22 +54,12 @@ function asPayload(value: unknown): DirectoryPayload {
54
54
  return { sessions: Array.isArray(sessions) ? (sessions as DirectoryEntry[]) : [] }
55
55
  }
56
56
 
57
- /**
58
- * Whether a session sits in this TUI's directory or below it, compared with the
59
- * same normalisation claims use so a Windows worktree does not look like a
60
- * different place because of a separator or a letter case.
61
- */
62
- function inPlace(candidate: string | undefined, home: string): boolean {
63
- if (candidate === undefined) return false
64
- const base = normalizeResource(home)
65
- const other = normalizeResource(candidate)
66
- return other === base || other.startsWith(`${base}/`)
67
- }
68
-
69
57
  function AvatarLine(props: {
70
58
  sessionID: string
71
59
  directory: () => DirectoryPayload
72
60
  entries: readonly AvatarEntry[]
61
+ /** This TUI's location; only peers inside it may be focused. */
62
+ home: string | undefined
73
63
  /** Starts a fresh staleness evaluation; see `SUMMARY_TICK_MS`. */
74
64
  tick: () => number
75
65
  }) {
@@ -100,7 +90,14 @@ function AvatarLine(props: {
100
90
  return (
101
91
  <Show when={picked()}>
102
92
  {() => (
103
- <box flexDirection="column" alignItems="center" gap={0}>
93
+ <box
94
+ flexDirection="column"
95
+ alignItems="center"
96
+ gap={0}
97
+ onMouseDown={() => {
98
+ focusPeer(context.ui.tabs, props.sessionID, props.home, session())
99
+ }}
100
+ >
104
101
  {/*
105
102
  Blocks on purpose: the sidebar sits in a scrollbox and the terminal
106
103
  we target (VS Code) announces sixel but does not paint it, so cell
@@ -203,7 +200,13 @@ export default Plugin.define({
203
200
  const unregister = context.ui.slot({
204
201
  append: "sidebar.content",
205
202
  render: (input) => (
206
- <AvatarLine sessionID={input.sessionID} directory={directory} entries={entries} tick={tick} />
203
+ <AvatarLine
204
+ sessionID={input.sessionID}
205
+ directory={directory}
206
+ entries={entries}
207
+ home={location?.directory}
208
+ tick={tick}
209
+ />
207
210
  ),
208
211
  })
209
212
 
package/src/types.ts CHANGED
@@ -86,7 +86,7 @@ export interface PeerView extends Peer {
86
86
  addressable: boolean
87
87
  }
88
88
 
89
- export type MessageKind = "message" | "status" | "request" | "answer" | "system"
89
+ export type MessageKind = "message" | "status" | "request" | "answer" | "decline" | "system"
90
90
 
91
91
  export type Delivery = "steer" | "queue"
92
92