sideora 0.0.1-alpha.0 → 0.1.0-alpha.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 (221) hide show
  1. package/LICENSE.md +9 -0
  2. package/README.md +57 -6
  3. package/assets/sounds/freesound_community-mail-40275.mp3 +0 -0
  4. package/assets/sounds/mixkit-clear-announce-tones-2861.wav +0 -0
  5. package/assets/sounds/mixkit-happy-bells-notification-937.wav +0 -0
  6. package/assets/sounds/mixkit-musical-alert-notification-2309.wav +0 -0
  7. package/assets/sounds/nice-chime.mp3 +0 -0
  8. package/bin/sideora.js +2430 -12
  9. package/extension/dist/assets/background.ts-NW8YqAlO.js +1 -0
  10. package/extension/dist/assets/fillCode-Ci8IkBvY.js +1 -0
  11. package/extension/dist/assets/index.html-DrrPha1M.js +2 -0
  12. package/extension/dist/assets/modulepreload-polyfill-DcjICKwh.js +1 -0
  13. package/extension/dist/assets/shell-82MNMljp.css +1 -0
  14. package/extension/dist/assets/shell-QYBN1bx1.js +1 -0
  15. package/extension/dist/icons/icon-128.png +0 -0
  16. package/extension/dist/icons/icon-16.png +0 -0
  17. package/extension/dist/icons/icon-32.png +0 -0
  18. package/extension/dist/icons/icon-48.png +0 -0
  19. package/extension/dist/manifest.json +40 -0
  20. package/extension/dist/service-worker-loader.js +1 -0
  21. package/extension/dist/src/newtab/index.html +14 -0
  22. package/extension/dist/src/panel/index.html +15 -0
  23. package/extension/dist-web/assets/abnfDiagram-WEYOIA3C-CoXOc872.js +1 -0
  24. package/extension/dist-web/assets/apple-touch-icon-DSgRQASq.png +0 -0
  25. package/extension/dist-web/assets/architecture-WOLXFQ4H-BkJ4AerO.js +1 -0
  26. package/extension/dist-web/assets/architectureDiagram-ZHVYKT53-aPkSDlxA.js +36 -0
  27. package/extension/dist-web/assets/blockDiagram-RJAE7QA3-CH1G4NBZ.js +140 -0
  28. package/extension/dist-web/assets/c4Diagram-XDPPPE54-Baum1zDu.js +38 -0
  29. package/extension/dist-web/assets/channel-PsQg-mnK.js +1 -0
  30. package/extension/dist-web/assets/chunk-2E7WHVMD-CKvLrWRa.js +88 -0
  31. package/extension/dist-web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  32. package/extension/dist-web/assets/chunk-4EMNKR2T-6fjnroCZ.js +1 -0
  33. package/extension/dist-web/assets/chunk-55XCU76K-Ygs3sNpi.js +1 -0
  34. package/extension/dist-web/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  35. package/extension/dist-web/assets/chunk-7S6XSTFO-iX5xYzfP.js +2 -0
  36. package/extension/dist-web/assets/chunk-AQDTSKZB-D9zwhFI8.js +72 -0
  37. package/extension/dist-web/assets/chunk-DSNLSHJZ-siGS-4qu.js +129 -0
  38. package/extension/dist-web/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  39. package/extension/dist-web/assets/chunk-HAGFOTED-_3dtnWXn.js +62 -0
  40. package/extension/dist-web/assets/chunk-HNE4Q36P-BPzRHi72.js +1 -0
  41. package/extension/dist-web/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  42. package/extension/dist-web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  43. package/extension/dist-web/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  44. package/extension/dist-web/assets/chunk-NQOKRVIF-AXbmOBjs.js +213 -0
  45. package/extension/dist-web/assets/chunk-UHW7PFBP-B3xrZ8sD.js +1 -0
  46. package/extension/dist-web/assets/chunk-VQ5W62QI-D_k7Pa6b.js +1 -0
  47. package/extension/dist-web/assets/chunk-WQQL4CDK-BBIrWwoZ.js +10 -0
  48. package/extension/dist-web/assets/chunk-XXDRQBXY-i7MKP1NY.js +1 -0
  49. package/extension/dist-web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  50. package/extension/dist-web/assets/chunk-YZO67HFG-Z7qp5QAI.js +1 -0
  51. package/extension/dist-web/assets/chunk-ZAUX2LTX-CSt3c0Rb.js +1 -0
  52. package/extension/dist-web/assets/chunk-ZCHMQSOR-g8XRABGK.js +2 -0
  53. package/extension/dist-web/assets/classDiagram-v2-4MYWR3UA-BL706wzc.js +217 -0
  54. package/extension/dist-web/assets/cose-bilkent-JH36ORCC-C6J2IoHg.js +1 -0
  55. package/extension/dist-web/assets/cynefin-EF2NZ3EQ-DLhQOiAy.js +1 -0
  56. package/extension/dist-web/assets/cynefinDiagram-WF24UDRP-Cv9Lx6_l.js +62 -0
  57. package/extension/dist-web/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  58. package/extension/dist-web/assets/d3-scale-CElPUUud.js +1 -0
  59. package/extension/dist-web/assets/d3-selection-COWvaQNI.js +1 -0
  60. package/extension/dist-web/assets/dagre-NK4GIZVX-ngM-w2EC.js +4 -0
  61. package/extension/dist-web/assets/diagram-CBK3MWTC-kp8sayNG.js +24 -0
  62. package/extension/dist-web/assets/diagram-I5XIIV2D-BZ_Dgs6K.js +24 -0
  63. package/extension/dist-web/assets/diagram-ODIL2UCW-DWhUyArG.js +30 -0
  64. package/extension/dist-web/assets/diagram-PFBEJUXE-CBAdEK7l.js +3 -0
  65. package/extension/dist-web/assets/diagram-RJA3I4VV-kOdIr_3K.js +41 -0
  66. package/extension/dist-web/assets/diagram-TYUNFSNR-BrWGa0x5.js +200 -0
  67. package/extension/dist-web/assets/dist-DdXDFcej.js +1 -0
  68. package/extension/dist-web/assets/docx-preview-D1zbEiLy.js +20 -0
  69. package/extension/dist-web/assets/earth-Ce3xs8Cb.webp +0 -0
  70. package/extension/dist-web/assets/ebnfDiagram-V4P3TTPT-0r3weWmj.js +1 -0
  71. package/extension/dist-web/assets/elk-QONTBCTQ-D3oElRZ3.js +27 -0
  72. package/extension/dist-web/assets/erDiagram-KYQIGQAA-B9oU7_j_.js +99 -0
  73. package/extension/dist-web/assets/eventmodeling-K75KTNOO-CMKgc1nP.js +1 -0
  74. package/extension/dist-web/assets/favicon-D_X6tUVf.svg +5 -0
  75. package/extension/dist-web/assets/flowDiagram-IUGLLWBU-yRwks0Mw.js +1 -0
  76. package/extension/dist-web/assets/ganttDiagram-R7GPNTJY-cJqD1qwQ.js +292 -0
  77. package/extension/dist-web/assets/gitGraph-VSP46ZUC-CuBQqkbr.js +1 -0
  78. package/extension/dist-web/assets/gitGraphDiagram-PDYL7XHY-D7bHnQXC.js +106 -0
  79. package/extension/dist-web/assets/graphlib-DS17s2tU.js +1 -0
  80. package/extension/dist-web/assets/home-CV7-8Trs.js +1 -0
  81. package/extension/dist-web/assets/index-CQvw7Wy_.js +7 -0
  82. package/extension/dist-web/assets/index-CVKnZ21i.css +1 -0
  83. package/extension/dist-web/assets/info-OHQRW6UA-B8kyzV4O.js +1 -0
  84. package/extension/dist-web/assets/infoDiagram-MVDRKAX5-CEm6lezX.js +2 -0
  85. package/extension/dist-web/assets/ishikawaDiagram-HPEHV2GE-Ce3uv2wr.js +70 -0
  86. package/extension/dist-web/assets/journeyDiagram-BOSHW7O7-QgdahHCP.js +139 -0
  87. package/extension/dist-web/assets/jszip.min-3XXygzvy.js +2 -0
  88. package/extension/dist-web/assets/kanban-definition-FNSA4HC5-DPuTtWgR.js +89 -0
  89. package/extension/dist-web/assets/katex-MEuSR36T.js +257 -0
  90. package/extension/dist-web/assets/mermaid-parser.core-h7U7YGn_.js +7 -0
  91. package/extension/dist-web/assets/mermaid.core-DkGhophj.js +44 -0
  92. package/extension/dist-web/assets/mindmap-definition-6OY57UG3-D7VQxbda.js +98 -0
  93. package/extension/dist-web/assets/mount-CBzzf6KQ.js +195 -0
  94. package/extension/dist-web/assets/mount-DtvYnQXt.css +1 -0
  95. package/extension/dist-web/assets/officeparser.browser.slim-kEjhTrQ1.js +1989 -0
  96. package/extension/dist-web/assets/packet-JDAUHWVQ-oafHgw6X.js +1 -0
  97. package/extension/dist-web/assets/pegDiagram-ECIUJNBX-C3zo1naj.js +1 -0
  98. package/extension/dist-web/assets/peoria-B5TBlKDG.jpg +0 -0
  99. package/extension/dist-web/assets/peoria-thumb-CN8upAdZ.jpg +0 -0
  100. package/extension/dist-web/assets/pie-XZMESJXO-DXzeBQqF.js +1 -0
  101. package/extension/dist-web/assets/pieDiagram-GNMPY74T-S5NzPthl.js +39 -0
  102. package/extension/dist-web/assets/quadrantDiagram-D57K4MC3-C9glHQmk.js +7 -0
  103. package/extension/dist-web/assets/radar-ABXABTNO-CWTNqtbu.js +1 -0
  104. package/extension/dist-web/assets/railroad-I3PHUGI6-BTpD5_Bu.js +1 -0
  105. package/extension/dist-web/assets/railroad-abnf-LNEFI6M7-bWyxoXQG.js +1 -0
  106. package/extension/dist-web/assets/railroad-ebnf-DWYD2UWJ-ri5733DQ.js +1 -0
  107. package/extension/dist-web/assets/railroad-peg-JR7BVNR7-CmGfTubP.js +1 -0
  108. package/extension/dist-web/assets/railroadDiagram-Y72NRBL7-DTfe6Dh1.js +1 -0
  109. package/extension/dist-web/assets/requirementDiagram-EQYSW5RA-DQDzcS3L.js +84 -0
  110. package/extension/dist-web/assets/rolldown-runtime-COiEfhsA.js +1 -0
  111. package/extension/dist-web/assets/rough.esm-Dy-Kn_BL.js +1 -0
  112. package/extension/dist-web/assets/sankeyDiagram-SY24JHO5-DyMKWxdB.js +40 -0
  113. package/extension/dist-web/assets/sequenceDiagram-BLEHNHQU-dIkB1mCn.js +169 -0
  114. package/extension/dist-web/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  115. package/extension/dist-web/assets/stateDiagram-v2-A6IESKWZ-Bj_vxEVF.js +291 -0
  116. package/extension/dist-web/assets/swimlanes-B3ENRKFQ-BSkWEwHR.js +1 -0
  117. package/extension/dist-web/assets/swimlanesDiagram-AYQRV4AK-BTzSDlSM.js +8 -0
  118. package/extension/dist-web/assets/timeline-definition-JXYKGLGB-TwfWS0pw.js +120 -0
  119. package/extension/dist-web/assets/treeView-D4JQ5SDB-BzA_8YYb.js +1 -0
  120. package/extension/dist-web/assets/treemap-SAJKECNS-BI9d6--2.js +1 -0
  121. package/extension/dist-web/assets/usecaseDiagram-WPOLBNNX-BOVbAUPk.js +328 -0
  122. package/extension/dist-web/assets/vennDiagram-Q3Y3IDCW-X2kYAWaj.js +34 -0
  123. package/extension/dist-web/assets/wardley-7MLQ67FV-CItxqJ8G.js +1 -0
  124. package/extension/dist-web/assets/wardleyDiagram-IVAIDKWA-BnUXvKD_.js +78 -0
  125. package/extension/dist-web/assets/xychartDiagram-4URNHDU4-ysvBXvyE.js +7 -0
  126. package/extension/dist-web/icon-192.png +0 -0
  127. package/extension/dist-web/icon-512.png +0 -0
  128. package/extension/dist-web/index.html +25 -0
  129. package/extension/dist-web/manifest.webmanifest +14 -0
  130. package/package.json +64 -12
  131. package/plugin/.claude-plugin/icon.png +0 -0
  132. package/plugin/.claude-plugin/plugin.json +6 -0
  133. package/plugin/.mcp.json +8 -0
  134. package/plugin/README.md +72 -0
  135. package/plugin/mcp-launcher.mjs +48 -0
  136. package/src/account-probe.js +45 -0
  137. package/src/accounts.js +687 -0
  138. package/src/ai.js +269 -0
  139. package/src/assistant-runs.js +32 -0
  140. package/src/attached-mail.js +76 -0
  141. package/src/auth-gate.js +70 -0
  142. package/src/backup-cli.js +158 -0
  143. package/src/backup.js +329 -0
  144. package/src/bimi.js +233 -0
  145. package/src/bridge.js +101 -0
  146. package/src/calendar-alerts.js +56 -0
  147. package/src/chats.js +27 -0
  148. package/src/compose-editor.js +58 -0
  149. package/src/config.js +420 -0
  150. package/src/connections.d.ts +24 -0
  151. package/src/connections.js +37 -0
  152. package/src/core/agent.js +92 -0
  153. package/src/core/assistant.d.ts +13 -0
  154. package/src/core/assistant.js +790 -0
  155. package/src/core/chats.js +323 -0
  156. package/src/core/markdown.d.ts +8 -0
  157. package/src/core/markdown.js +239 -0
  158. package/src/core/notes.js +445 -0
  159. package/src/core/otp.js +152 -0
  160. package/src/core/rules.js +196 -0
  161. package/src/core/runs.d.ts +9 -0
  162. package/src/core/runs.js +211 -0
  163. package/src/core/thread.js +526 -0
  164. package/src/core/write.js +247 -0
  165. package/src/core-db.js +131 -0
  166. package/src/core.js +174 -0
  167. package/src/credentials.js +320 -0
  168. package/src/daemon.js +564 -0
  169. package/src/events.js +213 -0
  170. package/src/extension-id.d.ts +2 -0
  171. package/src/extension-id.js +5 -0
  172. package/src/file-lock.js +27 -0
  173. package/src/files-index.js +154 -0
  174. package/src/google-contacts.js +315 -0
  175. package/src/google-signin.js +306 -0
  176. package/src/host/assistant-html.js +44 -0
  177. package/src/host/chats-files.js +137 -0
  178. package/src/host/file-prep.js +122 -0
  179. package/src/host/notes-files.js +158 -0
  180. package/src/host/office-text.js +224 -0
  181. package/src/host/office-worker.js +8 -0
  182. package/src/host/rules-file.js +20 -0
  183. package/src/host/secrets-file.js +91 -0
  184. package/src/host/systemd.js +90 -0
  185. package/src/hub.js +245 -0
  186. package/src/identity.js +316 -0
  187. package/src/labels.js +5 -0
  188. package/src/mail-port.d.ts +79 -0
  189. package/src/mail-port.js +148 -0
  190. package/src/mcp-server.js +747 -0
  191. package/src/microsoft-app.js +20 -0
  192. package/src/microsoft-signin.js +194 -0
  193. package/src/migrate.js +327 -0
  194. package/src/notes-html.js +450 -0
  195. package/src/notes.js +19 -0
  196. package/src/notify.js +105 -0
  197. package/src/onepassword.js +223 -0
  198. package/src/op-registry.d.ts +14 -0
  199. package/src/op-registry.js +150 -0
  200. package/src/ops.js +1251 -0
  201. package/src/otp.js +6 -0
  202. package/src/panel-ops.js +273 -0
  203. package/src/pictures.js +735 -0
  204. package/src/postinstall.js +25 -0
  205. package/src/relay-passkey.js +122 -0
  206. package/src/relay-request.js +155 -0
  207. package/src/relay-seal.js +56 -0
  208. package/src/relay-settings.js +139 -0
  209. package/src/relay.js +876 -0
  210. package/src/render.js +82 -0
  211. package/src/rules-store.js +8 -0
  212. package/src/safe-fetch.js +215 -0
  213. package/src/sender-auth.js +270 -0
  214. package/src/site-match.js +77 -0
  215. package/src/tui-agenda.js +266 -0
  216. package/src/tui.js +670 -0
  217. package/src/vmc.js +376 -0
  218. package/src/wake.js +96 -0
  219. package/src/web-access.js +185 -0
  220. package/src/web-server.js +241 -0
  221. package/src/web-service.js +152 -0
