@alexsun-top/opencode-chat-room 0.7.8 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/LICENSE +21 -0
  3. package/README.md +45 -36
  4. package/README.zh-CN.md +50 -41
  5. package/dist/cli.js +2629 -350
  6. package/package.json +13 -3
  7. package/packages/chat-room-channeld/README.md +242 -0
  8. package/packages/chat-room-channeld/dist/feishu-adapter.js +499 -0
  9. package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
  10. package/packages/chat-room-channeld/src/adapter.ts +475 -0
  11. package/packages/chat-room-channeld/src/cli.ts +124 -0
  12. package/packages/chat-room-channeld/src/config.ts +207 -0
  13. package/packages/chat-room-channeld/src/delivery.ts +158 -0
  14. package/packages/chat-room-channeld/src/feishu-adapter.ts +473 -0
  15. package/packages/chat-room-channeld/src/framing.ts +128 -0
  16. package/packages/chat-room-channeld/src/host-helpers.ts +41 -0
  17. package/packages/chat-room-channeld/src/host.ts +509 -0
  18. package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
  19. package/packages/chat-room-channeld/src/log.ts +26 -0
  20. package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
  21. package/packages/chat-room-channeld/src/protocol.ts +75 -0
  22. package/packages/chat-room-channeld/src/published.ts +37 -0
  23. package/packages/chat-room-channeld/src/rules.ts +127 -0
  24. package/packages/chat-room-channeld/src/state.ts +485 -0
  25. package/packages/chat-room-channeld/src/stats.ts +167 -0
  26. package/plugin.ts +22 -5
  27. package/server/addressing-routes.ts +130 -0
  28. package/server/assets/NOTICE.txt +2 -2
  29. package/server/assets/SHIKI-LICENSE +22 -0
  30. package/server/assets/base.css +9 -1
  31. package/server/assets/chat/doc-preview.js +3 -4
  32. package/server/assets/chat/forward.js +69 -0
  33. package/server/assets/chat/index.js +2 -0
  34. package/server/assets/chat/locales/de.js +5 -0
  35. package/server/assets/chat/locales/es.js +5 -0
  36. package/server/assets/chat/locales/fr.js +5 -0
  37. package/server/assets/chat/locales/it.js +5 -0
  38. package/server/assets/chat/locales/ja.js +5 -0
  39. package/server/assets/chat/locales/ko.js +5 -0
  40. package/server/assets/chat/markdown-footnotes.js +115 -0
  41. package/server/assets/chat/markdown.js +24 -35
  42. package/server/assets/chat/palette.js +1 -1
  43. package/server/assets/chat/replies.js +7 -1
  44. package/server/assets/chat/shiki.js +87 -0
  45. package/server/assets/chat/side-pane.js +8 -1
  46. package/server/assets/chat/state.js +14 -1
  47. package/server/assets/chat/system-messages.js +2 -0
  48. package/server/assets/code-highlight.css +20 -31
  49. package/server/assets/conversation.css +3 -2
  50. package/server/assets/doc-preview.css +2 -1
  51. package/server/assets/responsive.css +5 -0
  52. package/server/assets/shiki.bundle.js +152 -0
  53. package/server/channels.ts +314 -0
  54. package/server/chat-server.ts +27 -4
  55. package/server/chat.html +10 -3
  56. package/server/sw.js +1 -2
  57. package/skills/chatroom/SKILL.md +1 -1
  58. package/src/center/center-client.ts +79 -1
  59. package/src/config/file-config.ts +34 -0
  60. package/src/runtime/v2-plugin.ts +8 -2
  61. package/src/runtime/watch.ts +3 -2
  62. package/src/state/sqlite-state.ts +42 -11
  63. package/src/state/store.ts +9 -3
  64. package/src/tui/http.mjs +16 -2
  65. package/src/tui/main.mjs +1 -1
  66. package/server/assets/HIGHLIGHT-LICENSE +0 -29
  67. package/server/assets/highlight-10.7.3.min.js +0 -1358
