@alexsun-top/opencode-chat-room 0.8.6 → 0.8.7

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.8.6",
3
+ "version": "0.8.7",
4
4
  "description": "A chat-room server, web client, terminal client, and OpenCode/Codex/dsh plugins.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -41,6 +41,7 @@
41
41
  "server/routes",
42
42
  "server/app.ts",
43
43
  "server/channels.ts",
44
+ "server/mcp-http.ts",
44
45
  "server/channel-attachments.ts",
45
46
  "server/channel-settings.ts",
46
47
  "server/channel-integration.ts",
@@ -13,9 +13,11 @@ import {
13
13
  rpcError,
14
14
  rpcRequest,
15
15
  rpcResult,
16
+ FEATURE_VERSION_PATTERN,
16
17
  type Endpoint,
17
18
  type AccountField,
18
19
  type AdapterCapabilities,
20
+ type FeatureDeclaration,
19
21
  type IngestEvent,
20
22
  type JsonRpcId,
21
23
  type MessageRef,
@@ -157,9 +159,50 @@ function readCapabilities(result: unknown, accountId: string): AdapterCapabiliti
157
159
  const value = (send as Record<string, unknown>).idempotency;
158
160
  if (typeof value === "string" && value.trim()) capabilities.send = { idempotency: value.trim() };
159
161
  }
162
+ const features = readFeatures(entry.features);
163
+ if (features) capabilities.features = features;
160
164
  return Object.keys(capabilities).length ? capabilities : undefined;
161
165
  }
162
166
 
