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
package/src/bridge.js ADDED
@@ -0,0 +1,101 @@
1
+ // Chrome native-messaging host: the side-panel extension's way into the
2
+ // mailboxes. Chrome starts this process (`sideora bridge`, through the
3
+ // wrapper that `install-extension` writes) and talks to it over stdio; only
4
+ // the extension id named in the host manifest may connect. No port, no token.
5
+ //
6
+ // Wire format (both directions): 4-byte little-endian length + UTF-8 JSON.
7
+ // request { id, op, args }
8
+ // let go of { cancel: id } the request is stopped (a model turn: Stop)
9
+ // response { id, ok: true, result } | { id, ok: false, error }
10
+ // push { push: 'event', event } a daemon event (newmail, …)
11
+ // { push: 'gap', lost, oldest } events were missed: reload
12
+ // { push: 'daemon', up, error? } the daemon came or went
13
+ // Events come from two places: the daemon's cursor-backed queue (new mail —
14
+ // nothing is missed across a reconnect) and its live socket (`drafts`: a
15
+ // hint to reload, worth nothing later, so it is not queued).
16
+ // Chrome refuses host messages over 1 MB, so a larger frame is sent as
17
+ // { part: { key, i, n, data } } base64 slices of the JSON, reassembled by the extension.
18
+ //
19
+ // The ops and the pushes themselves are src/panel-ops.js (shared with the web
20
+ // app's server, src/web-server.js); this file is their wire to Chrome. An op is
21
+ // asked of the hub (the daemon, src/hub.js) when it runs, and done here when not.
22
+ // Events start on `subscribe`.
23
+
24
+ import { runOp, follow } from './panel-ops.js';
25
+ import { PANEL_OPS } from './op-registry.js';
26
+ import { keepConnections } from './core.js';
27
+ import { hubClient, hubServes, HUB_ONLY, NO_HUB } from './hub.js';
28
+
29
+ const MAX_FRAME = 900 * 1024; // under Chrome's 1 MB cap
30
+ const SLICE = 600 * 1024; // raw bytes per part (base64 grows it by a third)
31
+
32
+ let partSeq = 0;
33
+
34
+ function writeFrame(buf) {
35
+ const head = Buffer.alloc(4);
36
+ head.writeUInt32LE(buf.length, 0);
37
+ process.stdout.write(Buffer.concat([head, buf]));
38
+ }
39
+
40
+ function send(msg) {
41
+ const buf = Buffer.from(JSON.stringify(msg), 'utf8');
42
+ if (buf.length <= MAX_FRAME) return writeFrame(buf);
43
+ const key = 'p' + ++partSeq;
44
+ const n = Math.ceil(buf.length / SLICE);
45
+ for (let i = 0; i < n; i++) {
46
+ const data = buf.subarray(i * SLICE, (i + 1) * SLICE).toString('base64');
47
+ writeFrame(Buffer.from(JSON.stringify({ part: { key, i, n, data } }), 'utf8'));
48
+ }
49
+ }
50
+
51
+ let subscribed = false;
52
+ // (the extension's worker gives up on an op on its own, sooner than this; a model turn it waits on for longer)
53
+ const hub = hubClient({ callMs: 6 * 60_000 });
54
+ const running = new Map(); // requests under way, by id: their AbortControllers
55
+
56
+ async function handle(msg) {
57
+ if (msg && typeof msg === 'object' && 'cancel' in msg && !('op' in msg)) { running.get(msg.cancel)?.abort(); return; }
58
+ const { id, op, args } = msg || {};
59
+ if (op === 'subscribe') {
60
+ if (!subscribed) { subscribed = true; follow(send, args?.after); }
61
+ return send({ id, ok: true, result: { subscribed: true } });
62
+ }
63
+ // only what the side panel may ask (src/op-registry.js), and the extension's own greeting, not an op the registry does not name
64
+ if (op !== 'hello' && !PANEL_OPS.has(op)) return send({ id, ok: false, error: `unknown op "${op}"` });
65
+ const ac = new AbortController();
66
+ const mine = !running.has(id);
67
+ if (mine) running.set(id, ac);
68
+ try {
69
+ // the hub (the daemon) answers it when there is one, so that one process writes what is kept; without one, as
70
+ // ever, except the AI ops: the hub alone holds the connections and their keys
71
+ const answer = hubServes(op) ? await hub.call(op, args, { signal: ac.signal }) : null;
72
+ send({ id, ...(answer ?? (HUB_ONLY.has(op) ? { ok: false, error: NO_HUB } : await runOp(op, args, undefined, { signal: ac.signal }))) });
73
+ } finally {
74
+ if (mine) running.delete(id);
75
+ }
76
+ }
77
+
78
+ // --- stdio --------------------------------------------------------------------
79
+
80
+ export function runBridge() {
81
+ keepConnections(); // (this process answers the panel for as long as it is open: its IMAP connections are kept between uses)
82
+ // stdout is the wire: anything a library prints there would corrupt it
83
+ console.log = console.info = console.debug = (...a) => console.error(...a);
84
+
85
+ let pending = Buffer.alloc(0);
86
+ process.stdin.on('data', (chunk) => {
87
+ pending = Buffer.concat([pending, chunk]);
88
+ while (pending.length >= 4) {
89
+ const len = pending.readUInt32LE(0);
90
+ if (pending.length < 4 + len) break;
91
+ const body = pending.subarray(4, 4 + len);
92
+ pending = pending.subarray(4 + len);
93
+ let msg;
94
+ try { msg = JSON.parse(body.toString('utf8')); } catch { continue; }
95
+ handle(msg);
96
+ }
97
+ });
98
+ // Chrome closes stdin when the extension disconnects or the browser quits
99
+ process.stdin.on('end', () => process.exit(0));
100
+ process.stdout.on('error', () => process.exit(0));
101
+ }
@@ -0,0 +1,56 @@
1
+ // Daemon side of the calendar: mailcore's calendar watcher for one account
2
+ // (a snapshot of the next `lookaheadDays` of the default calendar, refreshed
3
+ // on push and every `pollMinutes`, at ~/.sideora/calendar-<account>.json
4
+ // so a restart neither re-announces every event nor repeats reminders), told
5
+ // the Sideora way:
6
+ // - `calendar` events on the bus when an event is created, updated,
7
+ // cancelled or deleted (new invitations and cancellations also notify),
8
+ // - `reminder` events `remindMinutes` before each event starts (desktop
9
+ // notification + sound), quiet hours respected.
10
+
11
+ import { watchCalendar, inQuietHours } from 'mailcore';
12
+ import { core } from './core.js';
13
+ import { loadRulesDoc } from './config.js';
14
+ import { playSound, notifyMac } from './notify.js';
15
+
16
+ const MAX_NOTIFY_PER_REFRESH = 3;
17
+
18
+ export function startCalendarWatch({ account, bus, log, authGate }) {
19
+ const settings = () => core.accounts[account]?.calendar || {};
20
+ const quiet = () => inQuietHours(loadRulesDoc().quietHours);
21
+ const watch = watchCalendar(core, { account, log, authGate, start: false });
22
+
23
+ watch.on('changes', (changes) => {
24
+ const cfg = settings();
25
+ const q = quiet();
26
+ let notified = 0;
27
+ for (const ch of changes) {
28
+ const ev = ch.event;
29
+ bus.emit('calendar', { action: ch.action, account, ...ev, ...(ch.previous ? { previous: ch.previous } : {}), quiet: q });
30
+ // only invitations from someone else and cancellations deserve an interruption
31
+ if (!ch.loud || q || cfg.notify === false || notified >= MAX_NOTIFY_PER_REFRESH) continue;
32
+ notified++;
33
+ if (notified === 1 && cfg.sound !== false) playSound(cfg.sound || 'ding');
34
+ notifyMac(ch.action === 'cancelled' ? '📅 Cancelled' : '📅 New invitation', `${ev.subject}\n${when(ev)}`);
35
+ }
36
+ });
37
+
38
+ watch.on('reminder', (ev) => {
39
+ const cfg = settings();
40
+ const q = quiet();
41
+ bus.emit('reminder', { ...ev, quiet: q });
42
+ if (q || cfg.notify === false) return;
43
+ if (cfg.sound !== false) playSound(cfg.sound || 'ding');
44
+ notifyMac(`⏰ In ${ev.minutes} min: ${ev.subject}`, `${when(ev)}${ev.location ? '\n' + ev.location : ''}`);
45
+ });
46
+
47
+ watch.start();
48
+ return { refresh: () => watch.refresh(), stop: () => watch.stop() };
49
+ }
50
+
51
+ function when(ev) {
52
+ const d = new Date(ev.start);
53
+ if (isNaN(d)) return ev.start;
54
+ if (ev.allDay) return d.toLocaleDateString();
55
+ return d.toLocaleString(undefined, { weekday: 'short', hour: '2-digit', minute: '2-digit' });
56
+ }
package/src/chats.js ADDED
@@ -0,0 +1,27 @@
1
+ // The assistant's chats on this Mac: the core's chats (src/core/chats.js, what a chat is and how it is kept) over
2
+ // this Mac's store (src/host/chats-files.js: one file a chat in ~/.sideora/chats, a lock across processes).
3
+
4
+ import path from 'node:path';
5
+ import { HOME_DIR } from './config.js';
6
+ import { makeChats, makeChatFiles } from './core/chats.js';
7
+ import { chatsFiles } from './host/chats-files.js';
8
+
9
+ export { CHANGED, GONE, MAX_FILE, kindOf } from './core/chats.js';
10
+ export const CHATS_DIR = path.join(HOME_DIR, 'chats');
11
+
12
+ /** The chats kept in `dir` (a test gives its own). */
13
+ export const chatsStore = ({ dir = CHATS_DIR } = {}) => makeChats({ store: chatsFiles(dir) });
14
+ /** The files of the chats kept in `dir` (in its `files`). */
15
+ export const chatFilesStore = ({ dir = CHATS_DIR } = {}) => makeChatFiles({ store: chatsFiles(dir) });
16
+
17
+ let own;
18
+ let ownFiles;
19
+ const filesOf = () => (ownFiles ??= chatFilesStore());
20
+ export const addChatFile = (a) => filesOf().add(a);
21
+ export const chatFile = (a) => filesOf().get(a);
22
+ export const expandChatFiles = (messages) => filesOf().expand(messages);
23
+ const mine = () => (own ??= chatsStore());
24
+ export const listChats = () => mine().list();
25
+ export const readChat = (a) => mine().read(a);
26
+ export const saveChat = (a) => mine().save(a);
27
+ export const removeChat = (a) => mine().remove(a);
@@ -0,0 +1,58 @@
1
+ // Compose a reply in $EDITOR (mutt-style). The temp file holds a short
2
+ // header block and the quoted original as '#' comment lines for reference;
3
+ // comment lines are stripped, the rest is the reply body. Returns null when
4
+ // the user left the body empty. Works from the TUI too: raw mode is released
5
+ // around the editor and restored afterwards.
6
+
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { spawnSync } from 'node:child_process';
11
+ import { renderHtmlWithLinks } from './render.js';
12
+
13
+ /** msg: a full message (getMessage/readMessage). opts.quote overrides the quoted text. */
14
+ export function composeInEditor(msg, { all = false, quote } = {}) {
15
+ const editor = process.env.VISUAL || process.env.EDITOR || 'vi';
16
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sideora-'));
17
+ const file = path.join(dir, 'reply.txt');
18
+ const original = quote != null ? quote : msg.bodyType === 'HTML' ? renderHtmlWithLinks(msg.body, { width: 90 }).text : String(msg.body || '');
19
+ const quoted = original.split('\n').slice(0, 200).map((l) => '# > ' + l).join('\n');
20
+ const to = all
21
+ ? [msg.fromEmail, ...(msg.to || []).map((r) => r.email), ...(msg.cc || []).map((r) => r.email)].filter(Boolean).join(', ')
22
+ : msg.fromEmail;
23
+ fs.writeFileSync(file, [
24
+ `# ${all ? 'Reply-all' : 'Reply'} to: ${to}`,
25
+ `# Subject: ${/^re:/i.test(msg.subject || '') ? msg.subject : 'Re: ' + (msg.subject || '')}`,
26
+ '# Lines starting with "#" are dropped. Write your reply below; save and quit',
27
+ '# to continue, leave it empty to discard. The original is appended by the server.',
28
+ '',
29
+ '',
30
+ '',
31
+ `# On ${msg.received}, ${msg.fromName || msg.fromEmail} wrote:`,
32
+ quoted
33
+ ].join('\n') + '\n', { mode: 0o600 });
34
+
35
+ // Hand the terminal to the editor: stop Node from consuming keystrokes
36
+ // (Ink keeps stdin flowing) and leave raw mode, then restore both.
37
+ const stdin = process.stdin;
38
+ const wasRaw = stdin.isTTY && stdin.isRaw;
39
+ const wasFlowing = stdin.readableFlowing;
40
+ if (wasRaw) stdin.setRawMode(false);
41
+ stdin.pause();
42
+ let r;
43
+ try {
44
+ r = spawnSync('/bin/sh', ['-c', `${editor} "$1"`, 'sh', file], { stdio: 'inherit' });
45
+ } finally {
46
+ if (wasRaw) stdin.setRawMode(true);
47
+ if (wasFlowing) stdin.resume();
48
+ }
49
+ let body = null;
50
+ try {
51
+ const text = fs.readFileSync(file, 'utf8');
52
+ body = text.split('\n').filter((l) => !l.startsWith('#')).join('\n').replace(/^\n+|\s+$/g, '');
53
+ } finally {
54
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch {}
55
+ }
56
+ if (r.status !== 0 && r.status != null) return null;
57
+ return body ? body : null;
58
+ }
package/src/config.js ADDED
@@ -0,0 +1,420 @@
1
+ // Config, paths and credential loading. Everything lives in ~/.sideora/
2
+ // (or $SIDEORA_HOME).
3
+ //
4
+ // config.json holds global settings plus an "accounts" map — one entry per
5
+ // mailbox, each with its own provider ("ews" or "imap") and credentials:
6
+ //
7
+ // "accounts": {
8
+ // "work": { "provider": "ews", "host": "https://mail.example.com",
9
+ // "credentials": { "source": "1password",
10
+ // "password": "op://<vaultId>/<itemId>/password",
11
+ // "label": { "item": "Mail Work", "vault": "Private" } } },
12
+ // "personal": { "provider": "imap", "email": "me@example.org",
13
+ // "imap": { "host": "imap.example.org", "port": 993 },
14
+ // "smtp": { "host": "smtp.example.org", "port": 587 } }
15
+ // }
16
+ //
17
+ // Where an account's password comes from is its "credentials" (src/credentials.js):
18
+ // keychain (the default), 1password, 1password-service or env. The older
19
+ // "onePassword": { "item", "vault" } is read as a 1password source, and
20
+ // rewritten to a reference by IDs the first time it is read.
21
+ //
22
+ // A legacy single-account config (top-level host/username/onePassword) is
23
+ // read as one account named "default".
24
+
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+ import os from 'node:os';
28
+ import { execFile, execFileSync, spawnSync } from 'node:child_process';
29
+ import YAML from 'yaml';
30
+ import { ACCOUNT_DEFAULTS as CORE_ACCOUNT_DEFAULTS, normalizeAccount, PROVIDERS, MAIL_PROVIDERS } from 'mailcore';
31
+
32
+ // SIDEORA_HOME points a copy at another data directory (tests, a trial run
33
+ // beside the daemon); Keychain entries and 1Password items stay the same.
34
+ export const HOME_DIR = process.env.SIDEORA_HOME ? path.resolve(process.env.SIDEORA_HOME) : path.join(os.homedir(), '.sideora');
35
+ export const CONFIG_PATH = path.join(HOME_DIR, 'config.json');
36
+ export const RULES_PATH = path.join(HOME_DIR, 'rules.yaml');
37
+ export const STATE_PATH = path.join(HOME_DIR, 'state.json');
38
+ export const MCP_CONFIG_PATH = path.join(HOME_DIR, 'mcp.json');
39
+ export const LOG_DIR = path.join(HOME_DIR, 'logs');
40
+ export const DIGEST_DIR = path.join(HOME_DIR, 'digests');
41
+ export const SOUNDS_DIR = path.join(HOME_DIR, 'sounds');
42
+ /** What a process started for Sideora (launchd, Chrome, Claude Code) needs in its environment to use this data directory: nothing for ~/.sideora. */
43
+ export const HOME_ENV = process.env.SIDEORA_HOME ? { SIDEORA_HOME: HOME_DIR } : {};
44
+
45
+ // Keychain: one generic-password entry per account (service fixed, account = name).
46
+ export const KEYCHAIN_SERVICE = 'sideora';
47
+ // the account shapes, their defaults and which hold mail or a calendar are mailcore's
48
+ export { PROVIDERS, MAIL_PROVIDERS, CACHE_DEFAULTS, CALENDAR_DEFAULTS, calendarProvider, hasMail } from 'mailcore';
49
+ export const DEFAULT_ACCOUNT = 'default';
50
+
51
+ export const DEFAULT_CONFIG = {
52
+ pollSeconds: 30,
53
+ claudePath: path.join(os.homedir(), '.local/bin/claude'),
54
+ claudeModel: 'sonnet',
55
+ passwordMaxAgeDays: 30,
56
+ // mcp.allowSend: expose a send_draft tool on the MCP server (default off —
57
+ // the server is drafts-only so agents can never send). Woken agents never
58
+ // get it regardless.
59
+ mcp: { allowSend: false },
60
+ // timeZone: IANA zone for all-day events and free-slot hours (default: this machine's)
61
+ timeZone: null,
62
+ accounts: {}
63
+ };
64
+
65
+ // Per-account defaults by provider: mailcore's (cache: an encrypted local copy
66
+ // of the inbox; calendar: the daemon's watch and reminders). Where the
67
+ // password comes from is the account's "credentials" (credentialsOf, below).
68
+ export const ACCOUNT_DEFAULTS = CORE_ACCOUNT_DEFAULTS;
69
+
70
+ /** Where a password can come from (an account's credentials.source). */
71
+ export const CREDENTIAL_SOURCES = ['keychain', '1password', '1password-service', 'env', 'microsoft'];
72
+ export const isOnePassword = (src) => src?.source === '1password' || src?.source === '1password-service';
73
+
74
+ /**
75
+ * Where an account's password comes from, as config.json says it now or said
76
+ * it before: { source, … }. `credentials` wins; the older `onePassword.item`
77
+ * is a 1password source by item name (`item`, `vault`); neither is the
78
+ * Keychain. A source not known is kept as it is (reading it says so).
79
+ */
80
+ /**
81
+ * The environment for a process Sideora starts that is not Sideora
82
+ * (a woken agent, a rule's command): this one's, without what holds a
83
+ * password: every variable an account's credentials.env names, and a
84
+ * 1Password service account token.
85
+ */
86
+ export function childEnv(extra = {}) {
87
+ const env = { ...process.env, ...extra };
88
+ delete env.OP_SERVICE_ACCOUNT_TOKEN;
89
+ for (const name of passwordVariables()) delete env[name];
90
+ return env;
91
+ }
92
+
93
+ /** The environment variables config.json names as holding a password (credentials.env, its calendars' too). */
94
+ export function passwordVariables() {
95
+ let raw;
96
+ try { raw = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')); } catch { return []; }
97
+ const out = new Set();
98
+ const look = (a) => { const c = a?.credentials; if (c && c.source === 'env' && typeof c.env === 'string' && c.env) out.add(c.env); };
99
+ for (const a of Object.values(raw?.accounts || {})) { look(a); look(a?.calendar); }
100
+ look(raw);
101
+ return [...out];
102
+ }
103
+
104
+ /** Where the password comes from, in words: 1Password "Mail Work", the environment variable X, the Keychain. */
105
+ export function passwordSource(acct) {
106
+ const src = credentialsOf(acct);
107
+ if (isOnePassword(src)) {
108
+ const item = src.label?.item || src.item || '';
109
+ return `1Password${src.source === '1password-service' ? ' (service account)' : ''}${item ? ` "${item}"` : ''}`;
110
+ }
111
+ if (src.source === 'env') return `the environment variable ${src.env || '(not named)'}`;
112
+ if (src.source === 'microsoft') return 'its Microsoft sign-in';
113
+ return src.source === 'keychain' ? 'the Keychain' : `"${src.source}"`;
114
+ }
115
+
116
+ export function credentialsOf(acct) {
117
+ const c = acct?.credentials;
118
+ if (c && typeof c === 'object' && !Array.isArray(c) && typeof c.source === 'string') return { ...c };
119
+ const op = acct?.onePassword;
120
+ if (op && typeof op === 'object' && op.item) return { source: '1password', item: String(op.item), ...(op.vault ? { vault: String(op.vault) } : {}) };
121
+ return { source: 'keychain' };
122
+ }
123
+
124
+ // Legacy top-level keys that describe the (single) EWS account.
125
+ const LEGACY_ACCOUNT_KEYS = ['host', 'username', 'domain', 'onePassword', 'streaming', 'password'];
126
+
127
+ export function ensureDirs() {
128
+ for (const d of [HOME_DIR, LOG_DIR, DIGEST_DIR, SOUNDS_DIR]) fs.mkdirSync(d, { recursive: true });
129
+ }
130
+
131
+ export function loadConfig() {
132
+ if (!fs.existsSync(CONFIG_PATH)) {
133
+ throw new Error(`No config at ${CONFIG_PATH} — run: sideora setup`);
134
+ }
135
+ return normalizeConfig(JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')));
136
+ }
137
+
138
+ /** Fold a legacy single-account config into accounts.default; fill defaults. */
139
+ export function normalizeConfig(raw) {
140
+ const cfg = { ...DEFAULT_CONFIG, ...raw, accounts: { ...(raw.accounts || {}) } };
141
+ if (Object.keys(cfg.accounts).length === 0 && raw.host) {
142
+ const legacy = { provider: 'ews' };
143
+ for (const k of LEGACY_ACCOUNT_KEYS) if (raw[k] !== undefined) legacy[k] = raw[k];
144
+ cfg.accounts[DEFAULT_ACCOUNT] = legacy;
145
+ }
146
+ for (const k of LEGACY_ACCOUNT_KEYS) delete cfg[k];
147
+ for (const [name, acct] of Object.entries(cfg.accounts)) {
148
+ const { onePassword: _legacy, ...a } = normalizeAccount(name, acct);
149
+ cfg.accounts[name] = a.provider === 'google' ? a : { ...a, credentials: credentialsOf(acct) };
150
+ }
151
+ return cfg;
152
+ }
153
+
154
+ export function saveConfig(cfg) {
155
+ ensureDirs();
156
+ const out = { ...cfg, accounts: {} };
157
+ for (const [name, acct] of Object.entries(cfg.accounts || {})) {
158
+ const { name: _n, ...rest } = acct;
159
+ out.accounts[name] = rest;
160
+ }
161
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(out, null, 2) + '\n', { mode: 0o600 });
162
+ }
163
+
164
+ /**
165
+ * Change config.json as it is written, not as it is read (loadConfig fills
166
+ * every default in, and those do not belong in the file): `change(raw)`
167
+ * edits the parsed file in place. A single-account file of the old shape
168
+ * becomes an accounts map first, the way it is read. Written beside the file
169
+ * and moved over it, so nothing reads half of it.
170
+ */
171
+ export function updateConfig(change) {
172
+ if (!fs.existsSync(CONFIG_PATH)) throw new Error(`No config at ${CONFIG_PATH} — run: sideora setup`);
173
+ // one writer at a time, across processes (two bridges, the daemon, the CLI): read, change and written under the lock
174
+ const unlock = lockConfig();
175
+ try { return changeConfig(change); } finally { unlock(); }
176
+ }
177
+
178
+ /** A lock file beside config.json, taken exclusively; one left by a process that died is taken over after a while. */
179
+ function lockConfig() {
180
+ const lock = `${CONFIG_PATH}.lock`;
181
+ const until = Date.now() + 10_000;
182
+ for (;;) {
183
+ try {
184
+ fs.writeFileSync(lock, String(process.pid), { flag: 'wx', mode: 0o600 });
185
+ return () => { try { fs.unlinkSync(lock); } catch { /* gone already */ } };
186
+ } catch (e) {
187
+ if (e.code !== 'EEXIST') throw e;
188
+ try { if (Date.now() - fs.statSync(lock).mtimeMs > 15_000) { fs.unlinkSync(lock); continue; } } catch { continue; }
189
+ if (Date.now() > until) throw new Error('the settings are being changed by another process: try again');
190
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50); // a short wait, without a busy loop
191
+ }
192
+ }
193
+ }
194
+
195
+ function changeConfig(change) {
196
+ const file = fs.realpathSync(CONFIG_PATH); // a link to a file kept elsewhere stays a link
197
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
198
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(`${CONFIG_PATH} is not a settings file`);
199
+ if ((!raw.accounts || Object.keys(raw.accounts).length === 0) && raw.host) {
200
+ const legacy = { provider: 'ews' };
201
+ for (const k of LEGACY_ACCOUNT_KEYS) if (raw[k] !== undefined) { legacy[k] = raw[k]; delete raw[k]; }
202
+ raw.accounts = { [DEFAULT_ACCOUNT]: legacy };
203
+ }
204
+ if (change(raw) === false) return; // nothing to change: the file is left as it is
205
+ const tmp = `${file}.${process.pid}.tmp`;
206
+ try {
207
+ fs.writeFileSync(tmp, JSON.stringify(raw, null, 2) + '\n', { mode: 0o600 });
208
+ fs.renameSync(tmp, file);
209
+ } catch (e) {
210
+ fs.rmSync(tmp, { force: true });
211
+ throw e;
212
+ }
213
+ }
214
+
215
+ export function accountNames(config) {
216
+ return Object.keys(config.accounts || {});
217
+ }
218
+
219
+ /** Accounts that hold mail (ews, imap). */
220
+ export function mailAccountNames(config) {
221
+ return accountNames(config).filter((n) => MAIL_PROVIDERS.includes(config.accounts[n].provider));
222
+ }
223
+
224
+
225
+ /** Resolve an account by name; with one account, name may be omitted. */
226
+ export function getAccount(config, name) {
227
+ const names = accountNames(config);
228
+ if (names.length === 0) throw new Error(`No accounts configured in ${CONFIG_PATH} — run: sideora setup`);
229
+ if (!name) {
230
+ if (names.length === 1) return config.accounts[names[0]];
231
+ if (config.defaultAccount && config.accounts[config.defaultAccount]) return config.accounts[config.defaultAccount];
232
+ throw new Error(`several accounts configured (${names.join(', ')}) — pass --account <name> or set "defaultAccount" in ${CONFIG_PATH}`);
233
+ }
234
+ const acct = config.accounts[name];
235
+ if (!acct) throw new Error(`unknown account "${name}" — configured: ${names.join(', ')}`);
236
+ return acct;
237
+ }
238
+
239
+ // Where secrets are kept: the login Keychain on the Mac; on Linux, a file of the person's own (src/host/secrets-file.js),
240
+ // under the same names. SIDEORA_SECRETS=file uses the file on the Mac too, =keychain the Keychain's `security` on
241
+ // any machine (the tests, with a stand-in for it).
242
+ const SECRETS_FILE = process.env.SIDEORA_SECRETS === 'file' || (process.platform !== 'darwin' && process.env.SIDEORA_SECRETS !== 'keychain');
243
+ const secretsFile = SECRETS_FILE ? await import('./host/secrets-file.js') : null;
244
+
245
+ /** A generic password of the login Keychain; null when there is none. */
246
+ export function keychainRead(service, account) {
247
+ if (secretsFile) { try { return secretsFile.read(HOME_DIR, service, account); } catch { return null; } }
248
+ try {
249
+ return execFileSync('security', ['find-generic-password', '-s', service, '-a', account, '-w'],
250
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).replace(/\n$/, '');
251
+ } catch {
252
+ return null;
253
+ }
254
+ }
255
+ /**
256
+ * keychainRead, telling "there is none" (null: `security` exit 44) from "it could not be read" (a locked Keychain,
257
+ * access refused: a throw), for a caller that must not take a failed read for an absence.
258
+ */
259
+ /**
260
+ * keychainReadStrict, without holding up the process while `security` answers (or waits on a Keychain prompt), and
261
+ * given up after `timeoutMs`: for the daemon, whose other work goes on meanwhile.
262
+ */
263
+ export function keychainReadStrictAsync(service, account, { timeoutMs = 20_000 } = {}) {
264
+ if (secretsFile) return new Promise((resolve, reject) => { try { resolve(secretsFile.read(HOME_DIR, service, account)); } catch (e) { reject(e); } });
265
+ return new Promise((resolve, reject) => {
266
+ execFile('security', ['find-generic-password', '-s', service, '-a', account, '-w'], { encoding: 'utf8', timeout: timeoutMs }, (e, out) => {
267
+ if (!e) return resolve(String(out).replace(/\n$/, ''));
268
+ if (e.code === 44) return resolve(null);
269
+ reject(new Error(e.killed ? 'the Keychain did not answer in time: is it unlocked, and is access to it allowed?' : `the Keychain could not be read (${e.code ?? 'error'}): is it unlocked, and is access to it allowed?`));
270
+ });
271
+ });
272
+ }
273
+
274
+ export function keychainReadStrict(service, account) {
275
+ if (secretsFile) return secretsFile.read(HOME_DIR, service, account);
276
+ try {
277
+ return execFileSync('security', ['find-generic-password', '-s', service, '-a', account, '-w'],
278
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).replace(/\n$/, '');
279
+ } catch (e) {
280
+ if (e?.status === 44) return null;
281
+ throw new Error(`the Keychain could not be read (${e?.status ?? 'error'}): is it unlocked, and is access to it allowed?`);
282
+ }
283
+ }
284
+ /**
285
+ * Keep a secret in the Keychain. It goes to `security -i` on its stdin,
286
+ * never in an argument (other processes can read those, and a failed
287
+ * command's message repeats them); a failure says so in fixed words.
288
+ * A secret with a line break (one command a line) or too long for a line is refused.
289
+ */
290
+ export function keychainWrite(service, account, secret) {
291
+ const s = String(secret ?? '');
292
+ if (!s) throw new Error('an empty password is not kept in the Keychain');
293
+ if (/[\r\n\0]/.test(s)) throw new Error('a password with a line break in it cannot be kept in the Keychain');
294
+ const line = `add-generic-password -U -s ${keychainQuote(service)} -a ${keychainQuote(account)} -w ${keychainQuote(s)}\n`;
295
+ if (Buffer.byteLength(line) > 4000) throw new Error('that password is too long to be kept in the Keychain');
296
+ if (secretsFile) { secretsFile.write(HOME_DIR, service, account, s); return; }
297
+ try {
298
+ execFileSync('security', ['-i'], { input: line, stdio: ['pipe', 'ignore', 'ignore'], timeout: 30_000 });
299
+ } catch {
300
+ throw new Error(`the Keychain did not keep the password of "${String(account).slice(0, 80)}" (is access to it allowed?)`);
301
+ }
302
+ }
303
+ /**
304
+ * A secret's bytes exactly as kept (null: there is none), for moving it: `security -w` may say a value in hex, and
305
+ * text that looks like hex is then not told from hex. `-g` says which it is: `password: "…"` for printable text,
306
+ * `password: 0x… …` for anything else. Throws when it could not be read, or not read unambiguously.
307
+ */
308
+ export function keychainReadBytes(service, account) {
309
+ if (secretsFile) { const v = secretsFile.read(HOME_DIR, service, account); return v === null ? null : Buffer.from(v, 'utf8'); }
310
+ const r = spawnSync('security', ['find-generic-password', '-s', service, '-a', account, '-g'], { stdio: ['ignore', 'ignore', 'pipe'], timeout: 30_000 });
311
+ if (r.status === 44) return null;
312
+ if (r.status !== 0) throw new Error(`the Keychain could not be read (${r.status ?? 'error'}): is it unlocked, and is access to it allowed?`);
313
+ const line = r.stderr.toString('latin1').split('\n').find((l) => l.startsWith('password:'));
314
+ if (line === undefined) throw new Error('the Keychain said no value');
315
+ const rest = line.slice('password:'.length).trim();
316
+ if (rest === '') return Buffer.alloc(0);
317
+ const hex = /^0x([0-9A-Fa-f]+)(?:\s|$)/.exec(rest);
318
+ if (hex) return Buffer.from(hex[1], 'hex');
319
+ const text = /^"(.*)"$/.exec(rest);
320
+ if (text && /^[\x20-\x7e]*$/.test(text[1])) return Buffer.from(text[1], 'latin1');
321
+ throw new Error('the Keychain said the value in a form not read unambiguously');
322
+ }
323
+ /**
324
+ * The [service, account] of every generic password the Keychain (or the secrets file) holds whose service passes
325
+ * `keep`; never a value: `security dump-keychain` without -d reads the items' names alone. Throws when they cannot be listed.
326
+ */
327
+ export function keychainList(keep = () => true) {
328
+ if (secretsFile) return secretsFile.list(HOME_DIR).filter(([s]) => keep(s));
329
+ const out = execFileSync('security', ['dump-keychain'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 256 * 1024 * 1024, timeout: 60_000 });
330
+ const found = [];
331
+ let item = null;
332
+ const value = (raw) => {
333
+ const hex = /^0x([0-9A-Fa-f]*)/.exec(raw);
334
+ if (hex) return Buffer.from(hex[1], 'hex').toString('utf8').replace(/\0+$/, '');
335
+ const q = /^"(.*)"$/.exec(raw);
336
+ return q ? q[1].replace(/\\([0-7]{3})/g, (_, o) => String.fromCharCode(parseInt(o, 8))).replace(/\\(.)/g, '$1') : null;
337
+ };
338
+ const done = () => { if (item?.genp && typeof item.svce === 'string' && typeof item.acct === 'string' && keep(item.svce)) found.push([item.svce, item.acct]); };
339
+ for (const line of out.split('\n')) {
340
+ if (line.startsWith('keychain: ')) { done(); item = {}; continue; }
341
+ if (!item) continue;
342
+ if (/^class: "genp"/.test(line) || /^class: 0x00000000/.test(line)) item.genp = true;
343
+ const m = /^\s*"(svce|acct)"<blob>=(.*)$/.exec(line);
344
+ if (m) item[m[1]] = value(m[2].trim());
345
+ }
346
+ done();
347
+ return found;
348
+ }
349
+ /** A word of a `security -i` line: in double quotes, a backslash before each " and \\. */
350
+ export const keychainQuote = (v) => `"${String(v).replace(/[\\"]/g, (c) => `\\${c}`)}"`;
351
+ /** Gone, or false when there was none. */
352
+ export function keychainDelete(service, account) {
353
+ if (secretsFile) return secretsFile.remove(HOME_DIR, service, account);
354
+ try {
355
+ execFileSync('security', ['delete-generic-password', '-s', service, '-a', account], { stdio: 'ignore' });
356
+ return true;
357
+ } catch (e) {
358
+ if (e?.status === 44) return false;
359
+ throw Object.assign(new Error(`the Keychain entry of "${String(account).slice(0, 80)}" could not be removed (${e?.status ?? 'error'})`), { status: e?.status });
360
+ }
361
+ }
362
+
363
+ export function keychainGet(account) {
364
+ const v = keychainRead(KEYCHAIN_SERVICE, account);
365
+ return v === null ? null : v.trim();
366
+ }
367
+ /**
368
+ * keychainGet, telling "there is none" (null: `security` exit 44) from "it could not be read"
369
+ * (a locked Keychain, access refused, `security` failing: a throw), for a caller that must not
370
+ * take a failed read for an absence.
371
+ */
372
+ export function keychainGetStrict(account) {
373
+ if (secretsFile) return secretsFile.read(HOME_DIR, KEYCHAIN_SERVICE, account)?.trim() ?? null;
374
+ try {
375
+ return execFileSync('security', ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', account, '-w'],
376
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).replace(/\n$/, '').trim();
377
+ } catch (e) {
378
+ if (e?.status === 44) return null;
379
+ throw new Error(`the Keychain could not be read (${e?.status ?? 'error'})`);
380
+ }
381
+ }
382
+
383
+ export function keychainSet(account, password) {
384
+ keychainWrite(KEYCHAIN_SERVICE, account, password);
385
+ }
386
+
387
+ export function keychainHas(account) {
388
+ return keychainGet(account) !== null;
389
+ }
390
+
391
+ /**
392
+ * An account's credentials: { username, domain, password } (src/credentials.js
393
+ * has how each source is read, cached and refreshed). forceRefresh: after an
394
+ * auth failure, read the source again rather than the Keychain cache.
395
+ */
396
+ export async function getCredentials(config, account, forceRefresh = false) {
397
+ return (await import('./credentials.js')).getCredentials(config, account, forceRefresh);
398
+ }
399
+
400
+ export function loadRulesDoc() {
401
+ if (!fs.existsSync(RULES_PATH)) return { rules: [], quietHours: { enabled: false } };
402
+ const doc = YAML.parse(fs.readFileSync(RULES_PATH, 'utf8')) || {};
403
+ return {
404
+ rules: (doc.rules || []).filter((r) => r && r.enabled !== false),
405
+ quietHours: doc.quietHours || { enabled: false }
406
+ };
407
+ }
408
+
409
+ export function loadState() {
410
+ try {
411
+ return JSON.parse(fs.readFileSync(STATE_PATH, 'utf8'));
412
+ } catch {
413
+ return { seenIds: [], baselined: false };
414
+ }
415
+ }
416
+
417
+ export function saveState(state) {
418
+ ensureDirs();
419
+ fs.writeFileSync(STATE_PATH, JSON.stringify(state, null, 2) + '\n');
420
+ }