@andorra-labs/code 0.1.18 → 0.1.19

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 (277) hide show
  1. package/dist/src/account-jev-savings.d.ts +4 -0
  2. package/dist/src/account-jev-savings.js +92 -0
  3. package/dist/src/acp-agent.js +2 -2
  4. package/dist/src/agent-execution.js +347 -45
  5. package/dist/src/agent-mcp.js +7 -1
  6. package/dist/src/agent-modifiers.js +5 -7
  7. package/dist/src/analytics.d.ts +19 -1
  8. package/dist/src/analytics.js +9 -1
  9. package/dist/src/andorra/entry.js +15 -6
  10. package/dist/src/andorra/hosted.d.ts +8 -0
  11. package/dist/src/andorra/hosted.js +22 -3
  12. package/dist/src/andorra/streams.d.ts +49 -0
  13. package/dist/src/andorra/streams.js +98 -0
  14. package/dist/src/antigravity-acp.d.ts +28 -0
  15. package/dist/src/antigravity-acp.js +150 -0
  16. package/dist/src/antigravity-terminal.d.ts +2 -0
  17. package/dist/src/antigravity-terminal.js +214 -0
  18. package/dist/src/app-server/adaptive-routing-settings.d.ts +37 -0
  19. package/dist/src/app-server/adaptive-routing-settings.js +69 -0
  20. package/dist/src/app-server/artifact.d.ts +14 -0
  21. package/dist/src/app-server/artifact.js +46 -0
  22. package/dist/src/app-server/legal-protocol.d.ts +33 -0
  23. package/dist/src/app-server/legal-protocol.js +16 -0
  24. package/dist/src/app-server/protocol.d.ts +23 -3
  25. package/dist/src/app-server/protocol.js +3 -1
  26. package/dist/src/app-server/telemetry-protocol.d.ts +53 -0
  27. package/dist/src/app-server/telemetry-protocol.js +2 -0
  28. package/dist/src/app-server/telemetry.d.ts +38 -0
  29. package/dist/src/app-server/telemetry.js +163 -0
  30. package/dist/src/app-server/workspace.d.ts +3 -1
  31. package/dist/src/app-server/workspace.js +39 -8
  32. package/dist/src/app-server.d.ts +50 -25
  33. package/dist/src/app-server.js +1008 -400
  34. package/dist/src/auth/AuthManager.d.ts +11 -2
  35. package/dist/src/auth/AuthManager.js +56 -13
  36. package/dist/src/auth/index.d.ts +5 -1
  37. package/dist/src/auth/index.js +8 -1
  38. package/dist/src/auth/lifecycle.d.ts +13 -0
  39. package/dist/src/auth/lifecycle.js +109 -0
  40. package/dist/src/auth/store.d.ts +1 -0
  41. package/dist/src/auth/store.js +12 -0
  42. package/dist/src/auth/types.d.ts +12 -0
  43. package/dist/src/automation-runner.js +2 -0
  44. package/dist/src/automation-service.js +7 -2
  45. package/dist/src/benchmark-scores.d.ts +88 -0
  46. package/dist/src/benchmark-scores.js +302 -0
  47. package/dist/src/bridge/command.js +4 -1
  48. package/dist/src/bridge/control.js +2 -1
  49. package/dist/src/bridge/engines.d.ts +2 -0
  50. package/dist/src/bridge/engines.js +9 -0
  51. package/dist/src/bridge/host-ops.d.ts +2 -2
  52. package/dist/src/bridge/host-ops.js +4 -2
  53. package/dist/src/bridge/host.d.ts +2 -0
  54. package/dist/src/bridge/host.js +63 -12
  55. package/dist/src/bridge/protocol.d.ts +1 -0
  56. package/dist/src/bridge/protocol.js +1 -0
  57. package/dist/src/browser-panel-tool.d.ts +12 -0
  58. package/dist/src/browser-panel-tool.js +30 -3
  59. package/dist/src/browser-runner.js +53 -62
  60. package/dist/src/browser-server.js +10 -4
  61. package/dist/src/browser-session.d.ts +14 -0
  62. package/dist/src/browser-session.js +57 -12
  63. package/dist/src/browser-view.d.ts +40 -1
  64. package/dist/src/browser-view.js +163 -9
  65. package/dist/src/browser-window-style.d.ts +27 -0
  66. package/dist/src/browser-window-style.js +244 -0
  67. package/dist/src/claude-provider.d.ts +1 -0
  68. package/dist/src/claude-provider.js +77 -36
  69. package/dist/src/cli.js +235 -58
  70. package/dist/src/codex-provider.d.ts +1 -0
  71. package/dist/src/codex-provider.js +43 -7
  72. package/dist/src/coding-tools.d.ts +1 -0
  73. package/dist/src/coding-tools.js +19 -5
  74. package/dist/src/command-screens.d.ts +1 -1
  75. package/dist/src/command-screens.js +2 -2
  76. package/dist/src/commands.d.ts +8 -1
  77. package/dist/src/commands.js +67 -63
  78. package/dist/src/completion.js +5 -3
  79. package/dist/src/config.d.ts +14 -3
  80. package/dist/src/config.js +54 -16
  81. package/dist/src/context-budget.d.ts +11 -2
  82. package/dist/src/context-budget.js +23 -2
  83. package/dist/src/context-compaction.d.ts +10 -8
  84. package/dist/src/context-compaction.js +23 -24
  85. package/dist/src/deadline.js +1 -1
  86. package/dist/src/decision/DecisionManager.d.ts +5 -0
  87. package/dist/src/decision/DecisionManager.js +39 -2
  88. package/dist/src/decision/applyToolMenu.js +6 -2
  89. package/dist/src/decision/hostedPolicy.js +6 -4
  90. package/dist/src/decision/optimizationPolicy.d.ts +10 -0
  91. package/dist/src/decision/optimizationPolicy.js +23 -3
  92. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +2 -1
  93. package/dist/src/decision/providers/AndorraDecisionProvider.js +17 -7
  94. package/dist/src/decision/providers/index.js +1 -1
  95. package/dist/src/decision/toolFamilies.js +1 -1
  96. package/dist/src/decision/types.d.ts +2 -0
  97. package/dist/src/efficiency.d.ts +75 -1
  98. package/dist/src/efficiency.js +114 -3
  99. package/dist/src/extensions.d.ts +2 -0
  100. package/dist/src/extensions.js +30 -20
  101. package/dist/src/github-app/agent-writes.d.ts +1 -1
  102. package/dist/src/github-app/agent-writes.js +1 -1
  103. package/dist/src/github-app/event-source.d.ts +0 -5
  104. package/dist/src/github-app/event-source.js +1 -31
  105. package/dist/src/github-app/metrics.d.ts +2 -5
  106. package/dist/src/github-app/metrics.js +2 -14
  107. package/dist/src/github-app/review-loop.d.ts +5 -5
  108. package/dist/src/github-app/review-loop.js +1 -1
  109. package/dist/src/github-app/review-node.d.ts +2 -2
  110. package/dist/src/github-app/triggers.d.ts +3 -3
  111. package/dist/src/glob-search.d.ts +1 -0
  112. package/dist/src/glob-search.js +3 -0
  113. package/dist/src/google-provider.d.ts +5 -28
  114. package/dist/src/google-provider.js +6 -141
  115. package/dist/src/graph-editor-session.d.ts +1 -0
  116. package/dist/src/graph-editor-session.js +2 -0
  117. package/dist/src/graph-health.js +3 -1
  118. package/dist/src/graph-runner.js +19 -13
  119. package/dist/src/graph-selection.d.ts +3 -1
  120. package/dist/src/graph-selection.js +2 -2
  121. package/dist/src/graph-server.d.ts +8 -1
  122. package/dist/src/graph-server.js +45 -10
  123. package/dist/src/graph-sync.d.ts +2 -1
  124. package/dist/src/graph-sync.js +13 -0
  125. package/dist/src/graph-ui/app.js +19 -8
  126. package/dist/src/graph-ui/index.html +1 -1
  127. package/dist/src/graphs.d.ts +17 -1
  128. package/dist/src/graphs.js +51 -5
  129. package/dist/src/grok-provider.js +17 -14
  130. package/dist/src/hardened-runtime.js +7 -4
  131. package/dist/src/jev-savings.d.ts +4 -0
  132. package/dist/src/jev-savings.js +13 -0
  133. package/dist/src/legal/client.d.ts +25 -0
  134. package/dist/src/legal/client.js +47 -0
  135. package/dist/src/legal/command.d.ts +13 -0
  136. package/dist/src/legal/command.js +98 -0
  137. package/dist/src/legal/documents.d.ts +2 -0
  138. package/dist/src/legal/documents.js +14 -0
  139. package/dist/src/legal/gate.d.ts +13 -0
  140. package/dist/src/legal/gate.js +96 -0
  141. package/dist/src/legal/manifest.d.ts +21 -0
  142. package/dist/src/legal/manifest.js +23 -0
  143. package/dist/src/legal/receipt.d.ts +13 -0
  144. package/dist/src/legal/receipt.js +137 -0
  145. package/dist/src/legal/release.d.ts +27 -0
  146. package/dist/src/legal/release.js +28 -0
  147. package/dist/src/managed-sign-in.d.ts +0 -1
  148. package/dist/src/managed-sign-in.js +0 -13
  149. package/dist/src/membership.d.ts +27 -1
  150. package/dist/src/membership.js +139 -7
  151. package/dist/src/model-metadata.js +3 -7
  152. package/dist/src/model-pool.d.ts +99 -0
  153. package/dist/src/model-pool.js +136 -0
  154. package/dist/src/model-relay/local.js +5 -0
  155. package/dist/src/model-relay/remote.d.ts +2 -0
  156. package/dist/src/model-relay/remote.js +4 -0
  157. package/dist/src/model-tiers.d.ts +13 -1
  158. package/dist/src/model-tiers.js +28 -4
  159. package/dist/src/opencode-cli-provider.js +59 -56
  160. package/dist/src/opencode-provider.js +16 -13
  161. package/dist/src/permissions.d.ts +5 -0
  162. package/dist/src/permissions.js +7 -0
  163. package/dist/src/plan-pass.js +2 -1
  164. package/dist/src/pool-scores.d.ts +45 -0
  165. package/dist/src/pool-scores.js +40 -0
  166. package/dist/src/provider-connection.js +3 -17
  167. package/dist/src/provider-engine.js +42 -12
  168. package/dist/src/provider-request-error.d.ts +8 -0
  169. package/dist/src/provider-request-error.js +12 -0
  170. package/dist/src/provider-settings.d.ts +1 -1
  171. package/dist/src/provider-settings.js +36 -18
  172. package/dist/src/provider-turn-deadline.d.ts +39 -0
  173. package/dist/src/provider-turn-deadline.js +139 -0
  174. package/dist/src/providers.d.ts +3 -9
  175. package/dist/src/providers.js +181 -146
  176. package/dist/src/pull-request-merge.d.ts +1 -8
  177. package/dist/src/pull-request-merge.js +0 -4
  178. package/dist/src/pull-requests.d.ts +82 -66
  179. package/dist/src/pull-requests.js +266 -276
  180. package/dist/src/qa/runtime/ProcessManager.d.ts +5 -1
  181. package/dist/src/qa/runtime/ProcessManager.js +9 -3
  182. package/dist/src/react-runtime.js +147 -56
  183. package/dist/src/reasoning-probe-cloud.d.ts +10 -0
  184. package/dist/src/reasoning-probe-cloud.js +209 -0
  185. package/dist/src/remote/engine-pool.d.ts +3 -0
  186. package/dist/src/remote/engine-pool.js +85 -18
  187. package/dist/src/remote/recovery.d.ts +6 -0
  188. package/dist/src/remote/recovery.js +37 -0
  189. package/dist/src/run-records.d.ts +13 -3
  190. package/dist/src/run-records.js +59 -34
  191. package/dist/src/runtime.d.ts +18 -1
  192. package/dist/src/runtime.js +25 -7
  193. package/dist/src/session-summary.d.ts +8 -0
  194. package/dist/src/session-summary.js +34 -0
  195. package/dist/src/sessions.d.ts +8 -0
  196. package/dist/src/sessions.js +12 -3
  197. package/dist/src/shell.js +6 -0
  198. package/dist/src/side-panel.js +36 -2
  199. package/dist/src/sign-in-detection.d.ts +1 -1
  200. package/dist/src/sign-in-detection.js +4 -10
  201. package/dist/src/sign-in-offer.js +1 -1
  202. package/dist/src/skill-commands.js +1 -1
  203. package/dist/src/skills/bundled/graph-manager/SKILL.md +2 -2
  204. package/dist/src/skills/bundled/graph-manager/patterns.md +13 -19
  205. package/dist/src/skills/bundled/provenance.json +2 -2
  206. package/dist/src/subagent-run.js +50 -50
  207. package/dist/src/subscription-usage.d.ts +50 -0
  208. package/dist/src/subscription-usage.js +92 -0
  209. package/dist/src/task-checkout.d.ts +20 -4
  210. package/dist/src/task-checkout.js +78 -8
  211. package/dist/src/telemetry/access.d.ts +18 -0
  212. package/dist/src/telemetry/access.js +43 -0
  213. package/dist/src/telemetry/aggregate.d.ts +18 -2
  214. package/dist/src/telemetry/aggregate.js +22 -9
  215. package/dist/src/telemetry/capture-core.d.ts +33 -14
  216. package/dist/src/telemetry/capture-core.js +124 -25
  217. package/dist/src/telemetry/capture.d.ts +3 -2
  218. package/dist/src/telemetry/capture.js +21 -1
  219. package/dist/src/telemetry/decision-capture.js +4 -0
  220. package/dist/src/telemetry/emitter.d.ts +6 -7
  221. package/dist/src/telemetry/emitter.js +124 -29
  222. package/dist/src/telemetry/gate.d.ts +41 -2
  223. package/dist/src/telemetry/gate.js +89 -4
  224. package/dist/src/telemetry/home.d.ts +1 -0
  225. package/dist/src/telemetry/home.js +20 -0
  226. package/dist/src/telemetry/identity.d.ts +6 -3
  227. package/dist/src/telemetry/identity.js +19 -6
  228. package/dist/src/telemetry/lifecycle.d.ts +8 -0
  229. package/dist/src/telemetry/lifecycle.js +76 -0
  230. package/dist/src/telemetry/outbox.d.ts +13 -8
  231. package/dist/src/telemetry/outbox.js +68 -12
  232. package/dist/src/telemetry/permission-command.d.ts +38 -0
  233. package/dist/src/telemetry/permission-command.js +208 -0
  234. package/dist/src/telemetry/permission.d.ts +168 -0
  235. package/dist/src/telemetry/permission.js +662 -0
  236. package/dist/src/telemetry/record-installation.d.ts +1 -0
  237. package/dist/src/telemetry/record-installation.js +9 -0
  238. package/dist/src/telemetry/region-data.d.ts +12 -0
  239. package/dist/src/telemetry/region-data.js +1314 -0
  240. package/dist/src/telemetry/region.d.ts +34 -0
  241. package/dist/src/telemetry/region.js +87 -0
  242. package/dist/src/telemetry/run-privacy.d.ts +11 -0
  243. package/dist/src/telemetry/run-privacy.js +165 -0
  244. package/dist/src/telemetry/schema.d.ts +27 -6
  245. package/dist/src/telemetry/schema.js +109 -14
  246. package/dist/src/telemetry/state.d.ts +11 -7
  247. package/dist/src/telemetry/state.js +39 -6
  248. package/dist/src/telemetry/surface.d.ts +20 -3
  249. package/dist/src/telemetry/surface.js +71 -15
  250. package/dist/src/telemetry/uploader.d.ts +6 -11
  251. package/dist/src/telemetry/uploader.js +72 -46
  252. package/dist/src/telemetry/uploads.d.ts +5 -1
  253. package/dist/src/telemetry/uploads.js +25 -6
  254. package/dist/src/telemetry/version.d.ts +5 -0
  255. package/dist/src/telemetry/version.js +34 -0
  256. package/dist/src/telemetry/workspace.d.ts +4 -1
  257. package/dist/src/telemetry/workspace.js +18 -3
  258. package/dist/src/terminal-ui.d.ts +3 -0
  259. package/dist/src/terminal-ui.js +48 -6
  260. package/dist/src/thinking-level-detect.d.ts +3 -1
  261. package/dist/src/thinking-level-detect.js +8 -3
  262. package/dist/src/thinking-levels.d.ts +1 -1
  263. package/dist/src/thinking-levels.js +11 -4
  264. package/dist/src/timers.d.ts +2 -0
  265. package/dist/src/todos.d.ts +2 -1
  266. package/dist/src/todos.js +24 -4
  267. package/dist/src/tool-argument-coercion.d.ts +7 -0
  268. package/dist/src/tool-argument-coercion.js +49 -0
  269. package/dist/src/tool-catalog.d.ts +2 -2
  270. package/dist/src/tools.js +67 -22
  271. package/dist/src/transcript.js +2 -1
  272. package/dist/src/types.d.ts +14 -1
  273. package/dist/src/update.js +4 -0
  274. package/dist/src/usage-analytics.d.ts +7 -0
  275. package/dist/src/usage-analytics.js +85 -13
  276. package/dist/telemetry-consent-v1 +1 -0
  277. package/package.json +97 -96