167
+ const FEATURE_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/;
168
+
169
+ function readFeatures(raw: unknown): Record<string, FeatureDeclaration[]> | undefined {
170
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
171
+ const features: Record<string, FeatureDeclaration[]> = {};
172
+ for (const [id, value] of Object.entries(raw as Record<string, unknown>)) {
173
+ if (!FEATURE_ID_PATTERN.test(id)) continue;
174
+ const declared = (Array.isArray(value) ? value : [value])
175
+ .map(readFeature)
176
+ .filter((feature): feature is FeatureDeclaration => feature !== undefined);
177
+ if (declared.length) features[id] = declared;
178
+ }
179
+ return Object.keys(features).length ? features : undefined;
180
+ }
181
+
182
+ function readFeature(raw: unknown): FeatureDeclaration | undefined {
183
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
184
+ const entry = raw as Record<string, unknown>;
185
+ if (typeof entry.version !== "string" || !FEATURE_VERSION_PATTERN.test(entry.version)) return undefined;
186
+ const feature: FeatureDeclaration = { version: entry.version };
187
+ if (entry.direction === "receive" || entry.direction === "send" || entry.direction === "both") {
188
+ feature.direction = entry.direction;
189
+ }
190
+ const limits = readLimits(entry.limits);
191
+ if (limits) feature.limits = limits;
192
+ return feature;
193
+ }
194
+
195
+ function readLimits(raw: unknown): Record<string, string | number | boolean> | undefined {
196
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
197
+ const limits: Record<string, string | number | boolean> = {};
198
+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
199
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
200
+ limits[key] = value;
201
+ }
202
+ }
203
+ return Object.keys(limits).length ? limits : undefined;
204
+ }
205
+
163
206
  export class AdapterProcess {
164
207
  readonly #account: AccountConfig;
165
208
  readonly #onIngest: AdapterContext["onIngest"];
@@ -244,6 +287,15 @@ export class AdapterProcess {
244
287
  log.info("adapter started", { account: this.#account.id });
245
288
  }
246
289
 
290
+ /**
291
+ * Platform operation declared by the adapter (history, members, ...).
292
+ * The adapter rejects ops it did not declare or lacks permission for.
293
+ */
294
+ async op(op: string, params: Record<string, unknown> = {}): Promise<unknown> {
295
+ if (!this.#started) throw new Error(`adapter ${this.#account.id} is not started`);
296
+ return this.#call("op", { op, ...params }, this.#sendTimeoutMs);
297
+ }
298
+
247
299
  /**
248
300
  * Read-only handshake used when a plugin is uploaded: initialize only, then
249
301
  * kill. It does not start the account and does not need credentials.
@@ -47,6 +47,8 @@ export interface ChannelConfig {
47
47
  rules: RuleConfig[];
48
48
  /** Room notifications for inbound events; never matched by outbound rules. */
49
49
  inbound: InboundRoute[];
50
+ /** Optional room that receives inbound events with no matching route. */
51
+ inboundFallback?: string;
50
52
  }
51
53
 
52
54
  type RecordValue = Record<string, unknown>;
@@ -244,7 +246,10 @@ export function parseConfig(value: unknown): ChannelConfig {
244
246
  if (ruleKeys.has(key)) throw new ConfigError(`config: duplicate rule "${rule.id}" version ${rule.version}`);
245
247
  ruleKeys.add(key);
246
248
  }
247
- return { stateFile, accounts, rules, inbound };
249
+ const inboundFallback = raw.inboundFallback === undefined
250
+ ? undefined
251
+ : stringValue(raw.inboundFallback, "inboundFallback");
252
+ return { stateFile, accounts, rules, inbound, ...(inboundFallback ? { inboundFallback } : {}) };
248
253
  }
249
254
 
250
255
  /** Load a config file. YAML parsing also accepts JSON documents. */
@@ -23,6 +23,8 @@ export interface AdapterHandle {
23
23
  target: Endpoint,
24
24
  payload: unknown,
25
25
  ): Promise<SendReceipt>;
26
+ /** Optional platform operation declared through capabilities. */
27
+ op?(op: string, params: Record<string, unknown>): Promise<unknown>;
26
28
  stop(): Promise<void>;
27
29
  }
28
30
 
@@ -115,6 +117,14 @@ export class ChannelHost {
115
117
  }
116
118
 
117
119
  /** Read-only view for routes: unknown ids or platform mismatches are missing. */
120
+ /** Run a capability-declared platform operation on a started adapter. */
121
+ async runOp(accountId: string, op: string, params: Record<string, unknown> = {}): Promise<unknown> {
122
+ const adapter = this.#adapters.get(accountId);
123
+ if (!adapter) throw new Error(`adapter ${accountId} is not running`);
124
+ if (!adapter.op) throw new Error(`adapter ${accountId} does not support operations`);
125
+ return adapter.op(op, params);
126
+ }
127
+
118
128
  targetStatus(platform: string, accountId: string): "ready" | "disabled" | "missing" {
119
129
  const account = this.#config.accounts.find((item) => item.id === accountId);
120
130
  if (!account || account.platform !== platform) return "missing";
@@ -519,13 +529,12 @@ export class ChannelHost {
519
529
  if (this.#disabled.has(accountId)) return;
520
530
  const account = this.#config.accounts.find((item) => item.id === accountId);
521
531
  if (!account) return;
522
- const key = `${account.platform}/${account.id}`;
523
532
  if (status.inbound === "failed") {
524
533
  const detail = sanitizeAccountError(`inbound failed: ${status.detail ?? "unknown"}`);
525
- this.#accountStates.set(key, { state: "started", lastError: detail });
534
+ this.#setAccountState(account, "started", detail);
526
535
  log.warn(detail, { account: accountId });
527
536
  } else if (status.inbound === "ready") {
528
- this.#accountStates.set(key, { state: "started" });
537
+ this.#setAccountState(account, "started");
529
538
  }
530
539
  }
531
540
 
@@ -534,10 +543,12 @@ export class ChannelHost {
534
543
  state: ChannelAccountRuntime["state"],
535
544
  lastError?: string,
536
545
  ): void {
537
- this.#accountStates.set(
538
- `${account.platform}/${account.id}`,
539
- lastError ? { state, lastError } : { state },
540
- );
546
+ const features = this.#adapters.get(account.id)?.capabilities?.features;
547
+ this.#accountStates.set(`${account.platform}/${account.id}`, {
548
+ state,
549
+ ...(lastError ? { lastError } : {}),
550
+ ...(features ? { features } : {}),
551
+ });
541
552
  }
542
553
 
543
554
  #disableAccount(accountId: string, reason: string): void {
@@ -1,7 +1,7 @@
1
1
  import type { ChannelConfig, InboundRoute } from "./config.ts";
2
2
  import type { IngestEvent } from "./protocol.ts";
3
3
 
4
- const MAX_RELAY_TEXT = 4000;
4
+ const MAX_RELAY_TEXT = 5000;
5
5
 
6
6
  /** Inbound routes that turn one committed external event into a room notification. */
7
7
  export function matchInboundRoutes(config: ChannelConfig, event: IngestEvent): InboundRoute[] {
@@ -13,6 +13,19 @@ export function matchInboundRoutes(config: ChannelConfig, event: IngestEvent): I
13
13
  );
14
14
  }
15
15
 
