opencode-collaboration 0.4.1 → 0.5.1

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
@@ -27,6 +27,7 @@ Run several opencode terminals in parallel (different repos, worktrees, or tasks
27
27
  - **Explicit TUI controls**: palette actions use host dialogs for selection and confirmation; slash wrappers remain available for automation and compatibility
28
28
  - Local only: everything stays on your machine (Unix-domain sockets on macOS/Linux, loopback TCP on Windows, plus a compatibility loopback listener for v1 peers)
29
29
  - The peer name is appended to this process's root session titles, so every opencode window shows who it is at a glance
30
+ - Peer-triggered turns run under the receiving session's selected agent/mode (e.g. a custom `teacher`) instead of opencode's default `build`, so that agent's model, tools and permission rules apply. The mode is the agent recorded server-side at session creation and by prompts (messages/commands); if none is known yet, the default agent is used. If the recorded agent is later removed, the next peer message falls back to the default agent
30
31
 
31
32
  ## Install
32
33
 
package/README.zh-CN.md CHANGED
@@ -27,6 +27,7 @@
27
27
  - **明确的 TUI 控制**:面板操作使用宿主对话框进行选择确认;斜杠命令封装仍可用于自动化和兼容性场景
28
28
  - 纯本地运行:一切都在你的机器上(macOS/Linux 使用 Unix 域套接字,Windows 使用回环 TCP,另有一个兼容 v1 对端的回环监听器)
29
29
  - 本进程的 peer 名字会追加到根会话标题后面,一眼就能看出每个 opencode 窗口是谁
30
+ - peer 触发的回合会沿用接收方会话当前选中的 agent/模式(如自定义的 `teacher`),而不是 opencode 默认的 `build`,因此该 agent 的模型、工具与权限规则都会生效。模式取自服务端记录的 agent(会话创建时写入,并随消息/命令的 prompt 更新);若尚无所知则使用默认 agent。若记录的 agent 之后被删除,下一条 peer 消息会回退到默认 agent
30
31
 
31
32
  ## 安装
32
33
 
@@ -18,6 +18,18 @@ export interface DeliveryOptions {
18
18
  logger: Logger;
19
19
  /** Protocol-v2 delivery targets this session immediately, even while busy. */
20
20
  immediate?: boolean;
21
+ /**
22
+ * The agent/mode the receiving session currently has selected (e.g. a custom
23
+ * "teacher"). When set, injected peer turns run under it instead of opencode's
24
+ * default agent. Returns undefined when unknown.
25
+ */
26
+ agent?: () => string | undefined;
27
+ /**
28
+ * Called when an injection failed because the recorded agent no longer
29
+ * exists, so the caller can drop it. The message is then retried once under
30
+ * opencode's default agent instead of requeue-looping on the same error.
31
+ */
32
+ onAgentRejected?: () => void;
21
33
  /**
22
34
  * Max time one prompt injection may take before it is treated as a delivery
23
35
  * failure and the message is requeued. Without this bound a hung
package/dist/delivery.js CHANGED
@@ -62,28 +62,15 @@ export function Delivery(opts) {
62
62
  const status = sdkResult?.response?.status;
63
63
  const statusText = sdkResult?.response?.statusText;
64
64
  const detail = status ? ` (${status}${statusText ? ` ${statusText}` : ""})` : "";
65
- throw new Error(`OpenCode prompt injection failed${detail}: ${String(sdkResult?.error ?? "request failed")}`);
65
+ const rawError = sdkResult?.error;
66
+ const errorText = rawError == null
67
+ ? "request failed"
68
+ : typeof rawError === "string"
69
+ ? rawError
70
+ : JSON.stringify(rawError);
71
+ throw new Error(`OpenCode prompt injection failed${detail}: ${errorText}`);
66
72
  }
67
- async function inject(sessionId, text, message) {
68
- const part = {
69
- type: "text",
70
- text,
71
- synthetic: true,
72
- metadata: {
73
- peerMessage: message ? {
74
- version: 2,
75
- messageId: message.id,
76
- fromEndpointId: message.from.instanceId,
77
- toSessionId: sessionId,
78
- } : true,
79
- },
80
- };
81
- const messageID = message ? deterministicPeerMessageId(sessionId, message) : undefined;
82
- const body = {
83
- ...(messageID ? { messageID } : {}),
84
- ...(message ? { system: REPLY_DIRECTIVE } : {}),
85
- parts: [part],
86
- };
73
+ async function sendPrompt(sessionId, body) {
87
74
  const session = opts.client.session;
88
75
  if (typeof session.promptAsync === "function") {
89
76
  const result = await withTimeout(session.promptAsync({
@@ -97,11 +84,63 @@ export function Delivery(opts) {
97
84
  }
98
85
  const result = await withTimeout(opts.client.session.prompt({
99
86
  path: { id: sessionId },
100
- body,
87
+ body: body,
101
88
  query: { directory: opts.directory },
102
89
  }));
103
90
  assertPromptSucceeded(result);
104
91
  }
92
+ async function agentStillExists(agent) {
93
+ // opencode reports an unknown agent as a generic 500 whose body has no
94
+ // "Agent not found" text, so decide by asking the server for the live list.
95
+ // If the list is unavailable, assume the agent is fine and let the caller
96
+ // requeue as before (only a definite miss triggers the downgrade).
97
+ try {
98
+ const response = await opts.client.app.agents();
99
+ const agents = response.data;
100
+ if (!Array.isArray(agents))
101
+ return true;
102
+ return agents.some((entry) => entry?.name === agent);
103
+ }
104
+ catch {
105
+ return true;
106
+ }
107
+ }
108
+ async function inject(sessionId, text, message) {
109
+ const messageID = message ? deterministicPeerMessageId(sessionId, message) : undefined;
110
+ const buildBody = (agent) => ({
111
+ ...(messageID ? { messageID } : {}),
112
+ ...(agent ? { agent } : {}),
113
+ ...(message ? { system: REPLY_DIRECTIVE } : {}),
114
+ parts: [
115
+ {
116
+ type: "text",
117
+ text,
118
+ synthetic: true,
119
+ metadata: {
120
+ peerMessage: message ? {
121
+ version: 2,
122
+ messageId: message.id,
123
+ fromEndpointId: message.from.instanceId,
124
+ toSessionId: sessionId,
125
+ } : true,
126
+ },
127
+ },
128
+ ],
129
+ });
130
+ const agent = opts.agent?.();
131
+ try {
132
+ await sendPrompt(sessionId, buildBody(agent));
133
+ }
134
+ catch (err) {
135
+ // The recorded agent may no longer exist (removed from config). Verify
136
+ // against the live agent list, and only then drop the record and retry
137
+ // once under opencode's default agent instead of requeue-looping.
138
+ if (!agent || (await agentStillExists(agent)))
139
+ throw err;
140
+ opts.onAgentRejected?.();
141
+ await sendPrompt(sessionId, buildBody(undefined));
142
+ }
143
+ }
105
144
  async function flushOnce() {
106
145
  if (flushing)
107
146
  return false;
package/dist/index.js CHANGED
@@ -291,6 +291,8 @@ export const PeersPlugin = async (ctx, pluginOptions) => {
291
291
  if (disposing)
292
292
  return;
293
293
  await runtime.noteActivity(input.sessionID);
294
+ if (input.agent)
295
+ await runtime.noteAgent(input.sessionID, input.agent);
294
296
  if (!disposing)
295
297
  await registry.heartbeat();
296
298
  },
@@ -28,6 +28,7 @@ export interface SessionRuntimeInstance {
28
28
  properties?: Record<string, unknown>;
29
29
  }) => Promise<boolean>;
30
30
  noteActivity: (sessionId: string) => Promise<void>;
31
+ noteAgent: (sessionId: string, agent: string) => Promise<void>;
31
32
  queueForSession: (sessionId: string) => QueueInstance | null;
32
33
  deliveryForSession: (sessionId: string) => DeliveryInstance | null;
33
34
  sweep: () => Promise<void>;
@@ -38,6 +38,8 @@ export function SessionRuntime(opts) {
38
38
  current.updatedAt = Math.max(current.updatedAt, session.time.updated);
39
39
  if (status)
40
40
  setStatus(current, status);
41
+ if (session.agent)
42
+ current.agent = session.agent;
41
43
  return current;
42
44
  }
43
45
  const queue = createSessionMessageQueue({ config: opts.config, sessionId: session.id, logger: opts.logger });
@@ -51,6 +53,7 @@ export function SessionRuntime(opts) {
51
53
  updatedAt: session.time.updated,
52
54
  queue,
53
55
  tracker,
56
+ agent: session.agent,
54
57
  delivery: undefined,
55
58
  };
56
59
  if (endpoint.status !== "idle")
@@ -62,6 +65,10 @@ export function SessionRuntime(opts) {
62
65
  directory: session.directory || opts.directory,
63
66
  logger: opts.logger,
64
67
  immediate: true,
68
+ agent: () => endpoint.agent,
69
+ onAgentRejected: () => {
70
+ endpoint.agent = undefined;
71
+ },
65
72
  });
66
73
  endpoints.set(session.id, endpoint);
67
74
  return endpoint;
@@ -390,6 +397,13 @@ export function SessionRuntime(opts) {
390
397
  setStatus(endpoint, "busy");
391
398
  });
392
399
  },
400
+ noteAgent(sessionId, agent) {
401
+ return whileRunning(undefined, async () => {
402
+ const endpoint = await findSession(sessionId);
403
+ if (endpoint)
404
+ endpoint.agent = agent;
405
+ });
406
+ },
393
407
  queueForSession(sessionId) {
394
408
  return endpoints.get(sessionId)?.queue ?? null;
395
409
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-collaboration",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "Cross-session messaging for opencode — let independent sessions discover and text each other, modeled after Claude Code's cross-session messaging",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",