sideora 0.0.1-alpha.0 → 0.1.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/LICENSE.md +9 -0
  2. package/README.md +57 -6
  3. package/assets/sounds/freesound_community-mail-40275.mp3 +0 -0
  4. package/assets/sounds/mixkit-clear-announce-tones-2861.wav +0 -0
  5. package/assets/sounds/mixkit-happy-bells-notification-937.wav +0 -0
  6. package/assets/sounds/mixkit-musical-alert-notification-2309.wav +0 -0
  7. package/assets/sounds/nice-chime.mp3 +0 -0
  8. package/bin/sideora.js +2430 -12
  9. package/extension/dist/assets/background.ts-NW8YqAlO.js +1 -0
  10. package/extension/dist/assets/fillCode-Ci8IkBvY.js +1 -0
  11. package/extension/dist/assets/index.html-DrrPha1M.js +2 -0
  12. package/extension/dist/assets/modulepreload-polyfill-DcjICKwh.js +1 -0
  13. package/extension/dist/assets/shell-82MNMljp.css +1 -0
  14. package/extension/dist/assets/shell-QYBN1bx1.js +1 -0
  15. package/extension/dist/icons/icon-128.png +0 -0
  16. package/extension/dist/icons/icon-16.png +0 -0
  17. package/extension/dist/icons/icon-32.png +0 -0
  18. package/extension/dist/icons/icon-48.png +0 -0
  19. package/extension/dist/manifest.json +40 -0
  20. package/extension/dist/service-worker-loader.js +1 -0
  21. package/extension/dist/src/newtab/index.html +14 -0
  22. package/extension/dist/src/panel/index.html +15 -0
  23. package/extension/dist-web/assets/abnfDiagram-WEYOIA3C-CoXOc872.js +1 -0
  24. package/extension/dist-web/assets/apple-touch-icon-DSgRQASq.png +0 -0
  25. package/extension/dist-web/assets/architecture-WOLXFQ4H-BkJ4AerO.js +1 -0
  26. package/extension/dist-web/assets/architectureDiagram-ZHVYKT53-aPkSDlxA.js +36 -0
  27. package/extension/dist-web/assets/blockDiagram-RJAE7QA3-CH1G4NBZ.js +140 -0
  28. package/extension/dist-web/assets/c4Diagram-XDPPPE54-Baum1zDu.js +38 -0
  29. package/extension/dist-web/assets/channel-PsQg-mnK.js +1 -0
  30. package/extension/dist-web/assets/chunk-2E7WHVMD-CKvLrWRa.js +88 -0
  31. package/extension/dist-web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  32. package/extension/dist-web/assets/chunk-4EMNKR2T-6fjnroCZ.js +1 -0
  33. package/extension/dist-web/assets/chunk-55XCU76K-Ygs3sNpi.js +1 -0
  34. package/extension/dist-web/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  35. package/extension/dist-web/assets/chunk-7S6XSTFO-iX5xYzfP.js +2 -0
  36. package/extension/dist-web/assets/chunk-AQDTSKZB-D9zwhFI8.js +72 -0
  37. package/extension/dist-web/assets/chunk-DSNLSHJZ-siGS-4qu.js +129 -0
  38. package/extension/dist-web/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  39. package/extension/dist-web/assets/chunk-HAGFOTED-_3dtnWXn.js +62 -0
  40. package/extension/dist-web/assets/chunk-HNE4Q36P-BPzRHi72.js +1 -0
  41. package/extension/dist-web/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  42. package/extension/dist-web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  43. package/extension/dist-web/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  44. package/extension/dist-web/assets/chunk-NQOKRVIF-AXbmOBjs.js +213 -0
  45. package/extension/dist-web/assets/chunk-UHW7PFBP-B3xrZ8sD.js +1 -0
  46. package/extension/dist-web/assets/chunk-VQ5W62QI-D_k7Pa6b.js +1 -0
  47. package/extension/dist-web/assets/chunk-WQQL4CDK-BBIrWwoZ.js +10 -0
  48. package/extension/dist-web/assets/chunk-XXDRQBXY-i7MKP1NY.js +1 -0
  49. package/extension/dist-web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  50. package/extension/dist-web/assets/chunk-YZO67HFG-Z7qp5QAI.js +1 -0
  51. package/extension/dist-web/assets/chunk-ZAUX2LTX-CSt3c0Rb.js +1 -0
  52. package/extension/dist-web/assets/chunk-ZCHMQSOR-g8XRABGK.js +2 -0
  53. package/extension/dist-web/assets/classDiagram-v2-4MYWR3UA-BL706wzc.js +217 -0
  54. package/extension/dist-web/assets/cose-bilkent-JH36ORCC-C6J2IoHg.js +1 -0
  55. package/extension/dist-web/assets/cynefin-EF2NZ3EQ-DLhQOiAy.js +1 -0
  56. package/extension/dist-web/assets/cynefinDiagram-WF24UDRP-Cv9Lx6_l.js +62 -0
  57. package/extension/dist-web/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  58. package/extension/dist-web/assets/d3-scale-CElPUUud.js +1 -0
  59. package/extension/dist-web/assets/d3-selection-COWvaQNI.js +1 -0
  60. package/extension/dist-web/assets/dagre-NK4GIZVX-ngM-w2EC.js +4 -0
  61. package/extension/dist-web/assets/diagram-CBK3MWTC-kp8sayNG.js +24 -0
  62. package/extension/dist-web/assets/diagram-I5XIIV2D-BZ_Dgs6K.js +24 -0
  63. package/extension/dist-web/assets/diagram-ODIL2UCW-DWhUyArG.js +30 -0
  64. package/extension/dist-web/assets/diagram-PFBEJUXE-CBAdEK7l.js +3 -0
  65. package/extension/dist-web/assets/diagram-RJA3I4VV-kOdIr_3K.js +41 -0
  66. package/extension/dist-web/assets/diagram-TYUNFSNR-BrWGa0x5.js +200 -0
  67. package/extension/dist-web/assets/dist-DdXDFcej.js +1 -0
  68. package/extension/dist-web/assets/docx-preview-D1zbEiLy.js +20 -0
  69. package/extension/dist-web/assets/earth-Ce3xs8Cb.webp +0 -0
  70. package/extension/dist-web/assets/ebnfDiagram-V4P3TTPT-0r3weWmj.js +1 -0
  71. package/extension/dist-web/assets/elk-QONTBCTQ-D3oElRZ3.js +27 -0
  72. package/extension/dist-web/assets/erDiagram-KYQIGQAA-B9oU7_j_.js +99 -0
  73. package/extension/dist-web/assets/eventmodeling-K75KTNOO-CMKgc1nP.js +1 -0
  74. package/extension/dist-web/assets/favicon-D_X6tUVf.svg +5 -0
  75. package/extension/dist-web/assets/flowDiagram-IUGLLWBU-yRwks0Mw.js +1 -0
  76. package/extension/dist-web/assets/ganttDiagram-R7GPNTJY-cJqD1qwQ.js +292 -0
  77. package/extension/dist-web/assets/gitGraph-VSP46ZUC-CuBQqkbr.js +1 -0
  78. package/extension/dist-web/assets/gitGraphDiagram-PDYL7XHY-D7bHnQXC.js +106 -0
  79. package/extension/dist-web/assets/graphlib-DS17s2tU.js +1 -0
  80. package/extension/dist-web/assets/home-CV7-8Trs.js +1 -0
  81. package/extension/dist-web/assets/index-CQvw7Wy_.js +7 -0
  82. package/extension/dist-web/assets/index-CVKnZ21i.css +1 -0
  83. package/extension/dist-web/assets/info-OHQRW6UA-B8kyzV4O.js +1 -0
  84. package/extension/dist-web/assets/infoDiagram-MVDRKAX5-CEm6lezX.js +2 -0
  85. package/extension/dist-web/assets/ishikawaDiagram-HPEHV2GE-Ce3uv2wr.js +70 -0
  86. package/extension/dist-web/assets/journeyDiagram-BOSHW7O7-QgdahHCP.js +139 -0
  87. package/extension/dist-web/assets/jszip.min-3XXygzvy.js +2 -0
  88. package/extension/dist-web/assets/kanban-definition-FNSA4HC5-DPuTtWgR.js +89 -0
  89. package/extension/dist-web/assets/katex-MEuSR36T.js +257 -0
  90. package/extension/dist-web/assets/mermaid-parser.core-h7U7YGn_.js +7 -0
  91. package/extension/dist-web/assets/mermaid.core-DkGhophj.js +44 -0
  92. package/extension/dist-web/assets/mindmap-definition-6OY57UG3-D7VQxbda.js +98 -0
  93. package/extension/dist-web/assets/mount-CBzzf6KQ.js +195 -0
  94. package/extension/dist-web/assets/mount-DtvYnQXt.css +1 -0
  95. package/extension/dist-web/assets/officeparser.browser.slim-kEjhTrQ1.js +1989 -0
  96. package/extension/dist-web/assets/packet-JDAUHWVQ-oafHgw6X.js +1 -0
  97. package/extension/dist-web/assets/pegDiagram-ECIUJNBX-C3zo1naj.js +1 -0
  98. package/extension/dist-web/assets/peoria-B5TBlKDG.jpg +0 -0
  99. package/extension/dist-web/assets/peoria-thumb-CN8upAdZ.jpg +0 -0
  100. package/extension/dist-web/assets/pie-XZMESJXO-DXzeBQqF.js +1 -0
  101. package/extension/dist-web/assets/pieDiagram-GNMPY74T-S5NzPthl.js +39 -0
  102. package/extension/dist-web/assets/quadrantDiagram-D57K4MC3-C9glHQmk.js +7 -0
  103. package/extension/dist-web/assets/radar-ABXABTNO-CWTNqtbu.js +1 -0
  104. package/extension/dist-web/assets/railroad-I3PHUGI6-BTpD5_Bu.js +1 -0
  105. package/extension/dist-web/assets/railroad-abnf-LNEFI6M7-bWyxoXQG.js +1 -0
  106. package/extension/dist-web/assets/railroad-ebnf-DWYD2UWJ-ri5733DQ.js +1 -0
  107. package/extension/dist-web/assets/railroad-peg-JR7BVNR7-CmGfTubP.js +1 -0
  108. package/extension/dist-web/assets/railroadDiagram-Y72NRBL7-DTfe6Dh1.js +1 -0
  109. package/extension/dist-web/assets/requirementDiagram-EQYSW5RA-DQDzcS3L.js +84 -0
  110. package/extension/dist-web/assets/rolldown-runtime-COiEfhsA.js +1 -0
  111. package/extension/dist-web/assets/rough.esm-Dy-Kn_BL.js +1 -0
  112. package/extension/dist-web/assets/sankeyDiagram-SY24JHO5-DyMKWxdB.js +40 -0
  113. package/extension/dist-web/assets/sequenceDiagram-BLEHNHQU-dIkB1mCn.js +169 -0
  114. package/extension/dist-web/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  115. package/extension/dist-web/assets/stateDiagram-v2-A6IESKWZ-Bj_vxEVF.js +291 -0
  116. package/extension/dist-web/assets/swimlanes-B3ENRKFQ-BSkWEwHR.js +1 -0
  117. package/extension/dist-web/assets/swimlanesDiagram-AYQRV4AK-BTzSDlSM.js +8 -0
  118. package/extension/dist-web/assets/timeline-definition-JXYKGLGB-TwfWS0pw.js +120 -0
  119. package/extension/dist-web/assets/treeView-D4JQ5SDB-BzA_8YYb.js +1 -0
  120. package/extension/dist-web/assets/treemap-SAJKECNS-BI9d6--2.js +1 -0
  121. package/extension/dist-web/assets/usecaseDiagram-WPOLBNNX-BOVbAUPk.js +328 -0
  122. package/extension/dist-web/assets/vennDiagram-Q3Y3IDCW-X2kYAWaj.js +34 -0
  123. package/extension/dist-web/assets/wardley-7MLQ67FV-CItxqJ8G.js +1 -0
  124. package/extension/dist-web/assets/wardleyDiagram-IVAIDKWA-BnUXvKD_.js +78 -0
  125. package/extension/dist-web/assets/xychartDiagram-4URNHDU4-ysvBXvyE.js +7 -0
  126. package/extension/dist-web/icon-192.png +0 -0
  127. package/extension/dist-web/icon-512.png +0 -0
  128. package/extension/dist-web/index.html +25 -0
  129. package/extension/dist-web/manifest.webmanifest +14 -0
  130. package/package.json +64 -12
  131. package/plugin/.claude-plugin/icon.png +0 -0
  132. package/plugin/.claude-plugin/plugin.json +6 -0
  133. package/plugin/.mcp.json +8 -0
  134. package/plugin/README.md +72 -0
  135. package/plugin/mcp-launcher.mjs +48 -0
  136. package/src/account-probe.js +45 -0
  137. package/src/accounts.js +687 -0
  138. package/src/ai.js +269 -0
  139. package/src/assistant-runs.js +32 -0
  140. package/src/attached-mail.js +76 -0
  141. package/src/auth-gate.js +70 -0
  142. package/src/backup-cli.js +158 -0
  143. package/src/backup.js +329 -0
  144. package/src/bimi.js +233 -0
  145. package/src/bridge.js +101 -0
  146. package/src/calendar-alerts.js +56 -0
  147. package/src/chats.js +27 -0
  148. package/src/compose-editor.js +58 -0
  149. package/src/config.js +420 -0
  150. package/src/connections.d.ts +24 -0
  151. package/src/connections.js +37 -0
  152. package/src/core/agent.js +92 -0
  153. package/src/core/assistant.d.ts +13 -0
  154. package/src/core/assistant.js +790 -0
  155. package/src/core/chats.js +323 -0
  156. package/src/core/markdown.d.ts +8 -0
  157. package/src/core/markdown.js +239 -0
  158. package/src/core/notes.js +445 -0
  159. package/src/core/otp.js +152 -0
  160. package/src/core/rules.js +196 -0
  161. package/src/core/runs.d.ts +9 -0
  162. package/src/core/runs.js +211 -0
  163. package/src/core/thread.js +526 -0
  164. package/src/core/write.js +247 -0
  165. package/src/core-db.js +131 -0
  166. package/src/core.js +174 -0
  167. package/src/credentials.js +320 -0
  168. package/src/daemon.js +564 -0
  169. package/src/events.js +213 -0
  170. package/src/extension-id.d.ts +2 -0
  171. package/src/extension-id.js +5 -0
  172. package/src/file-lock.js +27 -0
  173. package/src/files-index.js +154 -0
  174. package/src/google-contacts.js +315 -0
  175. package/src/google-signin.js +306 -0
  176. package/src/host/assistant-html.js +44 -0
  177. package/src/host/chats-files.js +137 -0
  178. package/src/host/file-prep.js +122 -0
  179. package/src/host/notes-files.js +158 -0
  180. package/src/host/office-text.js +224 -0
  181. package/src/host/office-worker.js +8 -0
  182. package/src/host/rules-file.js +20 -0
  183. package/src/host/secrets-file.js +91 -0
  184. package/src/host/systemd.js +90 -0
  185. package/src/hub.js +245 -0
  186. package/src/identity.js +316 -0
  187. package/src/labels.js +5 -0
  188. package/src/mail-port.d.ts +79 -0
  189. package/src/mail-port.js +148 -0
  190. package/src/mcp-server.js +747 -0
  191. package/src/microsoft-app.js +20 -0
  192. package/src/microsoft-signin.js +194 -0
  193. package/src/migrate.js +327 -0
  194. package/src/notes-html.js +450 -0
  195. package/src/notes.js +19 -0
  196. package/src/notify.js +105 -0
  197. package/src/onepassword.js +223 -0
  198. package/src/op-registry.d.ts +14 -0
  199. package/src/op-registry.js +150 -0
  200. package/src/ops.js +1251 -0
  201. package/src/otp.js +6 -0
  202. package/src/panel-ops.js +273 -0
  203. package/src/pictures.js +735 -0
  204. package/src/postinstall.js +25 -0
  205. package/src/relay-passkey.js +122 -0
  206. package/src/relay-request.js +155 -0
  207. package/src/relay-seal.js +56 -0
  208. package/src/relay-settings.js +139 -0
  209. package/src/relay.js +876 -0
  210. package/src/render.js +82 -0
  211. package/src/rules-store.js +8 -0
  212. package/src/safe-fetch.js +215 -0
  213. package/src/sender-auth.js +270 -0
  214. package/src/site-match.js +77 -0
  215. package/src/tui-agenda.js +266 -0
  216. package/src/tui.js +670 -0
  217. package/src/vmc.js +376 -0
  218. package/src/wake.js +96 -0
  219. package/src/web-access.js +185 -0
  220. package/src/web-server.js +241 -0
  221. package/src/web-service.js +152 -0