16
+ /** Inbound message kinds; action events such as message.forward_requested are internal. */
17
+ const INBOUND_KINDS = new Set(["message.created", "message"]);
18
+
19
+ /** Matched routes, or one fallback route for an unmatched inbound source. */
20
+ export function inboundRoutes(config: ChannelConfig, event: IngestEvent): InboundRoute[] {
21
+ const matched = matchInboundRoutes(config, event);
22
+ if (matched.length > 0 || !config.inboundFallback || !INBOUND_KINDS.has(event.kind)) return matched;
23
+ return [{
24
+ from: { platform: event.source.platform, account: event.source.accountId, room: event.source.roomId },
25
+ to: { room: config.inboundFallback },
26
+ }];
27
+ }
28
+
16
29
  export function platformLabel(platform: string): string {
17
30
  const value = platform.trim();
18
31
  return value ? value[0]!.toUpperCase() + value.slice(1) : "Channel";
@@ -57,14 +57,46 @@ export type AccountCapabilities = {
57
57
  env?: AccountField[];
58
58
  };
59
59
 
60
+ /** A feature contract version such as `v1`. A `domain/` prefix means a different contract; matching is exact. */
61
+ export const FEATURE_VERSION_PATTERN = /^(?:[A-Za-z0-9][A-Za-z0-9.-]*\/)?v[1-9]\d*$/;
62
+
63
+ export type FeatureDirection = "receive" | "send" | "both";
64
+
65
+ /** One capability, versioned on its own so features can evolve independently. */
66
+ export type FeatureDeclaration = {
67
+ version: string;
68
+ direction?: FeatureDirection;
69
+ limits?: Record<string, string | number | boolean>;
70
+ };
71
+
60
72
  /** Adapter-declared platform facts the generic host must not hardcode. */
61
73
  export type AdapterCapabilities = {
62
74
  displayName?: string;
63
75
  attachments?: AttachmentCapabilities;
64
76
  account?: AccountCapabilities;
65
77
  send?: { idempotency?: string };
78
+ /**
79
+ * Stable feature id to every version the adapter implements. An adapter may
80
+ * declare several versions of one feature; the host picks the highest it supports.
81
+ */
82
+ features?: Record<string, FeatureDeclaration[]>;
66
83
  };
67
84
 
85
+ /** Return the first host-supported version of a feature, or undefined when none match. */
86
+ export function selectFeature(
87
+ capabilities: AdapterCapabilities | undefined,
88
+ id: string,
89
+ hostVersions: string[],
90
+ ): FeatureDeclaration | undefined {
91
+ const declared = capabilities?.features?.[id];
92
+ if (!declared?.length) return undefined;
93
+ for (const version of hostVersions) {
94
+ const match = declared.find((feature) => feature.version === version);
95
+ if (match) return match;
96
+ }
97
+ return undefined;
98
+ }
99
+
68
100
  export interface IngestEvent {
69
101
  schemaVersion: number;
70
102
  eventId: string;
@@ -77,7 +109,12 @@ export interface IngestEvent {
77
109
  parent?: MessageRef;
78
110
  occurredAt?: string;
79
111
  receivedAt: string;
80
- content?: { text?: string; attachmentRefs?: string[]; attachments?: AttachmentRef[] };
112
+ content?: {
113
+ text?: string;
114
+ attachmentRefs?: string[];
115
+ attachments?: AttachmentRef[];
116
+ mentions?: Array<{ id: string; name: string }>;
117
+ };
81
118
  selectedMessage?: MessageRef;
82
119
  requestedTarget?: Endpoint;
83
120
  cause?: { rootEventId: string; visitedEndpoints: Endpoint[]; hopCount: number };
@@ -1,6 +1,7 @@
1
1
  import { PgDatabase } from "./pg/database.ts";
2
2
  import { Database, type SQLQueryBindings, type StateDatabase } from "./pg/sqlite.ts";
3
3
  import { PUBLISHED_RESULT_PREFIX } from "./published.ts";
4
+ import type { FeatureDeclaration } from "./protocol.ts";
4
5
 
5
6
  export type ChannelAccountState = "started" | "failed" | "disabled" | "unknown";
6
7
 
@@ -8,12 +9,14 @@ export type ChannelAccountState = "started" | "failed" | "disabled" | "unknown";
8
9
  export interface ChannelAccountRuntime {
9
10
  state: ChannelAccountState;
10
11
  lastError?: string;
12
+ features?: Record<string, FeatureDeclaration[]>;
11
13
  }
12
14
 
13
15
  export interface ChannelAccountStats {
14
16
  account: string;
15
17
  state: ChannelAccountState;
16
18
  lastError?: string;
19
+ features?: Record<string, FeatureDeclaration[]>;
17
20
  queueDepth: number;
18
21
  oldestBacklogAt: number | null;
19
22
  unknown: number;
@@ -183,6 +186,7 @@ function buildStats(
183
186
  account.state = live.state;
184
187
  const lastError = live.lastError ? sanitizeAccountError(live.lastError) : "";
185
188
  if (lastError) account.lastError = lastError;
189
+ if (live.features) account.features = live.features;
186
190
  accounts.set(key, account);
187
191
  }
188
192
 
package/plugin.ts CHANGED
@@ -281,10 +281,14 @@ export const roomArgs = z.object({
281
281
  platform: z.string().regex(/^[A-Za-z0-9._-]{1,128}$/).describe("Target platform identifier from forward_targets."),
282
282
  account: z.string().regex(/^[A-Za-z0-9._-]{1,128}$/).describe("Target account identifier from forward_targets."),
283
283
  room: z.string().regex(/^[A-Za-z0-9._-]{1,128}$/).describe("Target room identifier from forward_targets."),
284
- }).optional().describe("For forward: one exact ready target from forward_targets; tool arguments cannot choose credentials."),
284
+ }).optional().describe("For forward and send: one exact ready target from forward_targets; tool arguments cannot choose credentials."),
285
+ forward: z.object({
286
+ platform: z.string().regex(/^[A-Za-z0-9._-]{1,128}$/).describe("Target platform identifier from forward_targets."),
287
+ account: z.string().regex(/^[A-Za-z0-9._-]{1,128}$/).describe("Target account identifier from forward_targets."),
288
+ room: z.string().regex(/^[A-Za-z0-9._-]{1,128}$/).describe("Target room identifier from forward_targets."),
289
+ }).optional().describe("For send: queue the new reply to this exact target in the same call; sent first, then forwarded. Use forward_targets to read valid values."),
285
290
  resourceId: z.string().optional().describe("Resource UUID returned by upload_resource. read_resource and delete_resource also require roomId."),
286
291
  filePath: z.string().optional().describe("Absolute path to a regular local file to upload; central mode only; requires host read permission."),
287
- text: z.string().max(5000).optional().describe("Message text, at most 5000 characters; required for send."),
288
292
  isQuestion: z.boolean().optional().describe("For send: mark the message as a question awaiting an answer."),
289
293
  parentMessageId: z.string().optional().describe("For send: the ID of the message this one answers or replies to."),
290
294
  replyToMessageID: z.string().optional().describe("Legacy alias of parentMessageId for send."),
@@ -306,6 +310,7 @@ export const roomArgs = z.object({
306
310
  schedule: z.discriminatedUnion("type", [z.object({ type: z.literal("once"), at: z.string(), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() }), z.object({ type: z.literal("cron"), expression: z.string().regex(/^\S+\s+\S+\s+\S+\s+\S+\s+\S+$/), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() })]).optional(),
307
311
  paused: z.boolean().optional(),
308
312
  joinPolicy: z.enum(["open", "approval"]).optional().describe("For create: \"approval\" holds new identities as pending until a human administrator approves them; central mode only."),
313
+ text: z.string().max(5000).optional().describe("Message text, at most 5000 characters; required for send."),
309
314
  }).superRefine((args, ctx) => {
310
315
  if (args.action === "join" && !args.name?.trim()) {
311
316
  ctx.addIssue({ code: "custom", path: ["name"], message: "name is required to join a room; pass your participant display name" });
package/server/app.ts CHANGED
@@ -5,6 +5,7 @@ import { addressingRoutes } from "./addressing-routes.ts";
5
5
  import type { ChannelController } from "./channels.ts";
6
6
  import { historyRoute } from "./history-route.ts";
7
7
  import { joinRequestRoutes } from "./join-requests.ts";
8
+ import { mcpHttpRoutes } from "./mcp-http.ts";
8
9
  import { memberRoutes } from "./member-routes.ts";
9
10
  import { messageRecallRoutes } from "./message-recall-routes.ts";
10
11
  import { roomManagement } from "./newrooms.ts";
@@ -24,6 +25,7 @@ export type AppOptions = {
24
25
  operatorToken?: string;
25
26
  serveWakeUrl: string;
26
27
  channeld: () => ChannelController | undefined;
28
+ mcp?: { center: string; sessionID: string };
27
29
  };
28
30
 
29
31
  const json = (body: unknown, status = 200) =>
@@ -43,6 +45,10 @@ export function createApp(options: AppOptions): (req: Request) => Promise<Respon
43
45
  if (p === "/system" || p.startsWith("/system/")) {
44
46
  return operatorRoutes(req, url, { here: options.here, token: operatorToken });
45
47
  }
48
+ if (options.mcp) {
49
+ const mcp = await mcpHttpRoutes(req, url, { ...options.mcp, token: options.token });
50
+ if (mcp) return mcp;
51
+ }
46
52
  const page = await pageRoutes(req, url, options.here, options.channeld()?.enabled ?? false);
47
53
  if (page) return page;
48
54
  // ponytail: F1 — reject non-JSON POSTs; a text/plain simple request from a
@@ -589,7 +589,11 @@ export function initEvents(app) {
589
589
  app.closePanels();
590
590
  $("#btnRoomOptions").focus();
591
591
  }
592
- if (event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
592
+ const composer = $("#msgInput");
593
+ const composerEmpty = !!composer && event.target === composer && !composer.draftValue.trim();
594
+ // An empty composer has no history to walk, so plain arrows switch rooms.
595
+ const plainSwitch = composerEmpty && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey;
596
+ if ((event.altKey || plainSwitch) && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
593
597
  // Same switch as a rail row click on a joined room, in the order the rail renders.
594
598
  const joined = (app.state.availableRooms || []).filter((room) => app.state.rooms.has(room.id));
595
599
  const index = joined.findIndex((room) => room.id === app.state.room?.id);
@@ -348,9 +348,8 @@
348
348
  the all-read icon without depending on font metrics. */
349
349
  .message-readers { flex: 0 0 24px; align-self: flex-end; display: grid; place-items: center; margin: 0; padding: 0; width: 24px; height: 24px; border: 1px solid var(--line); border-radius: 50%; color: var(--ink-3); background: var(--surface); font: inherit; font-size: 10px; line-height: 1; cursor: pointer; box-shadow: 0 1px 3px rgb(20 40 32 / .06); }
350
350
  .message-readers[data-reader-state="empty"], .message-readers[data-reader-state="unknown"] { background: var(--surface-2); }
351
- .message-readers[data-reader-state="delivered"] { color: var(--ink-2); background: var(--surface-2); }
352
351
  .message-readers[data-reader-state="all"] { border-color: color-mix(in srgb, var(--accent) 45%, var(--line)); color: var(--accent); background: var(--accent-soft); }
353
- .message-read-check, .message-delivered-icon { display: block; width: 14px; height: 14px; }
352
+ .message-read-check { display: block; width: 14px; height: 14px; }
354
353
  .reader-delivered { margin-top: 10px; padding-top: 8px; border-top: 1px solid var(--line); }
355
354
  .message-readers:hover, .message-readers[aria-expanded="true"] { border-color: var(--accent); color: var(--accent); }
356
355
  .message-readers:focus-visible, .reader-close:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
@@ -718,7 +717,8 @@
718
717
  #roomList > li > .room-row, #roomListChat > li > .room-row { flex: 1; min-width: 0; }
719
718
  .room-row[draggable="true"] { cursor: grab; }
720
719
  .room-row.dragging { opacity: .45; }
721
- .room-row.drop-target { outline: 2px dashed var(--accent); outline-offset: 2px; }
720
+ .room-row.drop-before { box-shadow: inset 0 2px 0 var(--accent); }
721
+ .room-row.drop-after { box-shadow: inset 0 -2px 0 var(--accent); }
722
722
  .room-move { display: none; flex-direction: column; gap: 2px; margin-left: 2px; }
723
723
  .room-move-btn { display: grid; place-items: center; width: 26px; height: 24px; padding: 0; border: 1px solid transparent; border-radius: 7px; color: var(--ink-3); background: transparent; cursor: pointer; }
724
724
  .room-move-btn:hover { color: var(--accent); border-color: var(--line); background: var(--surface); }
@@ -25,7 +25,7 @@ import { createHost, type ChannelHost, type SpawnAdapter } from "../packages/cha
25
25
  import { validateTargets } from "../packages/chat-room-channeld/src/host-helpers.ts";
26
26
  import { EVENT_SCHEMA_VERSION, type Endpoint, type IngestEvent } from "../packages/chat-room-channeld/src/protocol.ts";
27
27
  import { matchRules, targetKey } from "../packages/chat-room-channeld/src/rules.ts";
28
- import { inboundRoomText, matchInboundRoutes } from "../packages/chat-room-channeld/src/inbound.ts";
28
+ import { inboundRoomText, inboundRoutes } from "../packages/chat-room-channeld/src/inbound.ts";
29
29
  import { forwardAttachments, inboundAttachments, prepareSendPayload } from "./channel-attachments.ts";
30
30
  import {
31
31
  isTerminalDeliveryState,
@@ -147,9 +147,9 @@ export function createInboundRelay(config: ChannelConfig): {
147
147
  notificationOnly: (event: IngestEvent) => boolean;
148
148
  } {
149
149
  return {
150
- notificationOnly: (event) => matchInboundRoutes(config, event).length > 0,
150
+ notificationOnly: (event) => inboundRoutes(config, event).length > 0,
151
151
  onIngestCommitted: async (event) => {
152
- for (const route of matchInboundRoutes(config, event)) {
152
+ for (const route of inboundRoutes(config, event)) {
153
153
  const text = inboundRoomText(event, route);
154
154
  if (!text && !event.content?.attachments?.length) continue;
155
155
  // Resource uploads are idempotent per event, room, and index, so a
@@ -332,7 +332,8 @@ export function createChannelController(
332
332
  const handle = async (req: Request, url: URL): Promise<Response | undefined> => {
333
333
  const adminPath = url.pathname === "/channeld/reload"
334
334
  || url.pathname === "/channeld/enable"
335
- || url.pathname === "/channeld/disable";
335
+ || url.pathname === "/channeld/disable"
336
+ || url.pathname === "/channeld/op";
336
337
  const integrationPath = url.pathname === "/channeld/plugins"
337
338
  || url.pathname.startsWith("/channeld/plugins/")
338
339
  || url.pathname === "/channeld/integration";
@@ -350,6 +351,22 @@ export function createChannelController(
350
351
 
351
352
  if (url.pathname === "/channeld/disable") return serial(disableCore);
352
353
 
354
+ if (url.pathname === "/channeld/op") {
355
+ if (!runtime) return json({ error: "relay is disabled; enable it first" }, 409);
356
+ const raw = await req.json().catch(() => undefined) as Record<string, unknown> | undefined;
357
+ const account = typeof raw?.account === "string" ? raw.account.trim() : "";
358
+ const op = typeof raw?.op === "string" ? raw.op.trim() : "";
359
+ if (!account || !op) return json({ error: "account and op are required" }, 400);
360
+ const params = raw?.params && typeof raw.params === "object" && !Array.isArray(raw.params)
361
+ ? raw.params as Record<string, unknown>
362
+ : {};
363
+ try {
364
+ return json({ ok: true, result: await runtime.host.runOp(account, op, params) });
365
+ } catch (error) {
366
+ return json({ error: error instanceof Error ? error.message : String(error) }, 502);
367
+ }
368
+ }
369
+
353
370
  const body = await readAdminBody(req);
354
371
  if (!body.ok) return json({ error: "invalid request body" }, 400);
355
372
  const configPath = body.config ?? settings.channeld.config;
@@ -17,6 +17,10 @@ const serve = createApp({
17
17
  token: bootstrap.token,
18
18
  serveWakeUrl: bootstrap.serveWakeUrl,
19
19
  channeld: () => channels,
20
+ mcp: {
21
+ center: `http://127.0.0.1:${bootstrap.port}`,
22
+ sessionID: process.env.CHAT_ROOM_MCP_SESSION ?? "ses_mcp_http",
23
+ },
20
24
  });
21
25
  // Test-only request accounting: asset hits prove whether a warm open re-downloaded.
22
26
  const handle: typeof serve = process.env.CHAT_ROOM_TEST_ACCESS_LOG === "1"
@@ -0,0 +1,88 @@
1
+ // Streamable HTTP transport for the MCP room tool (MCP 2025-03-26).
2
+ // Stateless: every POST carries one JSON-RPC message or a batch; SSE is not
3
+ // offered, so requests answer with application/json and notifications get 202.
4
+ import { randomUUID, timingSafeEqual } from "node:crypto";
5
+
6
+ import { createMcpHandler } from "../src/mcp/server.ts";
7
+
8
+ const MAX_BODY_BYTES = 1_048_576;
9
+
10
+ export type McpHttpOptions = {
11
+ sessionID: string;
12
+ center: string;
13
+ token?: string;
14
+ };
15
+
16
+ function json(body: unknown, status = 200, headers: Record<string, string> = {}): Response {
17
+ return new Response(JSON.stringify(body), {
18
+ status,
19
+ headers: { "content-type": "application/json", ...headers },
20
+ });
21
+ }
22
+
23
+ function sameSecret(given: string, secret: string): boolean {
24
+ const a = Buffer.from(given);
25
+ const b = Buffer.from(secret);
26
+ return a.length === b.length && timingSafeEqual(a, b);
27
+ }
28
+
29
+ function bearer(req: Request, token: string): boolean {
30
+ const header = req.headers.get("authorization") ?? "";
31
+ return header.startsWith("Bearer ") && sameSecret(header.slice("Bearer ".length), token);
32
+ }
33
+
34
+ function allowed(req: Request, url: URL, token: string | undefined): boolean {
35
+ if (url.pathname === "/mcp") return !token || bearer(req, token);
36
+ // A secret path lets clients that only offer "no authentication" connect.
37
+ const secret = url.pathname.slice("/mcp/".length);
38
+ return Boolean(token) && !secret.includes("/") && sameSecret(secret, token!);
39
+ }
40
+
41
+ function notify(): Response {
42
+ return new Response(null, { status: 202 });
43
+ }
44
+
45
+ export async function mcpHttpRoutes(
46
+ req: Request,
47
+ url: URL,
48
+ options: McpHttpOptions,
49
+ ): Promise<Response | undefined> {
50
+ if (url.pathname !== "/mcp" && !url.pathname.startsWith("/mcp/")) return undefined;
51
+ if (!allowed(req, url, options.token)) return json({ error: "unauthorized" }, 401);
52
+ if (req.method === "GET") {
53
+ return new Response("SSE stream not supported; use POST", { status: 405, headers: { allow: "POST, DELETE" } });
54
+ }
55
+ if (req.method === "DELETE") return new Response(null, { status: 204 });
56
+ if (req.method !== "POST") {
57
+ return new Response(null, { status: 405, headers: { allow: "POST, DELETE" } });
58
+ }
59
+ if (!req.headers.get("content-type")?.includes("application/json")) {
60
+ return json({ error: "content-type must be application/json" }, 415);
61
+ }
62
+ const body = await req.text();
63
+ if (Buffer.byteLength(body) > MAX_BODY_BYTES) return json({ error: "request body too large" }, 413);
64
+ let message: unknown;
65
+ try {
66
+ message = JSON.parse(body);
67
+ } catch {
68
+ return json({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } }, 400);
69
+ }
70
+
71
+ const handler = createMcpHandler(options.center, options.sessionID, options.token);
72
+ const initialize = !Array.isArray(message) && Boolean(message) && typeof message === "object" &&
73
+ (message as { method?: unknown }).method === "initialize";
74
+ const headers: Record<string, string> = initialize ? { "mcp-session-id": randomUUID() } : {};
75
+
76
+ if (Array.isArray(message)) {
77
+ if (!message.length) return notify();
78
+ const responses: unknown[] = [];
79
+ for (const item of message) {
80
+ const response = await handler(item);
81
+ if (response) responses.push(response);
82
+ }
83
+ return responses.length ? json(responses, 200, headers) : notify();
84
+ }
85
+
86
+ const response = await handler(message);
87
+ return response ? json(response, 200, headers) : notify();
88
+ }
@@ -36,7 +36,7 @@ Answer ChatRoom questions in their original room. When an authorized IM question
36
36
 
37
37
  1. Fetch the original message with `get_message` in the same room. Verify that it is an unrecalled Channel D system record, and identify its source `(platform, account, native room ID)` from the relay metadata, not from the message body. The source may be labeled `room_id` or, on older servers, `chat_id`. A user ID or OpenID is not a conversation ID.
38
38
  2. Call `room` with `action: "forward_targets"` (HTTP: `GET /rooms/{roomId}/forward-targets?sessionID=…`) and the same `roomId`. The tool uses the same center and session as `get_message`. Proceed only if one ready target matches all three source fields and you are authorized to send the answer there. If the action is unavailable or the source or route is missing or ambiguous, explain the blocker in the room; do not guess, read credentials, change relay rules, or call the provider directly.
39
- 3. Send a dedicated room reply with `parentMessageId` set to the original message ID. Include only the answer intended for the IM audience, not internal discussion. Then call `room` with `action: "forward"` (HTTP: `POST /rooms/{roomId}/forward`), `roomId`, `messageId` (the new reply's ID), and `target: {platform, account, room}` (the exact approved match). A room reply does not guarantee a native IM quote.
39
+ 3. Reply once with a single `room` call: `action: "send"`, `roomId`, `target: {platform, account, room}` (or `forward`, same shape), then `text`, and `parentMessageId` set to the original message ID. Put the forward target before the text so a streaming sender can start the text as soon as the target is known. The message is sent first and queued to that target in the same call. Only if the surface lacks `forward` on send, send first and then call `action: "forward"` with the new `messageId`. A room reply does not guarantee a native IM quote.
40
40
  4. `status: "queued"` and its `eventId` mean queued, not delivered. Check the correlated delivery result when available. If it cannot be confirmed, report it as queued or unconfirmed, not delivered. Do not create a new reply or resend after an ambiguous result; the same message and target identify the same forward.
41
41
 
42
42
  ## Ask humans in the room
@@ -65,6 +65,22 @@ Discuss shared questions in the room rather than opening private dialogs. Consol
65
65
  - Address the intended participant in the message text; use room broadcasts only for genuinely shared work.
66
66
  - Shared room tokens grant room access and management. A direct conversation is not private from other token holders.
67
67
 
68
+ ## Platform capabilities
69
+
70
+ Channel adapters declare each capability separately, so an IM feature can be used without assuming the others. The version is part of the contract: `v1` and `alexsun.top/v1` are different capabilities, and a host only uses an exact version it knows. An undeclared feature is unsupported; do not assume a working call.
71
+
72
+ `GET /channeld/status` lists each account with its `features`, for example `message.markdown` or `chat.members`. `POST /channeld/op` runs one adapter operation and returns its real result, including provider errors:
73
+
74
+ ```json
75
+ {"account":"feishu-main","op":"message.history","params":{"chatId":"oc_...","pageSize":20}}
76
+ ```
77
+
78
+ Operations are account-level, not room-level, and need the server token. Do not call them with a room identity, and do not present a queued or failed op as success.
79
+
80
+ Feishu v1 declares: `chat.list`, `chat.members` (read/write), `chat.announcement` (read/write), `message.text`, `message.post`, `message.mention` (send/receive), `message.markdown` (send), `message.card` (send/update), `message.image`, `message.file`, `message.audio` (receive), `message.history` (7 days), `message.read_receipt` (7 days), `message.edit` (max 20), `message.recall`. Streaming markdown is not implemented; it needs the `cardkit:card:write` scope and an app release.
81
+
82
+ A ChatRoom center can also be linked to another room through Channel: the `chatroom` adapter joins a remote room with its own session, relays text both ways, and relies on the ordinary rule and inbound-route editors. Link one direction per pair; never add the reverse rule as well, or messages loop.
83
+
68
84
  ## Protected rooms
69
85
 
70
86
  A room may require approval for new members. Create one with `joinPolicy: "approval"` only when the user asks to restrict a room; central mode is required. Do not create a protected room yourself unless the request explicitly assigns a human owner: only a person can own a room, so an Agent-created protected room has no human administrator to approve joins. Prefer asking a human to create it in the web UI. In such a room, `join` returns a pending request instead of membership. While pending you have no membership or inbox delivery, the web client cannot open the room, and you cannot send or poll. Never describe yourself as a member and do not retry repeatedly; a human administrator must approve you. Once approved, the join event is unread for your session and a client with background delivery receives it in the original session context. If you are unsure or your client has no background delivery, call `join_status`; silence before approval is not rejection.
@@ -18,7 +18,7 @@ import type { InboxItem } from "./center-inbox.ts";
18
18
  import { assertDeliveryLease } from "./session-delivery.ts";
19
19
  import { formatTasks, taskFields, validateTaskFields, type Task } from "../agent/task-tool.ts";
20
20
  import type { CatchUpOptions, CatchUpPage } from "../protocol/addressing.ts";
21
- import { runForwardAction } from "./forward-client.ts";
21
+ import { isForwardTarget, runForwardAction } from "./forward-client.ts";
22
22
  export { queueAdmissionId } from "./queue.ts";
23
23
  export { createQueueTransport, sendAsyncNotification, sendQueue } from "./queue-transport.ts";
24
24
  export type { QueueTransport, PushResult } from "./queue-transport.ts";
@@ -222,6 +222,7 @@ export async function centerAction(
222
222
  protocol?: "v1" | "v2";
223
223
  joinPolicy?: "open" | "approval";
224
224
  target?: unknown;
225
+ forward?: unknown;
225
226
  },
226
227
  sessionID: string,
227
228
  ): Promise<string> {
@@ -427,7 +428,18 @@ export async function centerAction(
427
428
  const sentID = [...parsed.messages].reverse()
428
429
  .find((message) => message.senderSessionID === sessionID && message.text === args.text!.trim())?.id
429
430
  ?? parsed.messages.at(-1)?.id;
430
- return `sent${sentID ? ` message_id=${sentID}` : ""} room_id=${parsed.id}`;
431
+ const sent = `sent${sentID ? ` message_id=${sentID}` : ""} room_id=${parsed.id}`;
432
+ if (args.forward === undefined) return sent;
433
+ if (!isForwardTarget(args.forward)) {
434
+ return `${sent}\nerror: forward must be one exact target {platform, account, room} from forward_targets`;
435
+ }
436
+ if (!sentID) return `${sent}\nerror: forward skipped because the sent message id is unknown`;
437
+ const forwarded = await runForwardAction(
438
+ opts,
439
+ { action: "forward", roomId: args.roomId, messageId: sentID, target: args.forward },
440
+ sessionID,
441
+ );
442
+ return `${sent}\n${forwarded}`;
431
443
  }
432
444
  case "recall": {
433
445
  if (!args.roomId) return "error: roomId is required; use a room UUID from the room list, not the room name";