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/bin/sideora.js CHANGED
@@ -1,19 +1,2437 @@
1
1
  #!/usr/bin/env node
2
- // sideora 0.0.1: the name, and what is coming. It does nothing else yet.
2
+ // sideora — Sideora's command line: mail, calendar, the background service, the web app, the MCP server.
3
3
 
4
- import { readFileSync } from 'node:fs';
4
+ import { EXTENSION_ID } from '../src/extension-id.js';
5
+ import * as systemd from '../src/host/systemd.js';
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import os from 'node:os';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { execFileSync, spawn } from 'node:child_process';
11
+ import {
12
+ HOME_DIR, HOME_ENV, keychainRead, CONFIG_PATH, RULES_PATH, MCP_CONFIG_PATH, LOG_DIR, SOUNDS_DIR,
13
+ DEFAULT_CONFIG, ACCOUNT_DEFAULTS, DEFAULT_ACCOUNT,
14
+ ensureDirs, loadConfig, saveConfig, accountNames, getAccount, keychainHas, keychainSet, calendarProvider,
15
+ CREDENTIAL_SOURCES, credentialsOf, isOnePassword, passwordSource } from '../src/config.js';
16
+ import { withAuthRetry, findAcross, readMessage, saveAttachments, replyTo, selectAccounts, splitId, prepareBody, awaitingReply, getThread } from '../src/core.js';
17
+ import { stableNode } from '../src/web-service.js';
5
18
 
