@alexsun-top/opencode-chat-room 0.8.0 → 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 (176) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +2 -2
  3. package/README.md +40 -8
  4. package/README.zh-CN.md +40 -8
  5. package/cli.ts +27 -1
  6. package/dist/cli.js +5406 -3088
  7. package/package.json +25 -5
  8. package/packages/chat-room-channeld/README.md +111 -33
  9. package/packages/chat-room-channeld/src/adapter.ts +179 -7
  10. package/packages/chat-room-channeld/src/config.ts +63 -1
  11. package/packages/chat-room-channeld/src/delivery.ts +6 -1
  12. package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
  13. package/packages/chat-room-channeld/src/host.ts +142 -9
  14. package/packages/chat-room-channeld/src/inbound.ts +35 -0
  15. package/packages/chat-room-channeld/src/protocol.ts +52 -1
  16. package/packages/chat-room-channeld/src/rules.ts +7 -2
  17. package/packages/chat-room-channeld/src/state.ts +17 -0
  18. package/packages/chat-room-channeld/src/stats.ts +43 -1
  19. package/plugin.ts +1 -1
  20. package/server/admin-state.ts +13 -13
  21. package/server/app.ts +95 -0
  22. package/server/assets/NOTICE.txt +2 -1
  23. package/server/assets/base.css +21 -9
  24. package/server/assets/chat/admin.js +0 -2
  25. package/server/assets/chat/announcements.js +69 -8
  26. package/server/assets/chat/chat-background.js +177 -0
  27. package/server/assets/chat/confirm-dialog.js +0 -1
  28. package/server/assets/chat/create-room-dialog.js +0 -1
  29. package/server/assets/chat/diagram-viewer.js +7 -1
  30. package/server/assets/chat/doc-preview.js +251 -46
  31. package/server/assets/chat/events.js +16 -5
  32. package/server/assets/chat/files.js +53 -7
  33. package/server/assets/chat/image-zoom.js +8 -1
  34. package/server/assets/chat/index.js +6 -2
  35. package/server/assets/chat/integration-account-schema.js +99 -0
  36. package/server/assets/chat/integration-editor.js +163 -0
  37. package/server/assets/chat/integration-values.js +124 -0
  38. package/server/assets/chat/integrations.js +648 -0
  39. package/server/assets/chat/locales/de.js +40 -4
  40. package/server/assets/chat/locales/es.js +40 -4
  41. package/server/assets/chat/locales/fr.js +40 -4
  42. package/server/assets/chat/locales/it.js +40 -4
  43. package/server/assets/chat/locales/ja.js +40 -4
  44. package/server/assets/chat/locales/ko.js +40 -4
  45. package/server/assets/chat/markdown-footnotes.js +1 -1
  46. package/server/assets/chat/markdown.js +45 -8
  47. package/server/assets/chat/messages.js +6 -5
  48. package/server/assets/chat/office-preview.js +69 -0
  49. package/server/assets/chat/palette.js +6 -1
  50. package/server/assets/chat/panels.js +56 -0
  51. package/server/assets/chat/recall.js +58 -7
  52. package/server/assets/chat/receipts.js +17 -6
  53. package/server/assets/chat/reminders.js +68 -9
  54. package/server/assets/chat/replies.js +0 -6
  55. package/server/assets/chat/resource-format.js +11 -0
  56. package/server/assets/chat/rooms.js +1 -6
  57. package/server/assets/chat/settings.js +98 -4
  58. package/server/assets/chat/shortcuts.js +0 -3
  59. package/server/assets/chat/side-pane.js +34 -10
  60. package/server/assets/chat/state.js +125 -12
  61. package/server/assets/chat/system-events.js +58 -0
  62. package/server/assets/chat/system-messages.js +32 -14
  63. package/server/assets/chat/task-row.js +0 -6
  64. package/server/assets/chat/tasks.js +119 -37
  65. package/server/assets/chat/window-controls.js +37 -0
  66. package/server/assets/code-highlight.css +71 -32
  67. package/server/assets/conversation.css +174 -31
  68. package/server/assets/doc-preview.css +40 -3
  69. package/server/assets/files.css +8 -0
  70. package/server/assets/fluent-icons.svg +2 -0
  71. package/server/assets/monaco/LICENSE +21 -0
  72. package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
  73. package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
  74. package/server/assets/monaco/editor.worker.js +45 -0
  75. package/server/assets/monaco/integration-rules.css +1 -0
  76. package/server/assets/monaco/integration-rules.js +1605 -0
  77. package/server/assets/monaco/json.worker.js +77 -0
  78. package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
  79. package/server/assets/office/docx.bundle.js +33 -0
  80. package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
  81. package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
  82. package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
  83. package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
  84. package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
  85. package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
  86. package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
  87. package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
  88. package/server/assets/office/licenses/zrender-LICENSE.txt +29 -0
  89. package/server/assets/office/pptx.bundle.js +104 -0
  90. package/server/assets/office/xlsx.bundle.js +141 -0
  91. package/server/assets/recall.css +5 -4
  92. package/server/assets/responsive.css +80 -11
  93. package/server/assets/settings.css +185 -9
  94. package/server/assets/tasks.css +57 -7
  95. package/server/assets/window-controls.css +36 -0
  96. package/server/channel-attachments.ts +133 -0
  97. package/server/channel-integration.ts +572 -0
  98. package/server/channel-settings.ts +77 -0
  99. package/server/channels.ts +274 -21
  100. package/server/chat-server.ts +32 -580
  101. package/server/chat.html +234 -34
  102. package/server/http-server.ts +3 -182
  103. package/server/manifest.webmanifest +1 -0
  104. package/server/resource-routes.ts +16 -16
  105. package/server/routes/inbox.ts +100 -0
  106. package/server/routes/pages.ts +83 -0
  107. package/server/routes/questions.ts +39 -0
  108. package/server/routes/room-actions.ts +162 -0
  109. package/server/routes/rooms.ts +160 -0
  110. package/server/startup.ts +84 -0
  111. package/server/sw.js +5 -0
  112. package/server/task-routes.ts +1 -1
  113. package/src/center/center-client.ts +3 -11
  114. package/src/config/file-config.ts +7 -54
  115. package/src/platform/http-server.ts +182 -0
  116. package/src/protocol/addressing.ts +21 -0
  117. package/src/protocol/config.ts +58 -0
  118. package/src/protocol/room.ts +51 -0
  119. package/src/rooms/resources.ts +26 -16
  120. package/src/rooms/room-service.ts +2 -48
  121. package/src/rooms/storage.ts +329 -0
  122. package/src/rooms/tasks.ts +21 -5
  123. package/src/runtime/watch.ts +1 -1
  124. package/src/state/pg-database.ts +183 -0
  125. package/src/state/pg-migrate.ts +175 -0
  126. package/src/state/pg-sql.mjs +175 -0
  127. package/src/state/pg-worker.mjs +133 -0
  128. package/src/state/sqlite-announcements.ts +25 -0
  129. package/src/state/sqlite-database.ts +130 -0
  130. package/src/state/sqlite-legacy.ts +90 -0
  131. package/src/state/sqlite-members.ts +155 -0
  132. package/src/state/sqlite-messages.ts +288 -0
  133. package/src/state/sqlite-resources.ts +39 -0
  134. package/src/state/sqlite-rooms.ts +194 -0
  135. package/src/state/sqlite-schema.ts +80 -0
  136. package/src/state/sqlite-state-store.ts +34 -0
  137. package/src/state/sqlite-state.ts +15 -897
  138. package/src/state/sqlite-tasks.ts +65 -0
  139. package/src/state/sqlite-transaction.ts +13 -0
  140. package/src/state/sqlite.ts +21 -1
  141. package/src/state/store.ts +5 -1
  142. package/src/tui/app.mjs +32 -19
  143. package/src/tui/config.mjs +12 -4
  144. package/src/tui/i18n.mjs +38 -0
  145. package/src/tui/info-app.mjs +50 -51
  146. package/src/tui/info-content.mjs +79 -44
  147. package/src/tui/join-app.mjs +9 -9
  148. package/src/tui/locales/en.mjs +349 -0
  149. package/src/tui/locales/zh-CN.mjs +349 -0
  150. package/src/tui/main.mjs +85 -37
  151. package/src/tui/markdown.mjs +3 -2
  152. package/src/tui/mentions.mjs +3 -1
  153. package/src/tui/message-app.mjs +22 -21
  154. package/src/tui/message-view.mjs +2 -1
  155. package/src/tui/palette-app.mjs +9 -8
  156. package/src/tui/palette.mjs +30 -24
  157. package/src/tui/prefs.mjs +92 -0
  158. package/src/tui/reminder-app.mjs +18 -17
  159. package/src/tui/room-settings-app.mjs +30 -28
  160. package/src/tui/settings-app.mjs +153 -0
  161. package/src/tui/ui-content.mjs +65 -86
  162. package/src/tui/ui-help.mjs +73 -0
  163. package/src/tui/ui-overlay-view.mjs +23 -7
  164. package/src/tui/ui-suggest.mjs +6 -5
  165. package/src/tui/ui-theme.mjs +37 -33
  166. package/src/tui/ui-view.mjs +22 -7
  167. package/src/tui/ui.mjs +15 -3
  168. package/src/web/editor.worker.ts +1 -0
  169. package/src/web/integration-rules-editor.ts +573 -0
  170. package/src/web/integration-rules.ts +26 -0
  171. package/src/web/integration-schema.ts +229 -0
  172. package/src/web/json.worker.ts +1 -0
  173. package/src/web/office-viewer.ts +221 -0
  174. package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -499
  175. package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -473
  176. package/server/assets/chat/forward.js +0 -69
