@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
@@ -0,0 +1,573 @@
1
+ /// <reference lib="dom" />
2
+
3
+ import * as monaco from "monaco-editor/editor/editor.api";
4
+ import { jsonDefaults } from "monaco-editor/languages/features/json/register";
5
+ import "monaco-editor/languages/definitions/yaml/register";
6
+ import { isMap, isScalar, isSeq, parseDocument, stringify as stringifyYaml } from "yaml";
7
+ import {
8
+ buildInboundSchema,
9
+ buildRulesSchema,
10
+ formatPath,
11
+ validateAgainstSchema,
12
+ type JsonSchema,
13
+ type RuleAccount,
14
+ type SchemaIssue,
15
+ } from "./integration-schema";
16
+
17
+ export type RulesKind = "rules" | "inbound";
18
+ export type RulesFormat = "json" | "yaml";
19
+ export type EditorError = { line: number; column: number; path: string; message: string };
20
+ export type EditorValidation = {
21
+ kind: RulesKind;
22
+ format: RulesFormat;
23
+ text: string;
24
+ value: unknown;
25
+ valid: boolean;
26
+ errors: EditorError[];
27
+ };
28
+ export type IntegrationRulesEditor = {
29
+ getKind: () => RulesKind;
30
+ getFormat: () => RulesFormat;
31
+ setFormat: (format: RulesFormat) => void;
32
+ setValue: (value: unknown) => void;
33
+ setAccounts: (accounts: RuleAccount[]) => void;
34
+ validate: () => EditorValidation;
35
+ reveal: (line: number, column: number) => void;
36
+ setReadOnly: (readOnly: boolean) => void;
37
+ focus: () => void;
38
+ dispose: () => void;
39
+ };
40
+ type Options = {
41
+ kind: RulesKind;
42
+ container: HTMLElement;
43
+ value: unknown;
44
+ format?: RulesFormat;
45
+ accounts: RuleAccount[];
46
+ onChange?: (validation: EditorValidation) => void;
47
+ };
48
+
49
+ type RegistryEntry = { kind: RulesKind; uri: string; schema: JsonSchema; modelUri: string };
50
+ const registry = new Map<RulesKind, RegistryEntry>();
51
+ let completionRegistered = false;
52
+ let hoverRegistered = false;
53
+ let themeObserver: MutationObserver | null = null;
54
+ let themeMedia: MediaQueryList | null = null;
55
+ let previewCount = 0;
56
+
57
+ const scope = globalThis as typeof globalThis & { MonacoEnvironment?: { getWorker?: (workerId: string, label: string) => Worker } };
58
+ scope.MonacoEnvironment = {
59
+ getWorker(_workerId, label) {
60
+ return new Worker(`/assets/monaco/${label === "json" ? "json" : "editor"}.worker.js`);
61
+ },
62
+ };
63
+
64
+ function isDarkTheme(): boolean {
65
+ const theme = document.documentElement.dataset.theme;
66
+ if (theme === "custom") return document.documentElement.dataset.customDark === "true";
67
+ if (theme === "dark") return true;
68
+ return theme !== "light" && theme !== "forest" && theme !== "sand" && matchMedia("(prefers-color-scheme: dark)").matches;
69
+ }
70
+
71
+ function applyTheme() {
72
+ const read = (name: string, fallback: string) => {
73
+ // Monaco only accepts hex token colors. Resolve the CSS variable to a
74
+ // concrete color first, then normalize rgb()/color() through a canvas.
75
+ const probe = document.createElement("span");
76
+ probe.style.position = "absolute";
77
+ probe.style.visibility = "hidden";
78
+ probe.style.background = `var(${name})`;
79
+ document.documentElement.append(probe);
80
+ const resolved = getComputedStyle(probe).backgroundColor;
81
+ probe.remove();
82
+ const canvas = document.createElement("canvas").getContext("2d");
83
+ if (!canvas || !resolved) return fallback;
84
+ canvas.fillStyle = "#000000";
85
+ canvas.fillStyle = resolved;
86
+ return /^#[0-9a-f]{6}$/i.test(canvas.fillStyle) ? canvas.fillStyle : fallback;
87
+ };
88
+ monaco.editor.defineTheme("chatroom-light", {
89
+ base: "vs",
90
+ inherit: true,
91
+ rules: [],
92
+ colors: {
93
+ "editor.background": read("--surface", "#fffefa"),
94
+ "editorGutter.background": read("--surface", "#fffefa"),
95
+ "editor.lineHighlightBackground": read("--surface-2", "#f2f0e8"),
96
+ "editorLineNumber.foreground": read("--ink-3", "#63716b"),
97
+ "menu.background": read("--surface", "#fffefa"),
98
+ "menu.foreground": read("--ink", "#1e2c29"),
99
+ "menu.selectionBackground": read("--surface-2", "#f2f0e8"),
100
+ "menu.selectionForeground": read("--ink", "#1e2c29"),
101
+ "menu.border": read("--line", "#dcded4"),
102
+ "editorWidget.background": read("--surface", "#fffefa"),
103
+ "editorWidget.foreground": read("--ink", "#1e2c29"),
104
+ "editorWidget.border": read("--line", "#dcded4"),
105
+ },
106
+ });
107
+ monaco.editor.defineTheme("chatroom-dark", {
108
+ base: "vs-dark",
109
+ inherit: true,
110
+ rules: [],
111
+ colors: {
112
+ "editor.background": read("--surface", "#182522"),
113
+ "menu.background": read("--surface", "#182522"),
114
+ "menu.foreground": read("--ink", "#e6efe9"),
115
+ "menu.selectionBackground": read("--surface-2", "#22322e"),
116
+ "menu.selectionForeground": read("--ink", "#e6efe9"),
117
+ "menu.border": read("--line", "#31433d"),
118
+ "editorWidget.background": read("--surface", "#182522"),
119
+ "editorWidget.foreground": read("--ink", "#e6efe9"),
120
+ "editorWidget.border": read("--line", "#31433d"),
121
+ },
122
+ });
123
+ monaco.editor.setTheme(isDarkTheme() ? "chatroom-dark" : "chatroom-light");
124
+ }
125
+
126
+ function watchTheme() {
127
+ applyTheme();
128
+ if (themeObserver) return;
129
+ themeObserver = new MutationObserver(applyTheme);
130
+ themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "data-custom-dark"] });
131
+ themeMedia = matchMedia("(prefers-color-scheme: dark)");
132
+ themeMedia.addEventListener("change", applyTheme);
133
+ }
134
+
135
+ function publishJsonSchemas() {
136
+ jsonDefaults.setDiagnosticsOptions({
137
+ validate: false,
138
+ allowComments: false,
139
+ enableSchemaRequest: false,
140
+ schemas: [...registry.values()].map((entry) => ({
141
+ uri: entry.uri,
142
+ fileMatch: [`*integration-${entry.kind}*`],
143
+ schema: entry.schema,
144
+ })),
145
+ });
146
+ }
147
+
148
+ function schemaAtPath(root: JsonSchema, path: Array<string | number>, key?: string): JsonSchema | undefined {
149
+ let schema: JsonSchema | undefined = root;
150
+ for (const part of path) {
151
+ if (!schema) return undefined;
152
+ if (typeof part === "number") schema = schema.items;
153
+ else schema = schema.properties?.[part];
154
+ }
155
+ return key ? schema?.properties?.[key] : schema;
156
+ }
157
+
158
+ function nodeAtPath(node: any, path: Array<string | number>): any {
159
+ let current = node;
160
+ for (const part of path) {
161
+ if (!current) return current;
162
+ if (typeof part === "number") {
163
+ if (!isSeq(current)) return current;
164
+ current = current.items[part];
165
+ } else {
166
+ if (!isMap(current)) return current;
167
+ const pair = current.items.find((item: any) => isScalar(item.key) && item.key.value === part);
168
+ if (!pair) return current;
169
+ current = pair.value;
170
+ }
171
+ }
172
+ return current;
173
+ }
174
+
175
+ function pathAtOffset(node: any, offset: number, path: Array<string | number> = []): Array<string | number> | null {
176
+ const range = node?.range;
177
+ if (!Array.isArray(range) || offset < range[0] || offset > range[2]) return null;
178
+ if (isSeq(node)) {
179
+ for (let index = 0; index < node.items.length; index++) {
180
+ const found = pathAtOffset(node.items[index], offset, [...path, index]);
181
+ if (found) return found;
182
+ }
183
+ } else if (isMap(node)) {
184
+ for (const pair of node.items) {
185
+ if (!isScalar(pair.key) || typeof pair.key.value !== "string") continue;
186
+ const found = pathAtOffset(pair.value, offset, [...path, pair.key.value]);
187
+ if (found) return found;
188
+ }
189
+ }
190
+ return path;
191
+ }
192
+
193
+ function valueSuggestions(schema: JsonSchema, model: monaco.editor.ITextModel, position: monaco.Position) {
194
+ const values = schema.const !== undefined ? [schema.const] : schema.enum;
195
+ if (!values) return [];
196
+ const word = model.getWordUntilPosition(position);
197
+ const range = monaco.Range.fromPositions(
198
+ new monaco.Position(position.lineNumber, word.startColumn),
199
+ new monaco.Position(position.lineNumber, word.endColumn),
200
+ );
201
+ return values.map((value) => ({
202
+ label: String(value),
203
+ kind: monaco.languages.CompletionItemKind.Value,
204
+ insertText: String(value),
205
+ range,
206
+ detail: schema.description,
207
+ }));
208
+ }
209
+
210
+ function ensureYamlCompletion() {
211
+ if (completionRegistered) return;
212
+ completionRegistered = true;
213
+ monaco.languages.registerCompletionItemProvider("yaml", {
214
+ triggerCharacters: [":", " ", "-"],
215
+ provideCompletionItems(model, position) {
216
+ const entry = [...registry.values()].find((item) => item.modelUri === model.uri.toString());
217
+ if (!entry) return { suggestions: [] };
218
+ let doc: any;
219
+ try { doc = parseDocument(model.getValue()); } catch { return { suggestions: [] }; }
220
+ const root = doc.contents;
221
+ const offset = model.getOffsetAt(position);
222
+ const path = pathAtOffset(root, offset) ?? [];
223
+ const line = model.getLineContent(position.lineNumber).slice(0, position.column - 1);
224
+ const match = /^\s*(?:-\s*)?["']?([A-Za-z0-9_.-]+)["']?\s*:\s*(.*)$/.exec(line);
225
+ if (match) {
226
+ const key = match[1]!;
227
+ const container = path[path.length - 1] === key ? path.slice(0, -1) : path;
228
+ const schema = schemaAtPath(entry.schema, container, key);
229
+ return { suggestions: schema ? valueSuggestions(schema, model, position) : [] };
230
+ }
231
+ const schema = schemaAtPath(entry.schema, path);
232
+ const properties = schema?.properties;
233
+ if (!properties) return { suggestions: [] };
234
+ const existing = new Set<string>();
235
+ const container = nodeAtPath(root, path);
236
+ if (isMap(container)) {
237
+ for (const pair of container.items) if (isScalar(pair.key) && typeof pair.key.value === "string") existing.add(pair.key.value);
238
+ }
239
+ const word = model.getWordUntilPosition(position);
240
+ const range = monaco.Range.fromPositions(
241
+ new monaco.Position(position.lineNumber, word.startColumn),
242
+ new monaco.Position(position.lineNumber, word.endColumn),
243
+ );
244
+ return {
245
+ suggestions: Object.entries(properties)
246
+ .filter(([key]) => !existing.has(key))
247
+ .map(([key, child]) => ({
248
+ label: key,
249
+ kind: monaco.languages.CompletionItemKind.Property,
250
+ insertText: `${key}: `,
251
+ range,
252
+ detail: child.type,
253
+ documentation: child.description,
254
+ })),
255
+ };
256
+ },
257
+ });
258
+ }
259
+
260
+ function ensureYamlHover() {
261
+ if (hoverRegistered) return;
262
+ hoverRegistered = true;
263
+ monaco.languages.registerHoverProvider("yaml", {
264
+ provideHover(model, position) {
265
+ const entry = [...registry.values()].find((item) => item.modelUri === model.uri.toString());
266
+ if (!entry) return null;
267
+ let doc: any;
268
+ try { doc = parseDocument(model.getValue()); } catch { return null; }
269
+ const root = doc.contents;
270
+ const path = pathAtOffset(root, model.getOffsetAt(position));
271
+ if (!path) return null;
272
+ const line = model.getLineContent(position.lineNumber);
273
+ const match = /^\s*(?:-\s*)?["']?([A-Za-z0-9_.-]+)["']?\s*:/.exec(line);
274
+ let schema: JsonSchema | undefined;
275
+ let label = "";
276
+ if (match) {
277
+ const key = match[1]!;
278
+ const container = path[path.length - 1] === key ? path.slice(0, -1) : path;
279
+ schema = schemaAtPath(entry.schema, container, key);
280
+ label = key;
281
+ } else {
282
+ schema = schemaAtPath(entry.schema, path);
283
+ label = String(path[path.length - 1] ?? "");
284
+ }
285
+ if (!schema?.description) return null;
286
+ const word = model.getWordAtPosition(position);
287
+ const range = word
288
+ ? new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn)
289
+ : undefined;
290
+ const type = schema.type ? ` (${String(schema.type)})` : "";
291
+ return {
292
+ range,
293
+ contents: [
294
+ { value: `**${label}**` },
295
+ { value: `${type.trim()}${type ? " " : ""}${schema.description}` },
296
+ ],
297
+ };
298
+ },
299
+ });
300
+ }
301
+
302
+ type ParseResult = {
303
+ value?: unknown;
304
+ doc?: any;
305
+ failure?: { line: number; column: number; message: string };
306
+ };
307
+
308
+ function lineStarts(text: string): number[] {
309
+ const starts = [0];
310
+ for (let index = 0; index < text.length; index++) if (text[index] === "\n") starts.push(index + 1);
311
+ return starts;
312
+ }
313
+
314
+ function positionAt(starts: number[], offset: number): { line: number; column: number } {
315
+ let low = 0, high = starts.length - 1;
316
+ while (low < high) {
317
+ const middle = Math.ceil((low + high) / 2);
318
+ if ((starts[middle] ?? 0) <= offset) low = middle;
319
+ else high = middle - 1;
320
+ }
321
+ return { line: low + 1, column: offset - (starts[low] ?? 0) + 1 };
322
+ }
323
+
324
+ function cleanSyntaxMessage(message: string): string {
325
+ return message
326
+ .replace(/ in JSON at position \d+.*$/i, "")
327
+ .replace(/\s*\(line \d+ column \d+\)$/i, "")
328
+ .replace(/\s+at line \d+, column \d+.*$/i, "")
329
+ .trim();
330
+ }
331
+
332
+ function parseJson(text: string): ParseResult {
333
+ if (!text.trim()) return { failure: { line: 1, column: 1, message: "Rules cannot be empty." } };
334
+ try {
335
+ const value = JSON.parse(text);
336
+ let doc;
337
+ try { doc = parseDocument(text); } catch { doc = undefined; }
338
+ return { value, doc };
339
+ } catch (error) {
340
+ const message = String((error as Error).message || error);
341
+ const starts = lineStarts(text);
342
+ const offset = Number(/position (\d+)/.exec(message)?.[1] ?? 0);
343
+ const position = positionAt(starts, offset);
344
+ return { failure: { ...position, message: cleanSyntaxMessage(message) || "Invalid JSON." } };
345
+ }
346
+ }
347
+
348
+ function parseYaml(text: string): ParseResult {
349
+ if (!text.trim()) return { failure: { line: 1, column: 1, message: "Rules cannot be empty." } };
350
+ const doc = parseDocument(text, { prettyErrors: true });
351
+ if (doc.errors.length) {
352
+ const error = doc.errors[0]!;
353
+ const starts = lineStarts(text);
354
+ const offset = Number(error.pos?.[0] ?? 0);
355
+ const fallback = positionAt(starts, offset);
356
+ const line = error.linePos?.[0]?.line ?? fallback.line;
357
+ const column = error.linePos?.[0]?.col ?? fallback.column;
358
+ return { failure: { line, column, message: cleanSyntaxMessage(error.message) || "Invalid YAML." } };
359
+ }
360
+ try {
361
+ return { value: doc.toJS(), doc };
362
+ } catch (error) {
363
+ return { failure: { line: 1, column: 1, message: String((error as Error).message || error) } };
364
+ }
365
+ }
366
+
367
+ function issuePosition(issue: SchemaIssue, doc: any, text: string, kind: RulesKind): EditorError {
368
+ const path = formatPath(kind === "inbound" ? "inbound" : "rules", issue.path);
369
+ if (doc) {
370
+ const node = nodeAtPath(doc.contents, issue.path);
371
+ const range = node?.range;
372
+ if (Array.isArray(range)) {
373
+ const starts = lineStarts(text);
374
+ const start = positionAt(starts, range[0]);
375
+ return { ...start, path, message: issue.message };
376
+ }
377
+ }
378
+ return { line: 1, column: 1, path, message: issue.message };
379
+ }
380
+
381
+ function stringifyValue(value: unknown, format: RulesFormat): string {
382
+ if (format === "yaml") return stringifyYaml(value, { indent: 2, lineWidth: 0 });
383
+ return JSON.stringify(value, null, 2);
384
+ }
385
+
386
+ function formatLabel(format: RulesFormat): string {
387
+ return format === "yaml" ? "YAML" : "JSON";
388
+ }
389
+
390
+ export function createIntegrationRulesEditor(options: Options): IntegrationRulesEditor {
391
+ const kind = options.kind;
392
+ let format: RulesFormat = options.format ?? "yaml";
393
+ let accounts = options.accounts;
394
+ let schema = kind === "inbound" ? buildInboundSchema(accounts) : buildRulesSchema(accounts);
395
+ const entry: RegistryEntry = {
396
+ kind,
397
+ uri: `inmemory://chat/integration-${kind}.schema.json`,
398
+ schema,
399
+ modelUri: `inmemory://chat/integration-${kind}.json`,
400
+ };
401
+ registry.set(kind, entry);
402
+ publishJsonSchemas();
403
+ ensureYamlCompletion();
404
+ ensureYamlHover();
405
+ watchTheme();
406
+
407
+ const text = stringifyValue(options.value ?? [], format);
408
+ const model = monaco.editor.createModel(text, formatLabel(format).toLowerCase(), monaco.Uri.parse(entry.modelUri));
409
+ const editor = monaco.editor.create(options.container, {
410
+ model,
411
+ theme: isDarkTheme() ? "chatroom-dark" : "chatroom-light",
412
+ automaticLayout: true,
413
+ ariaLabel: kind === "inbound" ? "Inbound routes" : "Integration rules",
414
+ minimap: { enabled: false },
415
+ scrollBeyondLastLine: false,
416
+ fontSize: 12,
417
+ lineNumbersMinChars: 3,
418
+ tabSize: 2,
419
+ insertSpaces: true,
420
+ autoIndent: "none",
421
+ autoClosingBrackets: "never",
422
+ autoClosingQuotes: "never",
423
+ wordWrap: "on",
424
+ fixedOverflowWidgets: true,
425
+ renderLineHighlight: "line",
426
+ overviewRulerLanes: 0,
427
+ hideCursorInOverviewRuler: true,
428
+ padding: { top: 8, bottom: 8 },
429
+ scrollbar: { verticalScrollbarSize: 8, horizontalScrollbarSize: 8 },
430
+ suggest: { showWords: false },
431
+ });
432
+
433
+ const onWheel = (event: WheelEvent) => {
434
+ // Modifiers belong to Monaco: Ctrl/Cmd zooms, Shift scrolls horizontally.
435
+ if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return;
436
+ const max = Math.max(0, editor.getScrollHeight() - editor.getLayoutInfo().height);
437
+ const top = editor.getScrollTop();
438
+ const atTop = event.deltaY < 0 && top <= 0;
439
+ const atBottom = event.deltaY > 0 && top >= max - 1;
440
+ if (!atTop && !atBottom) return;
441
+ // Hand the wheel to the page once the editor cannot scroll further.
442
+ let node = options.container.parentElement;
443
+ while (node) {
444
+ const style = getComputedStyle(node);
445
+ if (/(auto|scroll)/.test(style.overflowY) && node.scrollHeight > node.clientHeight + 1) {
446
+ node.scrollTop += event.deltaY;
447
+ event.preventDefault();
448
+ event.stopPropagation();
449
+ return;
450
+ }
451
+ node = node.parentElement;
452
+ }
453
+ };
454
+ options.container.addEventListener("wheel", onWheel, { capture: true, passive: false });
455
+
456
+ const validate = (): EditorValidation => {
457
+ const current = model.getValue();
458
+ const parsed = format === "yaml" ? parseYaml(current) : parseJson(current);
459
+ const errors: EditorError[] = [];
460
+ if (parsed.failure) {
461
+ errors.push({ line: parsed.failure.line, column: parsed.failure.column, path: "", message: parsed.failure.message });
462
+ } else {
463
+ for (const issue of validateAgainstSchema(parsed.value, schema)) {
464
+ errors.push(issuePosition(issue, parsed.doc, current, kind));
465
+ }
466
+ }
467
+ errors.sort((left, right) => left.line - right.line || left.column - right.column);
468
+ monaco.editor.setModelMarkers(model, "integration-rules", errors.map((error) => {
469
+ const lineLength = model.getLineMaxColumn(Math.min(error.line, model.getLineCount()));
470
+ return {
471
+ severity: monaco.MarkerSeverity.Error,
472
+ message: error.message,
473
+ startLineNumber: error.line,
474
+ startColumn: error.column,
475
+ endLineNumber: error.line,
476
+ endColumn: Math.max(error.column + 1, Math.min(lineLength, error.column + 80)),
477
+ };
478
+ }));
479
+ return { kind, format, text: current, value: parsed.value, valid: errors.length === 0, errors };
480
+ };
481
+
482
+ const emit = () => {
483
+ const validation = validate();
484
+ options.onChange?.(validation);
485
+ return validation;
486
+ };
487
+
488
+ const setValue = (value: unknown) => {
489
+ const next = stringifyValue(value ?? [], format);
490
+ if (next === model.getValue()) emit();
491
+ else model.setValue(next);
492
+ };
493
+
494
+ const setFormat = (next: RulesFormat) => {
495
+ if (next === format) return;
496
+ const parsed = format === "yaml" ? parseYaml(model.getValue()) : parseJson(model.getValue());
497
+ format = next;
498
+ monaco.editor.setModelLanguage(model, formatLabel(format).toLowerCase());
499
+ if (!parsed.failure) {
500
+ const nextText = stringifyValue(parsed.value, format);
501
+ if (nextText !== model.getValue()) model.setValue(nextText);
502
+ else emit();
503
+ } else {
504
+ emit();
505
+ }
506
+ };
507
+
508
+ const setAccounts = (next: RuleAccount[]) => {
509
+ accounts = next;
510
+ schema = kind === "inbound" ? buildInboundSchema(accounts) : buildRulesSchema(accounts);
511
+ entry.schema = schema;
512
+ publishJsonSchemas();
513
+ emit();
514
+ };
515
+
516
+ const change = model.onDidChangeContent(() => { emit(); });
517
+ return {
518
+ getKind: () => kind,
519
+ getFormat: () => format,
520
+ setFormat,
521
+ setValue,
522
+ setAccounts,
523
+ validate,
524
+ reveal: (line, column) => {
525
+ const position = { lineNumber: Math.max(1, line), column: Math.max(1, column) };
526
+ editor.revealPositionInCenter(position);
527
+ editor.setPosition(position);
528
+ editor.focus();
529
+ },
530
+ setReadOnly: (readOnly) => editor.updateOptions({ readOnly }),
531
+ focus: () => editor.focus(),
532
+ dispose: () => {
533
+ options.container.removeEventListener("wheel", onWheel, true);
534
+ change.dispose();
535
+ editor.dispose();
536
+ model.dispose();
537
+ registry.delete(kind);
538
+ publishJsonSchemas();
539
+ },
540
+ };
541
+ }
542
+
543
+ export type CodePreviewOptions = { container: HTMLElement; value: string; language?: string };
544
+
545
+ export function createCodePreviewEditor(options: CodePreviewOptions): { dispose: () => void } {
546
+ watchTheme();
547
+ const language = options.language || "plaintext";
548
+ const model = monaco.editor.createModel(
549
+ options.value,
550
+ language,
551
+ monaco.Uri.parse(`inmemory://chat/code-preview-${++previewCount}.${language}`),
552
+ );
553
+ const editor = monaco.editor.create(options.container, {
554
+ model,
555
+ theme: isDarkTheme() ? "chatroom-dark" : "chatroom-light",
556
+ readOnly: true,
557
+ automaticLayout: true,
558
+ minimap: { enabled: false },
559
+ scrollBeyondLastLine: false,
560
+ fontSize: 12,
561
+ lineNumbers: "on",
562
+ wordWrap: "off",
563
+ renderLineHighlight: "none",
564
+ overviewRulerLanes: 0,
565
+ hideCursorInOverviewRuler: true,
566
+ folding: true,
567
+ padding: { top: 10, bottom: 10 },
568
+ scrollbar: { verticalScrollbarSize: 8, horizontalScrollbarSize: 8, useShadows: false },
569
+ contextmenu: true,
570
+ ariaLabel: "Code preview",
571
+ });
572
+ return { dispose: () => { editor.dispose(); model.dispose(); } };
573
+ }
@@ -0,0 +1,26 @@
1
+ // Build entry for the lazy integration rules editor. Keeping Monaco contributions out
2
+ // of integrations.js means the editor bundle is fetched only when the panel opens.
3
+ import "monaco-editor/basic-languages/monaco.contribution";
4
+ import "monaco-editor/editor/contrib/bracketMatching/browser/bracketMatching";
5
+ import "monaco-editor/editor/contrib/clipboard/browser/clipboard";
6
+ import "monaco-editor/editor/contrib/codeAction/browser/codeActionContributions";
7
+ import "monaco-editor/editor/contrib/contextmenu/browser/contextmenu";
8
+ import "monaco-editor/editor/contrib/find/browser/findController";
9
+ import "monaco-editor/editor/contrib/folding/browser/folding";
10
+ import "monaco-editor/editor/contrib/format/browser/formatActions";
11
+ import "monaco-editor/editor/contrib/gotoError/browser/gotoError";
12
+ import "monaco-editor/editor/contrib/hover/browser/hoverContribution";
13
+ import "monaco-editor/editor/contrib/linesOperations/browser/linesOperations";
14
+ import "monaco-editor/editor/contrib/multicursor/browser/multicursor";
15
+ import "monaco-editor/editor/contrib/placeholderText/browser/placeholderText.contribution";
16
+ import "monaco-editor/editor/contrib/snippet/browser/snippetController2";
17
+ import "monaco-editor/editor/contrib/suggest/browser/suggestController";
18
+ import "monaco-editor/editor/contrib/wordHighlighter/browser/wordHighlighter";
19
+ import "monaco-editor/editor/contrib/wordOperations/browser/wordOperations";
20
+ import "monaco-editor/editor/contrib/codelens/browser/codeLensCache";
21
+ import "monaco-editor/editor/contrib/codelens/browser/codelensController";
22
+ import "monaco-editor/editor/common/services/treeViewsDndService";
23
+ import "monaco-editor/editor/browser/coreCommands";
24
+
25
+ export { createCodePreviewEditor, createIntegrationRulesEditor } from "./integration-rules-editor";
26
+ export type { CodePreviewOptions, IntegrationRulesEditor, EditorValidation, RulesFormat, RulesKind } from "./integration-rules-editor";