package/src/ai.js ADDED
@@ -0,0 +1,269 @@
1
+ // AI models for the web app: the connections, their keys and the requests to
2
+ // the model, kept and made on this Mac.
3
+ //
4
+ // In the extension they live in its service worker (@amenophis1er/byok). A
5
+ // page in a browser has no worker of its own, and a key typed there should
6
+ // not stay there: here the same worker code runs in this process
7
+ // (useAiPlatform), so the page's settings and assistant talk to it with the
8
+ // same messages and get the same answers. Nothing secret goes back to the
9
+ // page: a connection is shown with the last characters of its key.
10
+ //
11
+ // Kept in $SIDEORA_HOME/ai.json (mode 600): the connections, their keys
12
+ // and tokens as AES-256-GCM ciphertext. The key that opens them is in the
13
+ // macOS Keychain, not in that file: a copy of the file alone opens nothing.
14
+ // An Ollama device key (Ed25519) is kept there too, its private half
15
+ // encrypted the same way.
16
+ //
17
+ // aiMessage({ type: 'mw:ai-…', … }) one message of the settings' client → its answer
18
+ // aiChat({ system, messages, tools, connectionId?, model? }) one model turn → { ok, text, toolCalls, … } | { ok: false, error }
19
+
20
+ import crypto from 'node:crypto';
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import { HOME_DIR, keychainReadStrictAsync, keychainWrite } from './config.js';
24
+
25
+ export const AI_PATH = path.join(HOME_DIR, 'ai.json');
26
+ export const AI_PREFIX = 'mw';
27
+ const KEY_SERVICE = 'sideora-ai';
28
+ const KEY_ACCOUNT = 'connections-key';
29
+ const { subtle } = crypto.webcrypto;
30
+
31
+ /**
32
+ * The messages of the settings' client that are answered (those of @amenophis1er/byok's createAiClient the panel
33
+ * sends). `ai-chat` (the settings' "try this connection") is a model turn like any other: it goes through `turn`.
34
+ */
35
+ const MESSAGES = new Set([
36
+ 'ai-get', 'ai-set-active', 'ai-save-connection', 'ai-delete-connection', 'ai-list-models', 'ai-chat',
37
+ 'ai-anthropic-login-start', 'ai-anthropic-login-complete', 'ai-anthropic-paste-token', 'ai-chatgpt-login-start', 'ai-chatgpt-login-poll',
38
+ 'ai-ollama-login-start', 'ai-ollama-login-poll', 'ai-opencode-login-start', 'ai-opencode-login-poll'
39
+ ]);
40
+
41
+ // A turn is the Mac's to bound, whoever asks: how much it may answer, how much it may be sent, how many at once.
42
+ const MAX_OUTPUT_TOKENS = 3000;
43
+ const MAX_TURN_BYTES = 20 * 1024 * 1024; // a conversation with a few attachments in it
44
+ const MAX_TURNS_AT_ONCE = 4;
45
+
46
+ /**
47
+ * Where the key that opens the connections is kept: the Keychain (a test gives its own). `read` gives null only
48
+ * when there is none; a Keychain that cannot be read (locked, access refused, no answer) rejects: it is not "no
49
+ * key". Read without holding up the daemon, which this runs in.
50
+ */
51
+ export const keychainStore = {
52
+ read: () => keychainReadStrictAsync(KEY_SERVICE, KEY_ACCOUNT),
53
+ write: (secret) => keychainWrite(KEY_SERVICE, KEY_ACCOUNT, secret)
54
+ };
55
+
56
+ const b64 = (buf) => Buffer.from(buf).toString('base64');
57
+
58
+ /**
59
+ * What the worker code asks of where it runs (byok's AiPlatform), on this Mac: `file` for what is kept, `keyStore`
60
+ * for the key that encrypts it.
61
+ */
62
+ export function macPlatform({ file = AI_PATH, keyStore = keychainStore } = {}) {
63
+ const session = new Map(); // a sign-in waiting for its approval: for as long as this process runs
64
+ let doc; // { local: { <key>: value }, signing: { <id>: { pub, priv: { iv, ct } } } }
65
+ let writing = Promise.resolve();
66
+
67
+ const read = () => {
68
+ if (doc) return doc;
69
+ try {
70
+ const had = JSON.parse(fs.readFileSync(file, 'utf8'));
71
+ doc = { local: had?.local && typeof had.local === 'object' ? had.local : {}, signing: had?.signing && typeof had.signing === 'object' ? had.signing : {} };
72
+ } catch (e) {
73
+ if (e.code !== 'ENOENT') throw new Error(`the AI connections could not be read (${file}): ${e.message}`);
74
+ doc = { local: {}, signing: {} };
75
+ }
76
+ return doc;
77
+ };
78
+ // one write at a time, each of the whole file: made beside it, then moved over it
79
+ const write = () => {
80
+ writing = writing.catch(() => {}).then(() => {
81
+ fs.mkdirSync(path.dirname(file), { recursive: true });
82
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
83
+ fs.writeFileSync(tmp, JSON.stringify(doc, null, 2) + '\n', { mode: 0o600 });
84
+ fs.renameSync(tmp, file);
85
+ });
86
+ return writing;
87
+ };
88
+
89
+ let key; // the AES key, read from the Keychain once (made there the first time a secret is kept)
90
+ const aes = () => {
91
+ key ??= (async () => {
92
+ let raw = await keyStore.read();
93
+ if (!raw) {
94
+ // none yet. Were secrets kept under one that is gone, they could not be opened again: said, not overwritten.
95
+ // (Sealed things only: a connection with no key, a local model's, is kept without any.)
96
+ if (/"ct":\s*"[^"]/.test(JSON.stringify(read()))) {
97
+ throw new Error('the key that opens the AI connections is not in the Keychain any more: remove them (delete ai.json in ~/.sideora) and add them again');
98
+ }
99
+ raw = b64(crypto.randomBytes(32));
100
+ keyStore.write(raw);
101
+ }
102
+ const bytes = Buffer.from(String(raw).trim(), 'base64');
103
+ if (bytes.length !== 32) throw new Error('the key that opens the AI connections is not one (the Keychain item sideora-ai)');
104
+ return subtle.importKey('raw', bytes, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
105
+ })();
106
+ key.catch(() => { key = undefined; }); // (asked again next time: the Keychain may have been locked)
107
+ return key;
108
+ };
109
+ const seal = async (bytes) => {
110
+ const iv = crypto.randomBytes(12);
111
+ return { iv: b64(iv), ct: b64(await subtle.encrypt({ name: 'AES-GCM', iv }, await aes(), bytes)) };
112
+ };
113
+ const open = async (blob) => {
114
+ const with_ = await aes();
115
+ try {
116
+ return Buffer.from(await subtle.decrypt({ name: 'AES-GCM', iv: Buffer.from(blob.iv, 'base64') }, with_, Buffer.from(blob.ct, 'base64')));
117
+ } catch {
118
+ throw new Error('a saved key could not be opened with the key in the Keychain (was that one replaced?): give the connection its key again');
119
+ }
120
+ };
121
+
122
+ return {
123
+ local: {
124
+ get: async (k) => structuredClone(read().local[k]),
125
+ set: async (k, value) => { read().local[k] = structuredClone(value); await write(); }
126
+ },
127
+ session: {
128
+ get: async (k) => session.get(k),
129
+ set: async (k, value) => { session.set(k, value); },
130
+ remove: async (k) => { session.delete(k); }
131
+ },
132
+ openTab: async () => {}, // the page opens the consent page itself, from the address it is answered
133
+ /** Device keys no connection uses (a sign-in started and left, before a restart): dropped. `connections`: the key the connections are kept under. */
134
+ tidy: async (connections = 'aiConnections') => {
135
+ const used = new Set((read().local[connections]?.connections || []).map((c) => c?.id));
136
+ const idle = Object.keys(read().signing).filter((id) => !used.has(id));
137
+ if (!idle.length) return;
138
+ for (const id of idle) delete read().signing[id];
139
+ await write();
140
+ },
141
+ secrets: {
142
+ encryptString: async (plain) => (plain ? seal(Buffer.from(plain, 'utf8')) : { iv: '', ct: '' }),
143
+ decryptBlob: async (blob) => (blob?.ct ? (await open(blob)).toString('utf8') : ''),
144
+ createSigningKey: async (id) => {
145
+ const made = await subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']);
146
+ const priv = Buffer.from(await subtle.exportKey('pkcs8', made.privateKey));
147
+ read().signing[id] = { pub: b64(await subtle.exportKey('spki', made.publicKey)), priv: await seal(priv) };
148
+ await write();
149
+ // (the pair handed out signs but cannot be read back, as the one kept: its private half leaves only sealed)
150
+ return { publicKey: made.publicKey, privateKey: await subtle.importKey('pkcs8', priv, { name: 'Ed25519' }, false, ['sign']) };
151
+ },
152
+ getSigningKey: async (id) => {
153
+ const kept = read().signing[id];
154
+ if (!kept) return undefined;
155
+ return {
156
+ publicKey: await subtle.importKey('spki', Buffer.from(kept.pub, 'base64'), { name: 'Ed25519' }, true, ['verify']),
157
+ privateKey: await subtle.importKey('pkcs8', await open(kept.priv), { name: 'Ed25519' }, false, ['sign'])
158
+ };
159
+ },
160
+ deleteSigningKey: async (id) => {
161
+ if (!read().signing[id]) return;
162
+ delete read().signing[id];
163
+ await write();
164
+ }
165
+ }
166
+ };
167
+ }
168
+
169
+ let started; // the worker code, once per process (it is one per process by its own making)
170
+
171
+ /** The worker code, on this Mac's platform: { handle(message) → Promise<answer>, chat(request, { signal }) }. */
172
+ export function aiHost(options) {
173
+ started ??= (async () => {
174
+ const byok = await import('@amenophis1er/byok/background');
175
+ const platform = macPlatform(options);
176
+ await platform.tidy().catch(() => {}); // (nothing waits for a sign-in as this starts: what no connection uses is left over)
177
+ byok.useAiPlatform(platform);
178
+ const handler = byok.createAiMessageHandler({ prefix: AI_PREFIX, openConsentTab: false, settingsHint: 'Open Sideora settings (the cog on the rail) → AI models.' });
179
+ return {
180
+ handle: (message) => new Promise((resolve, reject) => { if (!handler(message, resolve)) reject(new Error(`unknown AI message "${message?.type}"`)); }),
181
+ chat: byok.chat
182
+ };
183
+ })();
184
+ started.catch(() => { started = undefined; });
185
+ return started;
186
+ }
187
+
188
+ /** One message of the settings' client (list the connections, save one, start a sign-in…): its answer, as the extension's worker gives it. */
189
+ export async function aiMessage(a = {}, ctx = {}) {
190
+ const type = typeof a.type === 'string' && a.type.startsWith(`${AI_PREFIX}:`) ? a.type.slice(AI_PREFIX.length + 1) : '';
191
+ if (!MESSAGES.has(type)) throw new Error(`unknown AI message "${a.type}"`);
192
+ if (type === 'ai-chat') {
193
+ // the worker's own answer to it (an AIChatResult), under this Mac's bounds
194
+ const { type: _t, v: _v, ...request } = a;
195
+ return turn(request, ctx);
196
+ }
197
+ // where a connection points is checked here: it is this Mac that goes there
198
+ const local = (type === 'ai-save-connection' || type === 'ai-list-models') && typeof a.baseUrl === 'string' && a.baseUrl.trim() ? serverOf(a.baseUrl) : null;
199
+ const answer = await (await aiHost()).handle(a);
200
+ // What a server on this very computer answers is not the page's to read: a failed listing there says that it
201
+ // failed, not what the server said (another program's page, an error with its details).
202
+ if (local?.loopback && type === 'ai-list-models' && answer?.ok === false) {
203
+ const status = /^HTTP (\d{3})\b/.exec(String(answer.error || ''))?.[1];
204
+ return { ok: false, error: status ? `The server on this computer answered ${status}.` : 'No model server answered at that address on this computer.' };
205
+ }
206
+ return answer;
207
+ }
208
+
209
+ const LOOPBACK = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i;
210
+ // addresses of a private network, or of this machine's own links, written as numbers
211
+ const PRIVATE = /^(0\.|10\.|127\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)|^\[(::|::1|f[cd][0-9a-f]{2}:.*|fe[89ab][0-9a-f]:.*|::ffff:.*)\]$/i;
212
+
213
+ /**
214
+ * Where a connection may point: a provider over https, or a model server on this computer (http://localhost, as
215
+ * Ollama and LM Studio are). Not a number of the private network, not plain http anywhere else: the Mac would be
216
+ * made to ask, for a page, things only the Mac can reach. Throws with the reason; gives { loopback }.
217
+ */
218
+ export function serverOf(baseUrl) {
219
+ const text = String(baseUrl).trim();
220
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text) && !/^https?:\/\//i.test(text)) throw new Error('That is not an address a model server can have.');
221
+ let url;
222
+ try { url = new URL(/^https?:\/\//i.test(text) ? text : `https://${text}`); } catch { throw new Error('That is not an address a model server can have.'); }
223
+ const host = url.hostname.toLowerCase();
224
+ const loopback = LOOPBACK.test(host);
225
+ if (url.username || url.password || url.search || url.hash || text.includes('?') || text.includes('#')) throw new Error('The address of a model server is its address alone: no name and password, nothing after a ? or a #.');
226
+ if (url.protocol === 'http:' && !loopback) throw new Error('A model server is reached over https, or on this computer (http://localhost).');
227
+ if (!loopback && PRIVATE.test(host)) throw new Error('A model server on the private network is not reached from the web app: only one on this computer (localhost), or a provider over https.');
228
+ return { loopback };
229
+ }
230
+
231
+ let turns = 0;
232
+ /** One model turn, bounded: stopped when whoever asked lets go, never longer than the worker's own limit, a few at once. */
233
+ async function turn(request, ctx) {
234
+ if (typeof request.system !== 'string' || !Array.isArray(request.messages)) throw new Error('a model turn needs system and messages');
235
+ if (Buffer.byteLength(JSON.stringify(request)) > MAX_TURN_BYTES) return { ok: false, error: 'That is too much to send to the model in one turn.' };
236
+ if (turns >= MAX_TURNS_AT_ONCE) return { ok: false, error: 'The model is already answering several things: try again in a moment.' };
237
+ turns++;
238
+ try {
239
+ const maxTokens = Math.min(Number(request.maxTokens) > 0 ? Number(request.maxTokens) : MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS);
240
+ // (a shorter wait than the worker's own may be asked for, as the settings' "try this connection" does; never a longer one, never none)
241
+ const { timeoutMs, ...rest } = request;
242
+ const wait = Number(timeoutMs) > 0 && Number(timeoutMs) < 120_000 ? { timeoutMs: Number(timeoutMs) } : {};
243
+ return await (await aiHost()).chat({ ...rest, ...wait, maxTokens }, { signal: ctx.signal });
244
+ } finally {
245
+ turns--;
246
+ }
247
+ }
248
+
249
+ /**
250
+ * One model turn for the assistant. The tools named are the page's own functions, run there: this only carries
251
+ * the conversation to the provider and back, with the connection's key. `ctx.signal`: whoever asked let go (Stop).
252
+ */
253
+ export async function aiChat(a = {}, ctx = {}) {
254
+ if (typeof a.system !== 'string' || !Array.isArray(a.messages)) throw new Error('aiChat needs system and messages');
255
+ // the files a chat's questions name (kept here: src/chats.js), as the model takes them
256
+ let messages = a.messages;
257
+ if (messages.some((m) => Array.isArray(m?.content) && m.content.some((p) => p?.type === 'file'))) {
258
+ try { messages = (await import('./chats.js')).expandChatFiles(messages); } catch (e) { return { ok: false, error: `A file attached to this chat could not be read: ${e.message}.` }; }
259
+ }
260
+ const tools = Array.isArray(a.tools) && a.tools.length ? a.tools : undefined;
261
+ // (a chat asked with another connection or model than the one chosen in the settings: one of those kept here, by
262
+ // its id; the worker's own code refuses one it does not have)
263
+ // (`connectionRevision`: the connection as it was when the run started; edited since, the turn is refused rather than sent where the run did not start)
264
+ const with_ = { ...(typeof a.connectionId === 'string' && a.connectionId ? { connectionId: a.connectionId } : {}), ...(Number.isFinite(a.connectionRevision) ? { connectionRevision: a.connectionRevision } : {}), ...(typeof a.model === 'string' && a.model ? { model: a.model } : {}) };
265
+ const r = await turn({ system: a.system, messages, tools, parallelToolCalls: tools ? true : undefined, maxTokens: MAX_OUTPUT_TOKENS, ...with_ }, ctx);
266
+ return r.ok
267
+ ? { ok: true, text: r.text ?? '', toolCalls: r.toolCalls, providerState: r.providerState, stopReason: r.stopReason, ...(r.webSearch ? { webSearch: r.webSearch } : {}) }
268
+ : { ok: false, error: r.error ?? 'The model did not answer.' };
269
+ }
@@ -0,0 +1,32 @@
1
+ // The assistant's answers, run here, by the hub (the daemon: src/hub.js), not by the page: the core's assistant
2
+ // (src/core/assistant.js) and its runs (src/core/runs.js), over this Mac's operations (src/panel-ops.js), its model
3
+ // turns (src/ai.js) and what the Mac does with files (src/host/file-prep.js, src/host/assistant-html.js).
4
+
5
+ import { makeAssistant } from './core/assistant.js';
6
+ import { makeRuns } from './core/runs.js';
7
+
8
+ let assistant;
9
+ async function theAssistant() {
10
+ if (assistant) return assistant;
11
+ const [{ OPS }, ai, html, files] = await Promise.all([import('./panel-ops.js'), import('./ai.js'), import('./host/assistant-html.js'), import('./host/file-prep.js')]);
12
+ const ops = async (name, args) => {
13
+ if (!Object.hasOwn(OPS, name) || name.startsWith('assistant')) throw new Error(`unknown op "${name}"`);
14
+ return OPS[name](args ?? {});
15
+ };
16
+ assistant = makeAssistant({
17
+ ops,
18
+ turn: (request, ctx) => ai.aiChat(request, ctx),
19
+ html: { draft: html.draftHtml, text: html.htmlText },
20
+ prepareFile: files.prepareFile
21
+ });
22
+ return assistant;
23
+ }
24
+
25
+ // (answers kept with their chats here: src/chats.js)
26
+ const runs = makeRuns(theAssistant, {
27
+ read: async (a) => (await import('./chats.js')).readChat(a),
28
+ save: async (a) => (await import('./chats.js')).saveChat(a)
29
+ });
30
+ export const { assistantStart, assistantWait, assistantAnswer, assistantStop } = runs;
31
+ /** For the tests: the answers under way. */
32
+ export const _runs = runs.runs;
@@ -0,0 +1,76 @@
1
+ // A mail that came attached to a mail (a .eml, message/rfc822, or an Exchange item attachment, which Exchange hands
2
+ // out as the same MIME): read as a mail is read, to be shown as one. A path names it: the outer attachment's id, then,
3
+ // for a mail inside that one, the id of its attachment there (n0, n1, … by its place among the parsed attachments),
4
+ // and so on, at most MAX_DEPTH deep. Its own attachments are listed with those ids, and their bytes are `fileAt`'s.
5
+ // Nothing in it is fetched or run here: its HTML goes to the panel, which shows it as it shows any mail (its pictures
6
+ // held back, its links checked).
7
+
8
+ import { simpleParser } from 'mailparser';
9
+ import { splitQuoted } from 'mailcore';
10
+
11
+ export const MAX_DEPTH = 5;
12
+ const MAX_BYTES = 30 * 1024 * 1024;
13
+
14
+ const isMail = (a) => /^message\/rfc822$/i.test(a?.contentType || '') || /\.eml$/i.test(a?.filename || a?.name || '');
15
+
16
+ /** The people of a parsed address header, as the panel's Person. */
17
+ function people(v) {
18
+ const list = Array.isArray(v) ? v.flatMap((x) => x?.value || []) : v?.value || [];
19
+ return list.filter((p) => p && (p.address || p.name)).slice(0, 200).map((p) => ({ name: String(p.name || ''), email: String(p.address || '') }));
20
+ }
21
+
22
+ async function parse(bytes) {
23
+ if (!Buffer.isBuffer(bytes) || !bytes.length) throw new Error('this attached mail is empty');
24
+ if (bytes.length > MAX_BYTES) throw new Error('this attached mail is over 30 MB: download it to open it');
25
+ // (its inline pictures into its HTML as data: addresses: the panel shows nothing fetched from elsewhere unless asked)
26
+ return simpleParser(bytes);
27
+ }
28
+
29
+ /**
30
+ * The bytes at a path: `read(attachmentId)` gives the outer attachment's (the mail's own), and each further step of
31
+ * the path takes an attachment of the mail those bytes are. Returns { name, contentType, contentId, content }.
32
+ */
33
+ export async function fileAt(path, read) {
34
+ if (!Array.isArray(path) || !path.length || path.length > MAX_DEPTH + 1 || path.some((p) => typeof p !== 'string' || !p || p.length > 200)) throw new Error('not a path to an attached file');
35
+ let file = await read(path[0]);
36
+ for (const step of path.slice(1)) {
37
+ if (!isMail({ contentType: file.contentType, filename: file.name })) throw new Error('that file is not a mail');
38
+ const parsed = await parse(file.content);
39
+ const i = /^n(\d{1,4})$/.exec(step);
40
+ const a = i ? (parsed.attachments || [])[Number(i[1])] : null;
41
+ if (!a) throw new Error('that attachment is not in this mail');
42
+ file = { name: a.filename || 'attachment', contentType: a.contentType || 'application/octet-stream', contentId: a.cid || null, content: a.content };
43
+ }
44
+ return file;
45
+ }
46
+
47
+ /** The mail at a path, as a read mail is (subject, people, date, its body, its attachments by their ids here). */
48
+ export async function mailAt(path, read) {
49
+ const file = await fileAt(path, read);
50
+ if (!isMail({ contentType: file.contentType, filename: file.name })) throw new Error('that file is not a mail');
51
+ const parsed = await parse(file.content);
52
+ const html = parsed.html || null;
53
+ const text = parsed.text || '';
54
+ const bodyType = html ? 'HTML' : 'Text';
55
+ const body = String(html || text).replace(/\r\n?/g, '\n');
56
+ let quoteAt = null;
57
+ try { const { head, tail } = splitQuoted(body, bodyType); if (tail && head.replace(/<[^>]+>|&nbsp;/g, '').trim()) quoteAt = head.length; } catch { /* the whole of it, then */ }
58
+ const from = people(parsed.from)[0] || { name: '', email: '' };
59
+ const date = parsed.date instanceof Date && !Number.isNaN(parsed.date.getTime()) ? parsed.date.toISOString() : null;
60
+ return {
61
+ subject: String(parsed.subject || ''),
62
+ fromName: from.name, fromEmail: from.email,
63
+ to: people(parsed.to), cc: people(parsed.cc), replyTo: people(parsed.replyTo),
64
+ received: date,
65
+ bodyType, body, quoteAt,
66
+ attachments: (parsed.attachments || []).map((a, i) => ({
67
+ id: `n${i}`,
68
+ name: a.filename || (isMail(a) ? `${a.contentType === 'message/rfc822' ? 'Attached mail' : 'attachment'}.eml` : '(unnamed)'),
69
+ size: a.size || a.content?.length || 0,
70
+ contentType: a.contentType || '',
71
+ contentId: a.cid || undefined,
72
+ // (a picture its HTML shows, which the parse put there as a data: address: not a file to list)
73
+ inline: !!html && /^image\//i.test(a.contentType || '') && (a.related === true || (!!a.cid && a.contentDisposition === 'inline'))
74
+ }))
75
+ };
76
+ }
@@ -0,0 +1,70 @@
1
+ // Back off from an account whose sign-in is rejected. Every attempt is a
2
+ // failed login on the server (up to 3 per poll: retry + 1Password refresh),
3
+ // and retrying every 30s can lock the account out. After a rejection the
4
+ // daemon's poll, push stream and calendar refresh all pause for that account
5
+ // on a growing schedule, or until the stored credentials change (another
6
+ // sideora command refreshed them from 1Password, or `sideora setup`
7
+ // ran). The user is alerted once, and again when sign-in works.
8
+
9
+ import crypto from 'node:crypto';
10
+ import { keychainGet, loadState, saveState } from './config.js';
11
+ import { notifyMac } from './notify.js';
12
+
13
+ const SCHEDULE_MIN = [2, 5, 15, 30, 60];
14
+
15
+ export function createAuthGate(account, { log, hint }) {
16
+ let s = null; // { since, failures, retryAt, fp, message }
17
+
18
+ // what the next attempt would sign in with — no 1Password call here
19
+ const fingerprint = () => {
20
+ try {
21
+ const c = loadState().creds?.[account] || {};
22
+ // (a Microsoft sign-in made again is a new attempt too: its tokens are part of what it signs in with)
23
+ return crypto.createHash('sha256').update(`${c.username}|${c.domain}|${keychainGet(account) || ''}|${keychainGet(`microsoft:${account}`) ? JSON.parse(keychainGet(`microsoft:${account}`)).signed_in_at ?? '' : ''}`).digest('hex');
24
+ } catch {
25
+ return '';
26
+ }
27
+ };
28
+ const persist = () => {
29
+ try {
30
+ const st = loadState();
31
+ const auth = { ...(st.auth || {}) };
32
+ if (s) auth[account] = { since: s.since, failures: s.failures, retryAt: s.retryAt, message: s.message };
33
+ else delete auth[account];
34
+ saveState({ ...st, auth });
35
+ } catch {}
36
+ };
37
+ persist(); // a restarted daemon starts unpaused
38
+
39
+ return {
40
+ /** True while sign-in for this account is paused. */
41
+ blocked() {
42
+ if (!s || Date.now() >= s.retryAt) return false;
43
+ if (fingerprint() === s.fp) return true;
44
+ log(`[${account}] credentials changed — retrying sign-in now`);
45
+ s.retryAt = 0;
46
+ return false;
47
+ },
48
+ /** An auth error survived the retry and the 1Password refresh. */
49
+ failed(e) {
50
+ const now = Date.now();
51
+ if (s && now < s.retryAt) return; // another path already reported this round
52
+ const failures = (s?.failures || 0) + 1;
53
+ const wait = SCHEDULE_MIN[Math.min(failures, SCHEDULE_MIN.length) - 1];
54
+ s = { since: s?.since || now, failures, retryAt: now + wait * 60e3, fp: fingerprint(), message: e.message };
55
+ persist();
56
+ log(`[${account}] sign-in rejected (${failures}×) — pausing checks for ${wait} min so the account does not get locked out`);
57
+ if (failures === 1) {
58
+ notifyMac('Sideora ⚠️ sign-in rejected', `${account}: checks paused. ${hint} Then run any sideora command to retry at once.`);
59
+ }
60
+ },
61
+ /** A sign-in succeeded. */
62
+ ok() {
63
+ if (!s) return;
64
+ log(`[${account}] sign-in works again`);
65
+ notifyMac('Sideora ✅', `${account}: sign-in works again — checks resumed`);
66
+ s = null;
67
+ persist();
68
+ }
69
+ };
70
+ }
@@ -0,0 +1,158 @@
1
+ // `sideora export` and `sideora import`, at the terminal (src/backup.js has what they do). The passphrase
2
+ // is typed, unseen, never an argument (other processes read those, and a shell keeps them); a script gives it in
3
+ // SIDEORA_PASSPHRASE.
4
+
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { HOME_DIR, keychainReadStrict, keychainWrite } from './config.js';
9
+ import { collect, seal, open, planImport } from './backup.js';
10
+
11
+ const tty = process.stdout.isTTY;
12
+ const paint = (code) => (s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
13
+ const bold = paint(1);
14
+ const dim = paint(2);
15
+ const green = paint(32);
16
+ const yellow = paint(33);
17
+
18
+ // (a read the Keychain refused, or a locked Keychain, is said: an export is not made without a secret it should hold)
19
+ const keychain = {
20
+ get: (service, account) => { try { return keychainReadStrict(service, account); } catch (e) { throw new Error(`${e.message} (reading "${account}"): nothing was written. Allow access when asked, or export with --no-secrets`); } },
21
+ set: (service, account, value) => keychainWrite(service, account, value)
22
+ };
23
+
24
+ /** What reads the data folder and keeps parts of it in memory: the background watcher, the web app (a service, or in a terminal). */
25
+ async function running() {
26
+ const { execFileSync } = await import('node:child_process');
27
+ const out = [];
28
+ const systemd = await import('./host/systemd.js');
29
+ for (const [label, what] of [['com.sideora.daemon', 'the background watcher'], ['com.sideora.web', 'the web app\'s service']]) {
30
+ if (systemd.isLinux) { if (systemd.state(label.split('.').pop()).pid) out.push({ label, what }); continue; }
31
+ try { if (/"PID"\s*=\s*\d+/.test(execFileSync('launchctl', ['list', label], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }))) out.push({ label, what }); } catch { /* not loaded */ }
32
+ }
33
+ try {
34
+ const port = Number(fs.readFileSync(path.join(HOME_DIR, 'web.port'), 'utf8'));
35
+ if (port && !out.some((r) => r.label === 'com.sideora.web') && await fetch(`http://127.0.0.1:${port}/api/session`, { signal: AbortSignal.timeout(1500) }).then((r) => r.ok, () => false)) out.push({ label: null, what: `\`sideora web\` in a terminal (port ${port})` });
36
+ } catch { /* not running */ }
37
+ return out;
38
+ }
39
+
40
+ /** Something typed at the terminal without being shown. Not at a terminal: SIDEORA_PASSPHRASE, or it is said that there is none. */
41
+ function typed(question) {
42
+ if (!process.stdin.isTTY) {
43
+ const given = process.env.SIDEORA_PASSPHRASE;
44
+ if (!given) throw new Error('the passphrase is typed at a terminal; a script gives it in SIDEORA_PASSPHRASE');
45
+ return Promise.resolve(given);
46
+ }
47
+ return new Promise((resolve, reject) => {
48
+ process.stdout.write(question);
49
+ const input = process.stdin;
50
+ let text = '';
51
+ input.setRawMode(true);
52
+ input.resume();
53
+ input.setEncoding('utf8');
54
+ const done = (fn) => { input.setRawMode(false); input.pause(); input.removeListener('data', on); process.stdout.write('\n'); fn(); };
55
+ const on = (chunk) => {
56
+ for (const ch of chunk) {
57
+ if (ch === '\r' || ch === '\n') return done(() => resolve(text));
58
+ if (ch === '\u0003') return done(() => reject(new Error('stopped'))); // Ctrl-C
59
+ if (ch === '\u007f' || ch === '\b') text = [...text].slice(0, -1).join('');
60
+ else if (ch >= ' ') text += ch;
61
+ }
62
+ };
63
+ input.on('data', on);
64
+ });
65
+ }
66
+
67
+ async function asked(question) {
68
+ if (!process.stdin.isTTY) return false;
69
+ const rl = (await import('node:readline/promises')).createInterface({ input: process.stdin, output: process.stdout });
70
+ try { return /^y(es)?$/i.test((await rl.question(question)).trim()); } finally { rl.close(); }
71
+ }
72
+
73
+ const size = (n) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`);
74
+ const count = (files, re) => files.filter((f) => re.test(f.path)).length;
75
+ const n = (k, what) => `${k} ${what}${k === 1 ? '' : 's'}`;
76
+ /** What a bundle holds, in a few lines. */
77
+ function summary(bundle) {
78
+ const config = (() => { try { return JSON.parse(bundle.files.find((f) => f.path === 'config.json')?.data.toString('utf8') ?? '{}'); } catch { return {}; } })();
79
+ const s = bundle.secrets;
80
+ const secrets = Object.keys(s.passwords).length + Object.keys(s.google).length + (s.onePassword ? 1 : 0) + (s.ai ? 1 : 0) + (s.relay ? 1 : 0);
81
+ return [
82
+ `${n(Object.keys(config.accounts ?? {}).length, 'account')}, the settings${bundle.files.some((f) => f.path === 'rules.yaml') ? ' and the rules' : ''}`,
83
+ `${n(count(bundle.files, /^notes\/[a-z0-9]+\.json$/), 'note')} (${n(count(bundle.files, /^notes\/pictures\//), 'picture')}), ${n(count(bundle.files, /^chats\/[a-z0-9]+\.json$/), 'chat')} (${n(count(bundle.files, /^chats\/files\//), 'file')})`,
84
+ bundle.files.some((f) => f.path === 'ai.json') ? 'the AI connections' : 'no AI connection',
85
+ secrets ? `${n(secrets, 'secret')} of the Keychain (passwords, sign-ins, keys)` : 'no secret (made with --no-secrets): accounts are signed in to again after an import',
86
+ bundle.files.some((f) => f.path === 'relay.json') ? 'this computer\'s place at the relay, with its paired devices' : 'not the place at the relay, nor the paired devices'
87
+ ];
88
+ }
89
+
90
+ /** sideora export <file> [--no-secrets] [--with-relay] [--force] */
91
+ export async function exportCmd(args) {
92
+ const out = args.find((a) => !a.startsWith('--'));
93
+ if (!out) throw new Error('export <file> [--no-secrets] [--with-relay]: the file to write (for example ~/sideora.mwx)');
94
+ const file = path.resolve(out.replace(/^~(?=\/|$)/, os.homedir()));
95
+ if (fs.existsSync(file) && !args.includes('--force')) throw new Error(`${file} is there already: name another file, or add --force to write over it`);
96
+ if (!fs.existsSync(path.join(HOME_DIR, 'config.json'))) throw new Error('there is nothing to export yet: `sideora setup` first');
97
+ let label = '';
98
+ try { label = JSON.parse(fs.readFileSync(path.join(HOME_DIR, 'relay.json'), 'utf8')).label || ''; } catch { /* no name */ }
99
+ const bundle = collect({ home: HOME_DIR, keychain, secrets: !args.includes('--no-secrets'), relay: args.includes('--with-relay'), label: label || os.hostname() });
100
+ console.log(bold('This export holds:'));
101
+ for (const line of summary(bundle)) console.log(` ${line}`);
102
+ const first = await typed('Passphrase (8 characters at least; it is not kept anywhere: without it the file opens nothing): ');
103
+ if (process.stdin.isTTY && (await typed('Again: ')) !== first) throw new Error('the two are not the same: nothing was written');
104
+ const bytes = seal(bundle, first);
105
+ const tmp = `${file}.${process.pid}.tmp`;
106
+ fs.writeFileSync(tmp, bytes, { mode: 0o600 });
107
+ fs.renameSync(tmp, file);
108
+ console.log(green('✓') + ` written: ${bold(file)} ${dim(`(${size(bytes.length)}, sealed)`)}`);
109
+ if (bundle.meta.relay) console.log(yellow('note:') + ' it holds this computer\'s place at the relay: imported on another computer while this one still runs, the two take the connection from each other. `sideora relay leave` here once the other has it.');
110
+ }
111
+
112
+ /** sideora import <file> [--replace] [--dry-run] [--yes] */
113
+ export async function importCmd(args) {
114
+ const from = args.find((a) => !a.startsWith('--'));
115
+ if (!from) throw new Error('import <file> [--replace] [--dry-run] [--yes]: a file made by `sideora export`');
116
+ const file = path.resolve(from.replace(/^~(?=\/|$)/, os.homedir()));
117
+ const bundle = open(fs.readFileSync(file), await typed('Passphrase of this file: '));
118
+ const replace = args.includes('--replace');
119
+ console.log(bold(`Made ${new Date(bundle.meta.created).toLocaleString()}${bundle.meta.label ? ` on ${bundle.meta.label}` : ''}. It holds:`));
120
+ for (const line of summary(bundle)) console.log(` ${line}`);
121
+ const plan = planImport(bundle, { home: HOME_DIR, keychain, replace });
122
+ const mark = { add: green('+ add '), replace: yellow('~ replace'), skip: dim('· keep ') };
123
+ console.log(bold(`\nHere (${HOME_DIR}) it would:`));
124
+ for (const a of plan.actions) console.log(` ${mark[a.action]} ${a.kind === 'account' ? `account ${a.what}` : a.kind === 'rule' ? `rule ${a.what}` : a.what}${a.action === 'skip' ? dim(a.why ? ` (${a.why})` : ' (here already)') : ''}`);
125
+ const doing = plan.actions.filter((a) => a.action !== 'skip').length;
126
+ if (!doing) { console.log(dim(`\nNothing to do: everything it holds is here already${replace ? '' : ' (--replace takes the file\'s where both have it)'}.`)); return; }
127
+ if (args.includes('--dry-run')) { console.log(dim('\n--dry-run: nothing was changed.')); return; }
128
+ // Not while something reads the data folder and keeps it in memory: it would write back what it holds over what is
129
+ // imported. The services are stopped for the import and started again after it; one in a terminal is said.
130
+ const busy = await running();
131
+ const inTerminal = busy.find((r) => !r.label);
132
+ if (inTerminal) throw new Error(`${inTerminal.what} is running: stop it (Ctrl-C there) and import again`);
133
+ if (busy.length) console.log(yellow('\nnote:') + ` ${busy.map((r) => r.what).join(' and ')} will be stopped for the import, and started again after it.`);
134
+ if (!args.includes('--yes') && !(await asked(`\n${replace ? 'Replace and add' : 'Add'} these ${doing}? [y/N] `))) { console.log(dim('Nothing was changed.')); return; }
135
+ const { execFileSync } = await import('node:child_process');
136
+ const systemd = await import('./host/systemd.js');
137
+ const plists = busy.map((r) => path.join(os.homedir(), 'Library/LaunchAgents', `${r.label}.plist`));
138
+ // (Linux: the systemd user units, stopped and started again the same way)
139
+ const units = systemd.isLinux ? busy.filter((r) => r.label).map((r) => r.label.split('.').pop()) : [];
140
+ for (const u of units) { try { systemd.stop(u); } catch { /* stopped already */ } }
141
+ if (!systemd.isLinux) for (const p of plists) { try { execFileSync('launchctl', ['unload', p], { stdio: 'ignore' }); } catch { /* stopped already */ } }
142
+ try {
143
+ // (planned again now that nothing else writes: what was shown is what is done, unless the services changed something meanwhile)
144
+ applied(busy.length ? planImport(bundle, { home: HOME_DIR, keychain, replace }) : plan);
145
+ } finally {
146
+ for (const u of units) { try { systemd.start(u); } catch { console.log(yellow('note:') + ` sideora-${u} could not be started again: \`systemctl --user start sideora-${u}\``); } }
147
+ if (!systemd.isLinux) for (const p of plists) { try { execFileSync('launchctl', ['load', p], { stdio: 'ignore' }); } catch { console.log(yellow('note:') + ` ${p} could not be started again: \`launchctl load ${p}\``); } }
148
+ }
149
+ if (busy.length) console.log(dim(` ${busy.map((r) => r.what).join(' and ')} started again`));
150
+ }
151
+
152
+ function applied(plan) {
153
+ const before = ['config.json', 'rules.yaml', 'ai.json', 'relay.json'].filter((f) => fs.existsSync(path.join(HOME_DIR, f)));
154
+ const done = plan.apply();
155
+ console.log(green('✓') + ` imported: ${n(done.files, 'file')} written, ${n(done.secrets, 'secret')} put in the Keychain`);
156
+ const kept = before.filter((f) => fs.existsSync(path.join(HOME_DIR, `${f}.before-import`)));
157
+ if (kept.length) console.log(dim(` what was here before is kept beside it (${kept.map((f) => `${f}.before-import`).join(', ')})`));
158
+ }