@alexsun-top/opencode-chat-room 0.8.1 → 0.8.2

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 (84) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +10 -10
  3. package/README.zh-CN.md +10 -10
  4. package/dist/cli.js +544 -88
  5. package/package.json +4 -4
  6. package/packages/chat-room-channeld/README.md +17 -12
  7. package/packages/chat-room-channeld/src/adapter.ts +145 -7
  8. package/packages/chat-room-channeld/src/host.ts +24 -9
  9. package/packages/chat-room-channeld/src/inbound.ts +13 -4
  10. package/packages/chat-room-channeld/src/protocol.ts +52 -1
  11. package/packages/chat-room-channeld/src/rules.ts +7 -2
  12. package/plugin.ts +1 -1
  13. package/server/assets/base.css +8 -2
  14. package/server/assets/chat/admin.js +0 -2
  15. package/server/assets/chat/announcements.js +2 -4
  16. package/server/assets/chat/chat-background.js +177 -0
  17. package/server/assets/chat/confirm-dialog.js +0 -1
  18. package/server/assets/chat/create-room-dialog.js +0 -1
  19. package/server/assets/chat/diagram-viewer.js +7 -1
  20. package/server/assets/chat/doc-preview.js +71 -15
  21. package/server/assets/chat/events.js +13 -5
  22. package/server/assets/chat/files.js +10 -6
  23. package/server/assets/chat/image-zoom.js +8 -1
  24. package/server/assets/chat/index.js +4 -2
  25. package/server/assets/chat/integration-account-schema.js +99 -0
  26. package/server/assets/chat/integration-editor.js +1 -1
  27. package/server/assets/chat/integrations.js +207 -57
  28. package/server/assets/chat/locales/de.js +1 -1
  29. package/server/assets/chat/locales/es.js +1 -1
  30. package/server/assets/chat/locales/fr.js +1 -1
  31. package/server/assets/chat/locales/it.js +1 -1
  32. package/server/assets/chat/locales/ja.js +1 -1
  33. package/server/assets/chat/locales/ko.js +1 -1
  34. package/server/assets/chat/markdown-footnotes.js +1 -1
  35. package/server/assets/chat/markdown.js +23 -0
  36. package/server/assets/chat/messages.js +1 -0
  37. package/server/assets/chat/palette.js +6 -1
  38. package/server/assets/chat/panels.js +23 -3
  39. package/server/assets/chat/receipts.js +2 -3
  40. package/server/assets/chat/reminders.js +2 -4
  41. package/server/assets/chat/replies.js +0 -6
  42. package/server/assets/chat/rooms.js +1 -6
  43. package/server/assets/chat/settings.js +69 -3
  44. package/server/assets/chat/shortcuts.js +0 -3
  45. package/server/assets/chat/side-pane.js +33 -8
  46. package/server/assets/chat/state.js +48 -18
  47. package/server/assets/chat/system-events.js +29 -3
  48. package/server/assets/chat/system-messages.js +9 -0
  49. package/server/assets/chat/tasks.js +2 -8
  50. package/server/assets/chat/window-controls.js +37 -0
  51. package/server/assets/code-highlight.css +22 -6
  52. package/server/assets/conversation.css +55 -12
  53. package/server/assets/doc-preview.css +6 -1
  54. package/server/assets/files.css +3 -0
  55. package/server/assets/monaco/integration-rules.css +1 -1
  56. package/server/assets/monaco/integration-rules.js +841 -533
  57. package/server/assets/responsive.css +32 -2
  58. package/server/assets/settings.css +117 -13
  59. package/server/assets/window-controls.css +36 -0
  60. package/server/channel-attachments.ts +133 -0
  61. package/server/channel-integration.ts +79 -26
  62. package/server/channels.ts +15 -5
  63. package/server/chat.html +71 -37
  64. package/server/manifest.webmanifest +1 -0
  65. package/server/sw.js +1 -0
  66. package/src/center/center-client.ts +1 -1
  67. package/src/state/pg-database.ts +5 -5
  68. package/src/state/pg-migrate.ts +7 -7
  69. package/src/state/pg-worker.mjs +2 -17
  70. package/src/state/sqlite-database.ts +14 -5
  71. package/src/state/sqlite-rooms.ts +130 -23
  72. package/src/state/sqlite-state-store.ts +6 -5
  73. package/src/state/sqlite.ts +3 -3
  74. package/src/web/integration-rules-editor.ts +139 -5
  75. package/src/web/integration-rules.ts +6 -2
  76. package/src/web/integration-schema.ts +7 -6
  77. package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -1262
  78. package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -303
  79. package/packages/chat-room-channeld/src/feishu-card.ts +0 -27
  80. package/packages/chat-room-channeld/src/feishu-inbound.ts +0 -158
  81. package/packages/chat-room-channeld/src/feishu-live.ts +0 -355
  82. package/packages/chat-room-channeld/src/feishu-send.ts +0 -342
  83. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +0 -173
  84. package/server/assets/chat/forward.js +0 -69
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.8.1",
3
+ "version": "0.8.2",
4
4
  "description": "A chat-room server, web client, terminal client, and OpenCode/Codex/dsh plugins.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -28,7 +28,6 @@
