-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathtelemetry.ts
More file actions
909 lines (855 loc) · 35.9 KB
/
Copy pathtelemetry.ts
File metadata and controls
909 lines (855 loc) · 35.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
/**
* Anonymous PostHog telemetry for Archon.
*
* Emits a small set of anonymous events — `archon_started` (once per process),
* `archon_active` (daily server heartbeat), `chat_turn_handled` (each direct
* AI chat turn), `workflow_invoked` (each workflow start), `workflow_completed`
* / `workflow_failed` (each terminal run), `workflow_approval_resolved` (each
* human approve/reject decision), and `codebase_registered` (count only) — so
* maintainers can see active installs, which surfaces and workflows get real
* usage, and run outcomes. No PII, no user identity.
* A random UUID is persisted to `${ARCHON_HOME}/telemetry-id` so we can count
* distinct installs.
*
* Every event carries the privacy invariants `$process_person_profile: false`
* (anonymous tier — no person profile ever created) and `$ip: ''` (PostHog
* drops the source IP at ingest). Machine context (os, arch, version,
* is_binary, runtime, is_ci, is_tty) rides along on every event via PostHog
* super-properties. What is collected is categorical only: workflow name (real
* for bundled workflows, `"custom"` for user-authored), platform, provider,
* model, node shape, run outcome/duration, a fixed-enum error class (never
* raw error text), chat-turn activity (platform + provider + model + outcome),
* aggregate usage numbers (token counts, cost USD, turn/run duration, loop
* iterations — numeric totals only), approval decisions (approved/rejected,
* nothing else), a bare project-registration count, and deployment shape
* (which adapters are enabled, db kind, auth mode — booleans/enums only).
* Never sent: code, prompts, message content, conversation ids, file paths,
* IP, geo, error text, or custom workflow names/descriptions.
*
* Opt-out (any one disables telemetry):
* - ARCHON_TELEMETRY_DISABLED=1
* - DO_NOT_TRACK=1 (de facto standard)
* - CI=true (auto-disabled in CI environments)
* - POSTHOG_API_KEY=off | 0 | false | disabled | '' (or whitespace-only)
*
* All capture functions are fire-and-forget: telemetry errors are swallowed
* (logged at `debug`, with the first network failure on a custom POSTHOG_HOST
* also logged at `warn` so self-hosters notice typo'd hosts). Capture must
* never crash Archon.
*/
import { randomUUID } from 'crypto';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
import { join } from 'path';
import type { PostHog } from 'posthog-node';
import { getArchonHome } from './archon-paths';
import { BUNDLED_IS_BINARY, BUNDLED_VERSION } from './bundled-build';
import { createLogger } from './logger';
/** Bumped when the captured property set changes (documented in README). */
export const TELEMETRY_SCHEMA_VERSION = 4;
// Minimal shape of posthog-node's `fetch` option — copied from @posthog/core
// (a transitive dep) to avoid pulling it in as a direct dependency.
interface PostHogFetchOptions {
method: 'GET' | 'POST' | 'PUT' | 'PATCH';
mode?: 'no-cors';
credentials?: 'omit';
headers: Record<string, string>;
body?: string | Blob;
signal?: AbortSignal;
}
interface PostHogFetchResponse {
status: number;
text: () => Promise<string>;
json: () => Promise<unknown>;
headers?: { get(name: string): string | null };
}
/**
* Embedded write-only PostHog project key. Safe to ship in source: `phc_*`
* keys can only write events, never read data. Override with POSTHOG_API_KEY
* for self-hosted PostHog or a different project, or set it to `off` / `0` /
* `false` / `disabled` / empty string to opt out entirely.
*/
const EMBEDDED_POSTHOG_API_KEY = 'phc_rR7oacut9mm4upGRbuoMptnyjRium34TTbbqobiQYS7x';
const DEFAULT_POSTHOG_HOST = 'https://us.i.posthog.com';
/**
* Filename for the one-time notice stamp written to ARCHON_HOME. Presence
* means the first-run notice has been shown; absence means it hasn't.
*/
// Bumped to `-v2` when the captured property set expanded (machine context +
// run outcomes), to `-v3` when chat-turn activity, deployment shape, and
// registration counts were added, and to `-v4` when aggregate usage totals
// (tokens/cost/duration/loop iterations) and approval decisions were added.
// Bumping re-shows the updated first-run notice once per install so existing
// users re-consent rather than silently getting broader capture.
const NOTICE_STAMP_FILENAME = 'telemetry-notice-shown-v4';
let cachedLog: ReturnType<typeof createLogger> | undefined;
function getLog(): ReturnType<typeof createLogger> {
if (!cachedLog) cachedLog = createLogger('telemetry');
return cachedLog;
}
/** Values of POSTHOG_API_KEY that are interpreted as "explicitly disabled". */
const KEY_OFF_VALUES = new Set(['', 'off', '0', 'false', 'disabled']);
/**
* Resolve the effective PostHog API key.
*
* - Unset env var → embedded default
* - Env var set to a recognized "off" sentinel → `null` (caller treats as opt-out)
* - Env var set to anything else → that value (self-hosted / alternate project)
*/
function getApiKey(): string | null {
const env = process.env.POSTHOG_API_KEY;
if (env === undefined) return EMBEDDED_POSTHOG_API_KEY;
const trimmed = env.trim();
if (KEY_OFF_VALUES.has(trimmed.toLowerCase())) return null;
return trimmed;
}
function getHost(): string {
return process.env.POSTHOG_HOST ?? DEFAULT_POSTHOG_HOST;
}
/**
* Privacy invariants attached to EVERY telemetry event. Kept per-event (not
* relying solely on super-properties) so each capture site is visibly correct
* and a super-property regression can never silently leak the source IP or
* create a person profile.
*/
const PRIVACY_INVARIANTS = {
$process_person_profile: false,
// Strip source IP at ingest. `disableGeoip: true` only prevents geo
// enrichment; `$ip: ''` drops the IP from the event entirely.
$ip: '',
} as const;
/**
* Stable machine/runtime context registered once as PostHog super-properties
* (attached to every event from this client). Categorical only — no
* identifiers, no paths. `install_method` is intentionally omitted until a
* build-time channel constant exists (never derive it from a filesystem path).
*/
function collectMachineProperties(): Record<string, string | boolean> {
const bunVersion = typeof Bun !== 'undefined' ? Bun.version : undefined;
return {
os: process.platform,
arch: process.arch,
archon_version: BUNDLED_VERSION,
is_binary: BUNDLED_IS_BINARY,
runtime_version: bunVersion ? `bun-${bunVersion}` : process.version,
// Mirrors the CI auto-disable check; when telemetry is enabled this is
// effectively always false, but it's cheap and future-proof.
is_ci: process.env.CI?.toLowerCase() === 'true',
// `process.stderr.isTTY` is `undefined` at runtime when stderr is not a TTY
// (servers, pipes, CI), so without coercion the field is silently omitted on
// the primary server path. bun-types incorrectly narrows it to `boolean`,
// which makes the lint rule think the coercion is redundant — it is not.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-conversion -- bun-types mis-types process.stderr.isTTY as always-boolean; runtime value is boolean|undefined and the coercion guarantees a present `false`.
is_tty: Boolean(process.stderr.isTTY),
};
}
/** Discovery source of a workflow, mirrored from `@archon/workflows` as a
* plain string union so `@archon/paths` keeps zero `@archon/*` dependencies. */
export type WorkflowTelemetrySource = 'bundled' | 'global' | 'project';
/**
* Apply the workflow-name privacy rule: bundled (Archon-authored) workflows
* report their real name so maintainers can see which defaults are popular;
* user-authored (global/project) workflows report `"custom"` so private names
* (e.g. "deploy-acme-prod") never leave the machine. `workflow_source` is
* always reported for the custom-vs-default split.
*/
export function classifyWorkflowForTelemetry(
name: string,
source: WorkflowTelemetrySource | undefined
): { workflow_name: string; is_builtin: boolean; workflow_source: WorkflowTelemetrySource } {
const isBuiltin = source === 'bundled';
return {
is_builtin: isBuiltin,
workflow_name: isBuiltin ? name : 'custom',
workflow_source: source ?? 'project',
};
}
/**
* Model ids are user-supplied (forwarded verbatim from workflow/`config.yaml`
* YAML), so unlike `provider` they're not structurally categorical. Forward a
* value only when it looks like a real model ref (alphanumerics plus `/._:-`,
* bounded length — covers `sonnet`, `gpt-5.3-codex`, `anthropic/claude-haiku-4-5`,
* `openrouter/qwen/qwen3-coder`). Anything else is dropped so a stray free-text
* value can't slip through the "categorical only" telemetry contract.
*
* Exported for direct testing of the privacy guard. @internal
*/
export function sanitizeModelForTelemetry(model: string | undefined): string | undefined {
if (model === undefined) return undefined;
return /^[a-zA-Z0-9/._:-]{1,64}$/.test(model) ? model : undefined;
}
/** Why telemetry is currently disabled. `null` means it's enabled. */
export type TelemetryDisabledReason =
| 'ARCHON_TELEMETRY_DISABLED'
| 'DO_NOT_TRACK'
| 'CI'
| 'POSTHOG_API_KEY';
interface TelemetryStatusBase {
/** Stable anonymous install UUID (always populated, even when disabled). */
distinctId: string;
/** PostHog ingest host. */
host: string;
}
/**
* Full current telemetry state. Discriminated on `enabled` so an enabled status
* can never carry a `disabledReason` (and vice versa), and so `keySource: 'none'`
* is only representable in the disabled arm.
*/
export type TelemetryStatus =
| (TelemetryStatusBase & {
enabled: true;
disabledReason: null;
/** Whether the active API key is the embedded default or a user override. */
keySource: 'embedded' | 'env';
})
| (TelemetryStatusBase & {
enabled: false;
disabledReason: TelemetryDisabledReason;
/** `'none'` means POSTHOG_API_KEY was set to an opt-out value. */
keySource: 'embedded' | 'env' | 'none';
});
/**
* Decide whether telemetry is disabled, and if so, why. The order here is
* also the precedence order: the first matching reason wins.
*/
function resolveDisabledReason(): TelemetryDisabledReason | null {
if (process.env.ARCHON_TELEMETRY_DISABLED === '1') return 'ARCHON_TELEMETRY_DISABLED';
if (process.env.DO_NOT_TRACK === '1') return 'DO_NOT_TRACK';
// Standard CI env var set by GitHub Actions, CircleCI, GitLab CI, Travis,
// Buildkite, etc. Forks running fixtures in CI shouldn't pollute telemetry.
// Matched case-insensitively because AppVeyor sets `CI=True`; `CI=1` is left
// alone (rare, and we keep the match narrow to "true").
if (process.env.CI?.toLowerCase() === 'true') return 'CI';
if (getApiKey() === null) return 'POSTHOG_API_KEY';
return null;
}
/**
* Check whether telemetry is disabled via env vars or missing/disabled key.
* Kept for backwards compatibility; new callers should prefer
* {@link getTelemetryStatus} for richer information.
*/
export function isTelemetryDisabled(): boolean {
return resolveDisabledReason() !== null;
}
/**
* Return the full current telemetry state — enabled/disabled, reason,
* distinct ID, host, and key source. Used by `archon telemetry status` and
* `archon doctor` to surface what's happening without duplicating logic.
*/
export function getTelemetryStatus(): TelemetryStatus {
const reason = resolveDisabledReason();
const host = getHost();
const envKeySet = process.env.POSTHOG_API_KEY !== undefined;
if (reason === null) {
// Enabled: a usable key exists, so keySource is embedded or env (never none).
return {
enabled: true,
disabledReason: null,
distinctId: getTelemetryId(),
host,
keySource: envKeySet ? 'env' : 'embedded',
};
}
// Disabled: read the install UUID without creating it, so inspecting status
// while opted out never materializes a telemetry-id file the user didn't ask for.
const keySource: 'embedded' | 'env' | 'none' =
getApiKey() === null ? 'none' : envKeySet ? 'env' : 'embedded';
return {
enabled: false,
disabledReason: reason,
distinctId: peekTelemetryId(),
host,
keySource,
};
}
/**
* Load or create a stable anonymous install UUID at `${ARCHON_HOME}/telemetry-id`.
* If the file can't be read or written (permissions, disk full), a fresh UUID
* is returned for this session — telemetry still works, just not correlated
* across runs.
*
* Exported so tests can exercise the id-resolution invariants directly
* without spinning up the PostHog client.
* @internal
*/
export function getOrCreateTelemetryId(): string {
const idPath = join(getArchonHome(), 'telemetry-id');
try {
if (existsSync(idPath)) {
const existing = readFileSync(idPath, 'utf8').trim();
if (existing) return existing;
}
} catch (error) {
getLog().debug({ err: error as Error, idPath }, 'telemetry.id_read_failed');
}
const id = randomUUID();
try {
mkdirSync(getArchonHome(), { recursive: true });
writeFileSync(idPath, id, 'utf8');
} catch (error) {
getLog().debug({ err: error as Error, idPath }, 'telemetry.id_persist_failed');
}
return id;
}
let telemetryIdCache: string | undefined;
function getTelemetryId(): string {
if (!telemetryIdCache) telemetryIdCache = getOrCreateTelemetryId();
return telemetryIdCache;
}
/**
* Read the persisted install UUID without creating it. Returns a fresh,
* unpersisted UUID when none exists yet. Used for status display while
* telemetry is disabled, so inspecting state (`telemetry status` / `doctor`)
* never writes a `telemetry-id` file for an opted-out user.
*/
function peekTelemetryId(): string {
const idPath = join(getArchonHome(), 'telemetry-id');
try {
if (existsSync(idPath)) {
const existing = readFileSync(idPath, 'utf8').trim();
if (existing) return existing;
}
} catch (error) {
getLog().debug({ err: error as Error, idPath }, 'telemetry.id_read_failed');
}
return randomUUID();
}
/**
* Force-rotate the persisted install UUID. Returns the new ID. Used by
* `archon telemetry reset`. Caller is responsible for any UX around it.
*
* Unlike the other functions here, this is NOT fire-and-forget: it is a
* deliberate, user-initiated write, so filesystem errors propagate.
* @throws {NodeJS.ErrnoException} if ARCHON_HOME can't be created or the id
* file can't be written (e.g. EACCES, ENOSPC). The CLI caller
* (`telemetryResetCommand`) catches this and exits non-zero.
*/
export function resetTelemetryId(): string {
const idPath = join(getArchonHome(), 'telemetry-id');
const newId = randomUUID();
mkdirSync(getArchonHome(), { recursive: true });
writeFileSync(idPath, newId, 'utf8');
telemetryIdCache = newId;
return newId;
}
/**
* Show a one-time stderr notice that telemetry is collected, then stamp the
* notice file so we don't show it again. Skipped when:
* - telemetry is disabled (no point notifying about a no-op)
* - the stamp file already exists
* - stderr is not a TTY (avoid polluting scripted / piped output)
*
* Idempotent in-process via `noticeChecked` so the worst case is one stat()
* per process, not one per workflow.
*/
let noticeChecked = false;
function maybeShowFirstRunNotice(): void {
if (noticeChecked) return;
noticeChecked = true;
// Self-contained guards so the function is safe for any caller, not just
// captureWorkflowInvoked: never notify about telemetry that won't be sent,
// and never pollute scripted / piped output.
if (isTelemetryDisabled()) return;
if (!process.stderr.isTTY) return;
const stampPath = join(getArchonHome(), NOTICE_STAMP_FILENAME);
try {
if (existsSync(stampPath)) return;
} catch (error) {
getLog().debug({ err: error as Error, stampPath }, 'telemetry.notice_stat_failed');
return;
}
const message =
'Archon collects anonymous usage telemetry — now also chat activity\n' +
'(platform/provider/model, never message content), aggregate usage totals\n' +
'(token counts, cost, durations, loop iterations), approval decisions\n' +
'(approved/rejected only), deployment shape, and a categorical failure\n' +
'class, alongside workflow name, run outcome, OS/arch, and version.\n' +
'Still no code, prompts, file paths, IP, or personal data — see README "Telemetry".\n' +
'Opt out anytime: DO_NOT_TRACK=1 or ARCHON_TELEMETRY_DISABLED=1\n';
try {
process.stderr.write(`\n${message}\n`);
} catch (error) {
getLog().debug({ err: error as Error }, 'telemetry.notice_write_failed');
}
try {
mkdirSync(getArchonHome(), { recursive: true });
writeFileSync(stampPath, new Date().toISOString(), 'utf8');
} catch (error) {
// Failure here means we'll re-show the notice on the next process run (the
// in-process `noticeChecked` guard still prevents a repeat this run);
// annoying but not broken. Log so repeat failures leave a diagnostic trace.
getLog().debug({ err: error as Error, stampPath }, 'telemetry.notice_stamp_failed');
}
}
/**
* Lazy singleton. `undefined` = not yet initialized; `null` = disabled or
* init failed; `PostHog` = live client. Init runs once per process.
*/
let clientInit: Promise<PostHog | null> | undefined;
async function getClient(): Promise<PostHog | null> {
if (clientInit === undefined) {
clientInit = initClient();
}
return clientInit;
}
/**
* Fetch wrapper that masks all failures as 200 responses. The PostHog SDK's
* internal `logFlushError` writes to stderr via `console.error` on any network
* or HTTP error, bypassing logger configuration (see `@posthog/core`
* `posthog-core-stateless.mjs` `logFlushError`). For a fire-and-forget
* telemetry path we want no user-visible noise on the default host when
* PostHog is unreachable (offline, firewalled, DNS broken, rate-limited), so
* we intercept failures before the SDK sees them.
*
* Self-hosters who override POSTHOG_HOST need *some* feedback when they typo a
* URL, so on a custom host the first failure in a process is logged at `warn`
* (visible at default log levels) and subsequent failures drop to `debug`.
* On the default host every failure stays at `debug`.
*/
const FAKE_OK_RESPONSE: PostHogFetchResponse = {
status: 200,
text: () => Promise.resolve('{"status":"ok"}'),
json: () => Promise.resolve({ status: 'ok' }),
headers: { get: () => null },
};
let firstFailureLogged = false;
function logFetchFailure(ctx: { status?: number; err?: Error }, event: string): void {
// Only self-hosters (POSTHOG_HOST overridden) get a visible warning about a
// typo'd host. Default-host users who are simply offline/firewalled stay at
// `debug`, per the "no user-visible noise on the default host" goal above.
if (process.env.POSTHOG_HOST !== undefined && !firstFailureLogged) {
firstFailureLogged = true;
getLog().warn(
{ ...ctx, host: getHost() },
`${event} (first failure shown; subsequent suppressed to debug)`
);
return;
}
getLog().debug(ctx, event);
}
async function silentFetch(
url: string,
options: PostHogFetchOptions
): Promise<PostHogFetchResponse> {
try {
const res = await fetch(url, options as RequestInit);
if (res.status < 200 || res.status >= 400) {
logFetchFailure({ status: res.status }, 'telemetry.http_non_2xx_suppressed');
return FAKE_OK_RESPONSE;
}
return res;
} catch (error) {
logFetchFailure({ err: error as Error }, 'telemetry.fetch_failed_suppressed');
return FAKE_OK_RESPONSE;
}
}
async function initClient(): Promise<PostHog | null> {
if (isTelemetryDisabled()) return null;
const apiKey = getApiKey();
if (apiKey === null) return null;
try {
const posthogModule = await import('posthog-node');
const client = new posthogModule.PostHog(apiKey, {
host: getHost(),
flushAt: 20,
flushInterval: 10000,
disableGeoip: true,
fetch: silentFetch,
});
// Defensive: also hook the client-level error channel in case a future
// posthog-node version routes errors there instead of (or in addition to)
// the internal console.error path.
client.on('error', (err: Error) => {
getLog().debug({ err }, 'telemetry.client_error');
});
// Attach machine context to every event as super-properties. The privacy
// invariants are NOT registered here — they stay per-event (see
// PRIVACY_INVARIANTS) so a register() regression can't silently drop them.
try {
await client.register(collectMachineProperties());
} catch (error) {
getLog().debug({ err: error as Error }, 'telemetry.register_failed');
}
return client;
} catch (error) {
getLog().debug({ err: error as Error }, 'telemetry.init_failed');
return null;
}
}
export interface WorkflowInvokedProperties {
workflowName: string;
/** Discovery source — drives the custom-vs-default split and name redaction. */
workflowSource?: WorkflowTelemetrySource;
platform?: string;
provider?: string;
model?: string;
nodeCount?: number;
usesLoop?: boolean;
usesApproval?: boolean;
usesScript?: boolean;
usesBash?: boolean;
// Advanced-feature adoption flags (presence on any node, categorical only) —
// these tell maintainers which features earn their maintenance cost.
usesOutputFormat?: boolean;
usesOutputType?: boolean;
usesPersistSession?: boolean;
usesMcp?: boolean;
usesSkills?: boolean;
usesFreshContext?: boolean;
interactive?: boolean;
usedIsolation?: boolean;
isResume?: boolean;
}
/**
* Deployment-shape context for server installs. Categorical only — booleans
* and fixed enums derived from which integrations are configured, never the
* configuration values themselves. Distinguishes solo-laptop installs from
* team server deployments.
*/
export interface DeploymentShapeProperties {
dbKind?: 'sqlite' | 'postgresql';
webAuthEnabled?: boolean;
/** Per-user credentials mode (TOKEN_ENCRYPTION_KEY configured). */
multiUser?: boolean;
githubAuthMode?: 'app' | 'pat' | 'none' | 'conflict';
adapterSlack?: boolean;
adapterTelegram?: boolean;
adapterDiscord?: boolean;
adapterGitea?: boolean;
adapterGitlab?: boolean;
}
/** Once-per-process startup event — the basis for active-install counting. */
export interface ArchonStartedProperties extends DeploymentShapeProperties {
surface: 'cli' | 'server';
}
/**
* One completed direct-chat AI turn (NOT workflow execution — workflows emit
* `workflow_invoked` instead). Carries only platform + provider; never
* message content, conversation ids, or prompt/response data.
*
* `platform`/`provider` are open strings because this leaf package cannot
* import the adapter/provider unions without inverting the dependency graph.
* Callers MUST pass only registry identifiers (`platform.getPlatformType()`,
* `aiClient.getType()`) — both are structurally categorical (fixed literals
* per adapter/provider implementation), never user input.
*/
export interface ChatTurnProperties {
platform?: string;
provider?: string;
/** Resolved model ref — passed through {@link sanitizeModelForTelemetry}. */
model?: string;
outcome: 'completed' | 'failed';
durationMs?: number;
/** Provider-reported aggregate usage for the turn. Numbers only. */
costUsd?: number;
tokensIn?: number;
tokensOut?: number;
}
/** Categorical terminal exit reason — a fixed enum, never raw error text. */
export type WorkflowExitReason = 'no_nodes_completed' | 'node_error' | 'unhandled_error';
/**
* Categorical failure class derived from the engine's error classifier
* (`classifyError` in `@archon/workflows`): `fatal` = auth/permission/credit,
* `transient` = timeout/network/rate-limit, `unknown` = everything else.
* A fixed enum — raw error text never leaves the machine.
*/
export type WorkflowErrorClass = 'fatal' | 'transient' | 'unknown';
/** Closed set of DAG node types, mirrored from `@archon/workflows` schemas. */
export type WorkflowNodeType =
| 'command'
| 'prompt'
| 'bash'
| 'script'
| 'loop'
| 'loop_group'
| 'approval'
| 'cancel';
/**
* Terminal workflow-run event (`workflow_completed` / `workflow_failed`).
* Cancellation is intentionally not tracked: external `/workflow cancel` exits
* via the `skipIfStatusChanged` paths in the DAG executor, which emit no
* telemetry by design (see "No Autonomous Lifecycle Mutation" in CLAUDE.md).
*/
export interface WorkflowCompletedProperties {
outcome: 'completed' | 'failed';
workflowName: string;
workflowSource?: WorkflowTelemetrySource;
provider?: string;
durationMs?: number;
nodesCompleted?: number;
nodesFailed?: number;
nodesSkipped?: number;
nodesTotal?: number;
exitReason?: WorkflowExitReason;
/** Failure taxonomy (failed runs only): fixed-enum class, never error text. */
errorClass?: WorkflowErrorClass;
/** Type of the first failed node (failed runs only). */
failedNodeType?: WorkflowNodeType;
/** Aggregate provider-reported cost (USD) for the run. Numeric total only. */
costUsd?: number;
/** Aggregate provider-reported input tokens for the run. */
tokensIn?: number;
/** Aggregate provider-reported output tokens for the run. */
tokensOut?: number;
/** Total loop iterations across all loop nodes in the run. */
loopIterations?: number;
}
/**
* Run a telemetry capture fire-and-forget: never awaited, never throws. Resolves
* the lazy client, skips when disabled/uninitialized, and swallows every error
* (network, SDK, malformed props) at `debug` — telemetry must never crash Archon.
* The per-event error policy lives here, in exactly one place.
*/
function fireAndForget(capture: (client: PostHog) => void): void {
void (async (): Promise<void> => {
try {
const client = await getClient();
if (!client) return;
capture(client);
} catch (error) {
getLog().debug({ err: error as Error }, 'telemetry.capture_failed');
}
})();
}
/**
* Fire-and-forget capture of a `workflow_invoked` event. Never throws, never
* awaits — safe to call from hot paths. Shows the first-run notice on first
* invocation when telemetry is enabled and stderr is interactive.
*/
export function captureWorkflowInvoked(props: WorkflowInvokedProperties): void {
if (isTelemetryDisabled()) return;
maybeShowFirstRunNotice();
const model = sanitizeModelForTelemetry(props.model);
fireAndForget(client => {
client.capture({
distinctId: getTelemetryId(),
event: 'workflow_invoked',
properties: {
...PRIVACY_INVARIANTS,
...classifyWorkflowForTelemetry(props.workflowName, props.workflowSource),
schema_version: TELEMETRY_SCHEMA_VERSION,
...(props.platform ? { platform: props.platform } : {}),
...(props.provider ? { provider: props.provider } : {}),
...(model ? { model } : {}),
...(props.nodeCount !== undefined ? { node_count: props.nodeCount } : {}),
uses_loop: Boolean(props.usesLoop),
uses_approval: Boolean(props.usesApproval),
uses_script: Boolean(props.usesScript),
uses_bash: Boolean(props.usesBash),
uses_output_format: Boolean(props.usesOutputFormat),
uses_output_type: Boolean(props.usesOutputType),
uses_persist_session: Boolean(props.usesPersistSession),
uses_mcp: Boolean(props.usesMcp),
uses_skills: Boolean(props.usesSkills),
uses_fresh_context: Boolean(props.usesFreshContext),
interactive: Boolean(props.interactive),
used_isolation: Boolean(props.usedIsolation),
is_resume: Boolean(props.isResume),
},
});
});
}
/**
* Serialize deployment-shape fields to wire properties, omitting absent ones
* (the CLI surface passes none; the server surface passes all). Kept in one
* place so `archon_started` and `archon_active` can never drift apart.
*/
function deploymentShapeWireProps(
props: DeploymentShapeProperties
): Record<string, string | boolean> {
return {
...(props.dbKind !== undefined ? { db_kind: props.dbKind } : {}),
...(props.webAuthEnabled !== undefined ? { web_auth_enabled: props.webAuthEnabled } : {}),
...(props.multiUser !== undefined ? { multi_user: props.multiUser } : {}),
...(props.githubAuthMode !== undefined ? { github_auth_mode: props.githubAuthMode } : {}),
...(props.adapterSlack !== undefined ? { adapter_slack: props.adapterSlack } : {}),
...(props.adapterTelegram !== undefined ? { adapter_telegram: props.adapterTelegram } : {}),
...(props.adapterDiscord !== undefined ? { adapter_discord: props.adapterDiscord } : {}),
...(props.adapterGitea !== undefined ? { adapter_gitea: props.adapterGitea } : {}),
...(props.adapterGitlab !== undefined ? { adapter_gitlab: props.adapterGitlab } : {}),
};
}
/**
* Fire-and-forget capture of an `archon_started` event. Call once per CLI
* invocation and per server boot (the single call sites in `cli.ts` / the
* server entrypoint enforce the "once per process" contract — there is no
* in-function dedup guard). This (not just `workflow_invoked`) is what makes
* active-install / DAU metrics honest, since users who only run
* `doctor`/`serve`/chat would otherwise be invisible. Machine context rides
* along via the registered super-properties. Also shows the first-run notice.
*/
export function captureArchonStarted(props: ArchonStartedProperties): void {
if (isTelemetryDisabled()) return;
maybeShowFirstRunNotice();
fireAndForget(client => {
client.capture({
distinctId: getTelemetryId(),
event: 'archon_started',
properties: {
...PRIVACY_INVARIANTS,
surface: props.surface,
schema_version: TELEMETRY_SCHEMA_VERSION,
...deploymentShapeWireProps(props),
},
});
});
}
/**
* Fire-and-forget capture of an `archon_active` heartbeat. Long-running
* servers emit `archon_started` once per boot and then go silent, which would
* make a server-only install drop out of active-install (DAU/WAU) metrics
* after day one. The server entrypoint calls this on a daily interval so
* "active installs" stays honest for the server surface. CLI invocations do
* NOT need this — each one already emits `archon_started`. Carries the same
* categorical properties as `archon_started` (this event alone would not have
* justified a schema bump; the v3 bump covers the full revision it shipped
* with). Intentionally does not show the first-run notice (heartbeats are
* background, never interactive).
*/
export function captureArchonActive(props: ArchonStartedProperties): void {
if (isTelemetryDisabled()) return;
fireAndForget(client => {
client.capture({
distinctId: getTelemetryId(),
event: 'archon_active',
properties: {
...PRIVACY_INVARIANTS,
surface: props.surface,
schema_version: TELEMETRY_SCHEMA_VERSION,
...deploymentShapeWireProps(props),
},
});
});
}
/**
* Fire-and-forget capture of a `chat_turn_handled` event — one per direct-chat
* AI turn across all platforms (slack/telegram/discord/github/web/cli).
* Workflow runs are excluded by construction (they emit `workflow_invoked`
* from the executor instead; the orchestrator capture sites sit on the
* chat-only completion paths). Carries platform + provider + outcome only —
* never message content or conversation ids.
*/
export function captureChatTurn(props: ChatTurnProperties): void {
if (isTelemetryDisabled()) return;
const chatModel = sanitizeModelForTelemetry(props.model);
fireAndForget(client => {
client.capture({
distinctId: getTelemetryId(),
event: 'chat_turn_handled',
properties: {
...PRIVACY_INVARIANTS,
outcome: props.outcome,
schema_version: TELEMETRY_SCHEMA_VERSION,
...(props.platform ? { platform: props.platform } : {}),
...(props.provider ? { provider: props.provider } : {}),
...(chatModel ? { model: chatModel } : {}),
...(props.durationMs !== undefined ? { duration_ms: props.durationMs } : {}),
...(props.costUsd !== undefined ? { cost_usd: props.costUsd } : {}),
...(props.tokensIn !== undefined ? { tokens_in: props.tokensIn } : {}),
...(props.tokensOut !== undefined ? { tokens_out: props.tokensOut } : {}),
},
});
});
}
/**
* Fire-and-forget capture of a `workflow_approval_resolved` event — one per
* human approve/reject decision at an approval gate, across every surface
* (chat command, CLI, web API, Slack buttons, manage_run tool, natural
* language). Carries ONLY the binary resolution — no run ids, workflow
* names, comments, or rejection reasons.
*/
export function captureApprovalResolved(props: { resolution: 'approved' | 'rejected' }): void {
if (isTelemetryDisabled()) return;
fireAndForget(client => {
client.capture({
distinctId: getTelemetryId(),
event: 'workflow_approval_resolved',
properties: {
...PRIVACY_INVARIANTS,
resolution: props.resolution,
schema_version: TELEMETRY_SCHEMA_VERSION,
},
});
});
}
/**
* Fire-and-forget capture of a `codebase_registered` event — a pure count
* (no name, path, or remote URL ever) emitted when a new codebase row is
* created. Together with `archon_started` this gives the activation funnel:
* installed → registered a project → first workflow run.
*/
export function captureCodebaseRegistered(): void {
if (isTelemetryDisabled()) return;
fireAndForget(client => {
client.capture({
distinctId: getTelemetryId(),
event: 'codebase_registered',
properties: {
...PRIVACY_INVARIANTS,
schema_version: TELEMETRY_SCHEMA_VERSION,
},
});
});
}
/**
* Fire-and-forget capture of a terminal workflow run. Emits `workflow_completed`
* when `outcome === 'completed'`, otherwise `workflow_failed`. Carries run
* outcome, duration, node counts, and a categorical exit reason so maintainers
* can measure success rates and funnels — not just intent. Intentionally does
* not show the first-run notice (that fires on start events, not completion).
*/
export function captureWorkflowCompleted(props: WorkflowCompletedProperties): void {
if (isTelemetryDisabled()) return;
fireAndForget(client => {
client.capture({
distinctId: getTelemetryId(),
event: props.outcome === 'completed' ? 'workflow_completed' : 'workflow_failed',
properties: {
...PRIVACY_INVARIANTS,
...classifyWorkflowForTelemetry(props.workflowName, props.workflowSource),
outcome: props.outcome,
schema_version: TELEMETRY_SCHEMA_VERSION,
...(props.provider ? { provider: props.provider } : {}),
...(props.durationMs !== undefined ? { duration_ms: props.durationMs } : {}),
...(props.nodesCompleted !== undefined ? { nodes_completed: props.nodesCompleted } : {}),
...(props.nodesFailed !== undefined ? { nodes_failed: props.nodesFailed } : {}),
...(props.nodesSkipped !== undefined ? { nodes_skipped: props.nodesSkipped } : {}),
...(props.nodesTotal !== undefined ? { nodes_total: props.nodesTotal } : {}),
...(props.exitReason ? { exit_reason: props.exitReason } : {}),
...(props.errorClass ? { error_class: props.errorClass } : {}),
...(props.failedNodeType ? { failed_node_type: props.failedNodeType } : {}),
...(props.costUsd !== undefined ? { cost_usd: props.costUsd } : {}),
...(props.tokensIn !== undefined ? { tokens_in: props.tokensIn } : {}),
...(props.tokensOut !== undefined ? { tokens_out: props.tokensOut } : {}),
...(props.loopIterations !== undefined ? { loop_iterations: props.loopIterations } : {}),
},
});
});
}
/**
* Flush queued events and close the PostHog client. Call on process exit
* (server SIGTERM, end of CLI command) so buffered events aren't lost.
* Safe to call when telemetry was never initialized.
*/
export async function shutdownTelemetry(): Promise<void> {
if (clientInit === undefined) return;
try {
const client = await clientInit;
if (client) {
await client.shutdown();
}
} catch (error) {
getLog().debug({ err: error as Error }, 'telemetry.shutdown_failed');
} finally {
clientInit = undefined;
}
}
/**
* Reset internal state for tests. Not part of the public API.
* @internal
*/
export function resetTelemetryForTests(): void {
clientInit = undefined;
telemetryIdCache = undefined;
noticeChecked = false;
firstFailureLogged = false;
}