@@ -71,11 +71,16 @@ export function applyReceipt(
71
71
  providerMessage: providerMessage ?? null,
72
72
  lastError: null,
73
73
  });
74
+ const event = state.getEvent(row.eventId);
74
75
  const echo = receipt.providerMessage?.nativeMessageId && receipt.providerMessage.endpoint
75
76
  ? {
76
77
  endpoint: targetKey(receipt.providerMessage.endpoint),
77
78
  nativeMessageId: receipt.providerMessage.nativeMessageId,
78
- logicalMessageId: row.eventId,
79
+ // The room's logical id is the selected message for a forward, the
80
+ // provider message for an adapter ingest, and the event id otherwise.
81
+ logicalMessageId: event?.selectedMessage?.nativeMessageId
82
+ ?? event?.message?.nativeMessageId
83
+ ?? row.eventId,
79
84
  }
80
85
  : undefined;
81
86
  state.recordSent({
@@ -30,6 +30,17 @@ export function validateTargets(config: ChannelConfig): void {
30
30
  }
31
31
  }
32
32
  }
33
+ for (const route of config.inbound) {
34
+ const account = accounts.get(route.from.account);
35
+ if (!account) {
36
+ throw new Error(`config: inbound route sources unknown account "${route.from.account}"`);
37
+ }
38
+ if (account.platform !== route.from.platform) {
39
+ throw new Error(
40
+ `config: inbound route sources platform "${route.from.platform}" but account "${route.from.account}" is "${account.platform}"`,
41
+ );
42
+ }
43
+ }
33
44
  }