@@ -0,0 +1,207 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { parse as parseYaml } from "yaml";
3
+
4
+ export class ConfigError extends Error {
5
+ constructor(message: string) {
6
+ super(message);
7
+ this.name = "ConfigError";
8
+ }
9
+ }
10
+
11
+ export type Transform =
12
+ | { op: "prefix-source" }
13
+ | { op: "trim" }
14
+ | { op: "truncate"; max: number }
15
+ | { op: "quote-preview" };
16
+
17
+ export type RuleTarget = { platform: string; account: string; room: string };
18
+ export type RuleSource = RuleTarget & { event?: string };
19
+
20
+ export interface RuleConfig {
21
+ id: string;
22
+ version: number;
23
+ from: RuleSource;
24
+ transforms: Transform[];
25
+ to: RuleTarget[];
26
+ onMissingParent: "quote_or_unthreaded" | "drop";
27
+ onUnsupported: "text_with_notice" | "drop";
28
+ }
29
+
30
+ export interface AccountConfig {
31
+ id: string;
32
+ platform: string;
33
+ adapter: { command: string[]; runtime?: string };
34
+ }
35
+
36
+ export interface ChannelConfig {
37
+ stateFile: string;
38
+ accounts: AccountConfig[];
39
+ rules: RuleConfig[];
40
+ }
41
+
42
+ type RecordValue = Record<string, unknown>;
43
+
44
+ function record(value: unknown, where: string): RecordValue {
45
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
46
+ throw new ConfigError(`config: ${where} must be a mapping`);
47
+ }
48
+ return value as RecordValue;
49
+ }
50
+
51
+ const IDENTIFIER = /^[A-Za-z0-9._-]+$/;
52
+
53
+ function stringValue(value: unknown, where: string): string {
54
+ if (typeof value !== "string" || !value.trim()) {
55
+ throw new ConfigError(`config: ${where} must be a non-empty string`);
56
+ }
57
+ return value;
58
+ }
59
+
60
+ function identifierValue(value: unknown, where: string): string {
61
+ const text = stringValue(value, where);
62
+ if (!IDENTIFIER.test(text)) {
63
+ throw new ConfigError(
64
+ `config: ${where} must match /^[A-Za-z0-9._-]+$/ (letters, digits, dot, underscore, hyphen; "/" is not allowed)`,
65
+ );
66
+ }
67
+ return text;
68
+ }
69
+
70
+ function optionalString(value: unknown, where: string): string | undefined {
71
+ if (value === undefined) return undefined;
72
+ return stringValue(value, where);
73
+ }
74
+
75
+ function arrayValue(value: unknown, where: string): unknown[] {
76
+ if (!Array.isArray(value) || value.length === 0) {
77
+ throw new ConfigError(`config: ${where} must be a non-empty array`);
78
+ }
79
+ return value;
80
+ }
81
+
82
+ function parseTarget(value: unknown, where: string): RuleTarget {
83
+ const raw = record(value, where);
84
+ return {
85
+ platform: identifierValue(raw.platform, `${where}.platform`),
86
+ account: identifierValue(raw.account, `${where}.account`),
87
+ room: identifierValue(raw.room, `${where}.room`),
88
+ };
89
+ }
90
+
91
+ function parseTransform(value: unknown, where: string): Transform {
92
+ const raw = record(value, where);
93
+ switch (raw.op) {
94
+ case "prefix-source":
95
+ case "trim":
96
+ case "quote-preview":
97
+ return { op: raw.op };
98
+ case "truncate": {
99
+ if (typeof raw.max !== "number" || !Number.isInteger(raw.max) || raw.max < 1) {
100
+ throw new ConfigError(`config: ${where}.max must be a positive integer`);
101
+ }
102
+ return { op: "truncate", max: raw.max };
103
+ }
104
+ default:
105
+ throw new ConfigError(
106
+ `config: ${where}.op must be one of prefix-source, trim, truncate, quote-preview`,
107
+ );
108
+ }
109
+ }
110
+
111
+ function parseAccount(value: unknown, where: string): AccountConfig {
112
+ const raw = record(value, where);
113
+ const adapter = record(raw.adapter, `${where}.adapter`);
114
+ const command = arrayValue(adapter.command, `${where}.adapter.command`).map((item, index) =>
115
+ stringValue(item, `${where}.adapter.command[${index}]`),
116
+ );
117
+ return {
118
+ id: identifierValue(raw.id, `${where}.id`),
119
+ platform: identifierValue(raw.platform, `${where}.platform`),
120
+ adapter: { command, runtime: optionalString(adapter.runtime, `${where}.adapter.runtime`) },
121
+ };
122
+ }
123
+
124
+ function parseRule(value: unknown, where: string): RuleConfig {
125
+ const raw = record(value, where);
126
+ const from = record(raw.from, `${where}.from`);
127
+ const version = raw.version;
128
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 1) {
129
+ throw new ConfigError(`config: ${where}.version must be a positive integer`);
130
+ }
131
+ const transforms = raw.transforms === undefined
132
+ ? []
133
+ : arrayValueAllowEmpty(raw.transforms, `${where}.transforms`).map((item, index) =>
134
+ parseTransform(item, `${where}.transforms[${index}]`),
135
+ );
136
+ const missingParent = optionalString(raw.onMissingParent, `${where}.onMissingParent`);
137
+ if (missingParent !== undefined && missingParent !== "quote_or_unthreaded" && missingParent !== "drop") {
138
+ throw new ConfigError(`config: ${where}.onMissingParent must be quote_or_unthreaded or drop`);
139
+ }
140
+ const unsupported = optionalString(raw.onUnsupported, `${where}.onUnsupported`);
141
+ if (unsupported !== undefined && unsupported !== "text_with_notice" && unsupported !== "drop") {
142
+ throw new ConfigError(`config: ${where}.onUnsupported must be text_with_notice or drop`);
143
+ }
144
+ return {
145
+ id: stringValue(raw.id, `${where}.id`),
146
+ version,
147
+ from: {
148
+ ...parseTarget({ platform: from.platform, account: from.account, room: from.room }, `${where}.from`),
149
+ event: optionalString(from.event, `${where}.from.event`),
150
+ },
151
+ transforms,
152
+ to: arrayValue(raw.to, `${where}.to`).map((item, index) => parseTarget(item, `${where}.to[${index}]`)),
153
+ onMissingParent: (missingParent ?? "quote_or_unthreaded") as RuleConfig["onMissingParent"],
154
+ onUnsupported: (unsupported ?? "text_with_notice") as RuleConfig["onUnsupported"],
155
+ };
156
+ }
157
+
158
+ function arrayValueAllowEmpty(value: unknown, where: string): unknown[] {
159
+ if (!Array.isArray(value)) throw new ConfigError(`config: ${where} must be an array`);
160
+ return value;
161
+ }
162
+
163
+ /** Validate a parsed YAML/JSON value. */
164
+ export function parseConfig(value: unknown): ChannelConfig {
165
+ const raw = record(value, "root");
166
+ const stateFile = stringValue(raw.stateFile, "stateFile");
167
+ const accounts = arrayValue(raw.accounts, "accounts").map((item, index) =>
168
+ parseAccount(item, `accounts[${index}]`),
169
+ );
170
+ const rules = raw.rules === undefined
171
+ ? []
172
+ : arrayValueAllowEmpty(raw.rules, "rules").map((item, index) => parseRule(item, `rules[${index}]`));
173
+
174
+ const accountIds = new Set<string>();
175
+ for (const account of accounts) {
176
+ if (accountIds.has(account.id)) throw new ConfigError(`config: duplicate account id "${account.id}"`);
177
+ accountIds.add(account.id);
178
+ }
179
+ const ruleKeys = new Set<string>();
180
+ for (const rule of rules) {
181
+ const key = `${rule.id}@${rule.version}`;
182
+ if (ruleKeys.has(key)) throw new ConfigError(`config: duplicate rule "${rule.id}" version ${rule.version}`);
183
+ ruleKeys.add(key);
184
+ }
185
+ return { stateFile, accounts, rules };
186
+ }
187
+
188
+ /** Load a config file. YAML parsing also accepts JSON documents. */
189
+ export function loadConfig(file: string): ChannelConfig {
190
+ let text: string;
191
+ try {
192
+ text = readFileSync(file, "utf8");
193
+ } catch (error) {
194
+ throw new ConfigError(
195
+ `config: cannot read ${file}: ${error instanceof Error ? error.message : String(error)}`,
196
+ );
197
+ }
198
+ let parsed: unknown;
199
+ try {
200
+ parsed = parseYaml(text);
201
+ } catch (error) {
202
+ throw new ConfigError(
203
+ `config: invalid YAML/JSON in ${file}: ${error instanceof Error ? error.message : String(error)}`,
204
+ );
205
+ }
206
+ return parseConfig(parsed);
207
+ }
@@ -0,0 +1,158 @@
1
+ import type { SendReceipt } from "./adapter.ts";
2
+ import { log } from "./log.ts";
3
+ import type { IngestEvent } from "./protocol.ts";
4
+ import { targetKey } from "./rules.ts";
5
+ import { isTerminalDeliveryState, type ChannelState, type DeliveryRow, type ReceiptRow } from "./state.ts";
6
+
7
+ const MAX_ATTEMPTS = 8;
8
+ const MAX_BACKOFF_MS = 30_000;
9
+ const RETRY_BASE_MS = 500;
10
+
11
+ export type DeliveryResultHandler = (
12
+ event: IngestEvent | undefined,
13
+ delivery: DeliveryRow,
14
+ receipt: ReceiptRow | undefined,
15
+ ) => void;
16
+
17
+ export interface NotifyDeliveryResultOptions {
18
+ /** Attempt whose receipt is attached; omit when the outcome has no receipt row. */
19
+ attemptId?: string;
20
+ /** Delivery ids already reported, so a later normal path cannot fire twice. */
21
+ notified: Set<string>;
22
+ }
23
+
24
+ /** Invoke the result callback once for a terminal delivery, with its receipt when one exists. */
25
+ export function notifyDeliveryResult(
26
+ state: ChannelState,
27
+ deliveryId: string,
28
+ handler: DeliveryResultHandler | undefined,
29
+ options: NotifyDeliveryResultOptions,
30
+ ): void {
31
+ if (options.notified.has(deliveryId)) return;
32
+ const delivery = state.getDelivery(deliveryId);
33
+ if (!delivery || !isTerminalDeliveryState(delivery.state)) return;
34
+ const receipt = options.attemptId
35
+ ? state.listReceipts(deliveryId).find((item) => item.attemptId === options.attemptId)
36
+ : undefined;
37
+ options.notified.add(deliveryId);
38
+ try {
39
+ state.recordPublishedResult(delivery, receipt);
40
+ } catch (error) {
41
+ log.warn(`could not record result.published: ${error instanceof Error ? error.message : String(error)}`, {
42
+ delivery: deliveryId,
43
+ });
44
+ }
45
+ if (!handler) return;
46
+ try {
47
+ handler(state.getEvent(delivery.eventId), delivery, receipt);
48
+ } catch (error) {
49
+ log.warn(`onDeliveryResult failed: ${error instanceof Error ? error.message : String(error)}`, {
50
+ delivery: deliveryId,
51
+ });
52
+ }
53
+ }
54
+
55
+ /** Persist one send outcome. The caller releases the ingest barrier afterwards. */
56
+ export function applyReceipt(
57
+ state: ChannelState,
58
+ row: DeliveryRow,
59
+ attemptId: string,
60
+ accountId: string,
61
+ receipt: SendReceipt,
62
+ now: number,
63
+ ): void {
64
+ const providerMessage = receipt.providerMessage
65
+ ? JSON.stringify(receipt.providerMessage)
66
+ : undefined;
67
+
68
+ switch (receipt.state) {
69
+ case "sent": {
70
+ state.markDelivery(row.deliveryId, "sent", {
71
+ providerMessage: providerMessage ?? null,
72
+ lastError: null,
73
+ });
74
+ const echo = receipt.providerMessage?.nativeMessageId && receipt.providerMessage.endpoint
75
+ ? {
76
+ endpoint: targetKey(receipt.providerMessage.endpoint),
77
+ nativeMessageId: receipt.providerMessage.nativeMessageId,
78
+ logicalMessageId: row.eventId,
79
+ }
80
+ : undefined;
81
+ state.recordSent({
82
+ deliveryId: row.deliveryId,
83
+ attemptId,
84
+ providerMessage: providerMessage ?? null,
85
+ detail: receipt.detail ?? null,
86
+ echo,
87
+ });
88
+ log.info("delivery sent", { account: accountId, delivery: row.deliveryId });
89
+ break;
90
+ }
91
+ case "retryable":
92
+ case "rate_limited": {
93
+ if (attemptCount(row) >= MAX_ATTEMPTS) {
94
+ state.markDelivery(row.deliveryId, "exhausted", {
95
+ lastError: receipt.detail ?? "attempt limit reached",
96
+ });
97
+ state.recordReceipt({
98
+ deliveryId: row.deliveryId,
99
+ attemptId,
100
+ state: "exhausted",
101
+ detail: receipt.detail ?? "attempt limit reached",
102
+ });
103
+ log.error(`delivery exhausted after ${attemptCount(row)} attempts`, {
104
+ account: accountId,
105
+ delivery: row.deliveryId,
106
+ });
107
+ break;
108
+ }
109
+ const delay = receipt.retryAfterMs ?? Math.min(2 ** attemptCount(row) * RETRY_BASE_MS, MAX_BACKOFF_MS);
110
+ state.markDelivery(row.deliveryId, receipt.state, {
111
+ nextAttemptAt: now + delay,
112
+ lastError: receipt.detail ?? null,
113
+ });
114
+ state.recordReceipt({
115
+ deliveryId: row.deliveryId,
116
+ attemptId,
117
+ state: receipt.state,
118
+ detail: receipt.detail ?? null,
119
+ });
120
+ log.warn(`delivery ${receipt.state}; retry in ${delay}ms`, {
121
+ account: accountId,
122
+ delivery: row.deliveryId,
123
+ });
124
+ break;
125
+ }
126
+ case "unknown": {
127
+ state.markDelivery(row.deliveryId, "unknown", {
128
+ lastError: receipt.detail ?? "unknown platform outcome",
129
+ });
130
+ state.recordReceipt({
131
+ deliveryId: row.deliveryId,
132
+ attemptId,
133
+ state: "unknown",
134
+ detail: receipt.detail ?? null,
135
+ });
136
+ log.warn("delivery unknown; not retried", { account: accountId, delivery: row.deliveryId });
137
+ break;
138
+ }
139
+ case "permanent":
140
+ case "unsupported": {
141
+ state.markDelivery(row.deliveryId, receipt.state, {
142
+ lastError: receipt.detail ?? null,
143
+ });
144
+ state.recordReceipt({
145
+ deliveryId: row.deliveryId,
146
+ attemptId,
147
+ state: receipt.state,
148
+ detail: receipt.detail ?? null,
149
+ });
150
+ log.error(`delivery ${receipt.state}`, { account: accountId, delivery: row.deliveryId });
151
+ break;
152
+ }
153
+ }
154
+ }
155
+
156
+ function attemptCount(row: DeliveryRow): number {
157
+ return row.attemptCount + 1;
158
+ }