@@ -0,0 +1,662 @@
1
+ /**
2
+ * Necessary home-wide privacy authority. Never imports analytics, identity, plan state or config.
3
+ * Lock states (all files below the checked private privacy/ directory):
4
+ * idle -> shared: register a unique reader under the short .save-lock mutex, then release mutex.
5
+ * shared + shared: producers/POSTs overlap; only their existing state/spool locks serialize them.
6
+ * any -> requested: a choice publishes its intent BEFORE waiting. New admissions stop immediately.
7
+ * requested -> exclusive: take mutex, wait for registered readers, commit choice/cleanup, release.
8
+ * exclusive -> idle: remove our intent only after commit/cleanup and release. No POST can follow ACK.
9
+ * Refusals (.telemetry-withdrawal-*) outrank Allow/Auto: a waiting affirmative writer yields its mutex
10
+ * to them and then rechecks CAS. Every POST gets fresh admission and checks intent again before fetch.
11
+ * Dead local owners (readers, intents, mutex) are recovered, never live/foreign owners; torn owner
12
+ * records need a grace period. Reader registration/recovery is mutex-serialized; release owns a UUID.
13
+ * A crashed writer's durable cleanup-pending choice remains off and execution startup resumes it.
14
+ * Functional run writes take ONLY their per-file lock and check the necessary choice inside it;
15
+ * cleanup takes the same file lock, so they never wait on a network/privacy lock or restore old data.
16
+ * Lock order: privacy admission -> config/telemetry state/spool. Never invert it. Status never writes.
17
+ */
18
+ import fs from 'node:fs/promises';
19
+ import { constants, lstatSync, openSync, fstatSync, readSync, closeSync, readdirSync } from 'node:fs';
20
+ import { hostname } from 'node:os';
21
+ import { randomBytes, randomUUID } from 'node:crypto';
22
+ import { join } from 'node:path';
23
+ import { telemetryHome } from './home.js';
24
+ import { AsyncLocalStorage } from 'node:async_hooks';
25
+ import { acquireSaveLock, SaveLockBusyError } from '../save-lock.js';
26
+ import { readLocalTelemetrySignals, resolveTelemetryRegion } from './region.js';
27
+ export const TELEMETRY_NOTICE_VERSION = 1;
28
+ export const TELEMETRY_CONSENT_VERSION = 1;
29
+ export const TELEMETRY_NOTICE = Object.freeze({
30
+ version: TELEMETRY_NOTICE_VERSION,
31
+ title: 'Send product usage reports?',
32
+ body: 'Help improve Andorra Code by sending feature-use counts, run outcomes, timings, model and tool usage totals, app/device details, and broad project language/framework categories. Reports use a random installation ID and are not linked to your account. They do not include code, prompts, responses, paths or keys.',
33
+ scope: "This choice applies to this installation's CLI and desktop app. You can change it at any time in Settings → Analytics or with /feedback, on any plan.",
34
+ allowLabel: 'Allow reports',
35
+ denyLabel: "Don't allow reports",
36
+ privacyUrl: 'https://andorracode.com/privacy',
37
+ });
38
+ const defaultIO = { fs, acquireLock: acquireSaveLock, activationId: () => randomBytes(16).toString('hex'), now: () => new Date().toISOString() };
39
+ const MAX_CONSENT_BYTES = 4096;
40
+ const missing = (error) => error.code === 'ENOENT';
41
+ export function telemetryConsentPath(home) { return join(telemetryHome(home), 'privacy', 'telemetry-consent.json'); }
42
+ const privacyDirectory = (home) => join(telemetryHome(home), 'privacy');
43
+ const ioFor = (input) => input.io ?? defaultIO;
44
+ const signalsFor = (input) => typeof input.signals === 'function' ? input.signals() : input.signals ?? readLocalTelemetrySignals();
45
+ export function validTelemetryConsent(value) {
46
+ if (!value || typeof value !== 'object' || Array.isArray(value))
47
+ return false;
48
+ const r = value;
49
+ const allowed = ['version', 'noticeVersion', 'answer', 'policy', 'revision', 'activationId', 'decidedAt', 'activation'];
50
+ if (Object.keys(r).some(key => !allowed.includes(key)) || r.version !== 1 || r.noticeVersion !== TELEMETRY_NOTICE_VERSION
51
+ || !['yes', 'no'].includes(r.answer) || !['ask', 'auto'].includes(r.policy)
52
+ || !Number.isSafeInteger(r.revision) || r.revision < 1 || r.revision > Number.MAX_SAFE_INTEGER
53
+ // Reserve the final safe revision for No so even the largest valid Yes can be withdrawn.
54
+ || (r.answer === 'yes' && r.revision === Number.MAX_SAFE_INTEGER)
55
+ || !['cleanup-pending', 'ready'].includes(r.activation)
56
+ || typeof r.decidedAt !== 'string' || r.decidedAt.length !== 24)
57
+ return false;
58
+ try {
59
+ if (new Date(r.decidedAt).toISOString() !== r.decidedAt)
60
+ return false;
61
+ }
62
+ catch {
63
+ return false;
64
+ }
65
+ return r.answer === 'yes' ? typeof r.activationId === 'string' && /^[a-f0-9]{32}$/.test(r.activationId) : r.activationId === undefined;
66
+ }
67
+ function privateOwner(info) {
68
+ return process.platform === 'win32' || ((info.mode & 0o077) === 0 && (process.getuid === undefined || info.uid === process.getuid()));
69
+ }
70
+ async function checkPrivacyDirectory(input) {
71
+ const filesystem = ioFor(input).fs;
72
+ const home = await filesystem.lstat(telemetryHome(input.home));
73
+ if (!home.isDirectory() || home.isSymbolicLink())
74
+ throw new Error('Unsafe installation home');
75
+ const info = await filesystem.lstat(privacyDirectory(input.home));
76
+ if (!info.isDirectory() || info.isSymbolicLink() || !privateOwner(info))
77
+ throw new Error('Unsafe privacy directory');
78
+ }
79
+ /** Missing/failed reads have no authority and perform no writes, mkdir, locks or telemetry I/O. */
80
+ export async function readTelemetryConsent(input) {
81
+ const io = ioFor(input);
82
+ let handle;
83
+ try {
84
+ await checkPrivacyDirectory(input);
85
+ // Windows may not implement O_NOFOLLOW; reject static file links on every platform too.
86
+ const entry = await io.fs.lstat(telemetryConsentPath(input.home));
87
+ if (entry.isSymbolicLink() || !entry.isFile())
88
+ return { kind: 'unavailable' };
89
+ handle = await io.fs.open(telemetryConsentPath(input.home), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
90
+ const info = await handle.stat();
91
+ if (!info.isFile() || !privateOwner(info) || info.size > MAX_CONSENT_BYTES)
92
+ return { kind: 'invalid' };
93
+ const bytes = Buffer.alloc(MAX_CONSENT_BYTES + 1);
94
+ let size = 0;
95
+ for (;;) {
96
+ const read = await handle.read(bytes, size, bytes.length - size, null);
97
+ size += read.bytesRead;
98
+ if (size > MAX_CONSENT_BYTES)
99
+ return { kind: 'invalid' };
100
+ if (read.bytesRead === 0)
101
+ break;
102
+ }
103
+ const value = JSON.parse(bytes.subarray(0, size).toString('utf8'));
104
+ return validTelemetryConsent(value) ? { kind: 'valid', record: value } : { kind: 'invalid' };
105
+ }
106
+ catch (error) {
107
+ return { kind: missing(error) ? 'missing' : error instanceof SyntaxError ? 'invalid' : 'unavailable' };
108
+ }
109
+ finally {
110
+ await handle?.close().catch(() => { });
111
+ }
112
+ }
113
+ const suppressed = new Set();
114
+ const controllers = new Map();
115
+ const revocations = new Map();
116
+ /** Weak registrations avoid retaining completed runs or installing polling/listener handles. */
117
+ export function trackTelemetryRevocation(home, target) {
118
+ const key = telemetryHome(home), targets = revocations.get(key) ?? new Set();
119
+ for (const ref of targets)
120
+ if (!ref.deref())
121
+ targets.delete(ref);
122
+ targets.add(new WeakRef(target));
123
+ revocations.set(key, targets);
124
+ }
125
+ /** Immediate process-local suppression/cancellation; not a claim of cross-process signalling. */
126
+ export function suppressTelemetry(home) {
127
+ const key = telemetryHome(home);
128
+ suppressed.add(key);
129
+ for (const controller of controllers.get(key) ?? [])
130
+ controller.abort();
131
+ const targets = revocations.get(key);
132
+ for (const ref of targets ?? []) {
133
+ const target = ref.deref();
134
+ if (target) {
135
+ try {
136
+ target.revoke();
137
+ }
138
+ catch { /* A sink must never prevent durable withdrawal. */ }
139
+ }
140
+ else
141
+ targets?.delete(ref);
142
+ }
143
+ if (!targets?.size)
144
+ revocations.delete(key);
145
+ }
146
+ export async function telemetryPermission(input) {
147
+ let read;
148
+ let resolution;
149
+ try {
150
+ read = await readTelemetryConsent(input);
151
+ resolution = resolveTelemetryRegion(signalsFor(input), read.kind === 'valid' ? read.record.policy : 'auto');
152
+ }
153
+ catch {
154
+ read = { kind: 'unavailable' };
155
+ resolution = { region: 'unknown', permissionRequired: true, reason: 'no-usable-signal' };
156
+ }
157
+ const record = read.kind === 'valid' ? read.record : undefined;
158
+ const bad = read.kind === 'invalid' || read.kind === 'unavailable' || suppressed.has(telemetryHome(input.home));
159
+ const pendingCleanup = record?.activation === 'cleanup-pending';
160
+ const permissionRequired = bad || pendingCleanup || resolution.permissionRequired;
161
+ const permitted = !bad && !pendingCleanup && (!permissionRequired || record?.answer === 'yes');
162
+ return {
163
+ region: bad || pendingCleanup ? 'unknown' : resolution.region,
164
+ permissionRequired, policy: record?.policy ?? 'auto',
165
+ answer: bad ? 'invalid' : record?.answer ?? 'pending', permitted, canChange: permissionRequired,
166
+ reason: bad ? 'privacy-state-unavailable' : pendingCleanup ? 'cleanup-pending' : !permissionRequired ? 'outside-policy'
167
+ : record?.answer === 'yes' ? 'permission-granted' : record?.answer === 'no' ? 'permission-declined' : 'permission-needed',
168
+ revision: record?.revision ?? 0, noticeVersion: TELEMETRY_NOTICE_VERSION, activation: record?.activation ?? 'none',
169
+ };
170
+ }
171
+ async function leaseFor(input, status) {
172
+ if (!status.permitted)
173
+ return undefined;
174
+ // Read again rather than returning a status as a cached admission credential.
175
+ const read = await readTelemetryConsent(input);
176
+ if (read.kind !== 'valid' && read.kind !== 'missing')
177
+ return undefined;
178
+ if (read.kind === 'valid' && (read.record.revision !== status.revision || read.record.activation !== 'ready'))
179
+ return undefined;
180
+ if (read.kind === 'missing' && status.revision !== 0)
181
+ return undefined;
182
+ const home = telemetryHome(input.home);
183
+ if (!status.permissionRequired)
184
+ return Object.freeze({ home, mode: 'out', revision: status.revision, ...(read.kind === 'valid' && read.record.activationId ? { activationId: read.record.activationId } : {}) });
185
+ return read.kind === 'valid' && read.record.answer === 'yes' && read.record.activationId
186
+ ? Object.freeze({ home, mode: 'consent', revision: read.record.revision, activationId: read.record.activationId }) : undefined;
187
+ }
188
+ export async function telemetryLease(input) {
189
+ return leaseFor(input, await telemetryPermission(input));
190
+ }
191
+ export function sameTelemetryLease(a, b) {
192
+ return !!a && !!b && a.home === b.home && a.mode === b.mode && a.revision === b.revision && a.activationId === b.activationId;
193
+ }
194
+ /**
195
+ * Read-only necessary-choice check for synchronous in-memory sinks. Does NOT authorize disk I/O:
196
+ * serialization/enqueue still require withTelemetryAdmission. Bounded and symlink-safe like async
197
+ * status; checking after every await/callback notices another process's durable withdrawal.
198
+ */
199
+ export function telemetryLeaseSnapshot(input) {
200
+ if (suppressed.has(telemetryHome(input.home)) || telemetryChoiceRequested(input.home))
201
+ return undefined;
202
+ let record;
203
+ let fd;
204
+ try {
205
+ const home = lstatSync(telemetryHome(input.home));
206
+ if (!home.isDirectory() || home.isSymbolicLink())
207
+ return undefined;
208
+ const directory = lstatSync(privacyDirectory(input.home));
209
+ if (!directory.isDirectory() || directory.isSymbolicLink() || !privateOwner(directory))
210
+ return undefined;
211
+ const entry = lstatSync(telemetryConsentPath(input.home));
212
+ if (!entry.isFile() || entry.isSymbolicLink())
213
+ return undefined;
214
+ fd = openSync(telemetryConsentPath(input.home), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
215
+ const info = fstatSync(fd);
216
+ if (!info.isFile() || !privateOwner(info) || info.size > MAX_CONSENT_BYTES)
217
+ return undefined;
218
+ const bytes = Buffer.alloc(MAX_CONSENT_BYTES + 1);
219
+ let size = 0;
220
+ for (;;) {
221
+ const n = readSync(fd, bytes, size, bytes.length - size, null);
222
+ size += n;
223
+ if (size > MAX_CONSENT_BYTES)
224
+ return undefined;
225
+ if (!n)
226
+ break;
227
+ }
228
+ const parsed = JSON.parse(bytes.subarray(0, size).toString('utf8'));
229
+ if (!validTelemetryConsent(parsed))
230
+ return undefined;
231
+ record = parsed;
232
+ }
233
+ catch (error) {
234
+ if (!missing(error))
235
+ return undefined;
236
+ }
237
+ finally {
238
+ if (fd !== undefined)
239
+ closeSync(fd);
240
+ }
241
+ try {
242
+ const resolution = resolveTelemetryRegion(signalsFor(input), record?.policy ?? 'auto');
243
+ if (record?.activation === 'cleanup-pending')
244
+ return undefined;
245
+ if (!resolution.permissionRequired)
246
+ return { home: telemetryHome(input.home), mode: 'out', revision: record?.revision ?? 0, ...(record?.activationId ? { activationId: record.activationId } : {}) };
247
+ return record?.answer === 'yes' && record.activationId
248
+ ? { home: telemetryHome(input.home), mode: 'consent', revision: record.revision, activationId: record.activationId } : undefined;
249
+ }
250
+ catch {
251
+ return undefined;
252
+ }
253
+ }
254
+ export function telemetryLeaseIsCurrent(input, lease) {
255
+ return sameTelemetryLease(lease, telemetryLeaseSnapshot(input));
256
+ }
257
+ const controlReads = new WeakSet();
258
+ export function telemetryControlReadIsCurrent(read, home) {
259
+ return controlReads.has(read) && read.home === telemetryHome(home) && read.current();
260
+ }
261
+ export async function readTelemetryControl(input, work) {
262
+ const status = await telemetryPermission(input);
263
+ if (status.permissionRequired || !status.permitted)
264
+ return undefined;
265
+ const lease = await leaseFor(input, status);
266
+ if (!lease || lease.mode !== 'out')
267
+ return undefined;
268
+ const read = Object.freeze({ home: lease.home, status,
269
+ current: () => controlReads.has(read) && telemetryLeaseIsCurrent(input, lease) });
270
+ controlReads.add(read);
271
+ try {
272
+ if (!read.current())
273
+ return undefined;
274
+ const result = await work(read);
275
+ return read.current() ? result : undefined;
276
+ }
277
+ finally {
278
+ controlReads.delete(read);
279
+ }
280
+ }
281
+ const admissionContext = new AsyncLocalStorage();
282
+ const liveAdmissions = new WeakSet();
283
+ /** Escaped async callbacks must reacquire admission, never reuse an already-released barrier. */
284
+ export function currentTelemetryAdmission() {
285
+ const current = admissionContext.getStore();
286
+ return current && liveAdmissions.has(current) && !current.signal.aborted ? current : undefined;
287
+ }
288
+ const privacyLockContext = new AsyncLocalStorage();
289
+ const READER = '.telemetry-reader-', CHOICE = '.telemetry-choice-', WITHDRAWAL = '.telemetry-withdrawal-';
290
+ const isIntent = (name) => name.startsWith(CHOICE) || name.startsWith(WITHDRAWAL);
291
+ const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
292
+ const CHOICE_WAIT_MS = 10_000; // exceeds a bounded 5s POST plus scheduling/cleanup margin
293
+ /** Read-only, fail-closed intent check, also used by synchronous captures and each POST. */
294
+ export function telemetryChoiceRequested(home) {
295
+ try {
296
+ const entry = lstatSync(privacyDirectory(home));
297
+ if (!entry.isDirectory() || entry.isSymbolicLink() || !privateOwner(entry))
298
+ return true;
299
+ return readdirSync(privacyDirectory(home)).some(isIntent);
300
+ }
301
+ catch (error) {
302
+ return !missing(error);
303
+ }
304
+ }
305
+ async function preparePrivacyDirectory(input) {
306
+ const io = ioFor(input);
307
+ const home = await io.fs.lstat(telemetryHome(input.home)).catch(error => { if (!missing(error))
308
+ throw error; return undefined; });
309
+ if (home && (!home.isDirectory() || home.isSymbolicLink()))
310
+ throw new Error('Unsafe installation home');
311
+ await io.fs.mkdir(telemetryHome(input.home), { recursive: true, mode: 0o700 });
312
+ await io.fs.mkdir(privacyDirectory(input.home), { mode: 0o700 }).catch(error => { if (error.code !== 'EEXIST')
313
+ throw error; });
314
+ await checkPrivacyDirectory(input);
315
+ }
316
+ async function barrierMarker(input, prefix) {
317
+ const io = ioFor(input), token = randomUUID(), path = join(privacyDirectory(input.home), prefix + token);
318
+ const handle = await io.fs.open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
319
+ try {
320
+ await handle.writeFile(JSON.stringify({ pid: process.pid, host: hostname(), token }));
321
+ }
322
+ catch (error) {
323
+ await io.fs.unlink(path).catch(() => { });
324
+ throw error;
325
+ }
326
+ finally {
327
+ await handle.close();
328
+ }
329
+ // Only our UUID is ever released. A writer cannot remove a live reader or reuse its name.
330
+ return async () => { await io.fs.unlink(path).catch(error => { if (!missing(error))
331
+ throw error; }); };
332
+ }
333
+ /** Called only with the registration mutex. Refuse links/non-files; never steal live owners. */
334
+ async function barrierHolders(input) {
335
+ const io = ioFor(input), holders = [];
336
+ for (const name of await io.fs.readdir(privacyDirectory(input.home))) {
337
+ if (!name.startsWith(READER) && !isIntent(name))
338
+ continue;
339
+ const path = join(privacyDirectory(input.home), name);
340
+ let handle;
341
+ try {
342
+ const entry = await io.fs.lstat(path);
343
+ if (!entry.isFile() || entry.isSymbolicLink() || !privateOwner(entry))
344
+ throw new Error('Unsafe privacy holder');
345
+ handle = await io.fs.open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
346
+ const info = await handle.stat();
347
+ if (!info.isFile() || !privateOwner(info) || info.size > MAX_CONSENT_BYTES)
348
+ throw new Error('Unsafe privacy holder');
349
+ const bytes = Buffer.alloc(MAX_CONSENT_BYTES + 1);
350
+ const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
351
+ if (bytesRead > MAX_CONSENT_BYTES)
352
+ throw new Error('Unsafe privacy holder');
353
+ let owner;
354
+ try {
355
+ const value = JSON.parse(bytes.subarray(0, bytesRead).toString('utf8'));
356
+ if (Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.host === 'string' && typeof value.token === 'string' && name.endsWith(value.token))
357
+ owner = value;
358
+ }
359
+ catch { /* A crash before publication gets the same grace as a legacy save lock. */ }
360
+ let stale = !owner && Date.now() - info.mtimeMs >= 30_000;
361
+ if (owner?.host === hostname()) {
362
+ try {
363
+ process.kill(owner.pid, 0);
364
+ }
365
+ catch (error) {
366
+ stale = error.code === 'ESRCH';
367
+ }
368
+ }
369
+ if (stale)
370
+ await io.fs.unlink(path);
371
+ else
372
+ holders.push(name);
373
+ }
374
+ catch (error) {
375
+ if (!missing(error))
376
+ throw error;
377
+ }
378
+ finally {
379
+ await handle?.close();
380
+ }
381
+ }
382
+ return holders;
383
+ }
384
+ async function privacyMutex(input, deadline, shared = false) {
385
+ for (;;) {
386
+ try {
387
+ return await ioFor(input).acquireLock(privacyDirectory(input.home));
388
+ }
389
+ catch (error) {
390
+ if (!(error instanceof SaveLockBusyError))
391
+ throw error;
392
+ if (shared && telemetryChoiceRequested(input.home))
393
+ return undefined;
394
+ if (Date.now() >= deadline)
395
+ throw error;
396
+ await wait(10);
397
+ }
398
+ }
399
+ }
400
+ async function withSharedPrivacyLock(input, run) {
401
+ await preparePrivacyDirectory(input);
402
+ const unlock = await privacyMutex(input, Date.now() + CHOICE_WAIT_MS, true);
403
+ if (!unlock)
404
+ return undefined;
405
+ let release;
406
+ try {
407
+ if ((await barrierHolders(input)).some(isIntent))
408
+ return undefined;
409
+ release = await barrierMarker(input, READER);
410
+ // A refusal can publish outside the mutex while this reader is registering.
411
+ if (telemetryChoiceRequested(input.home)) {
412
+ await release();
413
+ release = undefined;
414
+ return undefined;
415
+ }
416
+ }
417
+ finally {
418
+ await unlock();
419
+ }
420
+ try {
421
+ return await run();
422
+ }
423
+ finally {
424
+ await release();
425
+ }
426
+ }
427
+ /** Exclusive choices stop new admissions BEFORE waiting and drain only existing shared holders. */
428
+ async function withPrivacyLock(input, run, refusing = false) {
429
+ if (privacyLockContext.getStore()?.active)
430
+ throw new TelemetryPrivacyError('busy', 'Privacy mutations must not nest or invert lock order');
431
+ await preparePrivacyDirectory(input);
432
+ const releaseIntent = await barrierMarker(input, refusing ? WITHDRAWAL : CHOICE);
433
+ const deadline = Date.now() + CHOICE_WAIT_MS;
434
+ try {
435
+ for (;;) {
436
+ const unlock = (await privacyMutex(input, deadline));
437
+ let yielded = false;
438
+ try {
439
+ for (;;) {
440
+ const holders = await barrierHolders(input);
441
+ if (!refusing && holders.some(name => name.startsWith(WITHDRAWAL))) {
442
+ yielded = true;
443
+ break;
444
+ }
445
+ if (!holders.some(name => name.startsWith(READER)))
446
+ break;
447
+ if (Date.now() >= deadline)
448
+ throw new SaveLockBusyError();
449
+ await wait(10);
450
+ }
451
+ if (!yielded) {
452
+ const context = { home: telemetryHome(input.home), active: true };
453
+ try {
454
+ return await privacyLockContext.run(context, run);
455
+ }
456
+ finally {
457
+ context.active = false;
458
+ }
459
+ }
460
+ }
461
+ finally {
462
+ await unlock();
463
+ }
464
+ if (Date.now() >= deadline)
465
+ throw new SaveLockBusyError();
466
+ await wait(10); // let the higher-priority refusal take the mutex
467
+ }
468
+ }
469
+ finally {
470
+ await releaseIntent();
471
+ }
472
+ }
473
+ /**
474
+ * Guard EVERY analytics operation, including outside mode, and hold through disk work / bounded POST.
475
+ * A lease from the START of a run is required as expectedLease for later capture/finalization/replay.
476
+ * Nested guarded helpers reuse the admission (never take a spool lock then acquire privacy).
477
+ * undefined means blocked/failure: do not fall back to an unguarded operation.
478
+ */
479
+ export async function withTelemetryAdmission(input, work, expectedLease) {
480
+ const parent = currentTelemetryAdmission();
481
+ if (parent) {
482
+ if (parent.lease.home !== telemetryHome(input.home) || parent.signal.aborted || suppressed.has(telemetryHome(input.home))
483
+ || !sameTelemetryLease(parent.lease, telemetryLeaseSnapshot(input))
484
+ || (expectedLease && !sameTelemetryLease(expectedLease, parent.lease)))
485
+ return undefined;
486
+ return work(parent);
487
+ }
488
+ const before = await telemetryPermission(input);
489
+ if (!before.permitted)
490
+ return undefined; // absolutely no lock/directory writes before Yes
491
+ let entered = false;
492
+ try {
493
+ return await withSharedPrivacyLock(input, async () => {
494
+ const status = await telemetryPermission(input);
495
+ const lease = await leaseFor(input, status);
496
+ if (!lease || (expectedLease && !sameTelemetryLease(expectedLease, lease)))
497
+ return undefined;
498
+ const controller = new AbortController();
499
+ const key = telemetryHome(input.home);
500
+ const active = controllers.get(key) ?? new Set();
501
+ controllers.set(key, active);
502
+ active.add(controller);
503
+ entered = true;
504
+ const admission = { lease, signal: controller.signal, status };
505
+ liveAdmissions.add(admission);
506
+ try {
507
+ return await admissionContext.run(admission, () => work(admission));
508
+ }
509
+ finally {
510
+ liveAdmissions.delete(admission);
511
+ active.delete(controller);
512
+ if (!active.size)
513
+ controllers.delete(key);
514
+ }
515
+ });
516
+ }
517
+ catch (error) {
518
+ if (entered)
519
+ throw error; // do not mask failures in the caller's admitted operation
520
+ return undefined;
521
+ }
522
+ }
523
+ export class TelemetryPrivacyError extends Error {
524
+ code;
525
+ constructor(code, message) {
526
+ super(message);
527
+ this.code = code;
528
+ this.name = 'TelemetryPrivacyError';
529
+ }
530
+ }
531
+ async function publishConsent(input, record) {
532
+ if (!validTelemetryConsent(record))
533
+ throw new TelemetryPrivacyError('invalid-params', 'Invalid privacy choice');
534
+ const io = ioFor(input);
535
+ const temporary = join(privacyDirectory(input.home), `.telemetry-consent.${randomUUID()}.tmp`);
536
+ try {
537
+ const handle = await io.fs.open(temporary, 'wx', 0o600);
538
+ try {
539
+ await handle.writeFile(JSON.stringify(record) + '\n', 'utf8');
540
+ await handle.sync();
541
+ }
542
+ finally {
543
+ await handle.close();
544
+ }
545
+ await io.fs.rename(temporary, telemetryConsentPath(input.home));
546
+ if (process.platform !== 'win32') {
547
+ const directory = await io.fs.open(privacyDirectory(input.home), 'r');
548
+ try {
549
+ await directory.sync();
550
+ }
551
+ finally {
552
+ await directory.close();
553
+ }
554
+ }
555
+ }
556
+ finally {
557
+ await io.fs.unlink(temporary).catch(error => { if (!missing(error))
558
+ throw error; });
559
+ }
560
+ }
561
+ /**
562
+ * Fixed known-path deletion, without reading/parsing analytics. Called ONLY under the privacy barrier
563
+ * after an explicit choice (or its durable cleanup-pending retry). rm never follows detached symlinks.
564
+ * A fixed detachment path lets a restart finish removal without storing random path/history metadata.
565
+ */
566
+ export async function cleanupTelemetryStorage(input) {
567
+ if ((!privacyLockContext.getStore()?.active || privacyLockContext.getStore()?.home !== telemetryHome(input.home)))
568
+ throw new TelemetryPrivacyError('busy', 'Cleanup requires the privacy mutation barrier');
569
+ const read = await readTelemetryConsent(input);
570
+ if (read.kind !== 'valid' || read.record.activation !== 'cleanup-pending')
571
+ throw new TelemetryPrivacyError('invalid-params', 'Cleanup requires a durable explicit choice');
572
+ const io = ioFor(input);
573
+ const detached = join(privacyDirectory(input.home), 'telemetry-cleanup');
574
+ await io.fs.rm(detached, { recursive: true, force: true, maxRetries: 2, retryDelay: 50 });
575
+ await io.fs.rename(join(telemetryHome(input.home), 'telemetry'), detached).catch(error => { if (!missing(error))
576
+ throw error; });
577
+ await io.fs.rm(detached, { recursive: true, force: true, maxRetries: 2, retryDelay: 50 });
578
+ }
579
+ export async function assertTelemetryCleanupAuthority(home) {
580
+ if ((!privacyLockContext.getStore()?.active || privacyLockContext.getStore()?.home !== telemetryHome(home)))
581
+ throw new TelemetryPrivacyError('busy', 'Run cleanup requires the privacy mutation barrier');
582
+ const read = await readTelemetryConsent({ home });
583
+ if (read.kind !== 'valid' || read.record.activation !== 'cleanup-pending')
584
+ throw new TelemetryPrivacyError('invalid-params', 'Run cleanup requires a durable explicit choice');
585
+ }
586
+ async function finishCleanup(input, record, scrubRuns) {
587
+ try {
588
+ await cleanupTelemetryStorage(input);
589
+ const warnings = await scrubRuns(telemetryHome(input.home));
590
+ await publishConsent(input, { ...record, activation: 'ready' });
591
+ return warnings?.length ? { cleanupWarnings: warnings } : {};
592
+ }
593
+ catch {
594
+ // A failed final fsync may already have renamed ready: put the durable pending intent back.
595
+ await publishConsent(input, { ...record, activation: 'cleanup-pending' }).catch(() => { });
596
+ return { cleanupError: 'cleanup-failed' };
597
+ }
598
+ }
599
+ /** Compare-and-set against the prompt's revision. A stale Allow can NEVER overwrite a later No. */
600
+ export async function setTelemetryConsent(input, action, scrubRuns) {
601
+ if (!['allow', 'deny', 'ask-first', 'auto'].includes(action.action) || !Number.isSafeInteger(action.expectedRevision) || action.expectedRevision < 0
602
+ || action.noticeVersion !== TELEMETRY_NOTICE_VERSION || typeof scrubRuns !== 'function')
603
+ throw new TelemetryPrivacyError('invalid-params', 'Refresh the current privacy notice and choice before saving');
604
+ if (currentTelemetryAdmission())
605
+ throw new TelemetryPrivacyError('busy', 'Do not change privacy policy from an admitted analytics operation');
606
+ const refusing = action.action === 'deny' || action.action === 'ask-first';
607
+ if (refusing)
608
+ suppressTelemetry(input.home);
609
+ try {
610
+ return await withPrivacyLock(input, async () => {
611
+ const read = await readTelemetryConsent(input);
612
+ if (read.kind === 'unavailable')
613
+ throw new TelemetryPrivacyError('storage', 'Privacy choice is unavailable; nothing was saved');
614
+ const previous = read.kind === 'valid' ? read.record : undefined;
615
+ const revision = previous?.revision ?? 0;
616
+ // Repeated No is idempotent. A new refusal also overrides a stale prompt revision: unlike
617
+ // Allow/Auto it cannot grant collection, and must not lose to another window's newer Yes.
618
+ if (previous?.answer === 'no' && previous.policy === 'ask' && refusing) {
619
+ const cleanup = previous.activation === 'ready' ? {} : await finishCleanup(input, previous, scrubRuns);
620
+ suppressed.delete(telemetryHome(input.home));
621
+ return { saved: true, conflict: false, status: await telemetryPermission(input), ...cleanup };
622
+ }
623
+ if (!refusing && action.expectedRevision !== revision)
624
+ return { saved: false, conflict: true, status: await telemetryPermission(input) };
625
+ const policy = action.action === 'auto' ? 'auto' : refusing || resolveTelemetryRegion(signalsFor(input), previous?.policy).permissionRequired ? 'ask' : previous?.policy ?? 'auto';
626
+ const answer = action.action === 'allow' ? 'yes' : refusing ? 'no' : previous?.answer ?? 'no';
627
+ const record = {
628
+ version: 1, noticeVersion: TELEMETRY_NOTICE_VERSION, answer, policy, revision: revision + 1,
629
+ ...(answer === 'yes' ? { activationId: action.action === 'allow' ? ioFor(input).activationId() : previous.activationId } : {}),
630
+ decidedAt: action.action === 'auto' && previous ? previous.decidedAt : ioFor(input).now(),
631
+ activation: action.action === 'auto' ? previous?.activation ?? 'ready' : 'cleanup-pending',
632
+ };
633
+ await publishConsent(input, record); // No is authoritative BEFORE any cleanup, even if it fails.
634
+ const cleanup = record.activation === 'ready' ? {} : await finishCleanup(input, record, scrubRuns);
635
+ // A durable No is no longer an error; an explicit successful Allow/Auto clears local failure suppression.
636
+ suppressed.delete(telemetryHome(input.home));
637
+ return { saved: true, conflict: false, status: await telemetryPermission(input), ...cleanup };
638
+ }, refusing);
639
+ }
640
+ catch (error) {
641
+ suppressTelemetry(input.home);
642
+ if (error instanceof TelemetryPrivacyError)
643
+ throw error;
644
+ throw new TelemetryPrivacyError(error instanceof SaveLockBusyError ? 'busy' : 'storage', 'Privacy choice was not saved. Other windows may still report; retry to save your choice.');
645
+ }
646
+ }
647
+ /** Resume only durable cleanup intent at execution startup. Display-only status never invokes this. */
648
+ export async function resumeTelemetryCleanup(input, scrubRuns) {
649
+ if (typeof scrubRuns !== 'function')
650
+ throw new TelemetryPrivacyError('invalid-params', 'A run-metadata cleanup is required');
651
+ const read = await readTelemetryConsent(input);
652
+ if (read.kind !== 'valid' || read.record.activation !== 'cleanup-pending')
653
+ return { saved: false, conflict: false, status: await telemetryPermission(input) };
654
+ return withPrivacyLock(input, async () => {
655
+ const current = await readTelemetryConsent(input);
656
+ if (current.kind !== 'valid' || current.record.revision !== read.record.revision || current.record.activationId !== read.record.activationId) {
657
+ return { saved: false, conflict: true, status: await telemetryPermission(input) };
658
+ }
659
+ const cleanup = await finishCleanup(input, current.record, scrubRuns);
660
+ return { saved: true, conflict: false, status: await telemetryPermission(input), ...cleanup };
661
+ });
662
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ import { appVersion, releaseVersion } from './version.js';
2
+ import { drainTelemetry, reportInstallationObserved } from './surface.js';
3
+ // Invoked by the supported CLI installer and updater after the new package was verified on disk.
4
+ const [version, previous] = process.argv.slice(2);
5
+ if (previous !== undefined && releaseVersion('cli', await appVersion()) === version) {
6
+ const input = { surface: 'cli' };
7
+ await reportInstallationObserved(input, { version, previousVersion: previous === '' ? null : previous });
8
+ await drainTelemetry(input, AbortSignal.timeout(2_000));
9
+ }