34
45
 
35
46
  export function toEndpoint(config: ChannelConfig, ruleId: string, target: RuleTarget): Endpoint {
@@ -4,13 +4,17 @@ 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 } from "./protocol.ts";
7
+ import type { AdapterCapabilities, Endpoint, IngestEvent, MessageRef } from "./protocol.ts";
8
8
  import { matchRules, planPayload, sameEndpoint, targetKey } from "./rules.ts";
9
+ import type { ChannelAccountRuntime } from "./stats.ts";
10
+ import { sanitizeAccountError } from "./stats.ts";
9
11
  import { openState, type ChannelState, type DeliveryRow } from "./state.ts";
10
12
 
11
13
  export type { IngestResult } from "./ingest-gate.ts";
12
14
 
13
15
  export interface AdapterHandle {
16
+ /** Optional platform facts declared by the adapter during initialize. */
17
+ readonly capabilities?: AdapterCapabilities;
14
18
  start(): Promise<void>;
15
19
  send(
16
20
  deliveryId: string,
@@ -26,6 +30,7 @@ export interface SpawnAdapterContext {
26
30
  onIngest(event: IngestEvent): Promise<{ duplicate: boolean; eventId?: string }>;
27
31
  onExit(code: number | null, signal: NodeJS.Signals | null): void;
28
32
  onUnavailable(reason: string): void;
33
+ onStatus(status: { inbound?: string; detail?: string }): void;
29
34
  }
30
35
 
31
36
  export type SpawnAdapter = (account: AccountConfig, context: SpawnAdapterContext) => AdapterHandle;
@@ -36,6 +41,24 @@ export interface HostDeps {
36
41
  now?: () => number;
37
42
  deliveryIntervalMs?: number;
38
43
  onDeliveryResult?: DeliveryResultHandler;
44
+ /**
45
+ * Called once for a newly committed ingest event, never for duplicates or
46
+ * echoes. The host awaits it before reporting success: for an inbound
47
+ * notification, a rejection rolls the event back and becomes an ingest error
48
+ * so the provider retries instead of ACKing a lost message. Duplicate/replay
49
+ * suppression is durable via the event dedup key.
50
+ */
51
+ onIngestCommitted?: (event: IngestEvent) => Promise<void> | void;
52
+ /** Events used as inbound room notifications must not match outbound rules. */
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
+ }>;
39
62
  }
40
63
 
41
64
  function defaultSpawnAdapter(account: AccountConfig, context: SpawnAdapterContext): AdapterHandle {
@@ -49,18 +72,23 @@ export class ChannelHost {
49
72
  readonly #now: () => number;
50
73
  readonly #deliveryIntervalMs: number;
51
74
  readonly #onDeliveryResult?: DeliveryResultHandler;
75
+ readonly #onIngestCommitted?: (event: IngestEvent) => Promise<void> | void;
76
+ readonly #notificationOnly?: (event: IngestEvent) => boolean;
77
+ readonly #prepareSendPayload?: HostDeps["prepareSendPayload"];
52
78
  readonly #adapters = new Map<string, AdapterHandle>();
53
79
  readonly #timers = new Map<string, ReturnType<typeof setTimeout>>();
54
80
  readonly #inFlight = new Map<string, Set<string>>();
55
81
  readonly #notified = new Set<string>();
56
82
  readonly #active = new Set<Promise<void>>();
57
83
  readonly #disabled = new Set<string>();
84
+ readonly #accountStates = new Map<string, ChannelAccountRuntime>();
58
85
  readonly #gate = new IngestGate((accountId, _event, _error) => {
59
86
  this.#disableAccount(accountId, "ingest barrier limit reached");
60
87
  });
61
88
  #state?: ChannelState;
62
89
  #running = false;
63
90
  #starting = false;
91
+ #stopReason?: string;
64
92
  #idleTimer?: ReturnType<typeof setInterval>;
65
93
  #rejectionHandler?: (reason: unknown) => void;
66
94
 
@@ -71,6 +99,9 @@ export class ChannelHost {
71
99
  this.#now = deps.now ?? Date.now;
72
100
  this.#deliveryIntervalMs = deps.deliveryIntervalMs ?? 200;
73
101
  this.#onDeliveryResult = deps.onDeliveryResult;
102
+ this.#onIngestCommitted = deps.onIngestCommitted;
103
+ this.#notificationOnly = deps.notificationOnly;
104
+ this.#prepareSendPayload = deps.prepareSendPayload;
74
105
  }
75
106
 
76
107
  /** Account ids whose adapter failed to start or exited; their queues stay paused. */
@@ -78,6 +109,11 @@ export class ChannelHost {
78
109
  return [...this.#disabled];
79
110
  }
80
111
 
112
+ /** Live per-account state keyed by `platform/account`, including startup failures. */
113
+ get accountRuntimeStates(): ReadonlyMap<string, ChannelAccountRuntime> {
114
+ return new Map(this.#accountStates);
115
+ }
116
+
81
117
  /** Read-only view for routes: unknown ids or platform mismatches are missing. */
82
118
  targetStatus(platform: string, accountId: string): "ready" | "disabled" | "missing" {
83
119
  const account = this.#config.accounts.find((item) => item.id === accountId);
@@ -85,6 +121,14 @@ export class ChannelHost {
85
121
  return this.#disabled.has(accountId) ? "disabled" : "ready";
86
122
  }
87
123
 
124
+ /** Latest provider message sent for a logical room message, for native replies. */
125
+ findProviderMessage(endpoint: Endpoint, logicalMessageId: string): MessageRef | undefined {
126
+ const state = this.#state;
127
+ if (!state || !logicalMessageId) return undefined;
128
+ const nativeMessageId = state.findProviderMessage(targetKey(endpoint), logicalMessageId);
129
+ return nativeMessageId ? { endpoint, nativeMessageId } : undefined;
130
+ }
131
+
88
132
  async start(): Promise<void> {
89
133
  if (this.#running) throw new Error("host is already running");
90
134
  validateTargets(this.#config);
@@ -115,13 +159,17 @@ export class ChannelHost {
115
159
  onIngest: (event) => this.ingest(event),
116
160
  onExit: (code, signal) => this.#handleExit(account.id, code, signal),
117
161
  onUnavailable: (reason) => this.#disableAccount(account.id, reason),
162
+ onStatus: (status) => this.#handleAdapterStatus(account.id, status),
118
163
  });
119
164
  this.#adapters.set(account.id, adapter);
120
165
  await adapter.start();
166
+ const current = this.#accountStates.get(`${account.platform}/${account.id}`);
167
+ this.#setAccountState(account, "started", current?.lastError);
121
168
  this.#schedule(account.id);
122
169
  return { id: account.id };
123
170
  } catch (error) {
124
171
  const reason = startFailureReason(account.id, error);
172
+ this.#setAccountState(account, "failed", reason);
125
173
  this.#disabled.add(account.id);
126
174
  log.error(`adapter ${account.id} failed to start: ${reason}`, { account: account.id });
127
175
  if (adapter) {
@@ -146,6 +194,7 @@ export class ChannelHost {
146
194
  } else {
147
195
  const reason = result.reason instanceof Error ? result.reason.message : String(result.reason);
148
196
  failures.push({ id: account.id, reason });
197
+ this.#setAccountState(account, "failed", reason);
149
198
  this.#disabled.add(account.id);
150
199
  log.error(`adapter ${account.id} failed to start: ${reason}`, { account: account.id });
151
200
  }
@@ -169,6 +218,7 @@ export class ChannelHost {
169
218
  state.close();
170
219
  this.#state = undefined;
171
220
  this.#disabled.clear();
221
+ this.#accountStates.clear();
172
222
  const detail = failures.map((failure) => `${failure.id}: ${failure.reason}`).join("; ");
173
223
  throw new Error(`no adapters started${detail ? `: ${detail}` : ""}`);
174
224
  }
@@ -207,6 +257,27 @@ export class ChannelHost {
207
257
  const stored: IngestEvent = { ...event, ingressSeq: result.ingressSeq };
208
258
  log.info(`ingested ${stored.kind}`, { event: stored.eventId });
209
259
 
260
+ if (this.#onIngestCommitted) {
261
+ try {
262
+ await this.#onIngestCommitted(stored);
263
+ } catch (error) {
264
+ const message = error instanceof Error ? error.message : String(error);
265
+ // An inbound notification owns the ACK: roll back and fail the ingest so
266
+ // the provider retries. Other consumer failures stay contained as before.
267
+ if (this.#notificationOnly?.(stored)) {
268
+ state.deleteIngestEvent(stored.eventId);
269
+ log.error(`inbound commit rolled back: ${message}`, { event: stored.eventId });
270
+ throw error;
271
+ }
272
+ log.warn(`onIngestCommitted failed: ${message}`, { event: stored.eventId });
273
+ }
274
+ }
275
+
276
+ if (this.#notificationOnly?.(stored)) {
277
+ log.info("inbound notification only; outbound rules skipped", { event: stored.eventId });
278
+ return { duplicate: false, eventId: stored.eventId };
279
+ }
280
+
210
281
  if (stored.kind === "message.forward_requested") {
211
282
  const selected = stored.selectedMessage;
212
283
  const reason = !selected
@@ -256,7 +327,7 @@ export class ChannelHost {
256
327
  return { duplicate: false, eventId: stored.eventId };
257
328
  }
258
329
 
259
- async stop(): Promise<void> {
330
+ async stop(options: { abortInFlight?: boolean } = {}): Promise<void> {
260
331
  if (!this.#running && !this.#state) {
261
332
  this.#clearIdle();
262
333
  this.#removeRejectionGuard();
@@ -264,10 +335,17 @@ export class ChannelHost {
264
335
  }
265
336
  this.#running = false;
266
337
  this.#starting = false;
338
+ const stopReason = "relay runtime stopped";
339
+ this.#stopReason = stopReason;
267
340
  this.#clearIdle();
268
341
  for (const timer of this.#timers.values()) clearTimeout(timer);
269
342
  this.#timers.clear();
343
+ if (options.abortInFlight) {
344
+ this.#settleInFlightUnknown(stopReason);
345
+ await this.#stopAdapters();
346
+ }
270
347
  await Promise.allSettled([...this.#active]);
348
+ this.#settleInFlightUnknown(stopReason);
271
349
  await this.#stopAdapters();
272
350
  this.#state?.close();
273
351
  this.#state = undefined;
@@ -275,6 +353,7 @@ export class ChannelHost {
275
353
  this.#inFlight.clear();
276
354
  this.#notified.clear();
277
355
  this.#disabled.clear();
356
+ this.#accountStates.clear();
278
357
  this.#removeRejectionGuard();
279
358
  log.info("host stopped");
280
359
  }
@@ -343,19 +422,24 @@ export class ChannelHost {
343
422
  this.#gate.begin(accountId);
344
423
  try {
345
424
  let receipt: SendReceipt;
425
+ let cleanup: (() => Promise<void>) | undefined;
346
426
  try {
347
- receipt = await adapter.send(
348
- row.deliveryId,
349
- attemptId,
350
- row.idempotencyKey,
351
- target,
352
- JSON.parse(row.payload) as unknown,
353
- );
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
+ }
354
435
  } catch (error) {
355
436
  receipt = { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
356
437
  } finally {
357
438
  inFlight.delete(row.deliveryId);
439
+ await cleanup?.().catch(() => undefined);
358
440
  }
441
+ // A host stop wins over a late send result: reload must not auto-resend.
442
+ if (this.#stopReason) receipt = { state: "unknown", detail: this.#stopReason };
359
443
  applyReceipt(state, row, attemptId, accountId, receipt, this.#now());
360
444
  notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { attemptId, notified: this.#notified });
361
445
  } finally {
@@ -366,6 +450,27 @@ export class ChannelHost {
366
450
  }
367
451
  }
368
452
 
453
+ /** Stop must never leave rows that the next host would auto-resend. */
454
+ #settleInFlightUnknown(reason: string): void {
455
+ const state = this.#state;
456
+ if (!state) return;
457
+ for (const [accountId, deliveryIds] of this.#inFlight) {
458
+ for (const deliveryId of deliveryIds) {
459
+ try {
460
+ state.markDelivery(deliveryId, "unknown", { lastError: reason });
461
+ notifyDeliveryResult(state, deliveryId, this.#onDeliveryResult, { notified: this.#notified });
462
+ } catch (error) {
463
+ this.#safeWarn(
464
+ `could not mark delivery unknown: ${error instanceof Error ? error.message : String(error)}`,
465
+ accountId,
466
+ deliveryId,
467
+ );
468
+ }
469
+ }
470
+ }
471
+ this.#inFlight.clear();
472
+ }
473
+
369
474
  #pauseAccountDeliveries(accountId: string, reason: string): void {
370
475
  const state = this.#state;
371
476
  const account = this.#config.accounts.find((item) => item.id === accountId);
@@ -383,9 +488,37 @@ export class ChannelHost {
383
488
  }
384
489
  }
385
490
 
491
+ /** Inbound health is advisory: failures must not disable a working outbound account. */
492
+ #handleAdapterStatus(accountId: string, status: { inbound?: string; detail?: string }): void {
493
+ if (this.#disabled.has(accountId)) return;
494
+ const account = this.#config.accounts.find((item) => item.id === accountId);
495
+ if (!account) return;
496
+ const key = `${account.platform}/${account.id}`;
497
+ if (status.inbound === "failed") {
498
+ const detail = sanitizeAccountError(`inbound failed: ${status.detail ?? "unknown"}`);
499
+ this.#accountStates.set(key, { state: "started", lastError: detail });
500
+ log.warn(detail, { account: accountId });
501
+ } else if (status.inbound === "ready") {
502
+ this.#accountStates.set(key, { state: "started" });
503
+ }
504
+ }
505
+
506
+ #setAccountState(
507
+ account: AccountConfig,
508
+ state: ChannelAccountRuntime["state"],
509
+ lastError?: string,
510
+ ): void {
511
+ this.#accountStates.set(
512
+ `${account.platform}/${account.id}`,
513
+ lastError ? { state, lastError } : { state },
514
+ );
515
+ }
516
+
386
517
  #disableAccount(accountId: string, reason: string): void {
387
518
  if (this.#disabled.has(accountId)) return;
388
519
  this.#disabled.add(accountId);
520
+ const account = this.#config.accounts.find((item) => item.id === accountId);
521
+ if (account) this.#setAccountState(account, "disabled", reason);
389
522
 
390
523
  const timer = this.#timers.get(accountId);
391
524
  if (timer) {
@@ -0,0 +1,35 @@
1
+ import type { ChannelConfig, InboundRoute } from "./config.ts";
2
+ import type { IngestEvent } from "./protocol.ts";
3
+
4
+ const MAX_RELAY_TEXT = 4000;
5
+
6
+ /** Inbound routes that turn one committed external event into a room notification. */
7
+ export function matchInboundRoutes(config: ChannelConfig, event: IngestEvent): InboundRoute[] {
8
+ return config.inbound.filter((route) =>
9
+ route.from.platform === event.source.platform
10
+ && route.from.account === event.source.accountId
11
+ && route.from.room === event.source.roomId
12
+ && (route.from.event === undefined || route.from.event === event.kind)
13
+ );
14
+ }
15
+
16
+ /**
17
+ * Room-notification text. The native user id is opaque but stable; the account
18
+ * label shows which external bot and avoids exposing the chat id in room content.
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
+
25
+ export function inboundRoomText(event: IngestEvent, route: InboundRoute): string | undefined {
26
+ const text = event.content?.text?.trim();
27
+ const attachments = event.content?.attachments ?? [];
28
+ if (!text && attachments.length === 0) return undefined;
29
+ const actor = event.actor.nativeUserId || "unknown";
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}`;
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;
@@ -92,6 +92,8 @@ export type CommitResult =
92
92
 
93
93
  export interface ChannelState {
94
94
  commitIngest(event: IngestEvent): CommitResult;
95
+ /** Remove a freshly committed event when a downstream consumer failed. */
96
+ deleteIngestEvent(eventId: string): void;
95
97
  enqueueDeliveries(
96
98
  triggerEventId: string,
97
99
  rule: RuleConfig,
@@ -110,6 +112,8 @@ export interface ChannelState {
110
112
  getPublishedResult(deliveryId: string): PublishedResultEvent | undefined;
111
113
  recordEcho(endpoint: string, nativeMessageId: string, logicalMessageId: string, deliveryId?: string): void;
112
114
  findEcho(endpoint: string, nativeMessageId: string): string | undefined;
115
+ /** Latest sent provider message for one logical message at one endpoint. */
116
+ findProviderMessage(endpoint: string, logicalMessageId: string): string | undefined;
113
117
  getDelivery(deliveryId: string): DeliveryRow | undefined;
114
118
  getEvent(eventId: string): IngestEvent | undefined;
115
119
  listDeliveries(): DeliveryRow[];
@@ -241,6 +245,10 @@ export function openState(path: string): ChannelState {
241
245
  });
242
246
  },
243
247
 
248
+ deleteIngestEvent(eventId) {
249
+ db.prepare("DELETE FROM channel_events WHERE event_id = ?").run(eventId);
250
+ },
251
+
244
252
  enqueueDeliveries(triggerEventId, rule, targets, payloads) {
245
253
  if (targets.length !== payloads.length) {
246
254
  throw new Error("enqueueDeliveries: targets and payloads must have the same length");
@@ -447,6 +455,15 @@ export function openState(path: string): ChannelState {
447
455
  return row ? String(row.logical_message_id) : undefined;
448
456
  },
449
457
 
458
+ findProviderMessage(endpoint, logicalMessageId) {
459
+ const row = db.prepare(
460
+ `SELECT native_message_id FROM channel_echoes
461
+ WHERE endpoint = ? AND logical_message_id = ? AND delivery_id IS NOT NULL
462
+ ORDER BY rowid DESC LIMIT 1`,
463
+ ).get(endpoint, logicalMessageId) as RawRow | undefined;
464
+ return row ? String(row.native_message_id) : undefined;
465
+ },
466
+
450
467
  getDelivery,
451
468
 
452
469
  getEvent(eventId) {
@@ -1,7 +1,17 @@
1
1
  import { DatabaseSync } from "node:sqlite";
2
2
 
3
+ export type ChannelAccountState = "started" | "failed" | "disabled" | "unknown";
4
+
5
+ /** Live state supplied by a running host; stats itself only reads SQLite. */
6
+ export interface ChannelAccountRuntime {
7
+ state: ChannelAccountState;
8
+ lastError?: string;
9
+ }
10
+
3
11
  export interface ChannelAccountStats {
4
12
  account: string;
13
+ state: ChannelAccountState;
14
+ lastError?: string;
5
15
  queueDepth: number;
6
16
  oldestBacklogAt: number | null;
7
17
  unknown: number;
@@ -35,9 +45,18 @@ export interface ChannelStats {
35
45
 
36
46
  const REQUIRED_TABLES = ["channel_events", "channel_deliveries", "channel_receipts"];
37
47
  const QUEUE_STATES = new Set(["pending", "retryable", "rate_limited"]);
48
+ const MAX_LAST_ERROR = 200;
38
49
 
39
50
  type Row = Record<string, unknown>;
40
51
 
52
+ /** Keep status details short and free of credential-shaped fragments. */
53
+ export function sanitizeAccountError(value: string): string {
54
+ const redacted = value
55
+ .replace(/\bBearer\s+\S+/gi, "Bearer [redacted]")
56
+ .replace(/\b(secret|token|password|passwd|authorization|api[_-]?key)\b\s*[:=]\s*\S+/gi, "$1=[redacted]");
57
+ return redacted.replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim().slice(0, MAX_LAST_ERROR);
58
+ }
59
+
41
60
  function count(db: DatabaseSync, sql: string): number {
42
61
  const row = db.prepare(sql).get() as Row;
43
62
  return Number(row.count);
@@ -54,7 +73,11 @@ function accountKey(target: string): string {
54
73
  * Read queue and integrity counts without touching message content.
55
74
  * The database is opened read-only, so a missing state file is never created.
56
75
  */
57
- export function readChannelStats(path: string, now = Date.now()): ChannelStats {
76
+ export function readChannelStats(
77
+ path: string,
78
+ now = Date.now(),
79
+ runtime: ReadonlyMap<string, ChannelAccountRuntime> = new Map(),
80
+ ): ChannelStats {
58
81
  let db: DatabaseSync | undefined;
59
82
  try {
60
83
  db = new DatabaseSync(path, { readOnly: true });
@@ -83,6 +106,7 @@ export function readChannelStats(path: string, now = Date.now()): ChannelStats {
83
106
  if (!account) {
84
107
  account = {
85
108
  account: key,
109
+ state: "unknown",
86
110
  queueDepth: 0,
87
111
  oldestBacklogAt: null,
88
112
  unknown: 0,
@@ -106,6 +130,24 @@ export function readChannelStats(path: string, now = Date.now()): ChannelStats {
106
130
  }
107
131
  }
108
132
 
133
+ // Runtime entries add configured accounts without deliveries and override
134
+ // the SQLite-only default of "unknown" for a running host.
135
+ for (const [key, live] of runtime) {
136
+ const account = accounts.get(key) ?? {
137
+ account: key,
138
+ state: "unknown" as const,
139
+ queueDepth: 0,
140
+ oldestBacklogAt: null,
141
+ unknown: 0,
142
+ retryable: 0,
143
+ rateLimited: 0,
144
+ };
145
+ account.state = live.state;
146
+ const lastError = live.lastError ? sanitizeAccountError(live.lastError) : "";
147
+ if (lastError) account.lastError = lastError;
148
+ accounts.set(key, account);
149
+ }
150
+
109
151
  const pending = stateCounts.pending ?? 0;
110
152
  const retryable = stateCounts.retryable ?? 0;
111
153
  const rateLimited = stateCounts.rate_limited ?? 0;
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) {