6
- const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
7
- const arg = process.argv[2];
19
+ const SELF = fileURLToPath(import.meta.url);
20
+ const PLIST_LABEL = 'com.sideora.daemon';
21
+ const PLIST_PATH = path.join(os.homedir(), 'Library/LaunchAgents', PLIST_LABEL + '.plist');
22
+ /** How the background watcher stands as a service: launchd's job on the Mac, a systemd user unit on Linux. */
23
+ function daemonState() {
24
+ if (systemd.isLinux) return systemd.state('daemon');
25
+ if (!fs.existsSync(PLIST_PATH)) return { installed: false };
26
+ try {
27
+ const out = execFileSync('launchctl', ['list', PLIST_LABEL], { encoding: 'utf8' });
28
+ return { installed: true, loaded: true, pid: Number(out.match(/"PID"\s*=\s*(\d+)/)?.[1]) || null };
29
+ } catch { return { installed: true, loaded: false, pid: null }; }
30
+ }
31
+ const LAST_LIST_PATH = path.join(HOME_DIR, 'last-list.json');
32
+ const LAST_CAL_PATH = path.join(HOME_DIR, 'last-calendar.json');
33
+ /** Where your own sounds go, as said to you (~ for the home directory). */
34
+ const SOUNDS_SHOWN = SOUNDS_DIR.startsWith(os.homedir() + path.sep) ? '~' + SOUNDS_DIR.slice(os.homedir().length) : SOUNDS_DIR;
35
+
36
+ const EXAMPLE_RULES = `# Sideora rules. A mail alerts on the FIRST matching rule.
37
+ # senders / subjects: comma-separated, case-insensitive substrings.
38
+ # Senders match the display name OR the email address.
39
+ # sound: alarm | chime | ding | message | false
40
+ # wake: omit it for sound+notification only; add it to launch a Claude agent.
41
+ # account: optional — only watch this account (default: all accounts).
42
+
43
+ quietHours:
44
+ enabled: false
45
+ start: "18:00"
46
+ end: "08:00"
47
+
48
+ rules:
49
+ - name: Important sender (example — edit me)
50
+ enabled: false
51
+ senders: someone@example.com, Their Display Name
52
+ subjects: urgent, deploy
53
+ sound: alarm
54
+ notify: true
55
+ # wake: # uncomment to launch a Claude agent on match
56
+ # model: sonnet
57
+ # # prompt: | # optional — omit to use the built-in digest+draft prompt
58
+ # # Custom instructions... ({{from}}, {{subject}}, {{id}} are substituted)
59
+ `;
60
+
61
+ // --- output helpers -----------------------------------------------------------
62
+
63
+ const cmd = process.argv[2];
64
+ const args = process.argv.slice(3);
65
+ const asJson = args.includes('--json') || cmd === undefined && process.argv.includes('--json');
66
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR && !asJson;
67
+
68
+ const paint = (code, s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : s);
69
+ const dim = (s) => paint('2', s);
70
+ const bold = (s) => paint('1', s);
71
+ const cyan = (s) => paint('36', s);
72
+ const green = (s) => paint('32', s);
73
+ const yellow = (s) => paint('33', s);
74
+ const red = (s) => paint('31', s);
75
+
76
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
77
+
78
+ function fmtDate(iso) {
79
+ const d = new Date(iso);
80
+ if (isNaN(d)) return String(iso).slice(0, 16);
81
+ const pad = (n) => String(n).padStart(2, '0');
82
+ const base = `${MONTHS[d.getMonth()]} ${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
83
+ return d.getFullYear() === new Date().getFullYear() ? base : `${base} ${d.getFullYear()}`;
84
+ }
85
+
86
+ // Spinner on stderr while a network call runs (TTY only, never with --json).
87
+ async function spin(label, promise) {
88
+ if (!process.stderr.isTTY || asJson) return promise;
89
+ const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
90
+ let i = 0;
91
+ const draw = () => process.stderr.write(`\r${cyan(frames[i++ % frames.length])} ${dim(label)}`);
92
+ draw();
93
+ const timer = setInterval(draw, 80);
94
+ try {
95
+ return await promise;
96
+ } finally {
97
+ clearInterval(timer);
98
+ process.stderr.write('\r\x1b[2K');
99
+ }
100
+ }
101
+
102
+ function flag(name) {
103
+ const i = args.indexOf('--' + name);
104
+ return i >= 0 && args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : null;
105
+ }
106
+
107
+ function flagAll(name) {
108
+ const values = [];
109
+ args.forEach((a, i) => {
110
+ if (a === '--' + name && args[i + 1] && !args[i + 1].startsWith('--')) values.push(args[i + 1]);
111
+ });
112
+ return values;
113
+ }
114
+
115
+ function searchOptsFromArgs() {
116
+ const days = flag('days');
117
+ return {
118
+ limit: Number(flag('limit')) || 25,
119
+ unreadOnly: args.includes('--unread'),
120
+ folder: flag('folder') || 'inbox',
121
+ live: args.includes('--live'),
122
+ senderContains: flag('from') || undefined,
123
+ subjectContains: flag('subject') || undefined,
124
+ text: flagAll('text').length ? flagAll('text') : undefined,
125
+ hasAttachments: args.includes('--attachments') || undefined,
126
+ toContains: flag('to') || undefined,
127
+ fromMe: args.includes('--from-me') || undefined,
128
+ sinceIso: flag('since') ? new Date(flag('since')).toISOString() : days ? new Date(Date.now() - Number(days) * 86400e3).toISOString() : undefined,
129
+ untilIso: flag('until') ? new Date(flag('until')).toISOString() : undefined
130
+ };
131
+ }
132
+
133
+ async function awaiting() {
134
+ const days = Number(flag('days')) || 28;
135
+ const r = await spin('sweeping inbox and sent items…', awaitingReply({
136
+ days, account: flag('account'), limit: Number(flag('limit')) || 50,
137
+ includeCc: !args.includes('--no-cc'), since: flag('since') || undefined, onError: warnAccount
138
+ }));
139
+ ensureDirs();
140
+ fs.writeFileSync(LAST_LIST_PATH, JSON.stringify(r.threads.map((t) => ({ id: t.lastMessageId, changeKey: t.changeKey }))));
141
+ if (asJson) return console.log(JSON.stringify(r, null, 2));
142
+ if (!r.threads.length) return console.log(dim(`nothing waiting on you (${r.scanned.inbound} inbound, ${r.scanned.sent} sent, last ${days} days)`));
143
+ const width = process.stdout.columns || 120;
144
+ let accounts = [];
145
+ try { accounts = accountNames(loadConfig()); } catch {}
146
+ const acctWidth = accounts.length > 1 ? Math.min(10, Math.max(...accounts.map((a) => a.length))) + 1 : 0;
147
+ r.threads.forEach((t, idx) => {
148
+ const n = dim(('#' + (idx + 1)).padStart(3));
149
+ const date = dim(fmtDate(t.received).padEnd(13));
150
+ const from = cyan(String(t.from || '?').slice(0, 22).padEnd(22));
151
+ const acct = acctWidth ? yellow(String(t.account).slice(0, acctWidth - 1).padEnd(acctWidth)) : '';
152
+ const marks = `${t.askedSomething ? paint('35', '?') : ' '}${t.addressed === 'cc' ? dim('cc') : t.addressed === 'unknown' ? dim('??') : ' '}`;
153
+ const room = Math.max(20, width - (3 + 4 + 14 + 23 + acctWidth + 6));
154
+ let subject = t.subject;
155
+ if (subject.length > room) subject = subject.slice(0, room - 1) + '…';
156
+ if (!t.isRead) subject = bold(subject);
157
+ console.log(` ${marks} ${n} ${date} ${acct}${from} ${subject}`);
158
+ const extra = [];
159
+ if (t.myLastReplyAt) extra.push(`you replied ${fmtDate(t.myLastReplyAt)}, ${t.theirsSinceMyLast} since`);
160
+ else if (t.messages > 1) extra.push(`${t.messages} messages, none from you`);
161
+ if (t.snippet) extra.push(t.snippet.slice(0, Math.max(30, width - 14)));
162
+ if (extra.length) console.log(dim(` ${extra.join(' · ')}`));
163
+ if (args.includes('--ids')) console.log(dim(` id: ${t.lastMessageId}`));
164
+ });
165
+ console.log(dim(`\n ${r.threads.length} thread(s) waiting on you · ${r.scanned.inbound} inbound / ${r.scanned.sent} sent scanned, last ${days} days · ${paint('35', '?')} = asked something · reply with: sideora reply #<n>`));
166
+ }
167
+
168
+ async function thread() {
169
+ const token = args[0] && !args[0].startsWith('--') ? args[0] : null;
170
+ const subject = flag('subject');
171
+ if (!token && !subject) throw new Error('usage: sideora thread #N | <id> | --subject S [--days 14] [--account A]');
172
+ let id;
173
+ if (token) {
174
+ id = resolveId(token);
175
+ if (!splitId(id).account) id = `${getAccount(loadConfig(), flag('account')).name}:${id}`;
176
+ }
177
+ const items = await spin('collecting the thread…', getThread({ id, subject, days: Number(flag('days')) || 14, account: flag('account'), onError: warnAccount }));
178
+ if (asJson) return console.log(JSON.stringify(items, null, 2));
179
+ ensureDirs();
180
+ fs.writeFileSync(LAST_LIST_PATH, JSON.stringify(items.map((i) => ({ id: i.id, changeKey: i.changeKey }))));
181
+ if (!items.length) return console.log(dim('(no messages in that thread)'));
182
+ items.forEach((m, idx) => {
183
+ const n = dim(('#' + (idx + 1)).padStart(3));
184
+ const who = m.folder === 'sent' ? green('me → ' + (m.displayTo || '?')) : cyan(m.fromName || m.fromEmail || '?');
185
+ console.log(` ${n} ${dim(fmtDate(m.received).padEnd(13))} ${who}${m.folder === 'sent' ? '' : ' ' + dim(m.subject || '')}`);
186
+ if (args.includes('--ids')) console.log(dim(` id: ${m.id}`));
187
+ });
188
+ console.log(dim(`\n ${items.length} message(s), oldest first — read one with: sideora read #<n>`));
189
+ }
190
+
191
+ function printItems(items) {
192
+ // remember the listing so `read #2` works
193
+ ensureDirs();
194
+ fs.writeFileSync(LAST_LIST_PATH, JSON.stringify(items.map((i) => ({ id: i.id, changeKey: i.changeKey }))));
8
195
 
9
- if (arg === '--version' || arg === '-v') {
10
- console.log(version);
11
- } else {
12
- console.log(`sideora ${version}
196
+ if (asJson) return console.log(JSON.stringify(items, null, 2));
197
+ if (items.length === 0) return console.log(dim('(no matches)'));
198
+
199
+ const width = process.stdout.columns || 120;
200
+ const showIds = args.includes('--ids');
201
+ // account column whenever several accounts are configured (even if this
202
+ // listing happens to come from one of them)
203
+ let accounts = [];
204
+ try { accounts = accountNames(loadConfig()); } catch {}
205
+ const acctWidth = accounts.length > 1 ? Math.min(10, Math.max(...accounts.map((a) => a.length))) + 1 : 0;
206
+ items.forEach((m, idx) => {
207
+ const dot = m.isRead ? ' ' : green('●');
208
+ const n = dim(('#' + (idx + 1)).padStart(3));
209
+ const date = dim(fmtDate(m.received).padEnd(13));
210
+ const fromRaw = (m.fromName || m.fromEmail || (m.displayTo ? '→ ' + m.displayTo : '?')).slice(0, 22);
211
+ const from = cyan(fromRaw.padEnd(22));
212
+ const acct = acctWidth ? yellow(String(m.account || '').slice(0, acctWidth - 1).padEnd(acctWidth)) : '';
213
+ const prefix = 3 + 4 + 14 + 23 + acctWidth; // visible width before subject
214
+ let subject = m.subject || dim('(no subject)');
215
+ const room = Math.max(20, width - prefix - (m.hasAttachments ? 4 : 1));
216
+ if (subject.length > room) subject = subject.slice(0, room - 1) + '…';
217
+ if (!m.isRead) subject = bold(subject);
218
+ if (m.hasAttachments) subject = '📎 ' + subject;
219
+ console.log(` ${dot} ${n} ${date} ${acct}${from} ${subject}`);
220
+ if (showIds) console.log(dim(` id: ${m.id}`));
221
+ });
222
+ const cached = items.length && items.every((m) => m.cached);
223
+ console.log(dim(`\n ${items.length} message(s)${cached ? ' · from local cache (--live for the server)' : ''} — read one with: sideora read #<n>`));
224
+ }
225
+
226
+ function resolveId(token) {
227
+ if (/^#?\d+$/.test(token)) {
228
+ const n = Number(token.replace('#', ''));
229
+ let cache = [];
230
+ try { cache = JSON.parse(fs.readFileSync(LAST_LIST_PATH, 'utf8')); } catch {}
231
+ if (!cache[n - 1]) throw new Error(`no #${n} in the last listing — run sideora list/search first`);
232
+ return cache[n - 1].id;
233
+ }
234
+ return token;
235
+ }
236
+
237
+ function help() {
238
+ console.log(`${bold('sideora')} — your mail, calendar, notes and assistant, on this computer
239
+
240
+ ${bold('sideora')} inbox at a glance (newest 15)
241
+ ${bold('ui')} interactive inbox (TUI): browse, search, read — live-updating
242
+ ${bold('status')} daemon / last check / credentials health
243
+ ${bold('doctor')} check the whole setup and say what to fix
244
+ ${bold('list')} [--unread] [--folder F] [--limit N]
245
+ ${bold('search')} [--from X] [--subject Y] [--text Z] [--to X] [--from-me] [--since D] [--until D] [--attachments] [--days N] [--unread] [--folder F] [--limit N]
246
+ ${bold('awaiting')} [--days 28] [--account A] [--no-cc] [--since D] [--limit N] threads where the last word is theirs and I never answered
247
+ ${bold('thread')} #N | <id> | --subject S [--days 14] every message of a thread (Inbox + Sent), oldest first
248
+ ${dim('--text searches subject AND body; --attachments = only mail with files')}
249
+ ${bold('read')} #N | <id> read a message from the last listing (or by id)
250
+ ${bold('read')} --from X [--subject Y] read the newest matching message ${dim('(--plain: raw text body; links are numbered [n] and listed at the end)')}
251
+ ${bold('attachments')} #N | <id> [--save [DIR]] [--only NAME] list a mail's attachments / download them (default DIR: ~/Downloads)
252
+ ${bold('reply')} #N | <id> [--all] [--body "..."] [--markdown|--html] [--send] reply (or reply-all) — draft by default; body via --body, stdin, or $EDITOR
253
+ ${bold('compose')} --to a@b[,c@d] --subject S [--cc ...] [--body "..."] [--markdown|--html] [--attach F]... [--inline IMG]... [--send]
254
+ ${dim('saves a Draft by default; --send sends it')}
255
+ ${bold('rules')} list watch rules
256
+ ${bold('rules add')} --name N --senders "a,b" [--subjects "x,y"] [--sound S] [--no-notify] [--wake [--model M]]
257
+ ${bold('rules')} rm|enable|disable <#|name>, ${bold('rules edit')} ($EDITOR), ${bold('rules quiet')} on|off [--start HH:MM --end HH:MM]
258
+ ${bold('events')} [--json] live-subscribe to daemon events (newmail, match, wake, stream, calendar, reminder)
259
+ ${bold('events --wait')} [--after N] [--timeout S] [--all] [--account A] [--rule R] [--types newmail,reminder,calendar]
260
+ block until the next event (default: rule matches only), print it, exit
261
+ ${dim('exit 0 = got one, 3 = timeout; --json for {events, cursor}; events cursor = current cursor')}
262
+ ${bold('calendar')} [--days N | --from D --to D] [--calendar NAME|email] agenda (default: today → +7 days) ${dim('alias: cal')}
263
+ ${bold('calendar calendars')} list your calendars (${dim('--mailbox a@b: is that person\'s calendar shared with you?')})
264
+ ${bold('calendar show')} #N | <id> one event in full (attendees, responses, body)
265
+ ${bold('microsoft-login')} [--label X] [--port N] [--no-open] add a Microsoft 365 / Outlook.com mailbox (or sign one in again): Microsoft's page, then back here (over SSH: forward the port, ssh -L N:127.0.0.1:N)
266
+ ${bold('google-login')} <account> sign in to Google for a google calendar account: calendar and contacts (browser, PKCE; tokens in Keychain)
267
+ ${bold('calendar create')} --subject S --start D [--end D | --duration 30m] [--location L] [--body B] [--attendees a,b] [--all-day] [--reminder N] [--calendar C]
268
+ ${bold('calendar update')} #N | <id> [--subject S] [--start D] [--end D] [--location L] [--body B] [--reminder N]
269
+ ${bold('calendar delete')} #N | <id> remove it (sends cancellations when you organise the meeting)
270
+ ${bold('calendar accept|tentative|decline')} #N | <id> [--message M] [--no-notify]
271
+ ${bold('calendar freebusy')} a@b[,c@d] [--from D --to D] [--interval 30] who is busy when (anyone in the organisation)
272
+ ${bold('calendar free')} a@b[,c@d] [--duration 30m] [--days 5] [--hours 9-18] [--weekends] [--tentative-ok] common free slots
273
+ ${dim('dates: 2026-10-22 14:00, "tomorrow 9am", friday, +2d — --no-notify on create/update/delete keeps attendees uninformed')}
274
+ ${bold('logs')} [-f] [--lines N] show the daemon log, colorized (-f follows)
275
+ ${bold('sounds')} [all | set <alert> <Sound[:N]> | gen "<text>" [--tts]] hear / change / generate alert sounds
276
+ ${bold('watch')} run the watch loop in the foreground
277
+ ${bold('install')} [--port N] [--no-admin] [--no-open] [--pair] [--here] everything, to be set up from the browser: the background watcher, the web app, and a link that makes this browser its owner
278
+ ${bold('migrate')} move an install from before the rename (~/.mailwatcher) to Sideora's names
279
+ ${bold('install-daemon')} / ${bold('restart-daemon')} / ${bold('uninstall-daemon')} launchd background watcher
280
+ ${bold('mcp')} run the MCP server (stdio) for agents
281
+ ${bold('install-mcp')} register that server in Claude Code (all projects) — then just ask Claude about your mail
282
+ ${bold('install-extension')} / ${bold('uninstall-extension')} let the Chrome side-panel extension (extension/) reach your mail — native messaging, no port
283
+ ${bold('relay')} join <url> <invitation> | relay pair [--limited] | relay devices | relay admin <id> [off] | relay request <url> --name N --email E | relay confirm <code> | relay forget <id|all> | relay move <url> | relay leave the web app from another device, through a relay that forwards what it cannot read
284
+ ${bold('web')} [--port N] [--open] [--no-admin] | web pair | web sessions | web forget <id|all> the same app as a page in any browser on this computer; a browser is paired once, from here
285
+ ${bold('web install')} [--port N] [--no-admin] [--here] | web restart | web uninstall the web app as a service of this Mac: started at login, started again if it stops
286
+ ${bold('export')} <file> [--no-secrets] [--with-relay] what lives only on this Mac (settings, accounts and their passwords, rules, notes, chats, AI connections) as one file sealed under a passphrase
287
+ ${bold('import')} <file> [--replace] [--dry-run] [--yes] put an export's content here: what is missing is added, what is here stays (--replace: the file's instead)
288
+ ${bold('setup')} [name] add or edit an account (ews or imap)
289
+ ${bold('accounts')} [rm <name>] list configured accounts / remove one
290
+ ${bold('op-token')} set | clear a 1Password service account's token, kept in the Keychain ${dim('(set reads it from stdin or a hidden prompt, never an argument)')}
291
+ ${bold('cache')} [clear | prune] local encrypted mail cache: stats / wipe / drop old rows
292
+ ${bold('test')} [--account A] connectivity check (all accounts by default)
293
+
294
+ ${bold('completion')} zsh|bash print a shell completion script
295
+
296
+ Folders: ${dim('inbox (default), junk, sent, drafts, trash, archive')}
297
+ Options: ${dim('--json (machine-readable output on list/search/read), --ids (show full ids)')}
298
+ ${dim('--account NAME on list/search/compose/test/rules add — with several accounts, listings merge all of them')}
299
+ ${dim('--live on list/search/read — ask the server instead of the local cache')}
300
+ Rules: ${dim(RULES_PATH)}`);
301
+ }
302
+
303
+ // --- dispatch -----------------------------------------------------------------
304
+
305
+ try {
306
+ // an install from before the rename, and nothing under the new name yet: said, rather than started empty
307
+ if (!['migrate', 'install', 'help', '--help', '-h', 'completion'].includes(cmd) && (await import('../src/migrate.js')).pendingMigration()) {
308
+ throw new Error((await import('../src/migrate.js')).PENDING_MESSAGE);
309
+ }
310
+ switch (cmd) {
311
+ case undefined: await inboxDefault(); break;
312
+ case 'setup': await setup(); break;
313
+ case 'accounts': await accounts(); break;
314
+ case 'op-token': await opToken(); break;
315
+ case 'cache': await cacheCmd(); break;
316
+ case 'ui': case 'tui': await (await import('../src/tui.js')).runTui(); break;
317
+ case 'test': await test(); break;
318
+ case 'status': await status(); break;
319
+ case 'doctor': await doctor(); break;
320
+ case 'list': await list(); break;
321
+ case 'search': await search(); break;
322
+ case 'read': await read(); break;
323
+ case 'awaiting': await awaiting(); break;
324
+ case 'google-login': await googleLogin(); break;
325
+ case 'microsoft-login': await microsoftLogin(); break;
326
+ case 'thread': await thread(); break;
327
+ case 'attachments': case 'attach': case 'save': await attachments(); break;
328
+ case 'compose': await compose(); break;
329
+ case 'reply': await reply(); break;
330
+ case 'rules': await rules(); break;
331
+ case 'events': await events(); break;
332
+ case 'calendar': case 'cal': await calendar(); break;
333
+ case 'logs': await logs(); break;
334
+ case 'sounds': await sounds(); break;
335
+ case 'watch': {
336
+ {
337
+ // the service's job is this very process when the daemon starts itself
338
+ const { pid } = daemonState();
339
+ if (pid && pid !== process.pid && pid !== process.ppid) console.error(yellow('note:') + ' the background daemon is running too — two watchers will double-alert. Stop it first with: sideora uninstall-daemon');
340
+ }
341
+ (await import('../src/daemon.js')).runDaemon();
342
+ break;
343
+ }
344
+ case 'mcp': await (await import('../src/mcp-server.js')).runMcpServer(); break;
345
+ case 'install-mcp': installMcp(); break;
346
+ case 'bridge': (await import('../src/bridge.js')).runBridge(); break;
347
+ case 'web': await web(); break;
348
+ // what lives only on this Mac, as one sealed file: from here alone (no page, no relay, no agent's tool)
349
+ case 'export': await (await import('../src/backup-cli.js')).exportCmd(args); break;
350
+ case 'import': await (await import('../src/backup-cli.js')).importCmd(args); break;
351
+ case 'relay': await relayCmd(); break;
352
+ case 'install-extension': installExtension(); break;
353
+ case 'uninstall-extension': uninstallExtension(); break;
354
+ case 'install': await installAll(); break;
355
+ case 'migrate': await migrateCmd(); break;
356
+ case 'install-daemon': installDaemon(); break;
357
+ case 'uninstall-daemon': uninstallDaemon(); break;
358
+ case 'restart-daemon': case 'restart': uninstallDaemon(); installDaemon(); break;
359
+ case 'completion': completion(); break;
360
+ case 'help': case '--help': case '-h': help(); break;
361
+ default:
362
+ help();
363
+ process.exit(1);
364
+ }
365
+ } catch (e) {
366
+ console.error(yellow('Error:'), e.message);
367
+ process.exit(1);
368
+ }
369
+
370
+ async function inboxDefault() {
371
+ if (!fs.existsSync(CONFIG_PATH)) {
372
+ console.log(`${yellow('Welcome!')} No configuration yet — start with:\n`);
373
+ console.log(` ${bold('sideora setup')}\n`);
374
+ console.log(dim('Then: sideora doctor → sideora test → sideora install-daemon'));
375
+ console.log(dim('Full usage: sideora help'));
376
+ return;
377
+ }
378
+ printItems(await spin(fetching(flag('account')), findAcross(flag('account'), { limit: 15, live: args.includes('--live') }, warnAccount)));
379
+ }
380
+
381
+ function fetching(account) {
382
+ return account ? `fetching ${account}…` : 'fetching all accounts…';
383
+ }
384
+
385
+ function warnAccount(name, e) {
386
+ console.error(yellow(`(account "${name}" skipped: ${String(e.message).split('\n')[0]})`));
387
+ }
388
+
389
+ async function setup() {
390
+ ensureDirs();
391
+ const cfg = fs.existsSync(CONFIG_PATH) ? loadConfig() : { ...DEFAULT_CONFIG, accounts: {} };
392
+ const names = accountNames(cfg);
393
+ let name = args[0] && !args[0].startsWith('--') ? args[0] : null;
394
+
395
+ console.log(bold('Sideora setup') + dim(' — press Enter to keep the [default], type - to clear it\n'));
396
+ if (process.stdin.isTTY) {
397
+ const rl = (await import('node:readline/promises')).createInterface({ input: process.stdin, output: process.stdout });
398
+ const ask = async (q, def) => { const a = (await rl.question(` ${q}${def ? dim(` [${def}]`) : ''}: `)).trim(); return a === '-' ? '' : a || def || ''; }; // "-" clears a default
399
+ if (!name) {
400
+ if (names.length) console.log(dim(' existing accounts: ' + names.join(', ') + ' — name one to edit it, or a new name to add one'));
401
+ name = await ask('Account name', names.length ? names[0] : DEFAULT_ACCOUNT);
402
+ }
403
+ if (!/^[\w.-]+$/.test(name)) throw new Error('account names are letters, digits, . _ - only');
404
+ const existing = cfg.accounts[name] || {};
405
+ const provider = (await ask('Provider (ews = Exchange/OWA, imap = any IMAP mailbox, caldav = iCloud/Fastmail/CalDAV calendar, google = Google Calendar)', existing.provider || 'ews')).toLowerCase();
406
+ if (!ACCOUNT_DEFAULTS[provider]) throw new Error(`unknown provider "${provider}" — use ews, imap, caldav or google`);
407
+ const acct = { ...ACCOUNT_DEFAULTS[provider], ...existing, provider };
408
+ delete acct.onePassword; // the older shape: its item is asked for below, as a reference
409
+ if (provider === 'google') {
410
+ acct.email = await ask('Google account address', existing.email);
411
+ rl.close();
412
+ delete acct.name;
413
+ cfg.accounts[name] = acct;
414
+ saveConfig(cfg);
415
+ console.log('✓ wrote', CONFIG_PATH, dim(`(account "${name}")`));
416
+ console.log(`\nNow sign in: ${bold('sideora google-login ' + name)}`);
417
+ return;
418
+ }
419
+ if (provider === 'caldav') {
420
+ const service = (await ask('Service (icloud, fastmail, other)', existing.service || 'icloud')).toLowerCase();
421
+ acct.service = service;
422
+ if (service === 'other' || !['icloud', 'fastmail'].includes(service)) acct.server = await ask('CalDAV server URL (e.g. https://cloud.example.org/remote.php/dav/)', existing.server);
423
+ acct.email = await ask('Your address on that calendar (for invitations and replies)', existing.email);
424
+ acct.username = await ask('Sign-in name (iCloud: your Apple ID; Fastmail: your address)', existing.username || acct.email);
425
+ console.log(dim(' use an app-specific password: iCloud → account.apple.com → App-Specific Passwords; Fastmail → Settings → Privacy & Security → Integrations'));
426
+ } else if (provider === 'ews') {
427
+ acct.host = await ask('Exchange/OWA server URL', existing.host);
428
+ acct.username = await ask('Username (DOMAIN\\user; blank = the 1Password item\'s username)', existing.username);
429
+ } else {
430
+ acct.email = await ask('Your email address (login + From)', existing.email);
431
+ acct.imap = { ...ACCOUNT_DEFAULTS.imap.imap, ...(existing.imap || {}) };
432
+ acct.imap.host = await ask('IMAP host', existing.imap?.host || guessHost('imap', acct.email));
433
+ acct.imap.port = Number(await ask('IMAP port (993 = TLS)', String(existing.imap?.port || 993)));
434
+ acct.imap.secure = acct.imap.port === 993 || /^y/i.test(await ask('IMAP implicit TLS? (y/n)', acct.imap.port === 993 ? 'y' : 'n'));
435
+ acct.smtp = { ...ACCOUNT_DEFAULTS.imap.smtp, ...(existing.smtp || {}) };
436
+ acct.smtp.host = await ask('SMTP host (blank = drafts only, no sending)', existing.smtp?.host || guessHost('smtp', acct.email));
437
+ if (acct.smtp.host) {
438
+ acct.smtp.port = Number(await ask('SMTP port (587 = STARTTLS, 465 = TLS)', String(existing.smtp?.port || 587)));
439
+ acct.smtp.secure = acct.smtp.port === 465;
440
+ }
441
+ acct.username = await ask('Login username if different from the email (blank = email)', existing.username);
442
+ }
443
+ if (provider !== 'caldav') {
444
+ const cacheOn = /^y/i.test(await ask('Cache mail locally? (encrypted SQLite, inbox headers + new bodies; y/n)', existing.cache?.enabled === false ? 'n' : 'y'));
445
+ acct.cache = { ...(existing.cache || {}), enabled: cacheOn };
446
+ if (cacheOn) acct.cache.days = Number(await ask('Keep cached mail for how many days', String(existing.cache?.days || 30))) || 30;
447
+ }
448
+ acct.credentials = await askCredentials(rl, ask, name, acct, credentialsOf(existing));
449
+ if (cfg.accounts[name]) {
450
+ // its credentials or where it signs in changed: what was noted of its reads, and a password cached from 1Password, go
451
+ const { credIdentity, forgetCachedPassword } = await import('../src/credentials.js');
452
+ const was = cfg.accounts[name];
453
+ if ((isOnePassword(credentialsOf(was)) || isOnePassword(acct.credentials)) && credIdentity(was) !== credIdentity({ ...acct, name })) {
454
+ forgetCachedPassword(name);
455
+ console.log(dim(' its credentials changed: the password cached for it was dropped'));
456
+ }
457
+ }
458
+ let password = null;
459
+ if (acct.credentials.source === 'keychain') {
460
+ const has = keychainHas(name);
461
+ password = await askSecret(rl, has ? 'Password (blank = keep the one in Keychain)' : 'Password (hidden)');
462
+ if (!password && !has) console.log(yellow(' no password stored — add it later: security add-generic-password -U -s sideora -a ' + name + ' -w'));
463
+ }
464
+ rl.close();
465
+ console.log();
466
+ if (password) {
467
+ keychainSet(name, password);
468
+ console.log('✓ password stored in Keychain (account "' + name + '")');
469
+ }
470
+ delete acct.name;
471
+ cfg.accounts[name] = acct;
472
+ if (accountNames(cfg).length > 1 && !cfg.defaultAccount) cfg.defaultAccount = names[0] || name;
473
+ } else if (names.length === 0) {
474
+ throw new Error('setup needs a terminal to ask questions — or write ' + CONFIG_PATH + ' by hand (see README)');
475
+ }
476
+ saveConfig(cfg);
477
+ console.log('✓ wrote', CONFIG_PATH, name ? dim(`(account "${name}")`) : '');
478
+
479
+ if (!fs.existsSync(RULES_PATH)) {
480
+ fs.writeFileSync(RULES_PATH, EXAMPLE_RULES);
481
+ console.log('✓ wrote', RULES_PATH, '(edit your rules there)');
482
+ } else {
483
+ console.log('• rules exist:', RULES_PATH);
484
+ }
485
+ writeMcpConfig();
486
+ console.log('✓ wrote', MCP_CONFIG_PATH);
487
+
488
+ const src = name && cfg.accounts[name] ? credentialsOf(cfg.accounts[name]) : null;
489
+ if (src && isOnePassword(src)) {
490
+ console.log(`\nCredentials: ${passwordSource(cfg.accounts[name])}, read with its secret reference (by IDs: renaming the item or its vault changes nothing).`);
491
+ if (src.source === '1password') console.log('Enable 1Password → Settings → Developer → "Integrate with 1Password CLI".');
492
+ else console.log(`The service account token is kept in the Keychain: ${bold('sideora op-token set')}.`);
493
+ console.log('The password is cached in the macOS Keychain (one entry per account) and read again when it is refused or older than passwordMaxAgeDays.');
494
+ } else if (src?.source === 'env') {
495
+ console.log(`\nCredentials: read from ${passwordSource(cfg.accounts[name])} of whatever runs Sideora (the daemon's launchd job too).`);
496
+ } else if (name) {
497
+ console.log(dim(`\nThe password is in the Keychain. Store it again by hand: security add-generic-password -U -s sideora -a ${name} -w`));
498
+ }
499
+ console.log();
500
+ console.log('Next steps:');
501
+ console.log(' sideora install-mcp # let Claude Code use your mail (ask it to watch for mail, draft replies…)');
502
+ console.log(' sideora doctor # check the whole setup');
503
+ console.log(' sideora test # verify connectivity (1Password asks to authorize once)');
504
+ console.log(' sideora op-token set # a 1Password service account: store its token (read from stdin, never an argument)');
505
+ console.log(' sideora install-daemon # start watching in the background');
506
+ }
507
+
508
+ /**
509
+ * Where an account's password comes from, asked: keychain (typed next),
510
+ * 1password / 1password-service (a secret reference pasted, or an item picked
511
+ * from a list; stored by IDs), env (a variable's name). → its credentials.
512
+ */
513
+ async function askCredentials(rl, ask, name, acct, now) {
514
+ const { resolveRef, listItems, getItem, itemRefs, isIdRef } = await import('../src/onepassword.js');
515
+ const { serviceTokenStored, serviceToken, ENV_NAME } = await import('../src/credentials.js');
516
+ console.log(dim(' password from: keychain (typed now), 1password (the 1Password app), 1password-service (a service account), env (an environment variable)'));
517
+ const source = (await ask('Password from', now.source || 'keychain')).toLowerCase();
518
+ if (!CREDENTIAL_SOURCES.includes(source)) throw new Error(`"${source}" is not one of ${CREDENTIAL_SOURCES.join(', ')}`);
519
+ if (source === 'keychain') return { source };
520
+ if (source === 'env') {
521
+ const env = await ask('Environment variable holding the password', now.env || `SIDEORA_${name.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_PASSWORD`);
522
+ if (!ENV_NAME.test(env)) throw new Error(`"${env}" is not an environment variable name`);
523
+ if (!process.env[env]) console.log(yellow(` ${env} is not set here: set it where Sideora runs (the daemon's launchd job included)`));
524
+ return { source, env };
525
+ }
526
+ let token = null;
527
+ if (source === '1password-service') {
528
+ if (!serviceTokenStored()) throw new Error('no 1Password service account token is stored: run sideora op-token set, then setup again');
529
+ token = serviceToken();
530
+ }
531
+ const kept = now.source === source && now.password ? now : null;
532
+ console.log(dim(' a secret reference: in 1Password, the item → its password field → Copy Secret Reference (op://vault/item/password); ? picks an item from a list'));
533
+ for (;;) {
534
+ const typed = (await ask('Secret reference of the password', kept ? kept.password : '?')).trim();
535
+ try {
536
+ let item;
537
+ let refs;
538
+ if (!typed || typed === '?') {
539
+ const all = (await listItems({ token })).sort((a, b) => a.title.localeCompare(b.title));
540
+ if (!all.length) throw new Error('1Password lists no Login or Password item');
541
+ all.forEach((it, i) => console.log(` ${String(i + 1).padStart(3)}. ${it.title} ${dim('(' + it.vault.name + ')' + (it.urls[0] ? ' ' + it.urls[0] : ''))}`));
542
+ const n = Number(await ask('Item number', ''));
543
+ const pick = all[n - 1];
544
+ if (!pick) throw new Error('no item of that number');
545
+ item = await getItem(pick.id, { vault: pick.vault.id, token });
546
+ refs = itemRefs(item, { username: true });
547
+ } else if (kept && typed === kept.password && isIdRef(typed)) {
548
+ return kept; // unchanged
549
+ } else {
550
+ const r = await resolveRef(typed, { token });
551
+ item = r.item;
552
+ let username = null;
553
+ try { username = itemRefs(item, { username: true }).username; } catch { /* a reference to a field of an item without a password */ }
554
+ refs = { password: r.ref, ...(username ? { username } : {}) };
555
+ }
556
+ const out = { source, password: refs.password, label: { item: item.title, vault: item.vault.name } };
557
+ if (refs.username) {
558
+ const take = await ask(`Sign in with the item's username? (y/n${acct.username || acct.email ? `; n = ${acct.username || acct.email}` : ''})`, acct.username ? 'n' : 'y');
559
+ if (/^y/i.test(take)) out.username = refs.username;
560
+ }
561
+ console.log(green(' ✓') + ` 1Password "${item.title}" (${item.vault.name}) ${dim(out.password)}`);
562
+ return out;
563
+ } catch (e) {
564
+ console.log(yellow(' ' + String(e.message).split('\n')[0]));
565
+ if (!process.stdin.isTTY) throw e;
566
+ }
567
+ }
568
+ }
569
+
570
+ // readline echoes keystrokes; mute its output while a secret is typed.
571
+ async function askSecret(rl, q) {
572
+ const out = rl.output;
573
+ const write = out.write.bind(out);
574
+ out.write(` ${q}: `);
575
+ rl.output.write = (chunk, ...rest) => (/\r?\n/.test(String(chunk)) ? write(chunk, ...rest) : true);
576
+ try {
577
+ return (await rl.question('')).trim();
578
+ } finally {
579
+ rl.output.write = write;
580
+ }
581
+ }
582
+
583
+ /** The MCP server as a config file (~/.sideora/mcp.json) for `claude -p --mcp-config` and other MCP clients. */
584
+ function writeMcpConfig() {
585
+ const mcp = { mcpServers: { sideora: { command: stableNode(), args: [SELF, 'mcp'], ...(HOME_ENV.SIDEORA_HOME ? { env: HOME_ENV } : {}) } } };
586
+ fs.writeFileSync(MCP_CONFIG_PATH, JSON.stringify(mcp, null, 2) + '\n');
587
+ }
588
+
589
+ /** Claude Code's command line, or null. (The one of this home folder first: a test's HOME holds a stand-in.) */
590
+ function findClaude() {
591
+ return [path.join(os.homedir(), '.local/bin/claude'), '/opt/homebrew/bin/claude', '/usr/local/bin/claude', 'claude'].find((p) => {
592
+ try { execFileSync(p === 'claude' ? 'which' : 'test', p === 'claude' ? ['claude'] : ['-x', p], { stdio: 'ignore' }); return true; } catch { return false; }
593
+ }) || null;
594
+ }
595
+
596
+ function installMcp() {
597
+ const claude = findClaude();
598
+ if (!claude) throw new Error('Claude Code CLI (claude) not found — install it first: https://claude.com/claude-code');
599
+ try { execFileSync(claude, ['mcp', 'remove', '--scope', 'user', 'sideora'], { stdio: 'ignore' }); } catch {}
600
+ // a data directory of its own (SIDEORA_HOME) goes with the server, or it would read ~/.sideora
601
+ const env = Object.entries(HOME_ENV).flatMap(([k, v]) => ['-e', `${k}=${v}`]);
602
+ execFileSync(claude, ['mcp', 'add', '--scope', 'user', ...env, 'sideora', '--', stableNode(), SELF, 'mcp'], { stdio: 'inherit' });
603
+ // ("mail": its name before the rename, taken away once the new one is there)
604
+ try { execFileSync(claude, ['mcp', 'remove', '--scope', 'user', 'mail'], { stdio: 'ignore' }); } catch {}
605
+ console.log(green('✓') + ' registered the "sideora" MCP server in Claude Code for all your projects');
606
+ console.log(dim(' Start a new Claude Code session and ask things like "what\'s unread?", "draft a reply to #2",'));
607
+ console.log(dim(' or "tell me when mail from Victor arrives" — Claude watches your inbox in the background.'));
608
+ }
609
+
610
+ // --- Chrome side-panel extension: native messaging host -----------------------
611
+ // The manifest must name an executable (no arguments allowed), so a small
612
+ // wrapper runs `sideora bridge` with the node that owns the native
613
+ // modules. Only the extension id below may connect; it is fixed by the "key"
614
+ // in extension/manifest.json, so an unpacked load always gets the same id.
615
+
616
+ // (a function, not constants: the dispatch above runs before this point is evaluated)
617
+ function extHost() {
618
+ return {
619
+ EXT_HOST: 'com.sideora.bridge',
620
+ EXT_ID: EXTENSION_ID,
621
+ EXT_WRAPPER: path.join(HOME_DIR, 'native-host.sh'),
622
+ // (where each browser keeps its profile, whose NativeMessagingHosts folder it reads: on the Mac under
623
+ // Application Support, on Linux under ~/.config, by names of their own)
624
+ EXT_BROWSERS: process.platform === 'linux'
625
+ ? { Chrome: 'google-chrome', 'Chrome Beta': 'google-chrome-beta', Chromium: 'chromium', Brave: 'BraveSoftware/Brave-Browser', Edge: 'microsoft-edge' }
626
+ : { Chrome: 'Google/Chrome', 'Chrome Beta': 'Google/Chrome Beta', Chromium: 'Chromium', Brave: 'BraveSoftware/Brave-Browser', Edge: 'Microsoft Edge' },
627
+ extHostDir: (rel) => process.platform === 'linux'
628
+ ? path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), rel, 'NativeMessagingHosts')
629
+ : path.join(os.homedir(), 'Library/Application Support', rel, 'NativeMessagingHosts')
630
+ };
631
+ }
632
+
633
+ /** Text for an XML document (the launchd plist). */
634
+ function xmlText(s) {
635
+ return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
636
+ }
637
+
638
+ /**
639
+ * The web app (src/web-server.js): `web` serves it on this computer and prints the link that pairs a browser;
640
+ * `web pair` makes another such link while it runs; `web sessions` lists the paired browsers; `web forget` ends one, or all.
641
+ */
642
+ async function web() {
643
+ const access = await import('../src/web-access.js');
644
+ const { startWebServer, DEFAULT_PORT } = await import('../src/web-server.js');
645
+ const sub = args[0] && !args[0].startsWith('--') ? args[0] : '';
646
+ const port = Number(flag('port') || process.env.SIDEORA_WEB_PORT || DEFAULT_PORT);
647
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('--port must be a port number');
648
+ const link = (at) => { const { code } = access.newPairingCode(); return `http://127.0.0.1:${at}/#pair=${code}`; };
649
+ const ago = (t) => { const m = Math.round((Date.now() - t) / 60000); return m < 1 ? 'just now' : m < 60 ? `${m} min ago` : m < 1440 ? `${Math.round(m / 60)} h ago` : `${Math.round(m / 1440)} d ago`; };
650
+
651
+ if (sub === 'pair') {
652
+ // where the server said it listens (it may not be the usual port); none noted: it is not running
653
+ const at = access.notedPort();
654
+ if (!at) throw new Error('`sideora web` is not running: start it first (it prints a pairing link itself)');
655
+ console.log(link(at));
656
+ console.log(dim(' good once, for ten minutes; open it in the browser to pair'));
657
+ return;
658
+ }
659
+ if (sub === 'sessions') {
660
+ const list = access.listSessions();
661
+ if (asJson) return void console.log(JSON.stringify(list));
662
+ if (!list.length) return void console.log(dim('no browser is paired'));
663
+ for (const s of list) console.log(`${bold(s.id)} used ${ago(s.seen)}, paired ${ago(s.created)} ${dim(s.agent)}`);
664
+ return;
665
+ }
666
+ if (sub === 'forget') {
667
+ const which = args[1];
668
+ if (!which) throw new Error('web forget <id> (see `sideora web sessions`), or `web forget all`');
669
+ const n = access.endSessions(which);
670
+ console.log(n ? green('✓') + ` ${n} browser${n === 1 ? '' : 's'} forgotten` : dim('no such session'));
671
+ return;
672
+ }
673
+ // as a service of this Mac (src/web-service.js): started at login, started again when it stops
674
+ if (sub === 'install' || sub === 'uninstall' || sub === 'restart') {
675
+ const service = await import('../src/web-service.js');
676
+ if (sub === 'uninstall') {
677
+ console.log(service.uninstallWebService() ? green('✓') + ' the web app\'s service is stopped and removed' : dim('the web app is not set up as a service'));
678
+ return;
679
+ }
680
+ if (sub === 'restart') {
681
+ service.restartWebService();
682
+ console.log(green('✓') + ' the web app\'s service is starting again ' + dim(`(${service.WEB_LOG})`));
683
+ return;
684
+ }
685
+ loadConfig(); // fail early if setup has not run
686
+ const unfit = service.unfitToStay(SELF, service.stableNode());
687
+ if (unfit && !args.includes('--here')) throw new Error(`${unfit}`);
688
+ // one at a time for a data folder: one started in a terminal is stopped first (the service would be started over and over against it)
689
+ const was = service.webServiceState();
690
+ const other = access.notedPort();
691
+ if (other && !(was.installed && was.pid)) {
692
+ const up = await fetch(`http://127.0.0.1:${other}/api/session`, { signal: AbortSignal.timeout(1500) }).then((r) => r.ok && r.json(), () => null);
693
+ if (up && typeof up.paired === 'boolean') throw new Error(`\`sideora web\` is running in a terminal, at http://127.0.0.1:${other}: stop it first (Ctrl-C there), then install the service`);
694
+ }
695
+ const asked = flag('port') || process.env.SIDEORA_WEB_PORT;
696
+ service.installWebService({ self: SELF, port: asked ? port : undefined, admin: !args.includes('--no-admin') });
697
+ // (it says where it listens once it does)
698
+ let at = null;
699
+ for (let i = 0; i < 40 && !at; i++) {
700
+ await new Promise((r) => setTimeout(r, 250));
701
+ const noted = access.notedPort();
702
+ if (noted && await fetch(`http://127.0.0.1:${noted}/api/session`, { signal: AbortSignal.timeout(1000) }).then((r) => r.ok, () => false)) at = noted;
703
+ }
704
+ if (!at) {
705
+ console.log(yellow('○') + ' the service is set up, and the web app has not answered yet: see ' + service.WEB_LOG);
706
+ return null;
707
+ }
708
+ console.log(green('✓') + ` the web app runs as a service: ${bold(`http://127.0.0.1:${at}`)} ${dim('(started at login, started again if it stops)')}`);
709
+ console.log(dim(` logs: ${service.WEB_LOG}`));
710
+ console.log(dim(' `sideora web pair` pairs a browser; `sideora web restart` after an update; `sideora web uninstall` takes it away'));
711
+ return at; // (where it answered: `sideora install` pairs a browser there)
712
+ }
713
+ if (sub) throw new Error(`unknown: web ${sub} (web, web install, web restart, web uninstall, web pair, web sessions, web forget)`);
714
+
715
+ const inService = process.env.SIDEORA_WEB_SERVICE === '1';
716
+ if (inService) {
717
+ (await import('../src/web-service.js')).trimLog();
718
+ // not set up yet: nothing to serve, and nothing to start again until it is
719
+ if (!fs.existsSync(CONFIG_PATH)) { console.log(`${new Date().toISOString()} not started: there is no configuration yet (\`sideora setup\`)`); process.exit(0); }
720
+ }
721
+ // one at a time for a data folder: two would each keep their own copy of what they write (the AI connections, the sessions)
722
+ const other = access.notedPort();
723
+ if (other) {
724
+ const up = await fetch(`http://127.0.0.1:${other}/api/session`, { signal: AbortSignal.timeout(1500) }).then((r) => r.ok && r.json(), () => null);
725
+ if (up && typeof up.paired === 'boolean') {
726
+ const asService = (await import('../src/web-service.js')).webServiceState().pid;
727
+ const said = asService && !inService
728
+ ? `the web app already runs as a service, at http://127.0.0.1:${other} (\`sideora web pair\` pairs a browser, \`sideora web restart\` starts it again, \`sideora web uninstall\` takes it away)`
729
+ : `\`sideora web\` is already running, at http://127.0.0.1:${other} (stop it first, or use it)`;
730
+ // (the service, finding another serving this data folder: it ends saying so, and is not started again over and over)
731
+ if (inService) { console.log(`${new Date().toISOString()} not started: ${said}`); process.exit(0); }
732
+ throw new Error(said);
733
+ }
734
+ }
735
+ // whatever goes wrong while it answers one request is that request's trouble, not the end of the server
736
+ process.on('unhandledRejection', (e) => { console.error(dim(` ${new Date().toISOString()} (an error while answering: ${e?.message || e})`)); });
737
+ // (a person's own server: its accounts are set up from its page too, unless it was started with --no-admin;
738
+ // --admin, of before, is what it does anyway)
739
+ const admin = !args.includes('--no-admin');
740
+ // (its ops, and the relay's, asked of the daemon's hub when it runs: what they keep is then written by one process)
741
+ const { OPS } = await import('../src/panel-ops.js');
742
+ const { viaHub, hubClient } = await import('../src/hub.js');
743
+ // (no 100 s limit as for the extension, which gives up at 90 s: a page waits as long as it did when this process did it)
744
+ const hub = hubClient({ callMs: 15 * 60_000 });
745
+ const ops = viaHub(OPS, hub);
746
+ const server = await startWebServer({ port, admin, ops });
747
+ const { keepConnections, closeConnections } = await import('../src/core.js');
748
+ keepConnections();
749
+ access.notePort(server.port);
750
+ // As a service its words go to a log: no pairing link is written there (a link is asked for when a browser is to
751
+ // be paired: `sideora web pair`), and each line says when.
752
+ const service = process.env.SIDEORA_WEB_SERVICE === '1'; // (said by its LaunchAgent: words sent to a file or a pipe from a terminal are a person's still)
753
+ if (service) {
754
+ console.log(`${new Date().toISOString()} Sideora is at ${server.url}${admin ? '' : ' (--no-admin)'}, pid ${process.pid}`);
755
+ } else {
756
+ const first = link(server.port);
757
+ console.log(green('✓') + ` Sideora is at ${bold(server.url)} ${dim('(this computer only; Ctrl-C stops it)')}`);
758
+ console.log(dim(admin ? ' accounts can be added and changed from the page (`--no-admin` keeps that to this computer\'s terminal and the extension)' : ' accounts are set up here, not from the page (--no-admin): `sideora setup`, or the extension'));
759
+ console.log(` Pair a browser: ${cyan(first)}`);
760
+ console.log(dim(' that link is good once, for ten minutes; `sideora web pair` makes another, `sideora web sessions` lists who is paired'));
761
+ console.log(dim(' to keep it running without this terminal: `sideora web install`'));
762
+ if (args.includes('--open')) spawn(process.platform === 'darwin' ? 'open' : 'xdg-open', [first], { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
763
+ }
764
+ // joined to a relay: the same app from another device, through it (src/relay.js). The membership is followed:
765
+ // joined, moved or left from Settings (or a terminal) meanwhile, the connection follows, and says how it stands
766
+ // for Settings to show (src/relay-settings.js)
767
+ const relay = await import('../src/relay.js');
768
+ const { noteStatus } = await import('../src/relay-settings.js');
769
+ const at = () => new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
770
+ let afar = null;
771
+ let held = null;
772
+ let failed = 0; // attempts that failed in a row, for this membership
773
+ let retryAt = 0;
774
+ const membership = () => { const s = relay.readState(); return s ? `${s.url} ${s.instance}` : ''; };
775
+ const follow = async () => {
776
+ const now = membership();
777
+ if (now === held) return;
778
+ if (held === null && now && Date.now() < retryAt) return; // (it failed a moment ago: tried again a little later)
779
+ const first = held === null;
780
+ held = now;
781
+ if (afar) { afar.stop(); afar = null; console.log(dim(` ${at()} relay: let go of the connection (the membership changed)`)); }
782
+ if (!now) { noteStatus('off', { url: null }); return; }
783
+ const url = now.split(' ')[0];
784
+ noteStatus('connecting', { url });
785
+ try {
786
+ const conn = await relay.connectRelay({
787
+ ops,
788
+ // (with the time: a page that said the Mac was away is matched with what happened here then)
789
+ onStatus: (state, why) => { if (held === now) noteStatus(state, { url, why }); console.log(dim(` ${at()} relay: ${state === 'connected' ? 'connected' : state === 'refused' ? 'refused' : 'not connected, trying again'}${why ? ` (${why})` : ''}`)); },
790
+ onPasskey: (d) => console.log(` relay: ${bold(d.id)} ${dim(`(${d.name || 'a device'})`)} has its passkey: it locks when left unused`),
791
+ onPaired: (d) => console.log(` relay: ${bold(d.id)} paired ${dim(`(${d.name || 'a device'})`)}${d.admin ? ', ' + bold('with full access') : ''} ${dim('(`sideora relay forget ' + d.id + '` if that was not you)')}`)
792
+ });
793
+ if (held !== now) return void conn.stop(); // (changed again while it connected)
794
+ afar = conn;
795
+ failed = 0;
796
+ console.log(` ${first ? '' : dim(at() + ' ')}Also at ${bold(conn.url)} from a paired device ${dim('(`sideora relay pair` pairs one)')}`);
797
+ } catch (e) {
798
+ // (the Keychain locked for a moment, a membership half written: tried again, less and less often, up to a minute)
799
+ noteStatus('refused', { url, why: e.message });
800
+ console.log(dim(` relay: not connected (${e.message})`));
801
+ held = null;
802
+ retryAt = Date.now() + Math.min(60_000, 2000 * 2 ** failed++);
803
+ }
804
+ };
805
+ let following = follow();
806
+ await following;
807
+ const watch = setInterval(() => { following = following.then(follow, follow); }, 2000);
808
+ watch.unref?.();
809
+ // asked to join and waiting for the relay's owner: asked how it stands now and then; accepted, it is a membership,
810
+ // which the loop above then connects
811
+ const { relayRequestCheck, readRequest } = await import('../src/relay-request.js');
812
+ const asking = setInterval(() => { if (readRequest()?.state === 'pending') relayRequestCheck().then((r) => { if (r?.state === 'accepted') console.log(` ${at()} relay: the request was accepted: joined to ${bold(r.url)}`); }, () => {}); }, 30_000);
813
+ asking.unref?.();
814
+ await new Promise((done) => { for (const sig of ['SIGINT', 'SIGTERM']) process.once(sig, done); });
815
+ clearInterval(watch);
816
+ clearInterval(asking);
817
+ await following.catch(() => {});
818
+ afar?.stop();
819
+ noteStatus('off', { url: null });
820
+ hub.close(); // (its connection to the daemon's hub: kept open, it would keep this process running)
821
+ access.notePort(null);
822
+ await server.close();
823
+ await closeConnections();
824
+ }
825
+
826
+ /**
827
+ * The relay (src/relay.js): the web app from another device, through a server that forwards what it cannot read.
828
+ * join <url> <invitation> | pair [--limited] | devices | admin <id> [off] | forget <id|all> | leave; alone: where things stand.
829
+ */
830
+ async function relayCmd() {
831
+ const relay = await import('../src/relay.js');
832
+ const sub = args[0] && !args[0].startsWith('--') ? args[0] : 'status';
833
+ const ago = (t) => { const m = Math.round((Date.now() - t) / 60000); return m < 1 ? 'just now' : m < 60 ? `${m} min ago` : m < 1440 ? `${Math.round(m / 60)} h ago` : `${Math.round(m / 1440)} d ago`; };
834
+ const state = relay.readState();
835
+ if (sub === 'join') {
836
+ if (!args[1] || !args[2]) throw new Error('relay join <url> <invitation> (the relay\'s owner gives the invitation)');
837
+ const j = await relay.relayJoin({ url: args[1], code: args[2], label: flag('label') || undefined });
838
+ console.log(green('✓') + ` this Mac is joined to ${bold(j.url)} ${dim(`(instance ${j.instance})`)}`);
839
+ console.log(dim(' `sideora web` keeps the connection while it runs; `sideora relay pair` pairs a phone or another computer'));
840
+ return;
841
+ }
842
+ if (sub === 'request' || sub === 'confirm' || sub === 'cancel') {
843
+ const rq = await import('../src/relay-request.js');
844
+ if (sub === 'request') {
845
+ if (!args[1] || !flag('name') || !flag('email')) throw new Error('relay request <url> --name "Your name" --email you@example.com [--note "…"]: asks the relay\'s owner to let this computer in; a code is sent to the email');
846
+ const r = await rq.relayRequest({ url: args[1], name: flag('name'), email: flag('email'), note: flag('note') || '' });
847
+ console.log(green('✓') + ` asked ${bold(r.url)} as ${bold(r.phrase)}`);
848
+ console.log(dim(` a code was sent to ${r.email}: \`sideora relay confirm <code>\``));
849
+ return;
850
+ }
851
+ if (sub === 'confirm') {
852
+ if (!args[1]) throw new Error('relay confirm <code> (the code sent to the email)');
853
+ const r = await rq.relayRequestConfirm({ code: args[1] });
854
+ console.log(green('✓') + ` confirmed: the owner of ${bold(r.url)} is asked now. Your phrase: ${bold(r.phrase)}`);
855
+ console.log(dim(' this computer joins by itself once accepted, while `sideora web` runs; `sideora relay` says how it stands'));
856
+ return;
857
+ }
858
+ console.log(await rq.relayRequestCancel() ? green('✓') + ' the request is cancelled' : dim('no request is waiting'));
859
+ return;
860
+ }
861
+ if (sub === 'status') {
862
+ if (!state) {
863
+ const { readRequest, relayRequestCheck } = await import('../src/relay-request.js');
864
+ let r = readRequest();
865
+ if (r?.state === 'pending') r = await relayRequestCheck().catch(() => r);
866
+ if (r?.state === 'accepted') return void console.log(green('✓') + ` the request was accepted: joined to ${bold(r.url)}`);
867
+ if (r) return void console.log(`asked ${bold(r.url)} as ${bold(r.phrase)}: ${r.state === 'unconfirmed' ? 'the code sent to ' + r.email + ' is to be confirmed (`sideora relay confirm <code>`)' : r.state === 'pending' ? 'waiting for its owner' : 'declined (`sideora relay cancel` clears it)'}`);
868
+ return void console.log(dim('not joined to a relay (`sideora relay request <url> --name … --email …`, or `sideora relay join <url> <invitation>`)'));
869
+ }
870
+ if (asJson) return void console.log(JSON.stringify({ url: state.url, instance: state.instance, devices: relay.relayDevices() }));
871
+ const full = relay.relayDevices().filter((d) => d.full).length;
872
+ console.log(`joined to ${bold(state.url)} ${dim(`(instance ${state.instance})`)}, ${state.devices.length} device${state.devices.length === 1 ? '' : 's'} paired${full ? `, ${full} with full access` : ''}`);
873
+ console.log(dim(' reachable while `sideora web` runs'));
874
+ return;
875
+ }
876
+ if (!state) throw new Error('this Mac is not joined to a relay (`sideora relay join <url> <invitation>`)');
877
+ if (sub === 'pair') {
878
+ // (full access by default: the device paired is the person's own; --limited pairs one that changes no rule,
879
+ // account or AI connection. --admin, of before, is what it does anyway)
880
+ const admin = !args.includes('--limited');
881
+ if (args.slice(1).some((a) => a !== '--admin' && a !== '--limited')) throw new Error('relay pair [--limited]');
882
+ const link = await relay.relayPairLink({ admin });
883
+ console.log(link);
884
+ console.log(dim(' good once, for ten minutes: open it on the device to pair, or point its camera at this'));
885
+ console.log(dim(admin ? ' full access, once the device has made its passkey (asked for as the link opens; within ten minutes): it will change rules, accounts and AI connections too, each change confirmed with that passkey (`--limited` pairs one that cannot). Whoever opens the link first is that device: `sideora web` says who paired, `sideora relay devices` lists them' : ' limited: it reads and writes, and changes no rule, account or AI connection (`sideora relay admin <device>` gives it full access later)'));
886
+ // (the code, when the package that draws it is there; the link above works without)
887
+ const qr = await import('qrcode-terminal').then((m) => m.default ?? m, () => null);
888
+ if (qr && process.stdout.isTTY) qr.generate(link, { small: true });
889
+ return;
890
+ }
891
+ if (sub === 'devices') {
892
+ const list = relay.relayDevices();
893
+ if (asJson) return void console.log(JSON.stringify(list));
894
+ if (!list.length) return void console.log(dim('no device is paired'));
895
+ for (const d of list) console.log(`${bold(d.id)} used ${ago(d.seen)}, paired ${ago(d.created)} ${dim(d.name)} ${d.passkey ? 'passkey' : dim('no passkey')}${d.full ? ' ' + bold('full access') : d.admin ? ' ' + dim(d.passkey ? `full access given too long before its passkey: give it again (\`sideora relay admin ${d.id}\`)` : 'full access once it makes its passkey, within ten minutes of being given it') : ''}`);
896
+ return;
897
+ }
898
+ if (sub === 'admin') {
899
+ // full access, device by device, said here at the Mac: rules, accounts and AI connections from that device too
900
+ const on = args[2] !== 'off';
901
+ if (!args[1] || args.length > 3 || (args[2] && args[2] !== 'off' && args[2] !== 'on')) throw new Error('relay admin <id> [off] (see `sideora relay devices`); `relay admin all off` takes it back from every device');
902
+ const n = relay.relayAdmin(args[1], on);
903
+ if (n === null) return void console.log(dim('no such device (see `sideora relay devices`)'));
904
+ if (!n) return void console.log(dim(on ? 'that device has full access already' : args[1] === 'all' ? 'no device had full access' : 'that device did not have full access'));
905
+ const waits = on && !relay.relayDevices().find((d) => d.id === args[1])?.full;
906
+ console.log(green('✓') + (waits
907
+ ? ` ${args[1]} has full access once it makes its passkey, if it does within ten minutes ${dim('(on the device: Settings, This device; later than that, give it again)')}: it will change rules, accounts and AI connections too ${dim('(`sideora relay admin ' + args[1] + ' off` takes it back)')}`
908
+ : on
909
+ ? ` ${args[1]} has full access: it changes rules (one that runs a command can be switched on, moved or removed), accounts and AI connections too ${dim('(`sideora relay admin ' + args[1] + ' off` takes it back)')}`
910
+ : ` full access taken back from ${n} device${n === 1 ? '' : 's'} ${dim('(true of what is asked from now on: what was changed meanwhile stays as it is)')}`));
911
+ return;
912
+ }
913
+ if (sub === 'forget') {
914
+ if (!args[1]) throw new Error('relay forget <id> (see `sideora relay devices`), or `relay forget all`');
915
+ const n = relay.relayForget(args[1]);
916
+ console.log(n ? green('✓') + ` ${n} device${n === 1 ? '' : 's'} forgotten` : dim('no such device'));
917
+ return;
918
+ }
919
+ if (sub === 'move') {
920
+ if (!args[1] || args.length > 2) throw new Error('relay move <url>: the same relay at another address (this computer stays joined, its devices paired)');
921
+ const m = await relay.relayMove({ url: args[1] });
922
+ if (!m.moved) return void console.log(dim(`already at ${m.to}`));
923
+ console.log(green('✓') + ` this computer now reaches its relay at ${bold(m.to)} ${dim(`(was ${m.from})`)}`);
924
+ // the running web app holds the old address: it starts again, and connects at the new one
925
+ const service = await import('../src/web-service.js');
926
+ let restarted = false;
927
+ try { service.restartWebService(); restarted = true; } catch { /* not a service: said below */ }
928
+ console.log(restarted ? dim(' the web app is starting again, connected there') : yellow(' restart `sideora web` to connect there, and pair nothing before: until then it still speaks for the old address'));
929
+ console.log(dim(` devices paired at ${m.from} still work from there; \`sideora relay pair\` now pairs at ${m.to}, \`sideora relay forget <id>\` ends an old one`));
930
+ return;
931
+ }
932
+ if (sub === 'leave') {
933
+ await relay.relayLeave({ force: args.includes('--force') });
934
+ console.log(green('✓') + ' this Mac left the relay; its paired devices are forgotten');
935
+ return;
936
+ }
937
+ throw new Error(`unknown: relay ${sub} (join, request, confirm, cancel, pair, devices, admin, forget, move, leave)`);
938
+ }
939
+
940
+ function installExtension() {
941
+ const { EXT_HOST, EXT_ID, EXT_WRAPPER, EXT_BROWSERS, extHostDir } = extHost();
942
+ ensureDirs();
943
+ const id = flag('id') || EXT_ID;
944
+ if (!/^[a-p]{32}$/.test(id)) throw new Error('--id must be a 32-letter Chrome extension id');
945
+ const q = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'";
946
+ // Chrome starts hosts with a bare PATH; op and security must still be found
947
+ const homeLine = Object.entries(HOME_ENV).map(([k, v]) => `export ${k}=${q(v)}\n`).join(''); // a data directory of its own goes with the bridge
948
+ fs.writeFileSync(EXT_WRAPPER, `#!/bin/sh\nexport PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"\n${homeLine}exec ${q(stableNode())} ${q(SELF)} bridge\n`, { mode: 0o700 });
949
+ fs.chmodSync(EXT_WRAPPER, 0o700);
950
+ const manifest = {
951
+ name: EXT_HOST,
952
+ description: 'Sideora bridge for the side-panel extension',
953
+ path: EXT_WRAPPER,
954
+ type: 'stdio',
955
+ allowed_origins: [`chrome-extension://${id}/`]
956
+ };
957
+ const done = [];
958
+ for (const [name, rel] of Object.entries(EXT_BROWSERS)) {
959
+ if (!fs.existsSync(path.dirname(extHostDir(rel)))) continue; // browser not installed
960
+ fs.mkdirSync(extHostDir(rel), { recursive: true });
961
+ fs.writeFileSync(path.join(extHostDir(rel), EXT_HOST + '.json'), JSON.stringify(manifest, null, 2) + '\n', { mode: 0o600 });
962
+ done.push(name);
963
+ }
964
+ if (!done.length) throw new Error('no Chromium browser found (looked for ' + Object.keys(EXT_BROWSERS).join(', ') + ')');
965
+ const extDir = path.resolve(path.dirname(SELF), '..', 'extension');
966
+ const built = fs.existsSync(path.join(extDir, 'dist', 'manifest.json'));
967
+ console.log(green('✓') + ` native messaging host registered for ${done.join(', ')}`);
968
+ if (!built) console.log(dim(` Build the extension first: cd ${extDir} && npm install && npm run build`));
969
+ console.log(dim(' Load the extension once: chrome://extensions → Developer mode → Load unpacked →'));
970
+ console.log(dim(' ' + path.join(extDir, 'dist')));
971
+ console.log(dim(' Then click the Sideora toolbar button to open the side panel.'));
972
+ }
973
+
974
+ function uninstallExtension() {
975
+ const { EXT_HOST, EXT_WRAPPER, EXT_BROWSERS, extHostDir } = extHost();
976
+ let n = 0;
977
+ for (const rel of Object.values(EXT_BROWSERS)) {
978
+ try { fs.unlinkSync(path.join(extHostDir(rel), EXT_HOST + '.json')); n++; } catch {}
979
+ }
980
+ try { fs.unlinkSync(EXT_WRAPPER); } catch {}
981
+ console.log(n ? green('✓') + ' native messaging host removed' : dim('nothing to remove'));
982
+ }
983
+
984
+ function guessHost(kind, email) {
985
+ const domain = String(email || '').split('@')[1];
986
+ return domain ? `${kind}.${domain}` : '';
987
+ }
988
+
989
+ async function accounts() {
990
+ const cfg = loadConfig();
991
+ const sub = args[0];
992
+ if (sub === 'rm' || sub === 'remove') {
993
+ const name = args[1];
994
+ if (!name || !cfg.accounts[name]) throw new Error(`usage: sideora accounts rm <name> (configured: ${accountNames(cfg).join(', ')})`);
995
+ delete cfg.accounts[name];
996
+ if (cfg.defaultAccount === name) delete cfg.defaultAccount;
997
+ saveConfig(cfg);
998
+ console.log(green('✓') + ` removed account "${name}" ${dim('(its Keychain password entry is kept; delete with: security delete-generic-password -s sideora -a ' + name + ')')}`);
999
+ return;
1000
+ }
1001
+ const names = accountNames(cfg);
1002
+ if (asJson) return console.log(JSON.stringify(names.map((n) => cfg.accounts[n]), null, 2));
1003
+ if (names.length === 0) return console.log(dim('no accounts — run: sideora setup'));
1004
+ for (const n of names) {
1005
+ const a = cfg.accounts[n];
1006
+ const def = cfg.defaultAccount === n && names.length > 1 ? dim(' (default)') : '';
1007
+ const where = a.provider === 'imap' ? `${a.imap.host}:${a.imap.port}${a.smtp?.host ? ', smtp ' + a.smtp.host : ''}` : a.provider === 'caldav' ? (a.server || a.service) : a.provider === 'google' ? 'calendar.google.com' : a.host;
1008
+ const cal = calendarProvider(a);
1009
+ const calNote = cal && cal !== a.provider ? dim(` calendar: ${cal}`) : '';
1010
+ console.log(` ${bold(n)}${def} ${yellow(a.provider)} ${where}${a.email ? dim(' ' + a.email) : ''}${a.provider !== 'google' && credentialsOf(a).source !== 'keychain' ? dim(' password: ' + passwordSource(a)) : ''}${calNote}`);
1011
+ }
1012
+ console.log(dim('\nadd/edit: sideora setup <name> remove: sideora accounts rm <name>'));
1013
+ }
1014
+
1015
+ /**
1016
+ * The 1Password service account token (accounts whose credentials.source is
1017
+ * "1password-service"): `set` reads it from a hidden prompt or stdin, never
1018
+ * from the command line (other processes can read arguments); `clear`
1019
+ * removes it; alone, says whether one is stored. It is never printed.
1020
+ */
1021
+ async function opToken() {
1022
+ const { setServiceToken, clearServiceToken, serviceTokenStored, OP_TOKEN_SERVICE } = await import('../src/credentials.js');
1023
+ const sub = args[0];
1024
+ if (sub === 'set') {
1025
+ if (args.slice(1).some((a) => !a.startsWith('--'))) throw new Error('the token is read from stdin or a hidden prompt, never from the command line: run sideora op-token set, then paste it');
1026
+ let token;
1027
+ if (process.stdin.isTTY) {
1028
+ const rl = (await import('node:readline/promises')).createInterface({ input: process.stdin, output: process.stdout });
1029
+ try { token = await askSecret(rl, 'Service account token (hidden)'); } finally { rl.close(); }
1030
+ } else {
1031
+ token = fs.readFileSync(0, 'utf8');
1032
+ }
1033
+ token = String(token || '').trim();
1034
+ if (!token) throw new Error('no token was given');
1035
+ // asked of 1Password first: a token it refuses is not kept
1036
+ const { runOp } = await import('../src/onepassword.js');
1037
+ try {
1038
+ await runOp(['whoami'], { token, timeout: 30000 });
1039
+ } catch (e) {
1040
+ if (e.code === 'TOKEN') throw new Error('1Password refused that token: nothing was stored');
1041
+ console.error(yellow('note:') + ` it could not be checked (${String(e.message).split('\n')[0]}): stored anyway`);
1042
+ }
1043
+ setServiceToken(token);
1044
+ console.log(green('✓') + ` service account token stored in the Keychain ${dim(`(service "${OP_TOKEN_SERVICE}")`)}`);
1045
+ return;
1046
+ }
1047
+ if (sub === 'clear' || sub === 'rm' || sub === 'remove') {
1048
+ console.log(clearServiceToken() ? green('✓') + ' service account token removed from the Keychain' : dim('no service account token was stored'));
1049
+ // the accounts read through it keep no password it read
1050
+ const { forgetCachedPassword } = await import('../src/credentials.js');
1051
+ let cfg = null;
1052
+ try { cfg = loadConfig(); } catch { /* no config: no account */ }
1053
+ for (const n of cfg ? accountNames(cfg) : []) {
1054
+ const a = cfg.accounts[n];
1055
+ // the account's own password, and its calendar's (asked for as "<name>/calendar")
1056
+ const caches = [[n, a], ...(a.calendar && typeof a.calendar === 'object' ? [[`${n}/calendar`, a.calendar]] : [])];
1057
+ for (const [key, holder] of caches) {
1058
+ if (credentialsOf(holder).source === '1password-service') { forgetCachedPassword(key); console.log(dim(` the password cached for "${key}" was dropped`)); }
1059
+ }
1060
+ }
1061
+ return;
1062
+ }
1063
+ if (sub && sub !== 'status') throw new Error('usage: sideora op-token set | clear');
1064
+ console.log(serviceTokenStored() ? green('✓') + ' a 1Password service account token is stored in the Keychain' : dim('no 1Password service account token stored — sideora op-token set'));
1065
+ }
1066
+
1067
+ async function cacheCmd() {
1068
+ const { cache } = await import('../src/core.js');
1069
+ const sub = args[0];
1070
+ if (sub === 'clear') {
1071
+ // (the core's tables still in it, from before core.db, are moved out first: they are not the cache's to lose)
1072
+ try { (await (await import('../src/core-db.js')).theCoreDb()).open(); } catch { /* none to move to: as before */ }
1073
+ cache.clearCache();
1074
+ console.log(green('✓') + ' cache deleted — the daemon rebuilds it on its next poll (restart it to backfill now)');
1075
+ return;
1076
+ }
1077
+ if (sub === 'prune') {
1078
+ console.log(green('✓') + ` pruned ${cache.prune()} old row(s)`);
1079
+ return;
1080
+ }
1081
+ const stats = cache.cacheStats();
1082
+ if (asJson) return console.log(JSON.stringify(stats, null, 2));
1083
+ if (!stats) return console.log(dim('no cache yet — it is created by the daemon (sideora install-daemon) for accounts with cache.enabled'));
1084
+ console.log(`${dim('File:')} ${stats.path} ${dim('(' + fmtSize(stats.size) + ', SQLCipher, key in Keychain "sideora-cache")')}`);
1085
+ for (const a of stats.accounts) {
1086
+ const synced = a.synced ? `${Math.max(0, Math.round((Date.now() - a.synced) / 1000))}s ago` : 'never';
1087
+ console.log(` ${bold(a.account)} ${a.n} messages, ${a.bodies} with body, oldest ${fmtDate(a.oldest)}, synced ${synced}`);
1088
+ }
1089
+ const cfg = loadConfig();
1090
+ const off = accountNames(cfg).filter((n) => cfg.accounts[n].cache?.enabled === false);
1091
+ if (off.length) console.log(dim(` not cached: ${off.join(', ')}`));
1092
+ }
1093
+
1094
+ async function status() {
1095
+ const { onePasswordStatus } = await import('../src/credentials.js');
1096
+ const { googleAccessOf, accessWords } = await import('../src/google-signin.js');
1097
+ const cfg = fs.existsSync(CONFIG_PATH) ? loadConfig() : null;
1098
+ const state = (() => { try { return JSON.parse(fs.readFileSync(path.join(HOME_DIR, 'state.json'), 'utf8')); } catch { return {}; } })();
1099
+
1100
+ // daemon state via launchd
1101
+ let daemon = `○ not installed — run ${bold('sideora install-daemon')}`;
1102
+ const ds = daemonState();
1103
+ if (ds.installed) {
1104
+ daemon = ds.pid ? green('●') + ` running (pid ${ds.pid})` : ds.loaded ? yellow('○') + ' installed but not running (check logs)' : yellow('○') + ' installed but not loaded — run sideora install-daemon again';
1105
+ }
1106
+
1107
+ const ago = (ts) => {
1108
+ if (!ts) return dim('never');
1109
+ const s = Math.round((Date.now() - ts) / 1000);
1110
+ const txt = s < 90 ? `${s}s ago` : s < 5400 ? `${Math.round(s / 60)}m ago` : `${Math.round(s / 3600)}h ago`;
1111
+ return s < 120 ? green(txt) : s < 600 ? txt : yellow(txt);
1112
+ };
1113
+
1114
+ let rulesInfo = dim('no rules file');
1115
+ try {
1116
+ const { loadRulesDoc } = await import('../src/config.js');
1117
+ const { rules, quietHours } = loadRulesDoc();
1118
+ const waking = rules.filter((r) => r.wake).length;
1119
+ rulesInfo = `${rules.length} active (${waking} wake an agent)` + (quietHours?.enabled ? dim(` — quiet ${quietHours.start}–${quietHours.end}`) : '');
1120
+ } catch {}
1121
+
1122
+ let push = dim('off');
1123
+ if (state.streaming === 'connected') push = green('●') + ' streaming (instant)';
1124
+ else if (state.streaming === 'reconnecting') push = yellow('○') + ' reconnecting — polling covers the gap';
1125
+
1126
+ // the web app: as a service, in a terminal, or not at all
1127
+ let webLine = dim('○ not running') + ` — ${bold('sideora web install')} keeps it running`;
1128
+ try {
1129
+ const service = (await import('../src/web-service.js')).webServiceState();
1130
+ const at = (await import('../src/web-access.js')).notedPort();
1131
+ const up = at ? await fetch(`http://127.0.0.1:${at}/api/session`, { signal: AbortSignal.timeout(1500) }).then((r) => r.ok, () => false) : false;
1132
+ const relay = (await import('../src/relay.js')).readState();
1133
+ const where = up ? ` http://127.0.0.1:${at}${relay?.url ? dim(`, and ${relay.url}`) : ''}` : '';
1134
+ if (service.installed && service.pid) webLine = up ? green('●') + ` service (pid ${service.pid})${where}` : yellow('○') + ` service started (pid ${service.pid}), not answering yet (check logs/web.log)`;
1135
+ else if (service.installed) webLine = yellow('○') + (service.loaded ? ' service installed but not running (check logs/web.log)' : ` service installed but not loaded — run ${bold('sideora web install')} again`);
1136
+ else if (up) webLine = green('●') + ` in a terminal${where} ${dim('(`sideora web install` keeps it running without one)')}`;
1137
+ } catch { /* said as not running */ }
1138
+
1139
+ console.log(`${dim('Daemon:')} ${daemon}`);
1140
+ console.log(`${dim('Web app:')} ${webLine}`);
1141
+ console.log(`${dim('Push:')} ${push}`);
1142
+ console.log(`${dim('Last check:')} ${ago(state.lastPollAt)}`);
1143
+ const names = cfg ? accountNames(cfg) : [];
1144
+ if (names.length === 0) console.log(`${dim('Accounts:')} ${yellow('none configured — run sideora setup')}`);
1145
+ for (const n of names) {
1146
+ const a = cfg.accounts[n];
1147
+ const st = state.streams?.[n]?.state;
1148
+ const push = st === 'connected' ? green('●') : st === 'reconnecting' ? yellow('○') : dim('○');
1149
+ const where = a.provider === 'imap' ? a.imap.host : a.provider === 'caldav' ? (a.server || a.service) : a.provider === 'google' ? 'calendar.google.com' : a.host;
1150
+ console.log(`${dim('Account:')} ${push} ${bold(n)} ${dim(a.provider)} ${where}${a.provider !== 'google' && credentialsOf(a).source !== 'keychain' ? dim(` password: ${passwordSource(a)}`) : ''}${calendarProvider(a) ? dim(' 📅 ' + calendarProvider(a)) : ''}${calendarProvider(a) === 'google' ? dim(` Google: ${accessWords(googleAccessOf(n))}`) : ''}`);
1151
+ const op = a.provider !== 'google' ? onePasswordStatus(a, state) : null;
1152
+ if (op?.failed) console.log(`${dim('1Password:')} ${yellow('!')} the last read failed ${ago(Date.parse(op.failedAt))} (${op.why}) — the cached password is used meanwhile`);
1153
+ const auth = state.auth?.[n];
1154
+ if (auth) {
1155
+ const hhmm = (t) => new Date(t).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
1156
+ console.log(`${dim('Sign-in:')} ${red('✖')} rejected since ${hhmm(auth.since)} (${auth.failures}×) — checks paused, next try ${hhmm(auth.retryAt)}`);
1157
+ console.log(` ${dim(isOnePassword(credentialsOf(a)) || credentialsOf(a).source === 'env' ? `update ${passwordSource(a)}, then run any sideora command to retry now` : 'update the password (sideora setup) to retry now')}`);
1158
+ }
1159
+ }
1160
+ const credAge = (() => {
1161
+ const at = Math.max(state.credCachedAt || 0, ...Object.values(state.creds || {}).map((c) => c.cachedAt || 0));
1162
+ if (!at) return 'never';
1163
+ const min = Math.max(1, Math.round((Date.now() - at) / 60e3));
1164
+ if (min < 90) return `${min}m ago`;
1165
+ const h = Math.round(min / 60);
1166
+ return h < 48 ? `${h}h ago` : `${Math.round(h / 24)}d ago`;
1167
+ })();
1168
+ console.log(`${dim('Creds:')} Keychain cache (refreshed ${credAge})`);
1169
+ console.log(`${dim('Rules:')} ${rulesInfo} ${dim(RULES_PATH)}`);
1170
+ console.log(`${dim('Logs:')} ${path.join(LOG_DIR, 'daemon.log')}`);
1171
+ }
1172
+
1173
+ async function tcpCheck(label, host, port, ok, bad) {
1174
+ if (!host) return bad(`${label} host not set`, 'run: sideora setup');
1175
+ const net = await import('node:net');
1176
+ await new Promise((resolve) => {
1177
+ const sock = net.connect({ host, port: Number(port), timeout: 8000 });
1178
+ sock.once('connect', () => { ok(`${label} reachable`, `${host}:${port}`); sock.destroy(); resolve(); });
1179
+ const fail = (e) => { bad(`${label} unreachable at ${host}:${port}`, e?.code || 'timeout'); sock.destroy(); resolve(); };
1180
+ sock.once('error', fail);
1181
+ sock.once('timeout', () => fail(null));
1182
+ });
1183
+ }
1184
+
1185
+ /** Doctor: where an account's password comes from, and whether it is there (no secret is read, none printed). */
1186
+ async function checkPassword(n, a, ok, bad) {
1187
+ const src = credentialsOf(a);
1188
+ if (src.source === 'keychain') {
1189
+ if (keychainHas(n)) ok(`[${n}] password in the Keychain`);
1190
+ else bad(`[${n}] no password in the Keychain`, `sideora setup ${n} (type it, or take it from 1Password)`);
1191
+ } else if (src.source === 'microsoft') {
1192
+ // signed in with Microsoft: no password, its sign-in kept in the Keychain
1193
+ if (keychainHas(`microsoft:${n}`)) ok(`[${n}] signed in with Microsoft`);
1194
+ else bad(`[${n}] not signed in with Microsoft`, 'Settings, Accounts, Add a mailbox, Microsoft 365 / Outlook.com');
1195
+ } else if (src.source === 'env') {
1196
+ if (src.env && process.env[src.env]) ok(`[${n}] password from the environment variable ${src.env}`);
1197
+ else bad(`[${n}] the environment variable ${src.env || '(credentials.env)'} is not set here`, 'set it where Sideora runs (the daemon\'s launchd job included)');
1198
+ } else if (isOnePassword(src)) {
1199
+ const { checkOnePassword } = await import('../src/credentials.js');
1200
+ const r = await checkOnePassword(a);
1201
+ const what = r.ok ? `1Password "${r.item}" (${r.vault})` : passwordSource(a);
1202
+ if (r.ok) ok(`[${n}] ${what} resolves${src.source === '1password-service' ? ' (service account)' : ''}`, r.legacy ? 'named by its title: rewritten to a reference by IDs on its next read' : '');
1203
+ else bad(`[${n}] ${what} cannot be read: ${r.why}`, r.fix);
1204
+ if (keychainHas(n)) ok(`[${n}] password cached in Keychain`);
1205
+ else console.log(` ${dim('•')} [${n}] no cached password yet ${dim('(normal before the first `sideora test`)')}`);
1206
+ } else {
1207
+ bad(`[${n}] credentials.source "${src.source}" is not one of ${CREDENTIAL_SOURCES.join(', ')}`, `sideora setup ${n}`);
1208
+ }
1209
+ }
13
1210
 
14
- Your mail, calendar, contacts, notes, files and an assistant in one private
15
- place, on your own computer.
1211
+ async function doctor() {
1212
+ let failures = 0;
1213
+ const ok = (label, extra = '') => console.log(` ${green('✓')} ${label}${extra ? dim(' ' + extra) : ''}`);
1214
+ const bad = (label, fix) => {
1215
+ failures++;
1216
+ console.log(` ${yellow('✗')} ${label}`);
1217
+ if (fix) console.log(` ${dim('fix:')} ${fix}`);
1218
+ };
1219
+
1220
+ console.log(bold('sideora doctor\n'));
1221
+
1222
+ const { onPath } = await import('../src/notify.js');
1223
+ // 0. the command by its name (an install linked before it was called sideora has only the old names)
1224
+ if (process.platform !== 'win32' && !onPath('sideora')) bad('the `sideora` command is not on the PATH (this install has only its older names)', 'run `npm link` again in the Sideora folder');
1225
+
1226
+ // 1. config
1227
+ let cfg = null;
1228
+ if (fs.existsSync(CONFIG_PATH)) {
1229
+ try {
1230
+ cfg = loadConfig();
1231
+ ok('config', CONFIG_PATH);
1232
+ } catch (e) {
1233
+ bad('config unreadable: ' + e.message, 'run: sideora setup');
1234
+ }
1235
+ } else {
1236
+ bad('no config', 'run: sideora install (then add an account in the browser)');
1237
+ }
1238
+
1239
+ // 2. 1Password CLI: only when an account reads its password from it
1240
+ const names = cfg ? accountNames(cfg) : [];
1241
+ const opSources = names.map((n) => cfg.accounts[n]).filter((a) => a.provider !== 'google').map(credentialsOf).filter(isOnePassword);
1242
+ if (opSources.length) {
1243
+ const { runOp } = await import('../src/onepassword.js');
1244
+ try {
1245
+ ok('1Password CLI installed', `op ${(await runOp(['--version'], { timeout: 15000 })).trim()}`);
1246
+ } catch {
1247
+ bad('1Password CLI (op) not installed', 'brew install 1password-cli');
1248
+ }
1249
+ if (opSources.some((c) => c.source === '1password-service')) {
1250
+ const { serviceTokenStored } = await import('../src/credentials.js');
1251
+ if (serviceTokenStored()) ok('1Password service account token in the Keychain');
1252
+ else bad('no 1Password service account token stored', 'sideora op-token set');
1253
+ }
1254
+ }
1255
+
1256
+ // 3 + 4. per account: where its password comes from, and server reachability
1257
+ if (cfg && names.length === 0) bad('no accounts configured', 'run: sideora setup');
1258
+ for (const n of names) {
1259
+ const a = cfg.accounts[n];
1260
+ if (calendarProvider(a) === 'google') {
1261
+ const { googleAccessOf, accessWords } = await import('../src/google-signin.js');
1262
+ const g = googleAccessOf(n);
1263
+ if (g.state === 'signed-in') ok(`[${n}] signed in to Google (${accessWords(g)})`);
1264
+ else if (g.state === 'calendar-only') ok(`[${n}] signed in to Google (${accessWords(g)})`, `to allow contacts: sideora google-login ${n}`);
1265
+ else bad(`[${n}] Google: ${accessWords(g)}`, `run: sideora google-login ${n}`);
1266
+ if (g.contacts && g.state !== 'expired') await checkGoogleContacts(n, ok, bad);
1267
+ if (a.provider === 'google') continue;
1268
+ }
1269
+ await checkPassword(n, a, ok, bad);
1270
+ if (a.provider === 'imap') {
1271
+ if (!a.email) bad(`[${n}] email not set`, `set accounts.${n}.email in ${CONFIG_PATH} (needed as the From address)`);
1272
+ await tcpCheck(`[${n}] IMAP`, a.imap?.host, a.imap?.port, ok, bad);
1273
+ if (a.smtp?.host) await tcpCheck(`[${n}] SMTP`, a.smtp.host, a.smtp.port, ok, bad);
1274
+ else console.log(` ${dim('•')} [${n}] no SMTP host — drafts work, sending does not`);
1275
+ } else if (a.provider === 'caldav') {
1276
+ const server = a.server || (a.service === 'icloud' ? 'https://caldav.icloud.com/' : a.service === 'fastmail' ? 'https://caldav.fastmail.com/' : '');
1277
+ if (!server) bad(`[${n}] no CalDAV server`, `set accounts.${n}.server (or service: icloud | fastmail)`);
1278
+ else await tcpCheck(`[${n}] CalDAV`, new URL(server).hostname, 443, ok, bad);
1279
+ } else if (a.provider === 'jmap') {
1280
+ const session = a.jmap?.session;
1281
+ if (!session) bad(`[${n}] no JMAP session URL`, `set accounts.${n}.jmap.session in ${CONFIG_PATH}`);
1282
+ else await tcpCheck(`[${n}] JMAP`, new URL(session).hostname, 443, ok, bad);
1283
+ } else if (a.host) {
1284
+ try {
1285
+ const resp = await fetch(a.host.replace(/\/$/, '') + '/EWS/Exchange.asmx', {
1286
+ method: 'HEAD',
1287
+ signal: AbortSignal.timeout(8000)
1288
+ });
1289
+ if (resp.status === 401 || resp.ok) ok(`[${n}] Exchange EWS endpoint reachable`, a.host);
1290
+ else bad(`[${n}] EWS endpoint answered HTTP ${resp.status}`, 'check the server URL in ' + CONFIG_PATH);
1291
+ } catch (e) {
1292
+ bad(`[${n}] cannot reach ` + a.host, 'VPN/network? ' + (e.cause?.code || e.message));
1293
+ }
1294
+ } else {
1295
+ bad(`[${n}] no server URL`, `set accounts.${n}.host in ${CONFIG_PATH}`);
1296
+ }
1297
+ }
1298
+
1299
+ // 4b. cache
1300
+ if (cfg) {
1301
+ try {
1302
+ const { cache } = await import('../src/core.js');
1303
+ const on = cache.cachedAccounts(cfg);
1304
+ if (on.length === 0) console.log(` ${dim('•')} local cache off for every account`);
1305
+ else if (!fs.existsSync(cache.CACHE_PATH)) console.log(` ${dim('•')} cache enabled (${on.join(', ')}) — created on the daemon's first poll`);
1306
+ else if (!cache.cacheKeyExists()) bad('cache.db exists but its key is missing from Keychain', 'sideora cache clear');
1307
+ else { cache.openCache(); ok(`encrypted cache opens (${on.join(', ')})`, cache.CACHE_PATH); }
1308
+ } catch (e) {
1309
+ bad('cache unusable: ' + e.message, 'sideora cache clear');
1310
+ }
1311
+ }
1312
+ // 4c. the core's own database (files index, sender pictures, Google contacts: src/core-db.js)
1313
+ try {
1314
+ const { CORE_DB_PATH, coreDb } = await import('../src/core-db.js');
1315
+ const { cacheKey } = await import('../src/core.js');
1316
+ if (fs.existsSync(CORE_DB_PATH)) {
1317
+ let why = '';
1318
+ const db = coreDb({ key: () => cacheKey({ create: false }), log: (m) => { why = m; } });
1319
+ if (db.open()) { ok('core database opens', CORE_DB_PATH); db.close(); } else bad(why || 'core.db does not open', `rm ${CORE_DB_PATH} (it is made again, and filled again as it is used)`);
1320
+ }
1321
+ } catch (e) {
1322
+ bad('core database unusable: ' + e.message, 'rm ~/.sideora/core.db');
1323
+ }
1324
+
1325
+ // 5. rules
1326
+ try {
1327
+ const { loadRulesDoc } = await import('../src/config.js');
1328
+ const { rules } = loadRulesDoc();
1329
+ const enabled = rules.length;
1330
+ const waking = rules.filter((r) => r.wake).length;
1331
+ if (fs.existsSync(RULES_PATH)) ok(`rules parse (${enabled} active, ${waking} wake an agent)`, RULES_PATH);
1332
+ else ok('no rules yet', 'the file is made with the first rule');
1333
+ } catch (e) {
1334
+ bad('rules.yaml does not parse: ' + e.message, 'fix ' + RULES_PATH);
1335
+ }
1336
+
1337
+ // 6. claude binary (only needed for wake rules)
1338
+ if (cfg?.claudePath) {
1339
+ if (fs.existsSync(cfg.claudePath)) ok('claude binary for agent wakes', cfg.claudePath);
1340
+ else bad('claude binary not found at ' + cfg.claudePath, 'set claudePath in ' + CONFIG_PATH);
1341
+ }
1342
+
1343
+ // 7. daemon
1344
+ const dsd = daemonState();
1345
+ if (dsd.installed) {
1346
+ if (dsd.pid) ok(`daemon running (pid ${dsd.pid})`);
1347
+ else if (dsd.loaded) bad('daemon installed but not running', 'check ' + path.join(LOG_DIR, 'daemon.log'));
1348
+ else bad(systemd.isLinux ? 'daemon set up but not loaded' : 'daemon plist present but not loaded', 'run: sideora install-daemon');
1349
+ } else {
1350
+ console.log(` ${dim('•')} daemon not installed ${dim('(run `sideora install-daemon` when ready)')}`);
1351
+ }
1352
+
1353
+ console.log();
1354
+ if (failures === 0) {
1355
+ console.log(green('All good.') + ' Next: sideora test');
1356
+ } else {
1357
+ console.log(yellow(`${failures} issue(s) found.`) + ' Fix the ones above, then re-run sideora doctor.');
1358
+ process.exit(1);
1359
+ }
1360
+ }
1361
+
1362
+ /** Doctor: whether an account's Google contacts can be read now (People API): how many, or why not and what to do. Never a name or an address. */
1363
+ async function checkGoogleContacts(n, ok, bad) {
1364
+ try {
1365
+ const { googleContacts } = await import('../src/google-contacts.js');
1366
+ const rec = await (await googleContacts()).refresh({ name: n, contacts: true, signedInAt: (await import('../src/google-signin.js')).googleAccessOf(n).signedInAt || '' });
1367
+ if (!rec) return bad(`[${n}] Google contacts: the account's sign-in changed while they were read`, 're-run sideora doctor');
1368
+ const counts = `${rec.saved?.length ?? '?'} contacts, ${rec.other?.length ?? '?'} other contacts`;
1369
+ if (!rec.error) return ok(`[${n}] Google contacts readable`, counts);
1370
+ const fix = {
1371
+ GOOGLE_SCOPE: `allow contacts on Google's page: sideora google-login ${n}`,
1372
+ GOOGLE_API_DISABLED: 'enable the People API in the Google Cloud project of the OAuth client (console.cloud.google.com → APIs & Services → Library → People API)',
1373
+ MAIL_AUTH: `run: sideora google-login ${n}`,
1374
+ GOOGLE_RATE: 'Google is rate-limiting: try again in a few minutes'
1375
+ }[rec.error.code] || 'check the network, then re-run sideora doctor';
1376
+ const what = rec.error.list === 'other' ? 'other contacts' : rec.error.list === 'saved' ? 'contacts' : 'contacts';
1377
+ bad(`[${n}] Google ${what} not read: ${rec.error.message}${rec.saved || rec.other ? ` (${counts} kept)` : ''}`, fix);
1378
+ } catch (e) {
1379
+ bad(`[${n}] Google contacts not read: ${e.message}`, 'check the network, then re-run sideora doctor');
1380
+ }
1381
+ }
1382
+
1383
+ async function compose() {
1384
+ const to = (flag('to') || '').split(/[,;]/).map((s) => s.trim()).filter(Boolean);
1385
+ const cc = (flag('cc') || '').split(/[,;]/).map((s) => s.trim()).filter(Boolean);
1386
+ const subject = flag('subject') || '';
1387
+ let body = flag('body');
1388
+ const send = args.includes('--send');
1389
+ const format = bodyFormat();
1390
+
1391
+ if (to.length === 0 || !subject) {
1392
+ throw new Error('usage: sideora compose --to a@b[,c@d] --subject S [--cc ...] [--body "..."] [--markdown|--html] [--attach F]... [--inline IMG]... [--send]\n(body can also be piped on stdin; --inline embeds an image for an HTML body as <img src="cid:FILENAME">)');
1393
+ }
1394
+ if (body == null) {
1395
+ if (process.stdin.isTTY) {
1396
+ throw new Error('no body: pass --body "..." or pipe it (e.g. echo "hi" | sideora compose ...)');
1397
+ }
1398
+ body = await new Promise((res) => {
1399
+ let data = '';
1400
+ process.stdin.on('data', (c) => (data += c));
1401
+ process.stdin.on('end', () => res(data));
1402
+ });
1403
+ }
1404
+
1405
+ const account = flag('account');
1406
+ const inlinePaths = flagAll('inline');
1407
+ if (inlinePaths.length && format === 'text') throw new Error('--inline needs an HTML body: add --markdown or --html (reference the image as ![alt](cid:FILENAME) or <img src="cid:FILENAME">)');
1408
+ const prepared = prepareBody(body, format);
1409
+ body = prepared.body;
1410
+ const bodyType = prepared.bodyType;
1411
+ const attachPaths = [...inlinePaths.map((p) => ({ p, inline: true })), ...flagAll('attach').map((p) => ({ p, inline: false }))];
1412
+ if (attachPaths.length === 0) {
1413
+ await spin(send ? 'sending…' : 'saving draft…', withAuthRetry((ews) => ews.createMessage({ to, cc, subject, body, bodyType, send }), null, account));
1414
+ if (send) {
1415
+ console.log(green('✓ sent') + ` to ${to.join(', ')}${cc.length ? ' (cc ' + cc.join(', ') + ')' : ''}`);
1416
+ } else {
1417
+ console.log(green('✓ draft saved') + ' to your Drafts folder — review and send from any mail client');
1418
+ console.log(dim(' (or rerun with --send to send directly)'));
1419
+ }
1420
+ return;
1421
+ }
1422
+
1423
+ // With attachments: create the draft, attach each file, then send if asked
1424
+ // (Exchange cannot create-and-send with attachments in a single call).
1425
+ const draft = await withAuthRetry((ews) => ews.createMessage({ to, cc, subject, body, bodyType, send: false }), null, account);
1426
+ let ck = draft.changeKey;
1427
+ for (const { p, inline } of attachPaths) {
1428
+ const abs = path.resolve(p);
1429
+ const data = fs.readFileSync(abs);
1430
+ if (data.length > 35 * 1024 * 1024) throw new Error(`${abs} is ${fmtSize(data.length)} — too large to attach`);
1431
+ const r = await withAuthRetry((ews) =>
1432
+ ews.addAttachment(draft.draftId, ck, {
1433
+ name: path.basename(abs),
1434
+ contentBase64: data.toString('base64'),
1435
+ contentType: mimeFor(abs),
1436
+ inline,
1437
+ contentId: path.basename(abs)
1438
+ }), null, draft.draftId
1439
+ );
1440
+ ck = r.changeKey || ck;
1441
+ console.log(` ${inline ? '🖼 embedded' : '📎 attached'} ${path.basename(abs)} ${dim('(' + fmtSize(data.length) + ')')}`);
1442
+ }
1443
+ if (send) {
1444
+ await spin('sending…', withAuthRetry((ews) => ews.sendItem(draft.draftId, ck), null, draft.draftId));
1445
+ console.log(green('✓ sent') + ` to ${to.join(', ')}${cc.length ? ' (cc ' + cc.join(', ') + ')' : ''} with ${attachPaths.length} attachment(s)`);
1446
+ } else {
1447
+ console.log(green('✓ draft saved') + ` with ${attachPaths.length} attachment(s) — review and send from any mail client`);
1448
+ }
1449
+ }
1450
+
1451
+ async function reply() {
1452
+ const token = args[0] && !args[0].startsWith('--') ? args[0] : null;
1453
+ if (!token) throw new Error('usage: sideora reply #N | <id> [--all] [--body "..."] [--markdown|--html] [--send] (body: --body, piped stdin, or $EDITOR)');
1454
+ let id = resolveId(token);
1455
+ if (!splitId(id).account) id = `${getAccount(loadConfig(), flag('account')).name}:${id}`;
1456
+ const all = args.includes('--all');
1457
+ const send = args.includes('--send');
1458
+ let body = flag('body');
1459
+ if (body == null && !process.stdin.isTTY) {
1460
+ body = await new Promise((res) => { let d = ''; process.stdin.on('data', (c) => (d += c)); process.stdin.on('end', () => res(d)); });
1461
+ }
1462
+ if (body == null) {
1463
+ const { composeInEditor } = await import('../src/compose-editor.js');
1464
+ const m = await spin('reading…', readMessage(id, { bodyType: 'Text' }));
1465
+ body = composeInEditor(m, { all });
1466
+ if (body == null) return console.log(dim('discarded (empty reply)'));
1467
+ }
1468
+ const prepared = prepareBody(body, bodyFormat());
1469
+ const r = await spin(send ? 'sending…' : 'saving draft…', replyTo(id, prepared.body, { all, send, bodyType: prepared.bodyType }));
1470
+ if (r.sent) console.log(green('✓ sent') + (all ? ' (reply-all)' : ' (reply)'));
1471
+ else console.log(green('✓ draft saved') + ` to your Drafts folder${all ? ' (reply-all)' : ''} — review and send from any mail client ${dim('(or rerun with --send)')}`);
1472
+ }
1473
+
1474
+ async function microsoftLogin() {
1475
+ const { startSignIn, signInStatus, cancelSignIn } = await import('../src/microsoft-signin.js');
1476
+ const port = flag('port');
1477
+ const r = await startSignIn({ label: flag('label') ?? undefined, ...(port ? { port } : {}) });
1478
+ console.log(`Sign in to Microsoft on this page:\n ${bold(r.url)}`);
1479
+ if (port) console.log(dim(` From another computer, forward the port first: ssh -L ${port}:127.0.0.1:${port} <this computer>, then open the page there.`));
1480
+ if (!port && !args.includes('--no-open')) { try { (await import('node:child_process')).spawn('open', [r.url], { stdio: 'ignore', detached: true }).unref(); } catch { /* the address is above */ } }
1481
+ const stop = () => { cancelSignIn(); process.exit(130); };
1482
+ process.once('SIGINT', stop);
1483
+ let s = signInStatus();
1484
+ while (s.state === 'pending') { await new Promise((res) => setTimeout(res, 500)); s = signInStatus(); }
1485
+ process.off('SIGINT', stop);
1486
+ if (s.state === 'done') {
1487
+ console.log(green('✓') + ` ${s.renewed ? 'signed in again' : 'added'}: ${bold(s.account)} ${dim(s.email)} ${dim('(tokens in Keychain)')}`);
1488
+ if (!s.restarted) console.log(dim(' restart the background service for it to start: sideora restart'));
1489
+ return;
1490
+ }
1491
+ throw new Error(s.state === 'failed' ? s.reason : s.state === 'expired' ? 'the sign-in page waited too long: start again' : 'the sign-in was stopped');
1492
+ }
1493
+
1494
+ async function googleLogin() {
1495
+ const name = args[0] && !args[0].startsWith('--') ? args[0] : null;
1496
+ const cfg = loadConfig();
1497
+ const acct = getAccount(cfg, name);
1498
+ if (calendarProvider(acct) !== 'google') throw new Error(`account "${acct.name}" is not a Google calendar account (provider: google, or an IMAP account with calendar.provider: "google")`);
1499
+ const { loginGoogle, calendar: { listCalendars } } = await import('../src/core.js');
1500
+ const { googleAccess } = await import('../src/google-signin.js');
1501
+ const t = await loginGoogle(acct.name, { open: !args.includes('--no-open'), log: (m) => console.log(m), email: acct.email });
1502
+ const access = googleAccess(t);
1503
+ console.log(green('✓') + ` signed in to Google for "${acct.name}" ${dim('(tokens in Keychain)')}`);
1504
+ console.log(` allowed: ${[access.calendar ? 'calendar' : '', access.contacts ? 'contacts' : ''].filter(Boolean).join(', ') || 'nothing Sideora uses'}`);
1505
+ if (!access.contacts) console.log(yellow(' contacts were not allowed') + dim(` — People, suggestions and sender pictures will not use them; tick them on Google's page: sideora google-login ${acct.name}`));
1506
+ if (!access.calendar) { console.log(yellow(' the calendar was not allowed') + dim(` — tick it on Google's page: sideora google-login ${acct.name}`)); return; }
1507
+ const cals = await listCalendars(acct.name);
1508
+ console.log(` ${cals.length} calendar(s): ${cals.map((c) => c.name + (c.isDefault ? ' (default)' : '')).join(', ')}`);
1509
+ }
1510
+
1511
+ function bodyFormat() {
1512
+ if (args.includes('--html')) return 'html';
1513
+ if (args.includes('--markdown') || args.includes('--md')) return 'markdown';
1514
+ return 'text';
1515
+ }
1516
+
1517
+ function mimeFor(file) {
1518
+ const types = {
1519
+ pdf: 'application/pdf', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
1520
+ gif: 'image/gif', txt: 'text/plain', md: 'text/markdown', html: 'text/html',
1521
+ csv: 'text/csv', json: 'application/json', zip: 'application/zip',
1522
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
1523
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
1524
+ wav: 'audio/wav', mp3: 'audio/mpeg', m4a: 'audio/mp4', mp4: 'video/mp4'
1525
+ };
1526
+ return types[path.extname(file).slice(1).toLowerCase()] || 'application/octet-stream';
1527
+ }
1528
+
1529
+ async function test() {
1530
+ const config = loadConfig();
1531
+ let failed = 0;
1532
+ const all = [];
1533
+ for (const name of selectAccounts(flag('account'))) {
1534
+ const acct = config.accounts[name];
1535
+ const where = acct.provider === 'imap' ? `${acct.imap.host}:${acct.imap.port} via IMAP` : `${acct.host} via EWS/NTLM`;
1536
+ process.stdout.write(`[${name}] connecting to ${where}... `);
1537
+ try {
1538
+ const items = await withAuthRetry(
1539
+ (c) => c.findInbox({ limit: 5 }),
1540
+ () => process.stdout.write(`(password refused — reading it again from ${passwordSource(acct)}) `),
1541
+ name
1542
+ );
1543
+ console.log(green('OK ✓'));
1544
+ all.push(...items);
1545
+ } catch (e) {
1546
+ failed++;
1547
+ console.log(yellow('FAILED') + ' — ' + String(e.message).split('\n')[0]);
1548
+ }
1549
+ }
1550
+ console.log();
1551
+ printItems(all.sort((a, b) => new Date(b.received) - new Date(a.received)));
1552
+ if (failed) process.exitCode = 1;
1553
+ console.log(dim('\nEdit rules: ' + RULES_PATH));
1554
+ console.log(dim('Run the watcher: sideora watch (or: sideora install-daemon)'));
1555
+ }
1556
+
1557
+ async function list() {
1558
+ const opts = {
1559
+ limit: Number(flag('limit')) || 25,
1560
+ unreadOnly: args.includes('--unread'),
1561
+ folder: flag('folder') || 'inbox',
1562
+ live: args.includes('--live')
1563
+ };
1564
+ printItems(await spin(fetching(flag('account')), findAcross(flag('account'), opts, warnAccount)));
1565
+ }
1566
+
1567
+ async function search() {
1568
+ const opts = searchOptsFromArgs();
1569
+ if (!opts.senderContains && !opts.subjectContains && !opts.text && !opts.hasAttachments && !opts.unreadOnly && !opts.sinceIso) {
1570
+ throw new Error('usage: sideora search [--from X] [--subject Y] [--text Z] [--attachments] [--days N] [--unread] [--folder F] [--limit N]');
1571
+ }
1572
+ printItems(await spin(fetching(flag('account')), findAcross(flag('account'), opts, warnAccount)));
1573
+ }
1574
+
1575
+ async function read() {
1576
+ let token = args[0] && !args[0].startsWith('--') ? args[0] : null;
1577
+ let id;
1578
+ if (token) {
1579
+ id = resolveId(token);
1580
+ } else {
1581
+ const opts = { ...searchOptsFromArgs(), limit: 1 };
1582
+ if (!opts.senderContains && !opts.subjectContains) {
1583
+ throw new Error('usage: sideora read #N | <id> | --from X [--subject Y]');
1584
+ }
1585
+ const items = await spin(fetching(flag('account')), findAcross(flag('account'), opts, warnAccount));
1586
+ if (items.length === 0) throw new Error('no matching message found');
1587
+ id = items[0].id;
1588
+ }
1589
+ if (!splitId(id).account) id = `${getAccount(loadConfig(), flag('account')).name}:${id}`; // bare id → single/--account
1590
+ if (asJson) {
1591
+ const m = await spin('reading…', readMessage(id, { live: args.includes('--live') }));
1592
+ return console.log(JSON.stringify(m, null, 2));
1593
+ }
1594
+
1595
+ // Fetch the HTML body and flatten it to text (layout tables → blocks,
1596
+ // images dropped, wrapped to the terminal); --links keeps the hrefs.
1597
+ let m = await spin(`reading from ${splitId(id).account}…`, readMessage(id, { bodyType: args.includes('--plain') ? 'Text' : 'HTML', live: args.includes('--live') }));
1598
+ let body = m.body;
1599
+ if (m.bodyType === 'HTML') {
1600
+ const { renderHtml } = await import('../src/render.js');
1601
+ body = renderHtml(m.body, { width: (process.stdout.columns || 100) - 2 });
1602
+ }
1603
+
1604
+ if (accountNames(loadConfig()).length > 1) console.log(`${dim('Account:')} ${yellow(m.account)}`);
1605
+ console.log(`${dim('From:')} ${cyan(`${m.fromName} <${m.fromEmail}>`)}`);
1606
+ console.log(`${dim('To:')} ${m.to.map((r) => r.email || r.name).join(', ')}`);
1607
+ if (m.cc.length) console.log(`${dim('Cc:')} ${m.cc.map((r) => r.email || r.name).join(', ')}`);
1608
+ console.log(`${dim('Date:')} ${fmtDate(m.received)}`);
1609
+ console.log(`${dim('Subject:')} ${bold(m.subject)}${m.cached ? dim(' (cached)') : ''}`);
1610
+ const realAtts = (m.attachments || []).filter((a) => !a.inline);
1611
+ if (realAtts.length) {
1612
+ console.log(`${dim('Attach:')} 📎 ${realAtts.map((a) => `${a.name} ${dim('(' + fmtSize(a.size) + ')')}`).join(', ')}`);
1613
+ }
1614
+ console.log();
1615
+ console.log(body);
1616
+ }
1617
+
1618
+ async function attachments() {
1619
+ const token = args[0] && !args[0].startsWith('--') ? args[0] : null;
1620
+ if (!token) throw new Error('usage: sideora attachments #N | <id> [--save [DIR]] [--only NAME]');
1621
+ let id = resolveId(token);
1622
+ if (!splitId(id).account) id = `${getAccount(loadConfig(), flag('account')).name}:${id}`;
1623
+ const saveIdx = args.indexOf('--save');
1624
+ if (saveIdx < 0) {
1625
+ const m = await spin('reading…', readMessage(id, { bodyType: 'Text' }));
1626
+ const list = (m.attachments || []).filter((a) => !a.inline);
1627
+ if (asJson) return console.log(JSON.stringify(list, null, 2));
1628
+ if (list.length === 0) return console.log(dim('(no attachments)'));
1629
+ list.forEach((a, i) => console.log(` ${dim('#' + (i + 1))} 📎 ${bold(a.name)} ${dim(fmtSize(a.size) + (a.contentType ? ' · ' + a.contentType : ''))}`));
1630
+ console.log(dim(`\nsave them: sideora attachments ${token} --save [DIR]`));
1631
+ return;
1632
+ }
1633
+ const dirArg = args[saveIdx + 1] && !args[saveIdx + 1].startsWith('--') ? args[saveIdx + 1] : null;
1634
+ const dir = path.resolve(dirArg || path.join(os.homedir(), 'Downloads'));
1635
+ const saved = await spin('downloading…', saveAttachments(id, dir, { only: flag('only') || undefined }));
1636
+ if (asJson) return console.log(JSON.stringify(saved, null, 2));
1637
+ for (const f of saved) console.log(`${green('✓')} ${f.path} ${dim('(' + fmtSize(f.size) + ')')}`);
1638
+ }
1639
+
1640
+ function fmtSize(bytes) {
1641
+ if (!bytes) return '?';
1642
+ if (bytes < 1024) return bytes + ' B';
1643
+ if (bytes < 1048576) return Math.round(bytes / 1024) + ' KB';
1644
+ return (bytes / 1048576).toFixed(1) + ' MB';
1645
+ }
1646
+
1647
+ async function rules() {
1648
+ const store = await import('../src/rules-store.js');
1649
+ const sub = args[0] && !args[0].startsWith('--') ? args[0] : 'list';
1650
+ const subArgs = args.slice(1);
1651
+ const subFlag = (name) => {
1652
+ const i = subArgs.indexOf('--' + name);
1653
+ return i >= 0 && subArgs[i + 1] && !subArgs[i + 1].startsWith('--') ? subArgs[i + 1] : null;
1654
+ };
1655
+
1656
+ const printRules = () => {
1657
+ const { rules: all, quietHours } = store.listRules();
1658
+ if (asJson) return console.log(JSON.stringify({ rules: all, quietHours }, null, 2));
1659
+ const q = quietHours.enabled ? `on (${quietHours.start}–${quietHours.end})` : 'off';
1660
+ console.log(dim('Quiet hours: ') + q + '\n');
1661
+ if (all.length === 0) {
1662
+ console.log(dim('(no rules — add one with: sideora rules add --name "Boss" --senders boss@co.com)'));
1663
+ return;
1664
+ }
1665
+ all.forEach((r, i) => {
1666
+ const on = r.enabled !== false;
1667
+ const mark = on ? green('✓') : dim('✗');
1668
+ const bits = [];
1669
+ if (r.senders) bits.push(`senders: ${cyan(String(r.senders))}`);
1670
+ if (r.subjects) bits.push(`subjects: ${cyan(String(r.subjects))}`);
1671
+ bits.push(r.sound === false ? dim('silent') : `♪ ${r.sound || 'chime'}`);
1672
+ if (r.notify === false) bits.push(dim('no notification'));
1673
+ if (r.wake) bits.push(yellow(`wake agent${r.wake.model ? ` (${r.wake.model})` : ''}`));
1674
+ const name = on ? bold(r.name || '(unnamed)') : dim(r.name || '(unnamed)');
1675
+ console.log(` ${mark} ${dim('#' + (i + 1))} ${name.padEnd(28)} ${bits.join(dim(' · '))}`);
1676
+ });
1677
+ console.log(dim(`\n file: ${RULES_PATH} — changes apply within ~30s, no restart needed`));
1678
+ };
1679
+
1680
+ switch (sub) {
1681
+ case 'list':
1682
+ printRules();
1683
+ break;
1684
+ case 'add': {
1685
+ const rule = { name: subFlag('name') };
1686
+ if (subFlag('senders')) rule.senders = subFlag('senders');
1687
+ if (subFlag('subjects')) rule.subjects = subFlag('subjects');
1688
+ rule.sound = subFlag('sound') || 'chime';
1689
+ if (subArgs.includes('--no-notify')) rule.notify = false;
1690
+ if (subArgs.includes('--wake')) rule.wake = { model: subFlag('model') || 'sonnet' };
1691
+ if (subArgs.includes('--disabled')) rule.enabled = false;
1692
+ if (subFlag('account')) rule.account = subFlag('account');
1693
+ if (!rule.name) throw new Error('usage: sideora rules add --name N --senders "a,b" [--subjects "x"] [--sound alarm|chime|ding|message] [--no-notify] [--wake [--model M]] [--account A]');
1694
+ const count = store.addRule(rule);
1695
+ console.log(green('✓') + ` rule "${rule.name}" added (${count} total)`);
1696
+ break;
1697
+ }
1698
+ case 'rm': case 'remove': case 'delete': {
1699
+ if (!subArgs[0]) throw new Error('usage: sideora rules rm <#|name>');
1700
+ const removed = store.removeRule(subArgs[0]);
1701
+ console.log(green('✓') + ` removed rule "${removed?.name || subArgs[0]}"`);
1702
+ break;
1703
+ }
1704
+ case 'enable': case 'disable': {
1705
+ if (!subArgs[0]) throw new Error(`usage: sideora rules ${sub} <#|name>`);
1706
+ const r = store.setRuleEnabled(subArgs[0], sub === 'enable');
1707
+ console.log(green('✓') + ` "${r.name}" ${sub}d`);
1708
+ break;
1709
+ }
1710
+ case 'edit': {
1711
+ const editor = process.env.EDITOR || process.env.VISUAL || 'nano';
1712
+ store.listRules(); // ensures the file exists
1713
+ const { spawnSync } = await import('node:child_process');
1714
+ spawnSync(editor, [RULES_PATH], { stdio: 'inherit' });
1715
+ printRules();
1716
+ break;
1717
+ }
1718
+ case 'quiet': {
1719
+ const mode = subArgs[0];
1720
+ if (mode !== 'on' && mode !== 'off') throw new Error('usage: sideora rules quiet on|off [--start HH:MM] [--end HH:MM]');
1721
+ const q = store.setQuietHours({ enabled: mode === 'on', start: subFlag('start'), end: subFlag('end') });
1722
+ console.log(green('✓') + ` quiet hours ${q.enabled ? `on (${q.start}–${q.end})` : 'off'}`);
1723
+ break;
1724
+ }
1725
+ default:
1726
+ throw new Error(`unknown rules subcommand "${sub}" — use: list, add, rm, enable, disable, edit, quiet`);
1727
+ }
1728
+ }
1729
+
1730
+ async function events() {
1731
+ // events --wait: long-poll (exits on the first matching mail or on timeout)
1732
+ if (args.includes('--wait') || args[0] === 'cursor') {
1733
+ const { pollEvents, currentCursor } = await import('../src/events.js');
1734
+ if (args[0] === 'cursor') return console.log(asJson ? JSON.stringify({ cursor: await currentCursor() }) : await currentCursor());
1735
+ const r = await pollEvents({
1736
+ after: flag('after') || 'now',
1737
+ timeout: flag('timeout') != null ? Number(flag('timeout')) : 600,
1738
+ match: args.includes('--all') ? 'all' : 'rules',
1739
+ account: flag('account') || undefined,
1740
+ rule: flag('rule') || undefined,
1741
+ types: flag('types') ? flag('types').split(',') : undefined
1742
+ });
1743
+ if (asJson || !process.stdout.isTTY) console.log(JSON.stringify(r));
1744
+ else if (r.gap) console.log(yellow(`⚠ cursor ${flag('after')} predates the oldest event the daemon still has${r.oldest ? ` (${r.oldest})` : ''} — about ${r.lost} event(s) were lost; resync with sideora list --unread / calendar`));
1745
+ if (asJson || !process.stdout.isTTY) {}
1746
+ else if (r.events.length === 0) console.log(dim(`nothing within the timeout (cursor ${r.cursor})`));
1747
+ else for (const e of r.events) {
1748
+ if (e.type === 'reminder') console.log(`${green('reminder')} [${e.account}] in ${e.minutes} min: ${e.subject} ${dim(fmtDate(e.start) + (e.location ? ' · ' + e.location : '') + ' id ' + e.id + ' cursor ' + e.seq)}`);
1749
+ else if (e.type === 'calendar') console.log(`${green('calendar')} [${e.account}] ${e.action}: ${e.subject} ${dim(fmtDate(e.start) + ' id ' + e.id + ' cursor ' + e.seq)}`);
1750
+ else console.log(`${green(e.type)} [${e.account}]${e.rule ? yellow(' [' + e.rule + ']') : ''} ${e.from} — ${e.subject} ${dim('id ' + e.id + ' cursor ' + e.seq)}`);
1751
+ }
1752
+ process.exit(r.events.length ? 0 : 3);
1753
+ }
1754
+ const net = await import('node:net');
1755
+ const readline = await import('node:readline');
1756
+ const { EVENTS_SOCK } = await import('../src/events.js');
1757
+
1758
+ const sock = net.connect(EVENTS_SOCK);
1759
+ sock.on('error', (e) => {
1760
+ console.error(yellow('Error:'), `cannot connect to ${EVENTS_SOCK} — is the daemon running? (${e.code})`);
1761
+ console.error(dim('The event socket is served by `sideora watch` / the installed daemon (restart it if it predates this feature).'));
1762
+ process.exit(1);
1763
+ });
1764
+
1765
+ if (!asJson) console.log(dim(`subscribed to ${EVENTS_SOCK} — Ctrl-C to stop\n`));
1766
+ const rl = readline.createInterface({ input: sock });
1767
+ rl.on('line', (line) => {
1768
+ if (asJson) return console.log(line);
1769
+ let e;
1770
+ try { e = JSON.parse(line); } catch { return console.log(line); }
1771
+ const t = dim(new Date(e.ts).toLocaleTimeString());
1772
+ switch (e.type) {
1773
+ case 'hello': console.log(`${t} ${dim('connected to Sideora (pid ' + e.pid + ')')}`); break;
1774
+ case 'newmail': console.log(`${t} ${cyan('newmail')} ${e.from} — ${e.subject}${e.rule ? yellow(' [' + e.rule + ']') : ''}`); break;
1775
+ case 'match': console.log(`${t} ${green(bold('match'))} [${e.rule}] ${e.from} — ${e.subject}${e.quiet ? dim(' (quiet hours)') : ''}`); break;
1776
+ case 'wake': console.log(`${t} ${yellow(bold('wake'))} [${e.rule}] agent started → ${dim(e.log)}`); break;
1777
+ case 'stream': console.log(`${t} ${dim('stream ' + e.state)}`); break;
1778
+ case 'calendar': console.log(`${t} ${cyan('calendar')} ${e.action} — ${e.subject} ${dim(fmtDate(e.start))}`); break;
1779
+ case 'reminder': console.log(`${t} ${yellow(bold('reminder'))} in ${e.minutes} min — ${e.subject} ${dim(fmtDate(e.start) + (e.location ? ' · ' + e.location : ''))}`); break;
1780
+ default: console.log(`${t} ${e.type} ${dim(JSON.stringify(e))}`);
1781
+ }
1782
+ });
1783
+ sock.on('close', () => {
1784
+ if (!asJson) console.log(dim('\ndaemon closed the connection'));
1785
+ process.exit(0);
1786
+ });
1787
+ await new Promise(() => {}); // run until Ctrl-C
1788
+ }
1789
+
1790
+ async function logs() {
1791
+ const file = path.join(LOG_DIR, 'daemon.log');
1792
+ if (!fs.existsSync(file)) throw new Error('no daemon log yet at ' + file);
1793
+ const follow = args.includes('-f') || args.includes('--follow');
1794
+ const n = Number(flag('lines')) || 40;
1795
+ const { spawn } = await import('node:child_process');
1796
+ const readline = await import('node:readline');
1797
+
1798
+ const p = spawn('tail', follow ? ['-n', String(n), '-f', file] : ['-n', String(n), file]);
1799
+ const rl = readline.createInterface({ input: p.stdout });
1800
+ rl.on('line', (l) => console.log(colorizeLogLine(l)));
1801
+ p.on('exit', (code) => process.exit(code || 0));
1802
+ process.on('SIGINT', () => { p.kill(); process.exit(0); });
1803
+ await new Promise(() => {});
1804
+ }
1805
+
1806
+ function colorizeLogLine(l) {
1807
+ if (!useColor) return l;
1808
+ const m = l.match(/^(\[[^\]]+\])\s?(.*)$/);
1809
+ const ts = m ? dim(m[1]) + ' ' : '';
1810
+ const rest = m ? m[2] : l;
1811
+ if (/MATCH \[/.test(rest)) return ts + green(bold(rest));
1812
+ if (/woke agent/.test(rest)) return ts + yellow(rest);
1813
+ if (/error|failed/i.test(rest)) return ts + yellow(rest);
1814
+ if (/^\[stream\]/.test(rest)) return ts + dim(rest);
1815
+ if (/new mail \(no rule\)/.test(rest)) return ts + rest.replace(/^new mail \(no rule\):/, dim('new mail (no rule):'));
1816
+ return ts + rest;
1817
+ }
1818
+
1819
+ async function sounds() {
1820
+ const { availableSounds, resolveSound, playSound, DEFAULT_SOUNDS, BUNDLED_DIR, soundPlayer } = await import('../src/notify.js');
1821
+ const { execFileSync } = await import('node:child_process');
1822
+ const sub = args[0];
1823
+ const cfg = fs.existsSync(CONFIG_PATH) ? loadConfig() : {};
1824
+ const alerts = Object.keys(DEFAULT_SOUNDS);
1825
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1826
+
1827
+ if (!sub) {
1828
+ console.log(bold('Current alert sounds') + dim(' (playing each)\n'));
1829
+ for (const alert of alerts) {
1830
+ const { name, repeats, file } = resolveSound(alert, cfg);
1831
+ const where = file.startsWith('/System') ? '' : dim(' ' + file);
1832
+ console.log(` ${cyan(alert.padEnd(8))} ${name}${repeats > 1 ? dim(' ×' + repeats) : ''}${where}`);
1833
+ playSound(alert, cfg);
1834
+ await sleep(1600 * Math.max(1, repeats));
1835
+ }
1836
+ const { custom } = availableSounds();
1837
+ const usedFiles = alerts.map((a) => path.basename(resolveSound(a, cfg).file));
1838
+ const unused = custom.filter((f) => !usedFiles.includes(f));
1839
+ if (custom.length) {
1840
+ console.log('\n' + bold('Your sounds') + dim(` (${SOUNDS_SHOWN})`));
1841
+ for (const f of custom) {
1842
+ const mappedTo = alerts.filter((a) => path.basename(resolveSound(a, cfg).file) === f);
1843
+ console.log(
1844
+ ` ${f} ${mappedTo.length ? green('→ ' + mappedTo.join(', ')) : dim('unused — map it: sideora sounds set chime ' + f)}`
1845
+ );
1846
+ }
1847
+ } else {
1848
+ console.log(dim(`\nYour own sounds: drop .wav/.mp3/.m4a files into ${SOUNDS_SHOWN}/`));
1849
+ }
1850
+ const { bundled } = availableSounds();
1851
+ if (bundled.length) {
1852
+ console.log('\n' + bold('Bundled sounds'));
1853
+ for (const f of bundled) {
1854
+ const mappedTo = alerts.filter((a) => path.basename(resolveSound(a, cfg).file) === f);
1855
+ console.log(` ${f} ${mappedTo.length ? green('→ ' + mappedTo.join(', ')) : dim('map it: sideora sounds set chime ' + f)}`);
1856
+ }
1857
+ }
1858
+ console.log(dim(`\nAudition everything: sideora sounds all`));
1859
+ console.log(dim(`Generate with AI: sideora sounds gen "soft warm chime" [--tts]`));
1860
+ console.log(dim(`Change one: sideora sounds set alarm my-siren.wav:2`));
1861
+ return;
1862
+ }
1863
+
1864
+ if (sub === 'all') {
1865
+ const { custom, bundled, system } = availableSounds();
1866
+ if (bundled.length) {
1867
+ console.log(bold('Bundled sounds\n'));
1868
+ for (const f of bundled) {
1869
+ console.log(' ' + f);
1870
+ try { execFileSync('say', [f.replace(/\.\w+$/, '')]); } catch {}
1871
+ try { execFileSync(soundPlayer() ?? 'afplay', [path.join(BUNDLED_DIR, f)]); } catch {}
1872
+ await sleep(250);
1873
+ }
1874
+ console.log();
1875
+ }
1876
+ if (custom.length) {
1877
+ console.log(bold('Your sounds') + dim(` (${SOUNDS_SHOWN})\n`));
1878
+ for (const f of custom) {
1879
+ console.log(' ' + f);
1880
+ try { execFileSync('say', [f.replace(/\.\w+$/, '')]); } catch {}
1881
+ try { execFileSync(soundPlayer() ?? 'afplay', [path.join(SOUNDS_DIR, f)]); } catch {}
1882
+ await sleep(250);
1883
+ }
1884
+ console.log();
1885
+ }
1886
+ console.log(bold('System sounds') + dim(' — each name is spoken, then played\n'));
1887
+ for (const name of system) {
1888
+ console.log(' ' + name);
1889
+ try { execFileSync('say', [name]); } catch {}
1890
+ try { execFileSync(soundPlayer() ?? 'afplay', [`/System/Library/Sounds/${name}.aiff`]); } catch {}
1891
+ await sleep(250);
1892
+ }
1893
+ return;
1894
+ }
1895
+
1896
+ if (sub === 'set') {
1897
+ const [, alert, spec] = args;
1898
+ if (!alerts.includes(alert) || !spec) {
1899
+ const { custom, bundled, system } = availableSounds();
1900
+ throw new Error(
1901
+ `usage: sideora sounds set <${alerts.join('|')}> <Sound[:repeats]>\n` +
1902
+ `yours (${SOUNDS_SHOWN}): ${custom.join(', ') || '(none yet)'}\nbundled: ${bundled.join(', ') || '(none)'}\nsystem: ${system.join(', ')}`
1903
+ );
1904
+ }
1905
+ const next = { ...loadConfig(), sounds: { ...(loadConfig().sounds || {}), [alert]: spec } };
1906
+ const resolved = resolveSound(alert, next);
1907
+ const base = spec.split(':')[0];
1908
+ if (resolved.file.endsWith('/Glass.aiff') && base !== 'Glass' && !base.startsWith('Glass')) {
1909
+ const { custom, bundled, system } = availableSounds();
1910
+ throw new Error(`"${base}" not found.\nyours (${SOUNDS_SHOWN}): ${custom.join(', ') || '(none yet)'}\nbundled: ${bundled.join(', ') || '(none)'}\nsystem: ${system.join(', ')}`);
1911
+ }
1912
+ saveConfig(next);
1913
+ console.log(green('✓') + ` ${alert} → ${spec} ${dim(resolved.file)} (playing it)`);
1914
+ playSound(alert, next);
1915
+ return;
1916
+ }
1917
+
1918
+ if (sub === 'gen') {
1919
+ const text = args[1] && !args[1].startsWith('--') ? args[1] : null;
1920
+ if (!text) {
1921
+ throw new Error(
1922
+ 'usage: sideora sounds gen "<description or spoken text>" [--out name] [--tts] [--voice id] [--duration secs]\n' +
1923
+ ' default: ElevenLabs sound-effects (describe the sound, e.g. "warm soft two-note notification chime")\n' +
1924
+ ' --tts: ElevenLabs text-to-speech (the text is spoken, e.g. "New deploy request!")'
1925
+ );
1926
+ }
1927
+ const key = elevenLabsKey();
1928
+ const tts = args.includes('--tts');
1929
+ const out = (flag('out') || text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40)) + '.mp3';
1930
+ const dest = path.join(SOUNDS_DIR, out);
1931
+
1932
+ const url = tts
1933
+ ? `https://api.elevenlabs.io/v1/text-to-speech/${flag('voice') || '21m00Tcm4TlvDq8ikWAM'}`
1934
+ : 'https://api.elevenlabs.io/v1/sound-generation';
1935
+ const payload = tts
1936
+ ? { text, model_id: 'eleven_multilingual_v2' }
1937
+ : { text, duration_seconds: flag('duration') ? Number(flag('duration')) : undefined };
1938
+
1939
+ process.stdout.write(`Generating ${tts ? 'speech' : 'sound effect'} with ElevenLabs... `);
1940
+ const resp = await fetch(url, {
1941
+ method: 'POST',
1942
+ headers: { 'xi-api-key': key, 'Content-Type': 'application/json' },
1943
+ body: JSON.stringify(payload)
1944
+ });
1945
+ if (!resp.ok) {
1946
+ const errText = (await resp.text().catch(() => '')).slice(0, 300);
1947
+ throw new Error(`ElevenLabs HTTP ${resp.status}: ${errText}`);
1948
+ }
1949
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
1950
+ fs.writeFileSync(dest, Buffer.from(await resp.arrayBuffer()));
1951
+ console.log(green('done ✓'));
1952
+ console.log(`${green('✓')} saved ${dest} (playing it)`);
1953
+ try { execFileSync(soundPlayer() ?? 'afplay', [dest]); } catch { /* (no sound here: it is saved all the same) */ }
1954
+ console.log(dim(`use it: sideora sounds set alarm ${out}`));
1955
+ return;
1956
+ }
1957
+
1958
+ throw new Error('usage: sideora sounds [all | set <alert> <Sound[:N]> | gen "<text>" …]');
1959
+ }
1960
+
1961
+ function elevenLabsKey() {
1962
+ if (process.env.ELEVENLABS_API_KEY) return process.env.ELEVENLABS_API_KEY.trim();
1963
+ const kept = keychainRead('sideora-elevenlabs', 'default');
1964
+ if (kept?.trim()) return kept.trim();
1965
+ {
1966
+ throw new Error(
1967
+ 'No ElevenLabs API key. Either export ELEVENLABS_API_KEY, or store it in the Keychain:\n' +
1968
+ ' security add-generic-password -U -s sideora-elevenlabs -a default -w (a bare -w asks for it)'
1969
+ );
1970
+ }
1971
+ }
1972
+
1973
+ function completion() {
1974
+ const shell = (args[0] && !args[0].startsWith('--') ? args[0] : null)
1975
+ || ((process.env.SHELL || '').includes('bash') ? 'bash' : 'zsh');
1976
+ if (args.includes('--install')) {
1977
+ if (shell !== 'zsh' && shell !== 'bash') throw new Error('usage: sideora completion <zsh|bash> --install');
1978
+ const rc = path.join(os.homedir(), shell === 'zsh' ? '.zshrc' : '.bashrc');
1979
+ const line = `command -v sideora >/dev/null && eval "$(sideora completion ${shell})"`;
1980
+ const current = fs.existsSync(rc) ? fs.readFileSync(rc, 'utf8') : '';
1981
+ if (current.includes('sideora completion')) {
1982
+ console.log('• already installed in', rc);
1983
+ return;
1984
+ }
1985
+ fs.appendFileSync(rc, `\n# Sideora tab completion\n${line}\n`);
1986
+ console.log(green('✓') + ` added to ${rc} — restart your shell (or: source ${rc})`);
1987
+ return;
1988
+ }
1989
+ if (shell === 'zsh') {
1990
+ console.log(`_sideora() {
1991
+ local -a cmds
1992
+ cmds=(
1993
+ 'status:daemon, last check, credentials health'
1994
+ 'doctor:check the whole setup and say what to fix'
1995
+ 'list:list a mail folder'
1996
+ 'search:search the inbox'
1997
+ 'read:read a message'
1998
+ 'attachments:list or download the attachments of a mail'
1999
+ 'compose:write a new mail (draft by default)'
2000
+ 'reply:reply to a mail (draft by default)'
2001
+ 'rules:list and manage watch rules'
2002
+ 'events:live-subscribe to daemon events'
2003
+ 'calendar:agenda, events, free/busy (Exchange)'
2004
+ 'watch:run the watch loop in the foreground'
2005
+ 'install-daemon:install and start the background watcher'
2006
+ 'uninstall-daemon:stop and remove the background watcher'
2007
+ 'mcp:run the MCP server for agents'
2008
+ 'install-mcp:register the MCP server in Claude Code'
2009
+ 'web:the app as a page in a browser on this computer'
2010
+ 'relay:the web app from another device, through a relay'
2011
+ 'install-extension:register the Chrome side-panel bridge'
2012
+ 'setup:add or edit an account'
2013
+ 'accounts:list configured accounts'
2014
+ 'op-token:store or clear the 1Password service account token'
2015
+ 'cache:local cache stats / clear / prune'
2016
+ 'ui:interactive inbox (TUI)'
2017
+ 'test:connectivity check'
2018
+ 'completion:print a shell completion script'
2019
+ 'help:full usage'
2020
+ )
2021
+ local -a folders; folders=(inbox junk sent drafts trash archive)
2022
+ if (( CURRENT == 2 )); then
2023
+ _describe 'command' cmds
2024
+ return
2025
+ fi
2026
+ case $words[2] in
2027
+ list) _arguments '--account[account]:name:' '--live[bypass the local cache]' '--unread[only unread]' '--folder[folder]:folder:($folders)' '--limit[max results]:n:' '--json[JSON output]' '--ids[show full ids]' ;;
2028
+ awaiting) _arguments '--days[look-back days]:n:' '--account[account]:name:' '--no-cc[skip threads where I am only in Cc]' '--since[cursor]:date:' '--limit[max threads]:n:' '--json[JSON output]' '--ids[show full ids]' ;;
2029
+ microsoft-login) _arguments '--label[name it is shown by]:label:' '--port[local port, for a tunnel]:port:' '--no-open[print the URL instead of opening the browser]' ;;
2030
+ google-login) _arguments '1:account:' '--no-open[print the URL instead of opening the browser]' ;;
2031
+ thread) _arguments '--subject[subject]:text:' '--days[look-back days]:n:' '--account[account]:name:' '--json[JSON output]' '--ids[show full ids]' ;;
2032
+ search) _arguments '--account[account]:name:' '--live[bypass the local cache]' '--from[sender substring]:text:' '--subject[subject substring]:text:' '--days[last N days]:n:' '--unread[only unread]' '--folder[folder]:folder:($folders)' '--limit[max results]:n:' '--json[JSON output]' '--ids[show full ids]' ;;
2033
+ attachments) _arguments '--save[download to DIR]:dir:_files -/' '--only[one attachment by name]:name:' '--json[JSON output]' ;;
2034
+ read) _arguments '--live[bypass the local cache]' '--from[sender substring]:text:' '--subject[subject substring]:text:' '--plain[no HTML rendering]' '--json[JSON output]' ;;
2035
+ reply) _arguments '--all[reply to all]' '--body[body text]:text:' '--markdown[body is Markdown]' '--html[body is HTML]' '--send[send instead of saving a draft]' '--json[JSON output]' ;;
2036
+ compose) _arguments '--account[account]:name:' '--to[recipients]:emails:' '--cc[cc recipients]:emails:' '--subject[subject]:text:' '--body[body text]:text:' '--markdown[body is Markdown]' '--html[body is HTML]' '*--attach[attach a file]:file:_files' '*--inline[embed an image]:file:_files' '--send[send instead of saving a draft]' ;;
2037
+ rules) _arguments '1:action:(list add rm enable disable edit quiet)' '--name[rule name]:text:' '--senders[senders]:text:' '--subjects[keywords]:text:' '--sound[sound]:sound:(alarm chime ding message)' '--no-notify[no desktop notification]' '--wake[wake a Claude agent]' '--model[agent model]:model:' '--account[account]:name:' '--start[quiet start]:hh\\:mm:' '--end[quiet end]:hh\\:mm:' '--json[JSON output]' ;;
2038
+ accounts) _arguments '1:action:(rm)' ;;
2039
+ op-token) _arguments '1:action:(set clear)' ;;
2040
+ cache) _arguments '1:action:(clear prune)' ;;
2041
+ events) _arguments '1:action:(cursor)' '--wait[block until the next mail event]' '--after[cursor]:n:' '--timeout[seconds]:n:' '--all[every new mail, not only rule matches]' '--account[account]:name:' '--rule[rule name]:text:' '--types[event types]:types:' '--json[JSON output]' ;;
2042
+ calendar|cal) _arguments '1:action:(calendars show create update delete accept tentative decline freebusy free)' '--days[days ahead]:n:' '--from[start]:date:' '--to[end]:date:' '--calendar[calendar name or email]:name:' '--mailbox[email]:email:' '--account[account]:name:' '--subject[subject]:text:' '--start[start]:date:' '--end[end]:date:' '--duration[duration]:dur:' '--location[location]:text:' '--body[description]:text:' '--attendees[emails]:emails:' '--optional[emails]:emails:' '--all-day[all-day event]' '--reminder[minutes]:n:' '--message[note]:text:' '--no-notify[do not mail attendees]' '--interval[minutes]:n:' '--hours[window]:hh-hh:' '--weekends[include weekends]' '--tentative-ok[tentative counts as free]' '--json[JSON output]' '--ids[show full ids]' ;;
2043
+ completion) _arguments '1:shell:(zsh bash)' ;;
2044
+ esac
2045
+ }
2046
+ compdef _sideora sideora`);
2047
+ } else if (shell === 'bash') {
2048
+ console.log(`_sideora() {
2049
+ local cur prev
2050
+ cur="\${COMP_WORDS[COMP_CWORD]}"
2051
+ if [ "\$COMP_CWORD" -eq 1 ]; then
2052
+ COMPREPLY=( \$(compgen -W "status doctor list search read awaiting thread google-login compose watch install-daemon uninstall-daemon attachments reply calendar events rules mcp install-mcp web relay install-extension setup accounts op-token cache ui test completion help" -- "\$cur") )
2053
+ return
2054
+ fi
2055
+ case "\${COMP_WORDS[1]}" in
2056
+ list) COMPREPLY=( \$(compgen -W "--unread --folder --limit --json --ids" -- "\$cur") ) ;;
2057
+ search) COMPREPLY=( \$(compgen -W "--from --subject --text --to --from-me --since --until --days --unread --folder --limit --json --ids" -- "\$cur") ) ;;
2058
+ awaiting) COMPREPLY=( \$(compgen -W "--days --account --no-cc --since --limit --json --ids" -- "\$cur") ) ;;
2059
+ thread) COMPREPLY=( \$(compgen -W "--subject --days --account --json --ids" -- "\$cur") ) ;;
2060
+ read) COMPREPLY=( \$(compgen -W "--from --subject --plain --json" -- "\$cur") ) ;;
2061
+ compose) COMPREPLY=( \$(compgen -W "--to --cc --subject --body --markdown --html --attach --inline --send" -- "\$cur") ) ;;
2062
+ calendar|cal) COMPREPLY=( \$(compgen -W "calendars show create update delete accept tentative decline freebusy free --days --from --to --calendar --subject --start --end --duration --location --attendees --all-day --reminder --json" -- "\$cur") ) ;;
2063
+ esac
2064
+ if [ "\$prev" = "--folder" ]; then
2065
+ COMPREPLY=( \$(compgen -W "inbox junk sent drafts trash archive" -- "\$cur") )
2066
+ fi
2067
+ }
2068
+ complete -F _sideora sideora`);
2069
+ } else {
2070
+ throw new Error('usage: sideora completion <zsh|bash>');
2071
+ }
2072
+ }
2073
+
2074
+ // --- calendar -----------------------------------------------------------------
2075
+
2076
+ async function calendar() {
2077
+ const { calendar: cal } = await import('../src/core.js');
2078
+ const sub = args[0] && !args[0].startsWith('--') ? args[0] : 'agenda';
2079
+ const rest = args.slice(sub === 'agenda' ? 0 : 1);
2080
+ const token = rest[0] && !rest[0].startsWith('--') ? rest[0] : null;
2081
+ const account = flag('account') || undefined;
2082
+ const when = (v, d) => (v ? cal.parseWhen(v) : d);
2083
+ const notify = !args.includes('--no-notify');
2084
+ const out = (o) => console.log(JSON.stringify(o, null, 2));
2085
+
2086
+ switch (sub) {
2087
+ case 'agenda': case 'list': case 'upcoming': {
2088
+ const days = Number(flag('days')) || 7;
2089
+ const start = when(flag('from'), cal.dayStart());
2090
+ const end = when(flag('to'), new Date(start.getTime() + days * 86400e3));
2091
+ const items = await spin('loading calendar…', cal.listEvents({ account, start, end, calendar: flag('calendar') || undefined, limit: Number(flag('limit')) || 200, onError: warnAccount }));
2092
+ return printEvents(items, { start, end });
2093
+ }
2094
+ case 'calendars': {
2095
+ const list = await spin('loading calendars…', cal.listCalendars(account, { mailbox: flag('mailbox') || undefined, onError: warnAccount }));
2096
+ if (asJson) return out(list);
2097
+ if (list.length === 0) return console.log(dim('(no calendars)'));
2098
+ const multi = accountNames(loadConfig()).length > 1;
2099
+ for (const c of list) console.log(` ${c.isDefault ? green('●') : c.shared ? cyan('⇄') : ' '} ${multi ? yellow(c.account.padEnd(10)) : ''}${bold(c.name)} ${dim(c.shared ? `shared${c.owner ? ' — ' + c.owner : ''}${c.mailbox ? ` <${c.mailbox}>` : c.id && c.id.includes('@') && !c.owner ? ` <${c.id.split(':').slice(1).join(':')}>` : ''}` : `${c.itemCount != null ? c.itemCount + ' item(s)' : c.writable === false ? 'read-only' : ''}${c.mailbox ? ' · shared by ' + c.mailbox : ''}`)}${args.includes('--ids') && c.id ? dim('\n id: ' + c.id) : ''}`);
2100
+ if (list.some((c) => c.shared)) console.log(dim('\n ⇄ shared calendars: sideora calendar --calendar "<name>"'));
2101
+ return;
2102
+ }
2103
+ case 'show': case 'read': {
2104
+ if (!token) throw new Error('usage: sideora calendar show #N | <id>');
2105
+ const ev = await spin('reading event…', cal.readEvent(resolveEventId(token)));
2106
+ if (asJson) return out(ev);
2107
+ return printEvent(ev);
2108
+ }
2109
+ case 'create': case 'add': case 'new': {
2110
+ const subject = flag('subject');
2111
+ const startRaw = flag('start') || flag('at');
2112
+ if (!subject || !startRaw) throw new Error('usage: sideora calendar create --subject S --start D [--end D | --duration 30m] [--location L] [--body B] [--attendees a,b] [--optional c] [--all-day] [--reminder N] [--calendar C] [--no-notify]');
2113
+ const allDay = args.includes('--all-day');
2114
+ const start = cal.parseWhen(startRaw);
2115
+ const end = flag('end') ? cal.parseWhen(flag('end')) : new Date(start.getTime() + (allDay ? 86400e3 : cal.parseDuration(flag('duration'), 30) * 60e3));
2116
+ const split = (v) => (v ? v.split(/[,\s]+/).filter(Boolean) : []);
2117
+ const r = await spin('creating event…', cal.createEvent({
2118
+ account, calendar: flag('calendar') || undefined, subject, start, end, allDay,
2119
+ location: flag('location') || undefined, body: flag('body') || undefined,
2120
+ attendees: split(flag('attendees')), optionalAttendees: split(flag('optional')),
2121
+ reminderMinutes: flag('reminder') != null ? Number(flag('reminder')) : undefined,
2122
+ showAs: flag('show-as') || undefined, notify
2123
+ }));
2124
+ if (asJson) return out(r);
2125
+ console.log(`${green('✓')} created ${bold(subject)} — ${fmtRange(start, end, allDay)}${r.invitationsSent ? dim(' (invitations sent)') : ''}`);
2126
+ return console.log(dim('id: ' + r.id));
2127
+ }
2128
+ case 'update': case 'edit': case 'move': {
2129
+ if (!token) throw new Error('usage: sideora calendar update #N | <id> [--subject S] [--start D] [--end D] [--location L] [--body B] [--reminder N] [--attendees a,b] [--no-notify]');
2130
+ const fields = {};
2131
+ if (flag('subject') != null) fields.subject = flag('subject');
2132
+ if (flag('start')) fields.start = cal.parseWhen(flag('start'));
2133
+ if (flag('end')) fields.end = cal.parseWhen(flag('end'));
2134
+ if (flag('duration') && fields.start) fields.end = new Date(fields.start.getTime() + cal.parseDuration(flag('duration')) * 60e3);
2135
+ if (flag('location') != null) fields.location = flag('location');
2136
+ if (flag('body') != null) fields.body = flag('body');
2137
+ if (flag('reminder') != null) fields.reminderMinutes = Number(flag('reminder'));
2138
+ if (flag('show-as')) fields.showAs = flag('show-as');
2139
+ if (flag('attendees') != null) fields.attendees = flag('attendees').split(/[,\s]+/).filter(Boolean);
2140
+ if (args.includes('--all-day')) fields.allDay = true;
2141
+ if (Object.keys(fields).length === 0) throw new Error('nothing to change — pass --subject / --start / --end / --location / --body / --reminder / --attendees');
2142
+ const r = await spin('updating event…', cal.updateEvent({ id: resolveEventId(token), ...fields, notify }));
2143
+ if (asJson) return out(r);
2144
+ return console.log(`${green('✓')} updated ${dim(r.id)}`);
2145
+ }
2146
+ case 'delete': case 'rm': case 'remove': case 'cancel': {
2147
+ if (!token) throw new Error('usage: sideora calendar delete #N | <id> [--no-notify]');
2148
+ const id = resolveEventId(token);
2149
+ const ev = await cal.readEvent(id);
2150
+ await spin('deleting event…', cal.deleteEvent(id, { changeKey: ev.changeKey, notify }));
2151
+ if (asJson) return out({ ok: true, id });
2152
+ return console.log(`${green('✓')} deleted ${bold(ev.subject)}${ev.isMeeting && notify ? dim(' (attendees notified)') : ''}`);
2153
+ }
2154
+ case 'accept': case 'tentative': case 'decline': {
2155
+ if (!token) throw new Error(`usage: sideora calendar ${sub} #N | <id> [--message M] [--no-notify]`);
2156
+ const id = resolveEventId(token);
2157
+ await spin(`${sub}ing…`, cal.respondToEvent(id, sub, { message: flag('message') || undefined, notify }));
2158
+ if (asJson) return out({ ok: true, id, response: sub });
2159
+ return console.log(`${green('✓')} ${sub === 'tentative' ? 'tentatively accepted' : sub + 'ed'}${notify ? dim(' (organizer notified)') : ''}`);
2160
+ }
2161
+ case 'freebusy': case 'fb': case 'busy': {
2162
+ if (!token) throw new Error('usage: sideora calendar freebusy a@b[,c@d] [--from D] [--to D] [--interval 30]');
2163
+ const emails = token.split(/[,\s]+/).filter(Boolean);
2164
+ const start = when(flag('from'), cal.dayStart());
2165
+ const end = when(flag('to'), new Date(start.getTime() + 86400e3));
2166
+ const r = await spin('asking the server…', cal.freeBusy({ account, emails, start, end, intervalMinutes: Math.max(5, Number(flag('interval')) || 30) }));
2167
+ if (asJson) return out(r);
2168
+ for (const p of r) {
2169
+ console.log(`${cyan(p.email)} ${dim(p.ok ? `(${p.view})` : '— ' + p.error)}`);
2170
+ if (!p.ok) continue;
2171
+ if (p.events.length === 0) console.log(dim(' free the whole window'));
2172
+ for (const e of p.events) console.log(` ${fmtRange(e.start, e.end)} ${busyColor(e.status)}${e.subject ? ' ' + e.subject : ''}${e.location ? dim(' · ' + e.location) : ''}`);
2173
+ }
2174
+ return;
2175
+ }
2176
+ case 'free': case 'slots': case 'find': {
2177
+ if (!token) throw new Error('usage: sideora calendar free a@b[,c@d] [--duration 30m] [--days 5] [--from D] [--hours 9-18] [--weekends] [--tentative-ok] [--max N]');
2178
+ const emails = token.split(/[,\s]+/).filter(Boolean);
2179
+ const start = when(flag('from'), new Date());
2180
+ const end = when(flag('to'), new Date(start.getTime() + (Number(flag('days')) || 5) * 86400e3));
2181
+ const hours = (flag('hours') || '9-18').split('-').map(Number);
2182
+ const r = await spin('finding free slots…', cal.findFreeSlots({
2183
+ account, emails, start, end, durationMinutes: cal.parseDuration(flag('duration'), 30),
2184
+ hoursFrom: hours[0], hoursTo: hours[1] || 18, weekends: args.includes('--weekends'), tentativeOk: args.includes('--tentative-ok'), max: Number(flag('max')) || 10
2185
+ }));
2186
+ if (asJson) return out(r);
2187
+ if (r.slots.length === 0) return console.log(dim(`no common ${r.durationMinutes}-minute slot for ${emails.join(', ')} in that window`));
2188
+ console.log(dim(`${r.durationMinutes} min, everyone free: ${emails.join(', ')}`));
2189
+ r.slots.forEach((s, i) => console.log(` ${dim(('#' + (i + 1)).padStart(3))} ${fmtRange(s.start, s.end)}`));
2190
+ return;
2191
+ }
2192
+ default:
2193
+ throw new Error(`unknown calendar command "${sub}" — see: sideora help`);
2194
+ }
2195
+ }
2196
+
2197
+ function resolveEventId(token) {
2198
+ if (/^#?\d+$/.test(token)) {
2199
+ const n = Number(token.replace('#', ''));
2200
+ let last = [];
2201
+ try { last = JSON.parse(fs.readFileSync(LAST_CAL_PATH, 'utf8')); } catch {}
2202
+ if (!last[n - 1]) throw new Error(`no #${n} in the last calendar listing — run sideora calendar first`);
2203
+ return last[n - 1].id;
2204
+ }
2205
+ if (!splitId(token).account) return `${getAccount(loadConfig(), flag('account')).name}:${token}`;
2206
+ return token;
2207
+ }
2208
+
2209
+ function fmtRange(start, end, allDay = false) {
2210
+ const s = new Date(start);
2211
+ const e = new Date(end);
2212
+ if (isNaN(s) || isNaN(e)) return `${start} → ${end}`;
2213
+ const pad = (n) => String(n).padStart(2, '0');
2214
+ const day = (d) => `${['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getDay()]} ${MONTHS[d.getMonth()]} ${pad(d.getDate())}`;
2215
+ const hm = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;
2216
+ if (allDay) {
2217
+ const lastDay = new Date(e.getTime() - 1);
2218
+ return day(s) === day(lastDay) ? `${day(s)} (all day)` : `${day(s)} → ${day(lastDay)} (all day)`;
2219
+ }
2220
+ const sameDay = s.toDateString() === e.toDateString();
2221
+ return sameDay ? `${day(s)} ${hm(s)}–${hm(e)}` : `${day(s)} ${hm(s)} → ${day(e)} ${hm(e)}`;
2222
+ }
2223
+
2224
+ function busyColor(status) {
2225
+ const s = String(status || '');
2226
+ if (/free/i.test(s)) return green(s);
2227
+ if (/tentative/i.test(s)) return yellow(s);
2228
+ return paint('31', s || 'Busy');
2229
+ }
2230
+
2231
+ function printEvents(items, { start, end } = {}) {
2232
+ ensureDirs();
2233
+ fs.writeFileSync(LAST_CAL_PATH, JSON.stringify(items.map((i) => ({ id: i.id, changeKey: i.changeKey }))));
2234
+ if (asJson) return console.log(JSON.stringify(items, null, 2));
2235
+ if (items.length === 0) return console.log(dim(`(no events ${start ? fmtRange(start, end).replace('–', ' → ') : ''})`));
2236
+ const multi = accountNames(loadConfig()).length > 1;
2237
+ let lastDay = '';
2238
+ items.forEach((e, idx) => {
2239
+ const s = new Date(e.start);
2240
+ const dayKey = s.toDateString();
2241
+ if (dayKey !== lastDay) {
2242
+ lastDay = dayKey;
2243
+ const today = s.toDateString() === new Date().toDateString();
2244
+ console.log(`\n${bold(`${['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][s.getDay()]} ${MONTHS[s.getMonth()]} ${s.getDate()}`)}${today ? dim(' (today)') : ''}`);
2245
+ }
2246
+ const pad = (n) => String(n).padStart(2, '0');
2247
+ const time = e.allDay ? dim('all day ') : `${pad(s.getHours())}:${pad(s.getMinutes())}–${pad(new Date(e.end).getHours())}:${pad(new Date(e.end).getMinutes())}`;
2248
+ const n = dim(('#' + (idx + 1)).padStart(3));
2249
+ const mark = e.isCancelled ? paint('31', '✗') : e.myResponse === 'NoResponseReceived' && e.isMeeting ? yellow('?') : e.myResponse === 'Tentative' ? yellow('~') : ' ';
2250
+ let subject = e.subject || dim('(no subject)');
2251
+ if (e.isCancelled) subject = dim('CANCELLED: ') + subject;
2252
+ const where = e.location ? dim(' · ' + e.location.slice(0, 40)) : '';
2253
+ const who = e.isMeeting && e.organizerName ? dim(' — ' + e.organizerName) : '';
2254
+ const acct = multi ? yellow(String(e.account).slice(0, 9).padEnd(10)) : '';
2255
+ console.log(` ${mark} ${n} ${time} ${acct}${subject}${where}${who}${e.isRecurring ? dim(' ↻') : ''}`);
2256
+ if (args.includes('--ids')) console.log(dim(` id: ${e.id}`));
2257
+ });
2258
+ console.log(dim(`\n ${items.length} event(s) — details: sideora calendar show #<n> ${yellow('?')} = invitation awaiting your reply`));
2259
+ }
2260
+
2261
+ function printEvent(ev) {
2262
+ if (accountNames(loadConfig()).length > 1) console.log(`${dim('Account:')} ${yellow(ev.account)}`);
2263
+ console.log(`${dim('Subject:')} ${bold(ev.subject)}${ev.isCancelled ? paint('31', ' (cancelled)') : ''}`);
2264
+ console.log(`${dim('When:')} ${fmtRange(ev.start, ev.end, ev.allDay)}${ev.isRecurring ? dim(' (recurring)') : ''}`);
2265
+ if (ev.location) console.log(`${dim('Where:')} ${ev.location}`);
2266
+ if (ev.organizerEmail) console.log(`${dim('Organizer:')}${cyan(` ${ev.organizerName} <${ev.organizerEmail}>`)}`);
2267
+ if (ev.isMeeting) console.log(`${dim('Response:')} ${ev.myResponse}`);
2268
+ console.log(`${dim('Show as:')} ${ev.showAs}${ev.reminderMinutes != null ? dim(` · reminder ${ev.reminderMinutes} min before`) : ''}`);
2269
+ if (ev.attendees && ev.attendees.length) {
2270
+ console.log(dim('Attendees:'));
2271
+ for (const a of ev.attendees) console.log(` ${a.name || a.email} ${dim('<' + a.email + '>')} ${dim(a.role)} ${a.response === 'Accept' ? green(a.response) : a.response === 'Decline' ? paint('31', a.response) : dim(a.response)}`);
2272
+ }
2273
+ console.log(dim('id: ' + ev.id));
2274
+ if (ev.body && ev.body.trim()) console.log('\n' + ev.body.trim());
2275
+ }
2276
+
2277
+ /**
2278
+ * Sideora in one step, the rest from the browser: a configuration of its own (none yet: no account, set up from the
2279
+ * page), the background watcher, the web app as a service, and, while no browser is paired, a link that pairs one:
2280
+ * opened here where there is a screen, printed in any case. Holding it is what makes one the owner: the page is not
2281
+ * open to whoever reaches it first.
2282
+ */
2283
+ async function installAll() {
2284
+ // (an install from before the rename: moved over first, its services set up again from here)
2285
+ const { oldFound } = await import('../src/migrate.js');
2286
+ if (oldFound()) {
2287
+ if (!await migrateCmd()) throw new Error('the install from before the rename is not all moved over (said above): nothing more was set up');
2288
+ }
2289
+ ensureDirs();
2290
+ // (what would refuse the web app's service refuses all of it, before anything is set up: never half an install)
2291
+ const service = await import('../src/web-service.js');
2292
+ const unfit = service.unfitToStay(SELF, service.stableNode());
2293
+ if (unfit && !args.includes('--here')) throw new Error(`${unfit}`);
2294
+ const fresh = !fs.existsSync(CONFIG_PATH);
2295
+ if (fresh) {
2296
+ saveConfig({ ...DEFAULT_CONFIG, accounts: {} });
2297
+ console.log(green('✓') + ' a new Sideora: no mail account yet (they are added from the web app)');
2298
+ }
2299
+ installDaemon();
2300
+ args.unshift('install');
2301
+ const at = await web(); // (the web app's service, as `web install` sets it up, with the same flags: where it answered)
2302
+ if (!at) return; // (said already: it has not answered yet)
2303
+ const access = await import('../src/web-access.js');
2304
+ const home = `http://127.0.0.1:${at}`;
2305
+ // (a link for a new Sideora, or one no browser is paired to yet; installed again over one in use, none: a link is
2306
+ // a way in for ten minutes to whoever reads what was printed, and pairing another is asked for by name)
2307
+ if (!fresh && access.listSessions().length && !args.includes('--pair')) {
2308
+ console.log(`\nSideora is at ${bold(home)} ${dim('(`sideora web pair` pairs another browser)')}`);
2309
+ return;
2310
+ }
2311
+ const { code } = access.newPairingCode();
2312
+ const url = `${home}/#pair=${code}`;
2313
+ // (a screen of the person's own: not one reached over SSH, where the browser would open on a screen of the machine
2314
+ // that someone else may be at, and use the link up there)
2315
+ const remote = !!(process.env.SSH_CONNECTION || process.env.SSH_TTY);
2316
+ const screen = !remote && (process.platform === 'darwin' || !!(process.env.DISPLAY || process.env.WAYLAND_DISPLAY));
2317
+ console.log(`\n${bold('Open Sideora to finish setting it up:')} ${cyan(url)}`);
2318
+ console.log(dim(' good once, for ten minutes: the browser that opens it first is paired to this Sideora (`sideora web pair` makes another)'));
2319
+ if (screen && !args.includes('--no-open')) {
2320
+ spawn(process.platform === 'darwin' ? 'open' : 'xdg-open', [url], { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
2321
+ console.log(dim(' opened in this computer\'s browser'));
2322
+ } else if (!screen) {
2323
+ console.log(dim(` from your own computer: \`ssh -N -L ${at}:127.0.0.1:${at} <this one>\`, then open the link there`));
2324
+ }
2325
+ }
2326
+
2327
+ /**
2328
+ * `sideora migrate` (src/migrate.js): an install from before the rename moved over to Sideora's names. Its services
2329
+ * are set up again from here, so the same place as `install` is asked of this program. → whether all of it was done.
2330
+ */
2331
+ async function migrateCmd() {
2332
+ const m = await import('../src/migrate.js');
2333
+ const service = await import('../src/web-service.js');
2334
+ const old = m.findOld();
2335
+ const unfit = service.unfitToStay(SELF, service.stableNode());
2336
+ // (the services are set up from here: on a first run that finds them, and on a run that finishes one cut short)
2337
+ const journal = old.journal ? JSON.parse(fs.readFileSync(old.journal, 'utf8') || '{}') : {};
2338
+ if (unfit && (old.services.length || journal.daemon || journal.web) && !args.includes('--here')) throw new Error(`${unfit} (the services run from here; \`--here\` sets them up all the same)`);
2339
+ const { EXT_BROWSERS, extHostDir } = extHost();
2340
+ const steps = {
2341
+ hostDirs: () => Object.values(EXT_BROWSERS).map(extHostDir),
2342
+ installExtension: () => installExtension(),
2343
+ writeMcpConfig: () => writeMcpConfig(),
2344
+ mcpRegistered: (name) => {
2345
+ const claude = findClaude();
2346
+ if (!claude) return false;
2347
+ try { execFileSync(claude, ['mcp', 'get', name], { stdio: 'ignore', timeout: 30_000 }); return true; } catch { return false; }
2348
+ },
2349
+ installMcp: () => installMcp(),
2350
+ removeMcp: (name) => { try { execFileSync(findClaude(), ['mcp', 'remove', '--scope', 'user', name], { stdio: 'ignore', timeout: 30_000 }); } catch { /* not there */ } },
2351
+ // the Claude Code plugin: "mailwatcher" of the marketplace of that name before the rename, "sideora" now
2352
+ plugins: () => {
2353
+ const claude = findClaude();
2354
+ if (!claude) return [];
2355
+ const out = execFileSync(claude, ['plugin', 'list', '--json'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 60_000 });
2356
+ // (each plugin by its id, "name@marketplace", or by its name and its marketplace)
2357
+ const ids = new Set();
2358
+ const walk = (v) => {
2359
+ if (Array.isArray(v)) return v.forEach(walk);
2360
+ if (!v || typeof v !== 'object') return;
2361
+ if (typeof v.id === 'string' && /^[\w.-]+@[\w.-]+$/.test(v.id)) ids.add(v.id);
2362
+ else if (typeof v.name === 'string' && typeof v.marketplace === 'string') ids.add(`${v.name}@${v.marketplace}`);
2363
+ Object.values(v).forEach(walk);
2364
+ };
2365
+ walk(JSON.parse(out));
2366
+ return [...ids];
2367
+ },
2368
+ installPlugin: () => {
2369
+ const claude = findClaude();
2370
+ if (!claude) throw new Error('Claude Code was not found');
2371
+ // (this checkout's own marketplace when it has one; else the repository's)
2372
+ const local = path.resolve(path.dirname(SELF), '..');
2373
+ const source = fs.existsSync(path.join(local, '.claude-plugin', 'marketplace.json')) ? local : 'sideorahq/sideora';
2374
+ const quiet = { stdio: ['ignore', 'ignore', 'pipe'], timeout: 120_000 };
2375
+ execFileSync(claude, ['plugin', 'marketplace', 'add', source], quiet);
2376
+ execFileSync(claude, ['plugin', 'install', 'sideora@sideora'], quiet);
2377
+ if (!steps.plugins().includes('sideora@sideora')) throw new Error('Claude Code does not list it');
2378
+ },
2379
+ removePlugin: (id) => execFileSync(findClaude(), ['plugin', 'uninstall', id], { stdio: 'ignore', timeout: 60_000 }),
2380
+ removeMarketplace: (name) => execFileSync(findClaude(), ['plugin', 'marketplace', 'remove', name], { stdio: 'ignore', timeout: 60_000 }),
2381
+ installDaemon: () => installDaemon(),
2382
+ installWeb: ({ port, admin = true }) => service.installWebService({ self: SELF, port, admin })
2383
+ };
2384
+ const { problems } = m.migrate({ steps, log: (line) => console.log(line.startsWith('✓') ? green('✓') + line.slice(1) : line.startsWith('✗') ? red('✗') + line.slice(1) : dim(line)) });
2385
+ if (problems.length) {
2386
+ console.log(yellow(`\n${problems.length} thing${problems.length === 1 ? '' : 's'} not done (above): what they hold is kept where it was. Run \`sideora migrate\` again once fixed.`));
2387
+ process.exitCode = 1;
2388
+ return false;
2389
+ }
2390
+ return true;
2391
+ }
2392
+
2393
+ function installDaemon() {
2394
+ ensureDirs();
2395
+ loadConfig(); // fail early if setup hasn't run
2396
+ if (systemd.isLinux) {
2397
+ systemd.install('daemon', systemd.unitText({ description: 'Sideora: the background watcher and hub', args: [process.execPath, SELF, 'watch'], env: { ...HOME_ENV }, log: path.join(LOG_DIR, 'daemon.log'), restart: 'always', restartSec: 5 }));
2398
+ console.log(green('✓') + ' daemon installed and started: ' + systemd.unitName('daemon') + dim(' (systemd user unit; for it to run with nobody logged in: sudo loginctl enable-linger ' + os.userInfo().username + ')'));
2399
+ return;
2400
+ }
2401
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
2402
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2403
+ <plist version="1.0">
2404
+ <dict>
2405
+ <key>Label</key><string>${PLIST_LABEL}</string>
2406
+ <key>ProgramArguments</key>
2407
+ <array>
2408
+ <string>${stableNode()}</string>
2409
+ <string>${SELF}</string>
2410
+ <string>watch</string>
2411
+ </array>
2412
+ <key>RunAtLoad</key><true/>
2413
+ <key>KeepAlive</key><true/>
2414
+ <key>StandardOutPath</key><string>${path.join(LOG_DIR, 'daemon.log')}</string>
2415
+ <key>StandardErrorPath</key><string>${path.join(LOG_DIR, 'daemon.log')}</string>
2416
+ <key>EnvironmentVariables</key>
2417
+ <dict>
2418
+ <key>PATH</key><string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>${Object.entries(HOME_ENV).map(([k, v]) => `
2419
+ <key>${k}</key><string>${xmlText(v)}</string>`).join('')}
2420
+ </dict>
2421
+ </dict>
2422
+ </plist>
2423
+ `;
2424
+ fs.mkdirSync(path.dirname(PLIST_PATH), { recursive: true });
2425
+ fs.writeFileSync(PLIST_PATH, plist);
2426
+ try { execFileSync('launchctl', ['unload', PLIST_PATH], { stdio: 'ignore' }); } catch {}
2427
+ execFileSync('launchctl', ['load', PLIST_PATH]);
2428
+ console.log(green('✓') + ' daemon installed and started: ' + PLIST_LABEL);
2429
+ console.log(' logs:', path.join(LOG_DIR, 'daemon.log'));
2430
+ }
16
2431
 
17
- This is an early release: there is nothing to run yet.
18
- Follow along at https://sideora.com`);
2432
+ function uninstallDaemon() {
2433
+ if (systemd.isLinux) { systemd.uninstall('daemon'); console.log(green('✓') + ' daemon stopped and removed'); return; }
2434
+ try { execFileSync('launchctl', ['unload', PLIST_PATH], { stdio: 'ignore' }); } catch {}
2435
+ if (fs.existsSync(PLIST_PATH)) fs.unlinkSync(PLIST_PATH);
2436
+ console.log(green('✓') + ' daemon stopped and removed');
19
2437
  }