aegisone 1.0.34 → 1.0.35

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 (226) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1 -1
  3. package/SOURCE-OFFER.txt +9 -0
  4. package/bin/aegis.js +1 -322
  5. package/package.json +4 -5
  6. package/scripts/bump.mjs +1 -211
  7. package/scripts/bundle.js +1 -129
  8. package/scripts/predist.mjs +1 -976
  9. package/src/child.js +1 -285
  10. package/src/dispatch.js +1 -269
  11. package/src/doctor.js +1 -639
  12. package/src/host.js +1 -111
  13. package/src/permissions.js +1 -383
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/package.json +3 -7
  17. package/vendor/cli/scripts/check.mjs +1 -52
  18. package/vendor/cli/scripts/demo.mjs +1 -94
  19. package/vendor/cli/scripts/predist.mjs +1 -75
  20. package/vendor/cli/scripts/runtests.mjs +1 -56
  21. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  22. package/vendor/cli/src/agents.js +1 -139
  23. package/vendor/cli/src/app.js +1 -2957
  24. package/vendor/cli/src/art.js +1 -289
  25. package/vendor/cli/src/chatflow.js +1 -3023
  26. package/vendor/cli/src/checkpoint.js +1 -90
  27. package/vendor/cli/src/clipboard.js +1 -424
  28. package/vendor/cli/src/cloudsync.js +1 -528
  29. package/vendor/cli/src/commands.js +1 -4089
  30. package/vendor/cli/src/config.js +1 -581
  31. package/vendor/cli/src/connect.js +1 -349
  32. package/vendor/cli/src/credentials.js +1 -33
  33. package/vendor/cli/src/deps.js +1 -232
  34. package/vendor/cli/src/devrun.js +1 -187
  35. package/vendor/cli/src/diff.js +1 -333
  36. package/vendor/cli/src/diffview.js +1 -296
  37. package/vendor/cli/src/engine.js +1 -297
  38. package/vendor/cli/src/entitlement.js +1 -355
  39. package/vendor/cli/src/events.js +1 -707
  40. package/vendor/cli/src/export.js +1 -67
  41. package/vendor/cli/src/filepreview.js +1 -153
  42. package/vendor/cli/src/fingerprint.js +1 -592
  43. package/vendor/cli/src/format.js +1 -259
  44. package/vendor/cli/src/fuzzy.js +1 -119
  45. package/vendor/cli/src/history.js +1 -423
  46. package/vendor/cli/src/init.js +1 -175
  47. package/vendor/cli/src/input.js +1 -139
  48. package/vendor/cli/src/keys.js +1 -183
  49. package/vendor/cli/src/markdown.js +1 -306
  50. package/vendor/cli/src/models.js +1 -507
  51. package/vendor/cli/src/naming.js +1 -57
  52. package/vendor/cli/src/overlays.js +1 -462
  53. package/vendor/cli/src/panels.js +1 -1418
  54. package/vendor/cli/src/ping.js +1 -226
  55. package/vendor/cli/src/presence.js +1 -238
  56. package/vendor/cli/src/render.js +1 -516
  57. package/vendor/cli/src/screen.js +1 -518
  58. package/vendor/cli/src/screens.js +1 -896
  59. package/vendor/cli/src/secret.js +1 -59
  60. package/vendor/cli/src/securefs.js +1 -359
  61. package/vendor/cli/src/settings.js +1 -155
  62. package/vendor/cli/src/shared.js +1 -52
  63. package/vendor/cli/src/sharedpaths.js +1 -53
  64. package/vendor/cli/src/signup.js +1 -156
  65. package/vendor/cli/src/summarize.js +1 -95
  66. package/vendor/cli/src/sysdiag.js +1 -585
  67. package/vendor/cli/src/system.js +1 -40
  68. package/vendor/cli/src/theme.js +1 -570
  69. package/vendor/cli/src/title.js +1 -220
  70. package/vendor/cli/src/todos.js +1 -115
  71. package/vendor/cli/src/tokens.js +1 -263
  72. package/vendor/cli/src/topup.js +1 -210
  73. package/vendor/cli/src/update.js +1 -191
  74. package/vendor/cli/vendor/client/aegis.js +1 -2441
  75. package/vendor/cli/vendor/client/attest.js +1 -518
  76. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  77. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  78. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  79. package/vendor/cli/vendor/client/byok-catalog.js +1 -199
  80. package/vendor/cli/vendor/client/catalog-client.js +1 -487
  81. package/vendor/cli/vendor/client/conversation-export.js +1 -177
  82. package/vendor/cli/vendor/client/credentials.js +1 -494
  83. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  84. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  85. package/vendor/cli/vendor/client/drive-upload.js +1 -234
  86. package/vendor/cli/vendor/client/env-file.js +1 -1273
  87. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  88. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  89. package/vendor/cli/vendor/client/google-signin.js +1 -133
  90. package/vendor/cli/vendor/client/hooks.js +1 -430
  91. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  92. package/vendor/cli/vendor/client/naming.js +1 -283
  93. package/vendor/cli/vendor/client/platform.js +1 -937
  94. package/vendor/cli/vendor/client/prefs.js +1 -351
  95. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  96. package/vendor/cli/vendor/client/presence.js +1 -438
  97. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  98. package/vendor/cli/vendor/client/session-store.js +1 -575
  99. package/vendor/cli/vendor/client/topup.js +1 -297
  100. package/vendor/cli/vendor/client/touch.js +1 -458
  101. package/vendor/cli/vendor/client/update.js +1 -763
  102. package/vendor/cli/vendor/client/user-models.js +1 -381
  103. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  104. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -276
  105. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  106. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1028
  107. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -125
  108. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3666
  109. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  110. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  111. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2145
  112. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -280
  113. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  114. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -238
  115. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -75
  116. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  117. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  118. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  119. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  120. package/vendor/cli/vendor/hosts/install.js +1 -638
  121. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  122. package/vendor/cli/vendor/hosts/spec.js +1 -164
  123. package/vendor/cli/vendor/hosts/targets.js +1 -346
  124. package/vendor/cli/vendor/mcp/server.js +1 -221
  125. package/vendor/cli/vendor/mcp/tools.js +1 -408
  126. package/vendor/cli/vendor/one/src/child.js +1 -285
  127. package/vendor/cli/vendor/one/src/permissions.js +1 -383
  128. package/vendor/desktop/bin/aegis.js +1 -32
  129. package/vendor/desktop/lib/account-key.js +1 -56
  130. package/vendor/desktop/lib/auto.js +1 -461
  131. package/vendor/desktop/lib/avatar/companion.js +1 -698
  132. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  133. package/vendor/desktop/lib/avatar/events.js +1 -344
  134. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  135. package/vendor/desktop/lib/avatar/holders.js +1 -612
  136. package/vendor/desktop/lib/avatar/identity.js +1 -641
  137. package/vendor/desktop/lib/avatar/level.js +1 -368
  138. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  139. package/vendor/desktop/lib/avatar/persona.js +1 -388
  140. package/vendor/desktop/lib/avatar/profile.js +1 -977
  141. package/vendor/desktop/lib/avatar/register.js +1 -307
  142. package/vendor/desktop/lib/avatar/store.js +1 -472
  143. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  144. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  145. package/vendor/desktop/lib/avatar/turn.js +1 -216
  146. package/vendor/desktop/lib/avatar/voice.js +1 -328
  147. package/vendor/desktop/lib/avatar/xp.js +1 -404
  148. package/vendor/desktop/lib/deep-link.js +1 -120
  149. package/vendor/desktop/lib/fingerprint.js +2 -347
  150. package/vendor/desktop/lib/google-connect.js +1 -323
  151. package/vendor/desktop/lib/local/agents.js +1 -105
  152. package/vendor/desktop/lib/local/attachments.js +1 -276
  153. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  154. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  155. package/vendor/desktop/lib/local/context.js +1 -125
  156. package/vendor/desktop/lib/local/engine.js +1 -3666
  157. package/vendor/desktop/lib/local/entitlement.js +1 -660
  158. package/vendor/desktop/lib/local/git-scope.js +1 -228
  159. package/vendor/desktop/lib/local/local.js +1 -2145
  160. package/vendor/desktop/lib/local/prompt.js +1 -280
  161. package/vendor/desktop/lib/local/queue.js +1 -560
  162. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  163. package/vendor/desktop/lib/local/spill.js +1 -75
  164. package/vendor/desktop/lib/local/telemetry.js +1 -470
  165. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  166. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  167. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  168. package/vendor/desktop/lib/quick-launcher.js +1 -84
  169. package/vendor/desktop/lib/settings.js +1 -890
  170. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  171. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  172. package/vendor/desktop/lib/sync/sessions.js +1 -106
  173. package/vendor/desktop/lib/window-state.js +1 -66
  174. package/vendor/desktop/package.json +2 -4
  175. package/vendor/desktop/preload.js +1 -679
  176. package/vendor/desktop/renderer/app.js +1 -7250
  177. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  178. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  179. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  180. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  181. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  182. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  183. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  184. package/vendor/desktop/renderer/budget.js +1 -172
  185. package/vendor/desktop/renderer/companion.js +1 -223
  186. package/vendor/desktop/renderer/diff.js +1 -359
  187. package/vendor/desktop/renderer/diffview.js +1 -336
  188. package/vendor/desktop/renderer/filepreview.js +1 -211
  189. package/vendor/desktop/renderer/fingerprint.js +3 -789
  190. package/vendor/desktop/renderer/markdown.js +1 -168
  191. package/vendor/desktop/renderer/provider-mark.js +1 -311
  192. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  193. package/vendor/desktop/renderer/providers.js +1 -259
  194. package/vendor/desktop/renderer/quick.js +1 -285
  195. package/vendor/desktop/renderer/stream-policy.js +1 -387
  196. package/vendor/desktop/renderer/transcript-view.js +1 -323
  197. package/vendor/desktop/renderer/usage.js +1 -1239
  198. package/vendor/desktop/vendor/aegis.js +1 -2441
  199. package/vendor/desktop/vendor/attest.js +1 -518
  200. package/vendor/desktop/vendor/authorship-key.js +1 -410
  201. package/vendor/desktop/vendor/auto-provision.js +1 -134
  202. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  203. package/vendor/desktop/vendor/byok-catalog.js +1 -199
  204. package/vendor/desktop/vendor/catalog-client.js +1 -487
  205. package/vendor/desktop/vendor/conversation-export.js +1 -177
  206. package/vendor/desktop/vendor/credentials.js +1 -494
  207. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  208. package/vendor/desktop/vendor/drive-connect.js +1 -110
  209. package/vendor/desktop/vendor/drive-upload.js +1 -234
  210. package/vendor/desktop/vendor/env-file.js +1 -1273
  211. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  212. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  213. package/vendor/desktop/vendor/google-signin.js +1 -133
  214. package/vendor/desktop/vendor/hooks.js +1 -430
  215. package/vendor/desktop/vendor/model-discovery.js +1 -373
  216. package/vendor/desktop/vendor/naming.js +1 -283
  217. package/vendor/desktop/vendor/platform.js +1 -937
  218. package/vendor/desktop/vendor/prefs.js +1 -351
  219. package/vendor/desktop/vendor/presence-constants.js +1 -107
  220. package/vendor/desktop/vendor/presence.js +1 -438
  221. package/vendor/desktop/vendor/record-vault.js +3 -1055
  222. package/vendor/desktop/vendor/session-store.js +1 -575
  223. package/vendor/desktop/vendor/topup.js +1 -297
  224. package/vendor/desktop/vendor/touch.js +1 -458
  225. package/vendor/desktop/vendor/update.js +1 -763
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -1,472 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * Funnel telemetry — Phase 2 of docs/upgrade-conversion-plan.md.
10
- *
11
- * The plan asks for one thing: the funnel below defined ONCE, and the two steps
12
- * that today exist only as a DOM node (a prompt rendered, the prompt clicked)
13
- * reported per campaign, so `paid / prompt-shown` can be read per campaign
14
- * instead of guessed at.
15
- *
16
- * install -> key_connected -> first_auto_turn -> drain_used
17
- * -> upgrade_prompt_rendered -> upgrade_prompt_clicked
18
- * -> checkout_started -> paid
19
- *
20
- * The desktop client can only ever observe steps 5 and 6. The other six are
21
- * server-side facts (aegis1 auth rows, queue runs, Stripe checkout/`paid`
22
- * webhooks) and are named here so the whole funnel has exactly one definition
23
- * in code and the client's events can be checked against it — not so this
24
- * module can pretend to emit them.
25
- *
26
- * THREE PROPERTIES THIS MODULE IS BUILT AROUND, in order of importance:
27
- *
28
- * 1. It cannot break the UI. `record()` swallows everything: a missing
29
- * directory, a full disk, a bad payload, a throwing `sender`. It returns a
30
- * boolean, never throws, and never rejects. The renderer additionally
31
- * wraps its own call (see `promptEvent()` in renderer/app.js), because the
32
- * render path must be safe even if this file is broken or absent.
33
- * 2. It cannot leak. Records are rebuilt field by field from the payload —
34
- * never spread, never `JSON.stringify(payload)` — and only these keys can
35
- * ever reach disk or a sender: `event`, `campaign`, `surface`, `app`,
36
- * `install`, `ts`. No API key, no conversation content, no file paths, no
37
- * model output, no email, no machine identifier. `install` is 16 random
38
- * hex chars generated on this machine and stored in this app's userData;
39
- * it is an anonymous install counter, not a device fingerprint.
40
- * 3. It is OFF unless someone opted in (see `telemetryEnabled()`), and a
41
- * disabled store is a pure no-op: nothing is buffered, nothing is written,
42
- * no install id is created.
43
- *
44
- * TRANSPORT — LOCAL ONLY, TODAY. The task was to use "the same authenticated
45
- * client the desktop already uses to talk to aegiscloud.org"; that is
46
- * `client/aegis.js` (X-API-Key + Bearer), and it has NO event-ingest method.
47
- * aegis1 has no route that accepts client-named funnel events either — its
48
- * `analytics_events` table is written server-side by `_track_request()` off the
49
- * request path, and the only client-facing routes near this are
50
- * `/api/heartbeat` (updates `last_active_at`, takes no event) and
51
- * `/api/analytics` (GET, read-only). Inventing an ingest endpoint here would be
52
- * a client writing to a URL that 404s: the same silent zero the attribution
53
- * phase was about.
54
- *
55
- * So the transport is strictly local-first: a bounded in-memory ring buffer
56
- * plus an append-only JSONL at `<userData>/telemetry/funnel.jsonl`, read back
57
- * through `report()` (and `desktop/scripts/funnel-report.mjs`, which prints the
58
- * baseline table). `opts.sender` is the seam for the server half: the moment
59
- * aegis1 grows an ingest route, one function is passed in here and the same
60
- * records start flowing out with the same allowlist. Until then it is null and
61
- * the JSONL is the only sink.
62
- *
63
- * Nothing in this file may import Electron: it is plain Node so the tests can
64
- * drive it, and main.js is what injects the app version and the userData dir.
65
- */
66
-
67
- const fs = require('node:fs');
68
- const path = require('node:path');
69
- const crypto = require('node:crypto');
70
-
71
- /**
72
- * The funnel, in order. Steps 1-4 and 7-8 are server-side facts this client
73
- * cannot observe; 5 and 6 are the two it emits (EVENT_ALLOWLIST below). Kept as
74
- * one ordered list for the same reason the plan states it once: a funnel
75
- * defined twice drifts, and a funnel with a missing step reads as a drop-off
76
- * that never happened.
77
- */
78
- const FUNNEL = Object.freeze([
79
- 'install',
80
- 'key_connected',
81
- 'first_auto_turn',
82
- 'drain_used',
83
- 'upgrade_prompt_rendered',
84
- 'upgrade_prompt_clicked',
85
- 'checkout_started',
86
- 'paid',
87
- ]);
88
-
89
- /**
90
- * The ONLY event names this client may emit — the intersection of FUNNEL with
91
- * what the desktop can actually see. Anything else is dropped by
92
- * `sanitizeEvent()`, so a typo in the renderer costs a missing row, not a junk
93
- * row: a junky event name is indistinguishable from a real one in a sum.
94
- * `desktop/test/renderer-funnel-telemetry.test.mjs` fails if the renderer emits
95
- * a name that is not on this list.
96
- */
97
- const EVENT_ALLOWLIST = Object.freeze([
98
- 'upgrade_prompt_rendered',
99
- 'upgrade_prompt_clicked',
100
- ]);
101
-
102
- /**
103
- * Where a prompt was displayed. The campaign says WHICH prompt paid (Phase 1's
104
- * per-prompt ids); the surface says where it was read. Five values, the five
105
- * places a paid prompt can appear: the welcome panel, the autonomous queue
106
- * card, cloud memory, the status/settings card, the top-up/bank card.
107
- */
108
- const SURFACES = Object.freeze(['welcome', 'queue', 'memory', 'status', 'topup']);
109
-
110
- /**
111
- * The five fixed campaign ids from Phase 1 (`subscribeUrl()` in
112
- * renderer/app.js). An UNKNOWN campaign is dropped rather than sent: aegis1's
113
- * `_sanitize_signup_slug()` already discards slugs it does not know, and a
114
- * client-side event tagged with a campaign the server would never record is a
115
- * row that can never be joined to a click. `renderer-funnel-telemetry.test.mjs`
116
- * cross-checks this list against the renderer's, so the two cannot drift.
117
- */
118
- const CAMPAIGNS = Object.freeze([
119
- 'welcome_cloud',
120
- 'queue_cap',
121
- 'memory_quota',
122
- 'status_card',
123
- 'topup_bank',
124
- ]);
125
-
126
- /** Same shape aegis1 accepts (`_sanitize_signup_slug`): a second, looser regex
127
- * here would let through slugs the server silently drops. */
128
- const CAMPAIGN_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
129
-
130
- /** The exact record shape. Anything not in this list is not written and not
131
- * sent — this array is the privacy boundary, so it is asserted by a test. */
132
- const RECORD_KEYS = Object.freeze(['event', 'campaign', 'surface', 'app', 'install', 'ts']);
133
-
134
- /** Bounded ring: memory cannot grow with an unattended drain running for days. */
135
- const RING_MAX = 500;
136
-
137
- /** `AEGIS_TELEMETRY` — the operator's opt-in switch (1/true/on/yes). */
138
- const TELEMETRY_ENV = 'AEGIS_TELEMETRY';
139
-
140
- /** `<userData>/telemetry/` — this module owns this one directory, nothing else. */
141
- const DIR_NAME = 'telemetry';
142
- const FILE_NAME = 'funnel.jsonl';
143
- const INSTALL_ID_FILE = 'install-id';
144
-
145
- /**
146
- * Opt-in gate. Telemetry is OFF unless it is explicitly turned on, by either:
147
- *
148
- * - `AEGIS_TELEMETRY=1` in the environment (this process, or
149
- * `~/.aegiscode/.env` via the shared env loader), or
150
- * - the settings store's reserved `__telemetry` namespace
151
- * (`settings.setTelemetryOptIn(true)` — `getTelemetryOptIn()` is read
152
- * through a duck-typed accessor so this module stays free of settings.js).
153
- *
154
- * An unreadable store, a missing accessor, or an unrecognised value all mean
155
- * OFF. The default is deliberately the boring one: a funnel baseline collected
156
- * without asking would be a worse artifact than a funnel baseline collected a
157
- * week late.
158
- *
159
- * @param {Record<string,string|undefined>} env
160
- * @param {{getTelemetryOptIn?: () => boolean}} [settings]
161
- * @returns {boolean}
162
- */
163
- function telemetryEnabled(env, settings) {
164
- try {
165
- const raw = env && env[TELEMETRY_ENV];
166
- if (raw != null && String(raw).trim() !== '') {
167
- return /^(1|true|on|yes)$/i.test(String(raw).trim());
168
- }
169
- } catch {
170
- /* unreadable env: fall through to the settings flag */
171
- }
172
- try {
173
- if (settings && typeof settings.getTelemetryOptIn === 'function') {
174
- return settings.getTelemetryOptIn() === true;
175
- }
176
- } catch {
177
- /* an unreadable store is not consent */
178
- }
179
- return false;
180
- }
181
-
182
- /** ISO-8601 UTC, second precision. A funnel needs ordering, not microseconds. */
183
- function isoNow(now) {
184
- const t = typeof now === 'function' ? now() : Date.now();
185
- return new Date(Number.isFinite(t) ? t : Date.now()).toISOString().replace(/\.\d{3}Z$/, 'Z');
186
- }
187
-
188
- /**
189
- * Whitelist one emitted event, or return null.
190
- *
191
- * Drops, rather than repairs, anything it does not recognise: an unknown event
192
- * name, a campaign that is not one of the five fixed ids, a missing campaign, a
193
- * surface outside the enum, or a value of the wrong type. Dropping is the whole
194
- * design — the failure this guards is a payload that LOOKS fine and lands in
195
- * the denominator of the ratio the plan exists to measure.
196
- *
197
- * @param {unknown} name
198
- * @param {unknown} payload `{ campaign, surface }` plus anything else (ignored)
199
- * @param {{app?: string, install?: string, now?: () => number}} meta
200
- * @returns {null | {event: string, campaign: string, surface: string, app: string, install: string, ts: string}}
201
- */
202
- function sanitizeEvent(name, payload, meta) {
203
- try {
204
- const event = typeof name === 'string' ? name.trim() : '';
205
- if (!EVENT_ALLOWLIST.includes(event)) return null;
206
-
207
- const p = payload && typeof payload === 'object' ? payload : {};
208
- const campaign = typeof p.campaign === 'string' ? p.campaign.trim().toLowerCase() : '';
209
- const surface = typeof p.surface === 'string' ? p.surface.trim().toLowerCase() : '';
210
- if (!CAMPAIGN_RE.test(campaign) || !CAMPAIGNS.includes(campaign)) return null;
211
- if (!SURFACES.includes(surface)) return null;
212
-
213
- const m = meta || {};
214
- // Never spread `p`: fields are copied one by one on purpose (see the header).
215
- return {
216
- event,
217
- campaign,
218
- surface,
219
- app: typeof m.app === 'string' ? m.app.slice(0, 32) : '',
220
- install: typeof m.install === 'string' ? m.install.slice(0, 32) : '',
221
- ts: isoNow(m.now),
222
- };
223
- } catch {
224
- return null;
225
- }
226
- }
227
-
228
- /**
229
- * Count records. Pure, so both `report()` and the offline report script can use
230
- * it. Returns the two numbers the baseline table needs per campaign — prompts
231
- * shown and clicks — plus totals, and nothing derived from content.
232
- */
233
- function summarize(records) {
234
- const totals = {};
235
- const byCampaign = {};
236
- const bySurface = {};
237
- let dropped = 0;
238
- for (const rec of Array.isArray(records) ? records : []) {
239
- if (!rec || typeof rec !== 'object' || !EVENT_ALLOWLIST.includes(rec.event)) {
240
- dropped += 1;
241
- continue;
242
- }
243
- totals[rec.event] = (totals[rec.event] || 0) + 1;
244
- const c = byCampaign[rec.campaign] || { upgrade_prompt_rendered: 0, upgrade_prompt_clicked: 0 };
245
- c[rec.event] = (c[rec.event] || 0) + 1;
246
- byCampaign[rec.campaign] = c;
247
- const s = bySurface[rec.surface] || { upgrade_prompt_rendered: 0, upgrade_prompt_clicked: 0 };
248
- s[rec.event] = (s[rec.event] || 0) + 1;
249
- bySurface[rec.surface] = s;
250
- }
251
- return { totals, byCampaign, bySurface, dropped };
252
- }
253
-
254
- /** The store returned when telemetry is off. Every method answers, nothing
255
- * happens: no directory, no id, no buffer, no write. */
256
- function noopTelemetry() {
257
- return {
258
- enabled: false,
259
- transport: 'off',
260
- dir: null,
261
- file: null,
262
- record: () => false,
263
- events: () => [],
264
- report: () => ({ enabled: false, transport: 'off', file: null, buffered: 0, totals: {}, byCampaign: {}, bySurface: {}, dropped: 0 }),
265
- flush: () => Promise.resolve(),
266
- };
267
- }
268
-
269
- /**
270
- * @param {object} opts
271
- * @param {string} [opts.dir] Electron userData (main.js resolveUserDataDir)
272
- * @param {boolean} [opts.enabled] from telemetryEnabled()
273
- * @param {string} [opts.appVersion] app.getVersion()
274
- * @param {string} [opts.installId] test override; otherwise read/created on disk
275
- * @param {boolean} [opts.persist] false = ring buffer only (used by tests, and
276
- * by any future surface that must not touch disk)
277
- * @param {(record: object) => unknown} [opts.sender] the server seam; see the header
278
- * @param {(level: string, message: string, err?: unknown) => void} [opts.log]
279
- * @param {() => number} [opts.now]
280
- */
281
- function createTelemetry(opts = {}) {
282
- if (!opts.enabled) return noopTelemetry();
283
-
284
- const parent = typeof opts.dir === 'string' && opts.dir ? opts.dir : null;
285
- const dir = parent ? path.join(parent, DIR_NAME) : null;
286
- const file = dir ? path.join(dir, FILE_NAME) : null;
287
- const persist = opts.persist !== false && Boolean(file);
288
-
289
- // A failure is reported ONCE per kind, at debug level, and then never again —
290
- // the requirement is "swallowed and logged once at most". A disk that is full
291
- // does not need to fill the console of a running drain.
292
- const logged = new Set();
293
- const log = typeof opts.log === 'function' ? opts.log : () => {};
294
- function debugOnce(kind, err) {
295
- if (logged.has(kind)) return;
296
- logged.add(kind);
297
- try {
298
- log('debug', `telemetry: ${kind}`, err);
299
- } catch {
300
- /* a logger that throws is not allowed to matter */
301
- }
302
- }
303
-
304
- const ring = [];
305
- let droppedUnrecognised = 0;
306
- let installId = typeof opts.installId === 'string' ? opts.installId : null;
307
-
308
- /** 16 random hex chars. Not derived from hostname, MAC, user or install path. */
309
- function newInstallId() {
310
- try {
311
- return crypto.randomBytes(8).toString('hex');
312
- } catch {
313
- return `anon${Date.now().toString(16)}`;
314
- }
315
- }
316
-
317
- /** Read-or-create the anonymous install id. Best effort: if the disk refuses,
318
- * the id still exists for this session (records stay joinable within it). */
319
- function loadInstallId() {
320
- if (installId) return installId;
321
- installId = newInstallId();
322
- if (!persist) return installId;
323
- const idPath = path.join(dir, INSTALL_ID_FILE);
324
- try {
325
- const existing = fs.readFileSync(idPath, 'utf8').trim();
326
- if (/^[a-z0-9]{8,32}$/i.test(existing)) installId = existing;
327
- else fs.writeFileSync(idPath, installId, { mode: 0o600 });
328
- } catch {
329
- try {
330
- fs.mkdirSync(dir, { recursive: true });
331
- fs.writeFileSync(idPath, installId, { mode: 0o600 });
332
- } catch (err) {
333
- debugOnce('install-id', err);
334
- }
335
- }
336
- return installId;
337
- }
338
-
339
- // Appends are serialised through one promise chain: order is preserved, and
340
- // neither the IPC handler that calls this nor a render ever waits on it.
341
- let chain = Promise.resolve();
342
- function appendLine(line) {
343
- chain = chain
344
- .then(
345
- () =>
346
- new Promise((resolve) => {
347
- fs.mkdir(dir, { recursive: true }, () => {
348
- fs.appendFile(file, line, (err) => {
349
- if (err) debugOnce('append', err);
350
- resolve();
351
- });
352
- });
353
- })
354
- )
355
- .catch((err) => {
356
- debugOnce('append', err);
357
- });
358
- return chain;
359
- }
360
-
361
- /**
362
- * Record one event. Returns true when the record was accepted (buffered and
363
- * queued for writing) and false when it was dropped or telemetry is off.
364
- * NEVER throws and never rejects, whatever the caller passes and whatever the
365
- * disk or the sender does.
366
- */
367
- function record(name, payload) {
368
- try {
369
- const rec = sanitizeEvent(name, payload, {
370
- app: opts.appVersion,
371
- install: loadInstallId(),
372
- now: opts.now,
373
- });
374
- if (!rec) {
375
- droppedUnrecognised += 1;
376
- return false;
377
- }
378
- ring.push(rec);
379
- if (ring.length > RING_MAX) ring.splice(0, ring.length - RING_MAX);
380
- if (persist && file) appendLine(`${JSON.stringify(rec)}\n`);
381
- if (typeof opts.sender === 'function') {
382
- try {
383
- const sent = opts.sender(rec);
384
- if (sent && typeof sent.catch === 'function') sent.catch((err) => debugOnce('sender', err));
385
- } catch (err) {
386
- debugOnce('sender', err);
387
- }
388
- }
389
- return true;
390
- } catch (err) {
391
- debugOnce('record', err);
392
- return false;
393
- }
394
- }
395
-
396
- /** The buffered records, oldest first (a copy — the ring is not exported). */
397
- function events() {
398
- return ring.slice();
399
- }
400
-
401
- /**
402
- * The summary path. `byCampaign` is what the baseline table's middle four
403
- * columns come from; `checkouts`/`paid`/`revenue` are joined in from aegis1
404
- * (checkout_started, paid) and Stripe, which this client cannot see.
405
- */
406
- function report() {
407
- try {
408
- const summary = summarize(ring);
409
- return {
410
- enabled: true,
411
- transport: typeof opts.sender === 'function' ? 'local-jsonl+server' : 'local-jsonl',
412
- file: persist ? file : null,
413
- install: installId,
414
- buffered: ring.length,
415
- ...summary,
416
- droppedUnrecognised,
417
- };
418
- } catch (err) {
419
- debugOnce('report', err);
420
- return { enabled: true, error: 'report failed', totals: {}, byCampaign: {}, bySurface: {} };
421
- }
422
- }
423
-
424
- /** Resolves once every queued append has finished. For tests and shutdown. */
425
- function flush() {
426
- return chain.catch(() => {});
427
- }
428
-
429
- return { enabled: true, transport: 'local-jsonl', dir, file, record, events, report, flush, installId: () => loadInstallId() };
430
- }
431
-
432
- /**
433
- * Read a `funnel.jsonl` back. Tolerant by construction: a half-written last
434
- * line (the app was killed mid-append) is skipped rather than thrown, because
435
- * the report is run against a live directory.
436
- */
437
- function readFile(file) {
438
- try {
439
- const text = fs.readFileSync(file, 'utf8');
440
- const out = [];
441
- for (const line of text.split('\n')) {
442
- if (!line.trim()) continue;
443
- try {
444
- out.push(JSON.parse(line));
445
- } catch {
446
- /* torn tail from a hard kill — skip it */
447
- }
448
- }
449
- return out;
450
- } catch {
451
- return [];
452
- }
453
- }
454
-
455
- module.exports = {
456
- FUNNEL,
457
- EVENT_ALLOWLIST,
458
- SURFACES,
459
- CAMPAIGNS,
460
- CAMPAIGN_RE,
461
- RECORD_KEYS,
462
- RING_MAX,
463
- TELEMETRY_ENV,
464
- DIR_NAME,
465
- FILE_NAME,
466
- INSTALL_ID_FILE,
467
- telemetryEnabled,
468
- sanitizeEvent,
469
- summarize,
470
- createTelemetry,
471
- readFile,
472
- };
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),crypto=require("node:crypto"),FUNNEL=Object.freeze(["install","key_connected","first_auto_turn","drain_used","upgrade_prompt_rendered","upgrade_prompt_clicked","checkout_started","paid"]),EVENT_ALLOWLIST=Object.freeze(["upgrade_prompt_rendered","upgrade_prompt_clicked"]),SURFACES=Object.freeze(["welcome","queue","memory","status","topup"]),CAMPAIGNS=Object.freeze(["welcome_cloud","queue_cap","memory_quota","status_card","topup_bank"]),CAMPAIGN_RE=/^[a-z0-9][a-z0-9_-]{0,63}$/,RECORD_KEYS=Object.freeze(["event","campaign","surface","app","install","ts"]),RING_MAX=500,TELEMETRY_ENV="AEGIS_TELEMETRY",DIR_NAME="telemetry",FILE_NAME="funnel.jsonl",INSTALL_ID_FILE="install-id";function telemetryEnabled(e,t){try{const t=e&&e[TELEMETRY_ENV];if(null!=t&&""!==String(t).trim())return/^(1|true|on|yes)$/i.test(String(t).trim())}catch{}try{if(t&&"function"==typeof t.getTelemetryOptIn)return!0===t.getTelemetryOptIn()}catch{}return!1}function isoNow(e){const t="function"==typeof e?e():Date.now();return new Date(Number.isFinite(t)?t:Date.now()).toISOString().replace(/\.\d{3}Z$/,"Z")}function sanitizeEvent(e,t,r){try{const n="string"==typeof e?e.trim():"";if(!EVENT_ALLOWLIST.includes(n))return null;const i=t&&"object"==typeof t?t:{},o="string"==typeof i.campaign?i.campaign.trim().toLowerCase():"",a="string"==typeof i.surface?i.surface.trim().toLowerCase():"";if(!CAMPAIGN_RE.test(o)||!CAMPAIGNS.includes(o))return null;if(!SURFACES.includes(a))return null;const c=r||{};return{event:n,campaign:o,surface:a,app:"string"==typeof c.app?c.app.slice(0,32):"",install:"string"==typeof c.install?c.install.slice(0,32):"",ts:isoNow(c.now)}}catch{return null}}function summarize(e){const t={},r={},n={};let i=0;for(const o of Array.isArray(e)?e:[]){if(!o||"object"!=typeof o||!EVENT_ALLOWLIST.includes(o.event)){i+=1;continue}t[o.event]=(t[o.event]||0)+1;const e=r[o.campaign]||{upgrade_prompt_rendered:0,upgrade_prompt_clicked:0};e[o.event]=(e[o.event]||0)+1,r[o.campaign]=e;const a=n[o.surface]||{upgrade_prompt_rendered:0,upgrade_prompt_clicked:0};a[o.event]=(a[o.event]||0)+1,n[o.surface]=a}return{totals:t,byCampaign:r,bySurface:n,dropped:i}}function noopTelemetry(){return{enabled:!1,transport:"off",dir:null,file:null,record:()=>!1,events:()=>[],report:()=>({enabled:!1,transport:"off",file:null,buffered:0,totals:{},byCampaign:{},bySurface:{},dropped:0}),flush:()=>Promise.resolve()}}function createTelemetry(e={}){if(!e.enabled)return noopTelemetry();const t="string"==typeof e.dir&&e.dir?e.dir:null,r=t?path.join(t,DIR_NAME):null,n=r?path.join(r,FILE_NAME):null,i=!1!==e.persist&&Boolean(n),o=new Set,a="function"==typeof e.log?e.log:()=>{};function c(e,t){if(!o.has(e)){o.add(e);try{a("debug",`telemetry: ${e}`,t)}catch{}}}const l=[];let s=0,u="string"==typeof e.installId?e.installId:null;function p(){if(u)return u;if(u=function(){try{return crypto.randomBytes(8).toString("hex")}catch{return`anon${Date.now().toString(16)}`}}(),!i)return u;const e=path.join(r,"install-id");try{const t=fs.readFileSync(e,"utf8").trim();/^[a-z0-9]{8,32}$/i.test(t)?u=t:fs.writeFileSync(e,u,{mode:384})}catch{try{fs.mkdirSync(r,{recursive:!0}),fs.writeFileSync(e,u,{mode:384})}catch(e){c("install-id",e)}}return u}let f=Promise.resolve();return{enabled:!0,transport:"local-jsonl",dir:r,file:n,record:function(t,o){try{const u=sanitizeEvent(t,o,{app:e.appVersion,install:p(),now:e.now});if(!u)return s+=1,!1;if(l.push(u),l.length>500&&l.splice(0,l.length-500),i&&n&&(a=`${JSON.stringify(u)}\n`,f=f.then((()=>new Promise((e=>{fs.mkdir(r,{recursive:!0},(()=>{fs.appendFile(n,a,(t=>{t&&c("append",t),e()}))}))})))).catch((e=>{c("append",e)}))),"function"==typeof e.sender)try{const t=e.sender(u);t&&"function"==typeof t.catch&&t.catch((e=>c("sender",e)))}catch(e){c("sender",e)}return!0}catch(e){return c("record",e),!1}var a},events:function(){return l.slice()},report:function(){try{const t=summarize(l);return{enabled:!0,transport:"function"==typeof e.sender?"local-jsonl+server":"local-jsonl",file:i?n:null,install:u,buffered:l.length,...t,droppedUnrecognised:s}}catch(e){return c("report",e),{enabled:!0,error:"report failed",totals:{},byCampaign:{},bySurface:{}}}},flush:function(){return f.catch((()=>{}))},installId:()=>p()}}function readFile(e){try{const t=fs.readFileSync(e,"utf8"),r=[];for(const e of t.split("\n"))if(e.trim())try{r.push(JSON.parse(e))}catch{}return r}catch{return[]}}module.exports={FUNNEL:FUNNEL,EVENT_ALLOWLIST:EVENT_ALLOWLIST,SURFACES:SURFACES,CAMPAIGNS:CAMPAIGNS,CAMPAIGN_RE:CAMPAIGN_RE,RECORD_KEYS:RECORD_KEYS,RING_MAX:500,TELEMETRY_ENV:TELEMETRY_ENV,DIR_NAME:DIR_NAME,FILE_NAME:FILE_NAME,INSTALL_ID_FILE:"install-id",telemetryEnabled:telemetryEnabled,sanitizeEvent:sanitizeEvent,summarize:summarize,createTelemetry:createTelemetry,readFile:readFile};