28
28
  "src",
29
29
  "packages/chat-room-channeld/src",
30
30
  "packages/chat-room-channeld/dist/mock-adapter.js",
31
- "packages/chat-room-channeld/dist/feishu-adapter.js",
32
31
  "!src/tests",
33
32
  "!src/**/*.test.*",
34
33
  "!src/tui/test",
@@ -38,6 +37,7 @@
38
37
  "server/routes",
39
38
  "server/app.ts",
40
39
  "server/channels.ts",
40
+ "server/channel-attachments.ts",
41
41
  "server/channel-settings.ts",
42
42
  "server/channel-integration.ts",
43
43
  "server/http-server.ts",
@@ -76,10 +76,10 @@
76
76
  "scripts": {
77
77
  "build:cli": "bun build cli.ts --target=node --packages external --outfile dist/cli.js >&2",
78
78
  "build:channeld-mock": "bun build packages/chat-room-channeld/src/mock-adapter.ts --target=node --packages external --outfile packages/chat-room-channeld/dist/mock-adapter.js >&2",
79
- "build:channeld-feishu": "bun build packages/chat-room-channeld/src/feishu-adapter.ts --target=node --packages external --outfile packages/chat-room-channeld/dist/feishu-adapter.js >&2",
79
+ "build:adapter-feishu": "bun scripts/build-feishu-adapter.ts",
80
80
  "build:monaco": "bun scripts/build-monaco.ts",
81
81
  "build:office": "bun scripts/build-office.ts",
82
- "prepack": "bun run build:cli && bun run build:channeld-mock && bun run build:channeld-feishu && bun scripts/build-monaco.ts --quiet && bun scripts/build-office.ts --quiet",
82
+ "prepack": "bun run build:cli && bun run build:channeld-mock && bun scripts/build-monaco.ts --quiet && bun scripts/build-office.ts --quiet",
83
83
  "server": "node cli.ts",
84
84
  "server:bun": "bun cli.ts",
85
85
  "server:deno": "deno run --allow-env --allow-read --allow-write --allow-net cli.ts",
@@ -5,16 +5,15 @@ IM endpoints through adapter child processes. Explicit rules turn a source-room
5
5
  event into frozen deliveries for target accounts; each adapter owns one IM
6
6
  account and speaks JSON-RPC over stdio.
7
7
 
8
- This is the 0.1 MVP: static rules, text messages, outbound adapters with text and Markdown cards, a mock
9
- adapter, and a Feishu adapter with opt-in inbound long-connection events. Inbound Feishu
10
- events can be relayed into one chat-room as notifications; they are never matched by
11
- outbound rules.
8
+ This package is published as `@alexsun-top/chat-room-channeld`. Platform
9
+ adapters, including Feishu, are single files under the top-level
10
+ `plugins/` directory, not separate npm packages; their inbound events can be
11
+ relayed into one chat-room as notifications and are never matched by outbound
12
+ rules. The core launches any adapter through the account's `adapter.command`.
12
13
 
13
- This package is bundled inside `@alexsun-top/opencode-chat-room` 0.8.0 as
14
- source plus the Feishu and mock adapter entry points. Standalone npm
15
- publication, and the `npx @alexsun-top/chat-room-channeld` form, are planned
16
- for 0.8.x. In 0.8.0 use `GET /channeld/status` on the ChatRoom server, or run
17
- the CLI from a checkout with Bun.
14
+ The core ships the source plus the mock adapter entry point. Use
15
+ `GET /channeld/status` on the ChatRoom server, or run the CLI from a checkout
16
+ with Bun.
18
17
 
19
18
  ## Run from a checkout
20
19
 
@@ -123,7 +122,7 @@ retries. A room that stays missing keeps failing until it is created.
123
122
  accounts:
124
123
  - id: feishu-main
125
124
  platform: feishu
126
- adapter: { command: ["node", "/opt/chatroom/feishu-adapter.js"] }
125
+ adapter: { command: ["node", "/opt/chatroom/feishu-adapter.ts"] }
127
126
  env: { FEISHU_APP_ID: "cli_xxx", FEISHU_APP_SECRET: "xxx" }
128
127
  ```
129
128
 
@@ -170,7 +169,13 @@ from room `in` after starting, so the relay can be exercised end to end.
170
169
 
171
170
  ## Feishu adapter
172
171
 
173
- `dist/feishu-adapter.js` is a Feishu OpenAPI adapter. Outbound it sends interactive
172
+ The Feishu adapter is the generated typed single-file adapter
173
+ `plugins/feishu/dist/feishu-adapter.ts`, produced by concatenating the typed
174
+ source under `plugins/feishu/src` without a bundler so its TypeScript
175
+ annotations stay in the file. It is attached to the GitHub Release instead of being shipped inside the root
176
+ `@alexsun-top/opencode-chat-room` package and runs directly under Node 22.18+
177
+ through native type stripping (erasable syntax only: no `enum`, `namespace`, or
178
+ constructor parameter properties). Outbound it sends interactive
174
179
  cards and can reply natively to a Feishu message; inbound it can receive group
175
180
  messages over the event long connection. It speaks the same stdio JSON-RPC protocol
176
181
  as the mock adapter and has no room or session concepts.
@@ -219,7 +224,7 @@ keeps the account started for outbound sends, and reports a sanitized
219
224
  accounts:
220
225
  - id: feishu-bot
221
226
  platform: feishu
222
- adapter: { command: ["node", "/opt/chatroom/dist/feishu-adapter.js"], runtime: "node" }
227
+ adapter: { command: ["node", "/opt/chatroom/feishu-adapter.ts"], runtime: "node" }
223
228
  rules:
224
229
  - id: to-feishu
225
230
  version: 1
@@ -14,6 +14,8 @@ import {
14
14
  rpcRequest,
15
15
  rpcResult,
16
16
  type Endpoint,
17
+ type AccountField,
18
+ type AdapterCapabilities,
17
19
  type IngestEvent,
18
20
  type JsonRpcId,
19
21
  type MessageRef,
@@ -61,6 +63,98 @@ const STDERR_TAIL_LIMIT = 4096;
61
63
  const DEFAULT_INITIALIZE_TIMEOUT_MS = 10_000;
62
64
  const DEFAULT_SEND_TIMEOUT_MS = 15_000;
63
65
 
66
+ const ADAPTER_NODE_OPTIONS = [
67
+ "--experimental-transform-types",
68
+ "--disable-warning=ExperimentalWarning",
69
+ ] as const;
70
+
71
+ /**
72
+ * Adapter children execute uploaded .ts plugins, so they get Node's full
73
+ * TypeScript transform; the server process itself stays strip-only.
74
+ */
75
+ export function adapterChildEnv(account: AccountConfig): NodeJS.ProcessEnv {
76
+ const env = { ...process.env, ...account.env };
77
+ let options = env.NODE_OPTIONS?.trim() ?? "";
78
+ for (const flag of ADAPTER_NODE_OPTIONS) {
79
+ if (!options.split(/\s+/).includes(flag)) options = options ? `${options} ${flag}` : flag;
80
+ }
81
+ env.NODE_OPTIONS = options;
82
+ // Forced after account env: config validation also rejects these keys.
83
+ env.CHANNELD_ACCOUNT_ID = account.id;
84
+ env.CHANNELD_PLATFORM = account.platform;
85
+ return env;
86
+ }
87
+
88
+ /** Keep only well-formed adapter-declared facts; unknown fields are ignored. */
89
+ function readAccountFields(value: unknown): AccountField[] | undefined {
90
+ if (!Array.isArray(value)) return undefined;
91
+ const fields: AccountField[] = [];
92
+ const seen = new Set<string>();
93
+ for (const item of value) {
94
+ if (!item || typeof item !== "object") continue;
95
+ const raw = item as Record<string, unknown>;
96
+ const key = typeof raw.key === "string" ? raw.key.trim() : "";
97
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || seen.has(key)) continue;
98
+ const field: AccountField = { key };
99
+ if (typeof raw.label === "string" && raw.label.trim()) field.label = raw.label.trim();
100
+ if (typeof raw.type === "string" && ["string", "secret", "boolean", "number", "select"].includes(raw.type)) {
101
+ field.type = raw.type as AccountField["type"];
102
+ }
103
+ if (raw.required === true) field.required = true;
104
+ if (typeof raw.default === "string") field.default = raw.default;
105
+ if (typeof raw.description === "string" && raw.description.trim()) field.description = raw.description.trim();
106
+ if (Array.isArray(raw.options)) {
107
+ const options = raw.options
108
+ .filter((option): option is Record<string, unknown> => Boolean(option) && typeof option === "object")
109
+ .map((option) => typeof option.value === "string" && option.value
110
+ ? { value: option.value, ...(typeof option.label === "string" && option.label ? { label: option.label } : {}) }
111
+ : undefined)
112
+ .filter((option): option is { value: string; label?: string } => Boolean(option));
113
+ if (options.length) field.options = options;
114
+ }
115
+ seen.add(key);
116
+ fields.push(field);
117
+ }
118
+ return fields.length ? fields : undefined;
119
+ }
120
+
121
+ function readCapabilities(result: unknown, accountId: string): AdapterCapabilities | undefined {
122
+ if (!result || typeof result !== "object") return undefined;
123
+ const accounts = (result as { accounts?: unknown }).accounts;
124
+ if (!accounts || typeof accounts !== "object") return undefined;
125
+ const raw = (accounts as Record<string, unknown>)[accountId];
126
+ if (!raw || typeof raw !== "object") return undefined;
127
+ const entry = raw as Record<string, unknown>;
128
+ const capabilities: AdapterCapabilities = {};
129
+ if (typeof entry.displayName === "string" && entry.displayName.trim()) {
130
+ capabilities.displayName = entry.displayName.trim();
131
+ }
132
+ const attachment = entry.attachments;
133
+ if (attachment && typeof attachment === "object") {
134
+ const value = attachment as Record<string, unknown>;
135
+ const kinds = Array.isArray(value.kinds)
136
+ ? value.kinds.filter((kind): kind is "image" | "file" => kind === "image" || kind === "file")
137
+ : [];
138
+ if (kinds.length) {
139
+ capabilities.attachments = { kinds };
140
+ if (Number.isSafeInteger(value.imageMaxBytes) && (value.imageMaxBytes as number) > 0) {
141
+ capabilities.attachments.imageMaxBytes = value.imageMaxBytes as number;
142
+ }
143
+ if (Number.isSafeInteger(value.fileMaxBytes) && (value.fileMaxBytes as number) > 0) {
144
+ capabilities.attachments.fileMaxBytes = value.fileMaxBytes as number;
145
+ }
146
+ }
147
+ }
148
+ const account = entry.account;
149
+ if (account && typeof account === "object") {
150
+ const value = account as Record<string, unknown>;
151
+ const schema = readAccountFields(value.schema);
152
+ const env = readAccountFields(value.env);
153
+ if (schema || env) capabilities.account = { ...(schema ? { schema } : {}), ...(env ? { env } : {}) };
154
+ }
155
+ return Object.keys(capabilities).length ? capabilities : undefined;
156
+ }
157
+
64
158
  export class AdapterProcess {
65
159
  readonly #account: AccountConfig;
66
160
  readonly #onIngest: AdapterContext["onIngest"];
@@ -78,6 +172,7 @@ export class AdapterProcess {
78
172
  #stopping = false;
79
173
  #gone = false;
80
174
  #pollutionError?: Error;
175
+ #capabilities?: AdapterCapabilities;
81
176
 
82
177
  constructor(options: AdapterProcessOptions) {
83
178
  this.#account = options.account;
@@ -93,19 +188,17 @@ export class AdapterProcess {
93
188
  return this.#account.id;
94
189
  }
95
190
 
191
+ get capabilities(): AdapterCapabilities | undefined {
192
+ return this.#capabilities;
193
+ }
194
+
96
195
  async start(): Promise<void> {
97
196
  if (this.#child) throw new Error(`adapter ${this.#account.id} already started`);
98
197
  const [command, ...args] = this.#account.adapter.command;
99
198
  if (!command) throw new Error(`adapter ${this.#account.id} has an empty command`);
100
199
  const child = spawn(command, args, {
101
200
  stdio: ["pipe", "pipe", "pipe"],
102
- env: {
103
- ...process.env,
104
- ...this.#account.env,
105
- // Forced after account env: config validation also rejects these keys.
106
- CHANNELD_ACCOUNT_ID: this.#account.id,
107
- CHANNELD_PLATFORM: this.#account.platform,
108
- },
201
+ env: adapterChildEnv(this.#account),
109
202
  });
110
203
  this.#child = child;
111
204
  this.#attach(child);
@@ -124,6 +217,7 @@ export class AdapterProcess {
124
217
  this.#initializeTimeoutMs,
125
218
  );
126
219
  this.#assertReportedPlatform("initialize", initialized);
220
+ this.#capabilities = readCapabilities(initialized, this.#account.id);
127
221
  const started = await this.#call(
128
222
  "start",
129
223
  { accounts: [this.#account.id], cursors: {} },
@@ -145,6 +239,50 @@ export class AdapterProcess {
145
239
  log.info("adapter started", { account: this.#account.id });
146
240
  }
147
241
 
242
+ /**
243
+ * Read-only handshake used when a plugin is uploaded: initialize only, then
244
+ * kill. It does not start the account and does not need credentials.
245
+ */
246
+ async probe(): Promise<{ platform?: string; capabilities?: AdapterCapabilities }> {
247
+ if (this.#child) throw new Error(`adapter ${this.#account.id} already started`);
248
+ const [command, ...args] = this.#account.adapter.command;
249
+ if (!command) throw new Error(`adapter ${this.#account.id} has an empty command`);
250
+ const child = spawn(command, args, {
251
+ stdio: ["pipe", "pipe", "pipe"],
252
+ env: adapterChildEnv(this.#account),
253
+ });
254
+ this.#child = child;
255
+ this.#attach(child);
256
+ try {
257
+ const initialized = await this.#call(
258
+ "initialize",
259
+ {
260
+ protocolVersions: [PROTOCOL_VERSION],
261
+ eventSchemas: [EVENT_SCHEMA_VERSION],
262
+ sessionEpoch: `${Date.now().toString(36)}-${process.pid}`,
263
+ platform: this.#account.platform,
264
+ accounts: [this.#account.id],
265
+ maxFrameBytes: MAX_FRAME_BYTES,
266
+ },
267
+ this.#initializeTimeoutMs,
268
+ );
269
+ const reported = initialized && typeof initialized === "object"
270
+ ? (initialized as { platform?: unknown }).platform
271
+ : undefined;
272
+ this.#capabilities = readCapabilities(initialized, this.#account.id);
273
+ return {
274
+ ...(typeof reported === "string" && reported.trim() ? { platform: reported.trim() } : {}),
275
+ ...(this.#capabilities ? { capabilities: this.#capabilities } : {}),
276
+ };
277
+ } catch (error) {
278
+ const tail = this.#stderrTail.trim();
279
+ const message = this.#pollutionError?.message ?? (error instanceof Error ? error.message : String(error));
280
+ throw new Error(`adapter probe failed: ${message}${tail ? `\nstderr:\n${tail}` : ""}`);
281
+ } finally {
282
+ await this.stop().catch(() => undefined);
283
+ }
284
+ }
285
+
148
286
  /**
149
287
  * Send one delivery. Platform outcomes are returned; protocol failures and
150
288
  * timeouts become state "unknown" and never throw.
@@ -4,7 +4,7 @@ import { applyReceipt, notifyDeliveryResult, type DeliveryResultHandler } from "
4
4
  import { parseTarget, startFailureReason, toEndpoint, validateTargets } from "./host-helpers.ts";
5
5
  import { IngestGate, type IngestResult } from "./ingest-gate.ts";
6
6
  import { log } from "./log.ts";
7
- import type { Endpoint, IngestEvent, MessageRef } from "./protocol.ts";
7
+ import type { AdapterCapabilities, Endpoint, IngestEvent, MessageRef } from "./protocol.ts";
8
8
  import { matchRules, planPayload, sameEndpoint, targetKey } from "./rules.ts";
9
9
  import type { ChannelAccountRuntime } from "./stats.ts";
10
10
  import { sanitizeAccountError } from "./stats.ts";
@@ -13,6 +13,8 @@ import { openState, type ChannelState, type DeliveryRow } from "./state.ts";
13
13
  export type { IngestResult } from "./ingest-gate.ts";
14
14
 
15
15
  export interface AdapterHandle {
16
+ /** Optional platform facts declared by the adapter during initialize. */
17
+ readonly capabilities?: AdapterCapabilities;
16
18
  start(): Promise<void>;
17
19
  send(
18
20
  deliveryId: string,
@@ -49,6 +51,14 @@ export interface HostDeps {
49
51
  onIngestCommitted?: (event: IngestEvent) => Promise<void> | void;
50
52
  /** Events used as inbound room notifications must not match outbound rules. */
51
53
  notificationOnly?: (event: IngestEvent) => boolean;
54
+ /**
55
+ * Resolve a stored delivery payload into the adapter's wire form right before
56
+ * a send. The host calls cleanup after the attempt, whether it succeeded or not.
57
+ */
58
+ prepareSendPayload?: (payload: unknown, capabilities?: AdapterCapabilities) => Promise<{
59
+ payload: unknown;
60
+ cleanup?: () => Promise<void>;
61
+ }>;
52
62
  }
53
63
 
54
64
  function defaultSpawnAdapter(account: AccountConfig, context: SpawnAdapterContext): AdapterHandle {
@@ -64,6 +74,7 @@ export class ChannelHost {
64
74
  readonly #onDeliveryResult?: DeliveryResultHandler;
65
75
  readonly #onIngestCommitted?: (event: IngestEvent) => Promise<void> | void;
66
76
  readonly #notificationOnly?: (event: IngestEvent) => boolean;
77
+ readonly #prepareSendPayload?: HostDeps["prepareSendPayload"];
67
78
  readonly #adapters = new Map<string, AdapterHandle>();
68
79
  readonly #timers = new Map<string, ReturnType<typeof setTimeout>>();
69
80
  readonly #inFlight = new Map<string, Set<string>>();
@@ -90,6 +101,7 @@ export class ChannelHost {
90
101
  this.#onDeliveryResult = deps.onDeliveryResult;
91
102
  this.#onIngestCommitted = deps.onIngestCommitted;
92
103
  this.#notificationOnly = deps.notificationOnly;
104
+ this.#prepareSendPayload = deps.prepareSendPayload;
93
105
  }
94
106
 
95
107
  /** Account ids whose adapter failed to start or exited; their queues stay paused. */
@@ -251,7 +263,7 @@ export class ChannelHost {
251
263
  } catch (error) {
252
264
  const message = error instanceof Error ? error.message : String(error);
253
265
  // An inbound notification owns the ACK: roll back and fail the ingest so
254
- // Feishu retries. Other consumer failures stay contained as before.
266
+ // the provider retries. Other consumer failures stay contained as before.
255
267
  if (this.#notificationOnly?.(stored)) {
256
268
  state.deleteIngestEvent(stored.eventId);
257
269
  log.error(`inbound commit rolled back: ${message}`, { event: stored.eventId });
@@ -410,18 +422,21 @@ export class ChannelHost {
410
422
  this.#gate.begin(accountId);
411
423
  try {
412
424
  let receipt: SendReceipt;
425
+ let cleanup: (() => Promise<void>) | undefined;
413
426
  try {
414
- receipt = await adapter.send(
415
- row.deliveryId,
416
- attemptId,
417
- row.idempotencyKey,
418
- target,
419
- JSON.parse(row.payload) as unknown,
420
- );
427
+ const stored = JSON.parse(row.payload) as unknown;
428
+ if (this.#prepareSendPayload) {
429
+ const prepared = await this.#prepareSendPayload(stored, adapter.capabilities);
430
+ cleanup = prepared.cleanup;
431
+ receipt = await adapter.send(row.deliveryId, attemptId, row.idempotencyKey, target, prepared.payload);
432
+ } else {
433
+ receipt = await adapter.send(row.deliveryId, attemptId, row.idempotencyKey, target, stored);
434
+ }
421
435
  } catch (error) {
422
436
  receipt = { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
423
437
  } finally {
424
438
  inFlight.delete(row.deliveryId);
439
+ await cleanup?.().catch(() => undefined);
425
440
  }
426
441
  // A host stop wins over a late send result: reload must not auto-resend.
427
442
  if (this.#stopReason) receipt = { state: "unknown", detail: this.#stopReason };
@@ -15,12 +15,21 @@ export function matchInboundRoutes(config: ChannelConfig, event: IngestEvent): I
15
15
 
16
16
  /**
17
17
  * Room-notification text. The native user id is opaque but stable; the account
18
- * label shows which Feishu bot and avoids exposing the chat id in room content.
18
+ * label shows which external bot and avoids exposing the chat id in room content.
19
19
  */
20
+ export function platformLabel(platform: string): string {
21
+ const value = platform.trim();
22
+ return value ? value[0]!.toUpperCase() + value.slice(1) : "Channel";
23
+ }
24
+
20
25
  export function inboundRoomText(event: IngestEvent, route: InboundRoute): string | undefined {
21
26
  const text = event.content?.text?.trim();
22
- if (!text) return undefined;
27
+ const attachments = event.content?.attachments ?? [];
28
+ if (!text && attachments.length === 0) return undefined;
23
29
  const actor = event.actor.nativeUserId || "unknown";
24
- const body = text.length > MAX_RELAY_TEXT ? `${text.slice(0, MAX_RELAY_TEXT)}…` : text;
25
- return `[Feishu ${route.from.account}] ${actor}: ${body}`;
30
+ const messageID = event.message?.nativeMessageId ?? event.providerEventId ?? "unknown";
31
+ const names = attachments.map((attachment) =>
32
+ attachment.kind === "image" ? "[image]" : `[file ${attachment.name}]`).join(", ");
33
+ const body = text ? (text.length > MAX_RELAY_TEXT ? `${text.slice(0, MAX_RELAY_TEXT)}…` : text) : names;
34
+ return `[${platformLabel(event.source.platform)} ${route.from.account}] message_id=${messageID} chat_id=${event.source.roomId} sender=${actor}: ${body}`;
26
35
  }
@@ -13,6 +13,57 @@ export type MessageRef = {
13
13
 
14
14
  export type ActorKey = { platform: string; identityNamespace: string; nativeUserId: string };
15
15
 
16
+ /**
17
+ * One attachment carried by an event. Outbound chatroom forwards name a
18
+ * `resourceId` the host resolves at send time; inbound adapter events supply a
19
+ * local `path` the host imports into the room.
20
+ */
21
+ export type AttachmentRef = {
22
+ kind: "image" | "file";
23
+ name: string;
24
+ mimeType?: string;
25
+ size?: number;
26
+ resourceId?: string;
27
+ roomId?: string;
28
+ path?: string;
29
+ sourceId?: string;
30
+ error?: string;
31
+ };
32
+
33
+ export type AttachmentCapabilities = {
34
+ kinds: Array<"image" | "file">;
35
+ imageMaxBytes?: number;
36
+ fileMaxBytes?: number;
37
+ };
38
+
39
+ /**
40
+ * One account setting declared by an adapter. `key` is the env variable the
41
+ * adapter process reads; the UI renders the field and stores its value there.
42
+ */
43
+ export type AccountField = {
44
+ key: string;
45
+ label?: string;
46
+ type?: "string" | "secret" | "boolean" | "number" | "select";
47
+ required?: boolean;
48
+ default?: string;
49
+ description?: string;
50
+ options?: Array<{ value: string; label?: string }>;
51
+ };
52
+
53
+ export type AccountCapabilities = {
54
+ /** Primary form fields, in display order. */
55
+ schema?: AccountField[];
56
+ /** Advanced env declarations; keys not covered here stay free-form. */
57
+ env?: AccountField[];
58
+ };
59
+
60
+ /** Adapter-declared platform facts the generic host must not hardcode. */
61
+ export type AdapterCapabilities = {
62
+ displayName?: string;
63
+ attachments?: AttachmentCapabilities;
64
+ account?: AccountCapabilities;
65
+ };
66
+
16
67
  export interface IngestEvent {
17
68
  schemaVersion: number;
18
69
  eventId: string;
@@ -25,7 +76,7 @@ export interface IngestEvent {
25
76
  parent?: MessageRef;
26
77
  occurredAt?: string;
27
78
  receivedAt: string;
28
- content?: { text?: string; attachmentRefs?: string[] };
79
+ content?: { text?: string; attachmentRefs?: string[]; attachments?: AttachmentRef[] };
29
80
  selectedMessage?: MessageRef;
30
81
  requestedTarget?: Endpoint;
31
82
  cause?: { rootEventId: string; visitedEndpoints: Endpoint[]; hopCount: number };
@@ -1,5 +1,5 @@
1
1
  import { ConfigError, type ChannelConfig, type RuleConfig, type RuleTarget } from "./config.ts";
2
- import type { Endpoint, IngestEvent, MessageRef } from "./protocol.ts";
2
+ import type { AttachmentRef, Endpoint, IngestEvent, MessageRef } from "./protocol.ts";
3
3
 
4
4
  const QUOTE_PREVIEW_LIMIT = 280;
5
5
  export const UNSUPPORTED_NOTICE = "attachment/format unsupported";
@@ -10,6 +10,7 @@ export type DeliveryPayload = {
10
10
  text: string;
11
11
  degraded?: "empty" | "unthreaded";
12
12
  parent?: MessageRef;
13
+ attachments?: AttachmentRef[];
13
14
  };
14
15
 
15
16
  export type PayloadPlan = { payload: DeliveryPayload } | { dropped: string };
@@ -107,13 +108,17 @@ export function planPayload(rule: RuleConfig, event: IngestEvent, target: Endpoi
107
108
  });
108
109
 
109
110
  let payload: DeliveryPayload;
110
- if (rendered.degraded === "empty") {
111
+ if (rendered.degraded === "empty" && !event.content?.attachments?.length) {
111
112
  if (rule.onUnsupported === "drop") return { dropped: "rendered text is empty" };
112
113
  payload = { text: UNSUPPORTED_NOTICE, degraded: "empty" };
113
114
  } else {
114
115
  payload = { text: rendered.text };
115
116
  }
116
117
 
118
+ // Attachments are opaque to rule rendering: the host resolves chatroom
119
+ // resource ids to local files right before the adapter sends.
120
+ if (event.content?.attachments?.length) payload.attachments = event.content.attachments;
121
+
117
122
  if (event.parent) {
118
123
  if (sameEndpoint(event.parent.endpoint, target)) {
119
124
  payload.parent = event.parent;
package/plugin.ts CHANGED
@@ -501,7 +501,7 @@ const roomExecute = async (
501
501
  );
502
502
  const room = svc.getRoom(args.roomId);
503
503
  notifications.push({ roomId: args.roomId, roomName: room.name, messages: [...room.messages] });
504
- return `sent: ${args.text}\nmessage id: ${msg.id}\n${formatRoom(svc, room)}`;
504
+ return `sent: ${args.text}\nmessage_id=${msg.id} room_id=${room.id}\n${formatRoom(svc, room)}`;
505
505
  }
506
506
  case "poll": {
507
507
  if (!args.roomId) {
@@ -186,6 +186,10 @@
186
186
 
187
187
  .btn {
188
188
  appearance: none;
189
+ display: inline-flex;
190
+ align-items: center;
191
+ justify-content: center;
192
+ gap: 6px;
189
193
  border: none;
190
194
  cursor: pointer;
191
195
  font: inherit;
@@ -233,7 +237,8 @@
233
237
  #announcementsDialog.is-pane .announcements-body, #remindersDialog.is-pane .reminders-body { padding: 0 14px 18px 18px; }
234
238
  .announcements-dialog .announcement-list { margin: 0; max-height: none; }
235
239
  .reminders-dialog .reminder-list { margin: 0; }
236
- .announcement-list { list-style: none; padding: 0; margin: 10px 0; max-height: 150px; overflow: auto; }
240
+ #announcementStatus { min-height: 1.4em; }
241
+ .announcement-list { list-style: none; padding: 0; margin: 10px 0; min-height: 120px; max-height: 150px; overflow: auto; }
237
242
  .announcement-list button { width: 100%; padding: 8px 10px; border: 1px solid transparent; border-radius: 8px; background: transparent; color: var(--ink); text-align: left; font: inherit; overflow-wrap: anywhere; cursor: pointer; }
238
243
  .announcement-list button:hover, .announcement-list button[aria-current="true"] { background: var(--accent-soft); border-color: var(--line); }
239
244
  .announcement-list button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
@@ -325,7 +330,7 @@
325
330
  .keys-list { display: grid; gap: 2px; list-style: none; margin: 0; padding: 0; }
326
331
  .keys-list li { display: grid; grid-template-columns: max-content minmax(0, 1fr); align-items: center; gap: 4px 16px; padding: 7px 0; border-top: 1px solid color-mix(in srgb, var(--line) 72%, transparent); font-size: 13px; }
327
332
  .keys-list li:first-child { border-top: 0; }
328
- .keys-list li > span:last-child { color: var(--ink-2); }
333
+ .keys-list li > span:last-child { color: var(--ink-2); text-align: right; }
329
334
  .keys-group { display: inline-flex; align-items: center; gap: 6px; }
330
335
  @media (max-width: 560px) {
331
336
  .keys-dialog { padding: 18px; }
@@ -453,6 +458,7 @@
453
458
  .footnotes ol { margin: 0; padding-left: 20px; }
454
459
  .footnotes li { margin: 3px 0; }
455
460
  .footnote-ref { font-size: .78em; line-height: 0; }
461
+ .footnote-ref + .footnote-ref { margin-left: .3em; }
456
462
  .footnote-ref a { text-decoration: none; }
457
463
  .footnote-backref { margin-left: 2px; text-decoration: none; }
458
464
 
@@ -122,10 +122,8 @@ export function initAdmin(app) {
122
122
  });
123
123
  $("#btnCloseOwnerOnly").addEventListener("click", () => ownerDialog.close());
124
124
  $("#btnOwnerOnlyOk").addEventListener("click", () => ownerDialog.close());
125
- ownerDialog.addEventListener("click", (event) => { if (event.target === ownerDialog) ownerDialog.close(); });
126
125
  $("#btnCloseEditRoom").addEventListener("click", () => dialog.close());
127
126
  $("#btnCancelEditRoom").addEventListener("click", () => dialog.close());
128
- dialog.addEventListener("click", (event) => { if (event.target === dialog) dialog.close(); });
129
127
  dialog.addEventListener("close", () => {
130
128
  const target = opener;
131
129
  opener = null;
@@ -180,14 +180,12 @@ export function initAnnouncements(app) {
180
180
  $("#btnRefreshAnnouncements").addEventListener("click", () => void load());
181
181
  $("#btnCloseAnnouncement").addEventListener("click", () => dialog.close());
182
182
  $("#btnCancelAnnouncement").addEventListener("click", () => dialog.close());
183
- dialog.addEventListener("click", (event) => { if (event.target === dialog) dialog.close(); });
184
183
  trigger.addEventListener("click", () => {
185
184
  // The entry lives in the Options menu, so choosing it closes that menu first.
186
185
  app.closePanels();
187
186
  openSurface();
188
187
  });
189
188
  $("#btnCloseAnnouncements").addEventListener("click", () => closeSurface());
190
- surface.addEventListener("click", (event) => { if (event.target === surface) closeSurface(); });
191
189
  surface.addEventListener("cancel", (event) => { event.preventDefault(); closeSurface(); });
192
190
  surface.addEventListener("close", () => {
193
191
  if (pendingReopen) { pendingReopen = false; return; }
@@ -199,12 +197,12 @@ export function initAnnouncements(app) {
199
197
  if (focus && target?.isConnected) target.focus({ preventScroll: true });
200
198
  });
201
199
  document.addEventListener("keydown", (event) => {
202
- if (event.key !== "Escape" || !surface.open || !surface.classList.contains("is-pane")) return;
200
+ if (event.key !== "Escape" || event.altKey || !surface.open || !surface.classList.contains("is-pane")) return;
203
201
  if (!surface.contains(document.activeElement)) return;
204
202
  event.preventDefault();
205
203
  closeSurface();
206
204
  });
207
- app.registerPanelSurface?.("announcements", { close: () => closeSurface(false) });
205
+ app.registerPanelSurface?.("announcements", { element: surface, close: (restore = false) => closeSurface(restore) });
208
206
  app.watchPanel?.("announcements", syncMode);
209
207
  const closePanels = app.closePanels;
210
208
  app.closePanels = () => { closePanels(); if (dialog.open) dialog.close(); };