@@ -0,0 +1,196 @@
1
+ // The rules and quiet hours, in the core: how rules.yaml is changed, over the file the host gives (makeRules(file)):
2
+ // on this Mac, ~/.sideora/rules.yaml (src/host/rules-file.js). Edits go through YAML.parseDocument so comments and
3
+ // formatting in rules.yaml survive CLI/MCP changes. The daemon reloads rules on every poll, so changes apply within
4
+ // ~30s. This module touches no file and no setting.
5
+
6
+ import crypto from 'node:crypto';
7
+ import YAML from 'yaml';
8
+
9
+ const TEMPLATE = `# Sideora rules — manage with \`sideora rules\` or edit by hand.
10
+ quietHours:
11
+ enabled: false
12
+ start: "18:00"
13
+ end: "08:00"
14
+
15
+ rules: []
16
+ `;
17
+
18
+ export const SOUNDS = ['alarm', 'chime', 'ding', 'message'];
19
+
20
+ /** What a rule runs. An edit of anything else must leave these as they were, in every rule. */
21
+ export const RUNS = ['wake', 'webhook', 'exec'];
22
+ export const CHANGED = 'the rules were changed elsewhere — reload them and try again';
23
+ const runsOf = (rules) => rules.map((r) => JSON.stringify(RUNS.map((k) => r?.[k] ?? null)));
24
+ const rulesOf = (doc) => { const r = doc.toJS()?.rules; return Array.isArray(r) ? r : []; };
25
+
26
+ /** A rule as it stands in the file, in a few characters: what an editor shows back to say "the one I was looking at". */
27
+ export const revOf = (rule) => crypto.createHash('sha256').update(JSON.stringify(rule ?? null)).digest('hex').slice(0, 16);
28
+
29
+ /**
30
+ * The rules over `file` (src/host/rules-file.js is this Mac's):
31
+ * read() the text, or null when there is none yet
32
+ * create(text) a first one, when there is none
33
+ * write(text) the text, whole or not at all
34
+ */
35
+ export function makeRules(file) {
36
+ function loadDoc() {
37
+ let text = file.read();
38
+ if (text == null) { file.create(TEMPLATE); text = file.read() ?? TEMPLATE; } // (another may have made it meanwhile: its own is read)
39
+ const doc = YAML.parseDocument(text);
40
+ // half a rule list is worse than none: the daemon refuses this file too
41
+ if (doc.errors.length) throw new Error(`rules.yaml has a syntax error — fix it by hand: ${doc.errors[0].message.split('\n')[0]}`);
42
+ return doc;
43
+ }
44
+
45
+ /**
46
+ * Write the edited document. `runs` is what every rule must run afterwards
47
+ * (see runsOf): YAML anchors make one value stand in several places, so a
48
+ * change of a rule's senders could otherwise rewrite another field's command.
49
+ */
50
+ function saveDoc(doc, runs) {
51
+ let text;
52
+ let after;
53
+ try { after = runsOf(rulesOf(doc)); text = doc.toString(); } catch { after = null; }
54
+ if (!after || (runs && after.join('\n') !== runs.join('\n'))) {
55
+ throw new Error('rules.yaml shares values between fields (YAML anchors) and this change would alter them — edit the file by hand');
56
+ }
57
+ // whole or not at all: the daemon reads this file at every check
58
+ file.write(text);
59
+ }
60
+
61
+ /** `expect` (a revOf) names the rule the caller was shown: another one at that position is refused. */
62
+ function guard(rules, i, expect) {
63
+ if (expect !== undefined && revOf(rules[i]) !== expect) throw new Error(CHANGED);
64
+ }
65
+
66
+ function checkName(name) {
67
+ if (/^#?\d+$/.test(String(name).trim())) throw new Error('a rule name cannot be a number: numbers select a rule by its position');
68
+ }
69
+
70
+ /** The comment above the first rule is held by the list, not the rule: hand it to the rule, so it moves and goes with it. */
71
+ function ownComments(doc) {
72
+ const seq = doc.get('rules');
73
+ const first = seq?.items?.[0];
74
+ if (seq?.commentBefore && first && typeof first === 'object') {
75
+ first.commentBefore = first.commentBefore ? `${seq.commentBefore}\n${first.commentBefore}` : seq.commentBefore;
76
+ seq.commentBefore = undefined;
77
+ }
78
+ return seq;
79
+ }
80
+
81
+ function listRules() {
82
+ const plain = loadDoc().toJS() || {};
83
+ return {
84
+ rules: Array.isArray(plain.rules) ? plain.rules : [],
85
+ quietHours: plain.quietHours || { enabled: false }
86
+ };
87
+ }
88
+
89
+ function findIndex(rules, sel) {
90
+ const s = String(sel).replace(/^#/, '');
91
+ if (/^\d+$/.test(s)) {
92
+ const i = Number(s) - 1;
93
+ if (!rules[i]) throw new Error(`no rule #${s} (have ${rules.length})`);
94
+ return i;
95
+ }
96
+ const i = rules.findIndex((r) => (r?.name || '').toLowerCase() === s.toLowerCase());
97
+ if (i < 0) throw new Error(`no rule named "${sel}" — use \`rules\` to see names/numbers`);
98
+ return i;
99
+ }
100
+
101
+ function addRule(rule) {
102
+ if (!rule.name) throw new Error('rule needs a name');
103
+ checkName(rule.name);
104
+ if (!rule.senders && !rule.subjects) throw new Error('rule needs senders and/or subjects to match on');
105
+ if (rule.sound && rule.sound !== false && !SOUNDS.includes(rule.sound)) {
106
+ throw new Error(`sound must be one of: ${SOUNDS.join(', ')} (or false)`);
107
+ }
108
+ const doc = loadDoc();
109
+ const rules = rulesOf(doc);
110
+ if (rules.some((r) => (r?.name || '').toLowerCase() === rule.name.toLowerCase())) {
111
+ throw new Error(`a rule named "${rule.name}" already exists`);
112
+ }
113
+ if (!doc.get('rules')) doc.set('rules', doc.createNode([]));
114
+ doc.addIn(['rules'], doc.createNode(rule));
115
+ saveDoc(doc, runsOf([...rules, rule]));
116
+ return rules.length + 1;
117
+ }
118
+
119
+ function removeRule(sel, { expect } = {}) {
120
+ const doc = loadDoc();
121
+ const rules = rulesOf(doc);
122
+ const i = findIndex(rules, sel);
123
+ guard(rules, i, expect);
124
+ ownComments(doc);
125
+ doc.deleteIn(['rules', i]);
126
+ saveDoc(doc, runsOf(rules.filter((_, j) => j !== i)));
127
+ return rules[i];
128
+ }
129
+
130
+ /**
131
+ * Change fields of a rule in place (its comments and its other fields stay).
132
+ * A null value removes the field. `patch` may be a function of the rule as it
133
+ * is in the file, so what changes is decided on the very text that is edited.
134
+ */
135
+ function updateRule(sel, patch, { expect } = {}) {
136
+ const doc = loadDoc();
137
+ const rules = rulesOf(doc);
138
+ const i = findIndex(rules, sel);
139
+ guard(rules, i, expect);
140
+ if (typeof patch === 'function') patch = patch(rules[i] || {});
141
+ if (!Object.keys(patch).length) return rules[i];
142
+ if (patch.name != null) checkName(patch.name);
143
+ const next = { ...rules[i] };
144
+ for (const [k, v] of Object.entries(patch)) { if (v == null) delete next[k]; else next[k] = v; }
145
+ if (!next.senders && !next.subjects) throw new Error('rule needs senders and/or subjects to match on');
146
+ if (patch.sound && !SOUNDS.includes(patch.sound)) throw new Error(`sound must be one of: ${SOUNDS.join(', ')} (or false)`);
147
+ if (patch.name != null && rules.some((r, j) => j !== i && (r?.name || '').toLowerCase() === String(patch.name).toLowerCase())) {
148
+ throw new Error(`a rule named "${patch.name}" already exists`);
149
+ }
150
+ for (const [k, v] of Object.entries(patch)) {
151
+ if (v == null) doc.deleteIn(['rules', i, k]);
152
+ else doc.setIn(['rules', i, k], v);
153
+ }
154
+ saveDoc(doc, runsOf(rules.map((r, j) => (j === i ? next : r))));
155
+ return next;
156
+ }
157
+
158
+ /** Move a rule to position `to` (1-based). The first rule that matches a mail is the one that alerts. */
159
+ function moveRule(sel, to, { expect } = {}) {
160
+ const doc = loadDoc();
161
+ const rules = rulesOf(doc);
162
+ const i = findIndex(rules, sel);
163
+ guard(rules, i, expect);
164
+ const j = Math.max(0, Math.min(rules.length - 1, Number(to) - 1));
165
+ if (i === j) return rules[i];
166
+ const seq = ownComments(doc);
167
+ const [node] = seq.items.splice(i, 1);
168
+ seq.items.splice(j, 0, node);
169
+ const moved = [...rules];
170
+ moved.splice(j, 0, ...moved.splice(i, 1));
171
+ saveDoc(doc, runsOf(moved));
172
+ return rules[i];
173
+ }
174
+
175
+ function setRuleEnabled(sel, enabled) {
176
+ const doc = loadDoc();
177
+ const rules = rulesOf(doc);
178
+ const i = findIndex(rules, sel);
179
+ doc.setIn(['rules', i, 'enabled'], enabled);
180
+ saveDoc(doc, runsOf(rules));
181
+ return { ...rules[i], enabled };
182
+ }
183
+
184
+ function setQuietHours({ enabled, start, end }) {
185
+ const doc = loadDoc();
186
+ const rules = rulesOf(doc);
187
+ if (!doc.get('quietHours')) doc.set('quietHours', doc.createNode({ enabled: false, start: '18:00', end: '08:00' }));
188
+ if (enabled !== undefined) doc.setIn(['quietHours', 'enabled'], enabled);
189
+ if (start) doc.setIn(['quietHours', 'start'], start);
190
+ if (end) doc.setIn(['quietHours', 'end'], end);
191
+ saveDoc(doc, runsOf(rules));
192
+ return loadDoc().toJS().quietHours;
193
+ }
194
+
195
+ return { listRules, addRule, removeRule, updateRule, moveRule, setRuleEnabled, setQuietHours };
196
+ }
@@ -0,0 +1,9 @@
1
+ // Types of src/core/runs.js, for the page's harness (extension/harness/boot.ts).
2
+ import type { Assistant } from './assistant';
3
+ export function makeRuns(theAssistant: () => Promise<Assistant>, chats?: { read(a: { id: string }): Promise<any>; save(a: { id: string; rev: number; turns: unknown[] }): Promise<{ rev: number }> } | null): {
4
+ assistantStart(a: any): Promise<{ run: string }>;
5
+ assistantWait(a: any, ctx?: { signal?: AbortSignal }): Promise<any>;
6
+ assistantAnswer(a: any): Promise<{ ok: boolean }>;
7
+ assistantStop(a: any): Promise<{ ok: boolean }>;
8
+ runs: Map<string, unknown>;
9
+ };
@@ -0,0 +1,211 @@
1
+ // The assistant's answers under way (src/core/assistant.js), as the page asks for them: one is started, then followed
2
+ // (asked again and again for what happened since: a step, something to open, a web search to allow) until it is
3
+ // done. Kept by whoever runs the core (the hub, on the Mac: src/assistant-runs.js), in memory.
4
+ //
5
+ // assistantStart({ chat, askedAt, turns, text, files, asked?, model, zone? }) → { run }
6
+ // assistantWait({ run, after, waitMs? }) → { events, done, answer?, kept? } (waits up to 25 s for news)
7
+ // assistantAnswer({ run, ask, ok }) a web search allowed or not
8
+ // assistantStop({ run }) Stop: the answer ends, 'Stopped.'
9
+ // The answer is kept with its chat here, by the core (`kept`: the chat's revision with it), whether or not a page is
10
+ // still there: written after the question it answers (the chat's last turn, `askedAt`), and not when the chat went on
11
+ // otherwise meanwhile (the page then keeps it itself). An answer nobody follows any more is stopped after a while,
12
+ // and what it had is kept as stopped. A finished one is kept in memory a few minutes, for a page that comes back.
13
+
14
+ const AT_ONCE = 3; // answers being followed at once (one a page left keeps going, and does not count)
15
+ const RUNNING_MAX = 8; // answers at work at once, followed or not
16
+ const MAX_TURNS_BYTES = 4 * 1024 * 1024; // the chat sent with a question (its words and references: files are named, not sent)
17
+ const WAIT_MAX = 25_000;
18
+ const UNFOLLOWED = 2 * 60_000; // not asked after for this long: a web search waiting for the person's word is not let go
19
+ const MAX_RUN = 10 * 60_000; // an answer still at work after this long is stopped (and kept as stopped)
20
+ const KEPT = 10 * 60_000; // finished: kept for this long
21
+ const KEPT_AT_MOST = 50; // finished ones kept at once (the oldest let go of first)
22
+
23
+ /**
24
+ * The answers under way and just finished, over `theAssistant()` (→ makeAssistant's, made when first needed) and
25
+ * `chats` ({ read({ id }) → the chat, save({ id, rev, turns }) → its row }: where the answers are kept; none: not
26
+ * kept here): the four ops above, and `runs` (for the tests).
27
+ */
28
+ export function makeRuns(theAssistant, chats = null) {
29
+ const runs = new Map();
30
+
31
+ function sweep(now = Date.now()) {
32
+ for (const [id, r] of runs) {
33
+ if (r.done && now - r.doneAt > KEPT) runs.delete(id);
34
+ else if (!r.done && now - r.started > MAX_RUN) r.stop();
35
+ // (nobody there to allow a web search: it does not go, and the answer goes on without it)
36
+ else if (!r.done && now - r.seen > UNFOLLOWED) for (const resolve of [...r.asks.values()]) resolve(false);
37
+ }
38
+ const finished = [...runs.values()].filter((r) => r.done).sort((a, b) => a.doneAt - b.doneAt);
39
+ for (const r of finished.slice(0, Math.max(0, finished.length - KEPT_AT_MOST))) runs.delete(r.id);
40
+ }
41
+ const sweeper = setInterval(() => sweep(), 30_000);
42
+ sweeper.unref?.();
43
+
44
+ const str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
45
+ /** The files of a question, as the page names them: kept on the Mac already (addChatFile). */
46
+ const filesOf = (v) => (Array.isArray(v) ? v.slice(0, 6) : []).filter((f) => f && typeof f.id === 'string' && /^[a-f0-9]{16,128}$/i.test(f.id)).map((f) => ({ id: f.id, name: str(f.name, 200) || 'file', kind: str(f.kind, 10), size: Number(f.size) || 0 }));
47
+
48
+ /** What a run over one conversation is asked (task 'thread': src/core/thread.js), as the page names it. */
49
+ function threadOf(t) {
50
+ if (!t || typeof t !== 'object' || !['summary', 'event', 'ask', 'suggest', 'quick'].includes(t.what)) return null;
51
+ const id = (v) => (typeof v === 'string' && v && v.length <= 2000 ? v : '');
52
+ const messages = (Array.isArray(t.messages) ? t.messages : []).slice(-80).filter((m) => m && id(m.id)).map((m) => ({
53
+ id: m.id, ...(str(m.account, 200) ? { account: str(m.account, 200) } : {}), ...(str(m.conversationId, 2000) ? { conversationId: str(m.conversationId, 2000) } : {}),
54
+ subject: str(m.subject, 500), fromName: str(m.fromName, 300), fromEmail: str(m.fromEmail, 300)
55
+ }));
56
+ if (!messages.length) throw new Error('there is no conversation to work on');
57
+ return {
58
+ what: t.what, messages, inbound: id(t.inbound), hasCalendar: t.hasCalendar === true,
59
+ ...(t.what === 'ask' ? { request: str(t.request, 4000) } : {}),
60
+ ...(t.what === 'quick' ? { says: str(t.says, 600), kind: t.kind === 'replyAll' ? 'replyAll' : 'reply' } : {}),
61
+ // the reply or forward open under it in the page (`page`: a page follows, and writes what it has open), as Drafts has it when it does
62
+ ...(t.open && ['reply', 'replyAll', 'forward'].includes(t.open.kind) ? { open: { kind: t.open.kind, ...(id(t.open.draftId) ? { draftId: t.open.draftId } : {}) } } : {}),
63
+ page: t.page === true,
64
+ notes: (Array.isArray(t.notes) ? t.notes : []).slice(0, 10).filter((n) => n && /^[a-z0-9]{6,24}$/.test(String(n.id))).map((n) => ({ id: n.id, title: str(n.title, 200), beside: n.beside === true }))
65
+ };
66
+ }
67
+
68
+ /** What a run of "help me write" is asked (src/core/write.js): the mail as it stands, and what to do with it. */
69
+ function writeOf(w) {
70
+ if (!w || typeof w !== 'object' || !w.compose || typeof w.compose !== 'object') return null;
71
+ const instruction = str(w.instruction, 4000).trim();
72
+ if (!instruction) throw new Error('nothing was asked');
73
+ const c = w.compose;
74
+ // (the mail whole, or not at all: a part of it given to the model would be written back as the whole)
75
+ const list = (v, what) => { const l = Array.isArray(v) ? v : []; if (l.length > 100 || l.some((x) => typeof x !== 'string' || x.length > 320)) throw new Error(`the mail's ${what} is too long to be worked on here`); return l; };
76
+ const whole = (v, max, what) => { const t = typeof v === 'string' ? v : ''; if (t.length > max) throw new Error(`the mail's ${what} is too long to be worked on here`); return t; };
77
+ const kind = ['new', 'reply', 'replyAll', 'forward', 'edit'].includes(c.kind) ? c.kind : 'new';
78
+ const id = (v) => (typeof v === 'string' && v && v.length <= 2000 ? v : '');
79
+ if (w.page !== true) throw new Error('help with writing works on a mail open in a page');
80
+ return {
81
+ instruction,
82
+ compose: { kind, to: list(c.to, 'To'), cc: list(c.cc, 'Cc'), bcc: list(c.bcc, 'Bcc'), subject: whole(c.subject, 1000, 'subject'), hasSubject: c.hasSubject === true, html: whole(c.html, 400_000, 'text'), signature: str(c.signature, 2000) },
83
+ ...(w.source && id(w.source.id) ? { source: { id: w.source.id, from: str(w.source.from, 400), subject: str(w.source.subject, 1000) } } : {}),
84
+ ...(str(w.account, 200) ? { account: str(w.account, 200) } : {}),
85
+ page: true
86
+ };
87
+ }
88
+
89
+ async function assistantStart(a = {}) {
90
+ sweep();
91
+ const turns = Array.isArray(a.turns) ? a.turns : [];
92
+ if (new TextEncoder().encode(JSON.stringify(turns)).length > MAX_TURNS_BYTES) throw new Error('this chat is too long to be answered: start a new one');
93
+ const thread = threadOf(a.thread);
94
+ const write = writeOf(a.write);
95
+ const text = write ? write.instruction : thread ? (thread.request || thread.says || thread.what) : str(a.text, 20_000);
96
+ const files = filesOf(a.files);
97
+ if (!text.trim() && !files.length && !(turns.at(-1)?.role === 'user')) throw new Error('nothing was asked');
98
+ const now = Date.now();
99
+ // quick replies offered on opening a mail are extra: they never take the place of what the person asks, and are
100
+ // the first left out when much is going on
101
+ const light = thread?.what === 'suggest';
102
+ const working = [...runs.values()].filter((x) => !x.done && !x.light);
103
+ if (working.length >= RUNNING_MAX || working.filter((x) => now - x.seen < UNFOLLOWED).length >= AT_ONCE) throw new Error('the assistant is already answering several things: try again in a moment');
104
+ if (light && [...runs.values()].filter((x) => !x.done && x.light).length >= AT_ONCE) throw new Error('quick replies are being worked out for other mail: try again in a moment');
105
+ const asked = a.asked && typeof a.asked === 'object' ? {
106
+ ...(typeof a.asked.connectionId === 'string' && a.asked.connectionId ? { connectionId: a.asked.connectionId } : {}),
107
+ ...(Number.isFinite(a.asked.connectionRevision) ? { connectionRevision: a.asked.connectionRevision } : {}),
108
+ ...(typeof a.asked.model === 'string' && a.asked.model ? { model: a.asked.model } : {})
109
+ } : undefined;
110
+ const id = Array.from(globalThis.crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(16).padStart(2, '0')).join('');
111
+ const ac = new AbortController();
112
+ const r = {
113
+ id, light, chat: str(a.chat, 100), events: [], n: 0, done: false, answer: null, kept: null, doneAt: 0, seen: Date.now(), started: Date.now(),
114
+ waiters: new Set(), asks: new Map(),
115
+ // Stop: ended at once, said so; whatever the step under way finds when it comes back is dropped
116
+ stop: () => { if (r.done) return; ac.abort(); for (const resolve of r.asks.values()) resolve(false); r.asks.clear(); finish({ role: 'assistant', text: 'Stopped.', at: Date.now(), model: str(a.model, 200), failed: true }); }
117
+ };
118
+ let finishing = false;
119
+ async function finish(answer) {
120
+ if (r.done || finishing) return;
121
+ finishing = true;
122
+ r.answer = answer;
123
+ r.kept = await keep(r.chat, Number(a.askedAt), answer).catch(() => null);
124
+ r.done = true;
125
+ r.doneAt = Date.now();
126
+ emit({ type: 'done' });
127
+ }
128
+ // (once it is ending, a step still unwinding opens nothing more)
129
+ const emit = (event) => { if ((r.done || finishing || ac.signal.aborted) && event.type !== 'done') return; r.events.push({ n: ++r.n, ...event }); for (const w of r.waiters) w(); r.waiters.clear(); };
130
+ runs.set(id, r);
131
+ const ask = (query) => new Promise((resolve) => {
132
+ if (ac.signal.aborted) return resolve(false);
133
+ const askId = String(r.n + 1);
134
+ r.asks.set(askId, (ok) => { r.asks.delete(askId); emit({ type: 'asked', ask: askId, ok: !!ok }); resolve(!!ok); });
135
+ emit({ type: 'ask', ask: askId, query });
136
+ });
137
+ (async () => {
138
+ let answer;
139
+ try {
140
+ answer = await (await theAssistant()).answer({ turns, text, files, asked, model: str(a.model, 200), zone: str(a.zone, 64), ...(thread ? { thread } : {}), ...(write ? { write } : {}) }, { emit, ask, signal: ac.signal });
141
+ } catch (e) {
142
+ answer = { role: 'assistant', text: `That did not work: ${e?.message || e}`, at: Date.now(), model: str(a.model, 200), failed: true };
143
+ }
144
+ await finish(answer);
145
+ })();
146
+ return { run: id };
147
+ }
148
+
149
+ /**
150
+ * The answer written into its chat, after the question it answers: when that question is the chat's last turn
151
+ * (`askedAt`, its time, names it; the page has kept the question before it starts the answer).
152
+ * The chat having gone on otherwise (another answer, another question, removed): not written. Gives the chat's new
153
+ * revision, or null.
154
+ */
155
+ async function keep(id, askedAt, answer) {
156
+ if (!chats || !id || !Number.isFinite(askedAt)) return null;
157
+ for (let tries = 0; tries < 4; tries++) {
158
+ let c;
159
+ try { c = await chats.read({ id }); } catch { return null; } // (removed, or not kept at all: nothing to write into)
160
+ const last = c?.turns?.at(-1);
161
+ // (the question not its last turn: gone on since, or never kept there: the page's to keep)
162
+ if (last?.role !== 'user' || last.at !== askedAt) return null;
163
+ try { return (await chats.save({ id, rev: c.rev, turns: [...c.turns, answer] })).rev; } catch (e) {
164
+ if (!/changed elsewhere/.test(String(e?.message))) return null; // (too long, or anything else: not tried again)
165
+ }
166
+ await new Promise((res) => setTimeout(res, 100 * (tries + 1)));
167
+ }
168
+ return null;
169
+ }
170
+
171
+ const runOf = (a) => {
172
+ const r = runs.get(str(a?.run, 64));
173
+ if (!r) throw new Error('that answer is no longer here');
174
+ return r;
175
+ };
176
+
177
+ async function assistantWait(a = {}, ctx = {}) {
178
+ const r = runOf(a);
179
+ r.seen = Date.now();
180
+ const after = Number.isFinite(Number(a.after)) ? Number(a.after) : 0;
181
+ const news = () => r.events.filter((e) => e.n > after);
182
+ if (!news().length && !r.done) {
183
+ const waitMs = Math.max(0, Math.min(WAIT_MAX, Number(a.waitMs) || WAIT_MAX));
184
+ await new Promise((resolve) => {
185
+ const timer = setTimeout(done, waitMs);
186
+ function done() { clearTimeout(timer); r.waiters.delete(done); ctx.signal?.removeEventListener('abort', done); resolve(); }
187
+ r.waiters.add(done);
188
+ ctx.signal?.addEventListener('abort', done, { once: true });
189
+ });
190
+ r.seen = Date.now();
191
+ }
192
+ return { events: news(), done: r.done, ...(r.done ? { answer: r.answer, kept: r.kept } : {}) };
193
+ }
194
+
195
+ async function assistantAnswer(a = {}) {
196
+ const r = runOf(a);
197
+ r.seen = Date.now();
198
+ const answer = r.asks.get(str(a.ask, 20));
199
+ if (!answer) return { ok: false };
200
+ answer(a.ok === true);
201
+ return { ok: true };
202
+ }
203
+
204
+ async function assistantStop(a = {}) {
205
+ const r = runs.get(str(a?.run, 64));
206
+ r?.stop();
207
+ return { ok: true };
208
+ }
209
+
210
+ return { assistantStart, assistantWait, assistantAnswer, assistantStop, runs };
211
+ }