@cortex-agent/server 2026.10.21 → 2026.10.25
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.
- package/README.md +10 -6
- package/defaults/context/projects/AGENTS.md +1 -1
- package/defaults/gitignore +3 -3
- package/defaults/hooks/new-session-hook.mjs +1 -1
- package/defaults/hooks/status-md-guard.mjs +6 -6
- package/defaults/plugins/cortex-system/plugin.json +1 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +16 -9
- package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +2 -2
- package/defaults/rules/agents-md.md +1 -1
- package/defaults/rules/issues-md.md +1 -1
- package/defaults/rules/meta-conventions.md +3 -3
- package/defaults/rules/mission-md.md +1 -1
- package/defaults/rules/status-md.md +1 -1
- package/dist/agent-adapter/claude/bg-task-tracker.d.ts +3 -1
- package/dist/agent-adapter/claude/bg-task-tracker.js +6 -2
- package/dist/agent-adapter/claude/mcp-config.js +11 -0
- package/dist/agent-adapter/claude/turn-machine.d.ts +2 -1
- package/dist/agent-adapter/claude/turn-machine.js +8 -5
- package/dist/agent-adapter/continuation-phase.d.ts +6 -3
- package/dist/agent-adapter/continuation-phase.js +8 -3
- package/dist/agent-adapter/run-events.d.ts +4 -0
- package/dist/agent-adapter/types.d.ts +9 -2
- package/dist/build-info.json +1 -0
- package/dist/client-bundle/client.mjs +10 -5
- package/dist/client-bundle/manifest.json +2 -2
- package/dist/core/claude-credentials.d.ts +6 -0
- package/dist/core/claude-credentials.js +11 -0
- package/dist/core/gateway-generator.d.ts +17 -0
- package/dist/core/gateway-generator.js +42 -4
- package/dist/core/hook-bus.d.ts +1 -1
- package/dist/core/hook-bus.js +1 -8
- package/dist/core/locales/en.d.ts +1 -0
- package/dist/core/locales/slices/init.d.ts +1 -0
- package/dist/core/locales/slices/init.js +2 -0
- package/dist/core/log.d.ts +3 -0
- package/dist/core/log.js +18 -1
- package/dist/core/settings-spec.d.ts +5 -0
- package/dist/core/settings-spec.js +4 -0
- package/dist/core/types/agent-types.d.ts +3 -1
- package/dist/core/types/environment-types.d.ts +1 -6
- package/dist/domain/agents/environments/registry.js +3 -2
- package/dist/domain/agents/environments/schema.d.ts +3 -2
- package/dist/domain/agents/environments/schema.js +4 -3
- package/dist/domain/auth/auth-watch.js +48 -18
- package/dist/domain/mcp/tools/context.d.ts +0 -1
- package/dist/domain/mcp/tools/context.js +0 -1
- package/dist/domain/monitor/event-loop-monitor.d.ts +2 -0
- package/dist/domain/monitor/event-loop-monitor.js +5 -1
- package/dist/domain/plugins/authoring.d.ts +8 -1
- package/dist/domain/plugins/authoring.js +24 -9
- package/dist/domain/plugins/runtime-gc.d.ts +7 -0
- package/dist/domain/plugins/runtime-gc.js +52 -19
- package/dist/domain/plugins/runtime.js +2 -1
- package/dist/domain/remote/client-bootstrap.js +1 -1
- package/dist/domain/remote/client-manager.js +6 -1
- package/dist/domain/runs/retryable-errors.js +3 -1
- package/dist/domain/runs/service.d.ts +0 -9
- package/dist/domain/runs/service.js +29 -15
- package/dist/domain/scheduling/builtin-job-controller.d.ts +3 -1
- package/dist/domain/scheduling/builtin-job-controller.js +5 -2
- package/dist/domain/scheduling/builtin-jobs.js +7 -0
- package/dist/domain/scheduling/scheduler.js +14 -5
- package/dist/domain/system/server-update-check.js +2 -1
- package/dist/domain/telemetry/bus-collector.d.ts +3 -0
- package/dist/domain/telemetry/bus-collector.js +22 -0
- package/dist/domain/telemetry/child-exit.d.ts +11 -0
- package/dist/domain/telemetry/child-exit.js +36 -0
- package/dist/domain/telemetry/client-kind.d.ts +4 -0
- package/dist/domain/telemetry/client-kind.js +7 -0
- package/dist/domain/telemetry/crash-limits.d.ts +15 -0
- package/dist/domain/telemetry/crash-limits.js +50 -0
- package/dist/domain/telemetry/crash.d.ts +25 -0
- package/dist/domain/telemetry/crash.js +70 -0
- package/dist/domain/telemetry/daily-upload.d.ts +5 -0
- package/dist/domain/telemetry/daily-upload.js +20 -0
- package/dist/domain/telemetry/daily.d.ts +5 -0
- package/dist/domain/telemetry/daily.js +104 -0
- package/dist/domain/telemetry/endpoint.d.ts +7 -0
- package/dist/domain/telemetry/endpoint.js +40 -0
- package/dist/domain/telemetry/envelope.d.ts +6 -0
- package/dist/domain/telemetry/envelope.js +35 -0
- package/dist/domain/telemetry/error-digest.d.ts +7 -0
- package/dist/domain/telemetry/error-digest.js +43 -0
- package/dist/domain/telemetry/funnel.d.ts +6 -0
- package/dist/domain/telemetry/funnel.js +22 -0
- package/dist/domain/telemetry/gate.d.ts +19 -0
- package/dist/domain/telemetry/gate.js +67 -0
- package/dist/domain/telemetry/heartbeat.d.ts +17 -0
- package/dist/domain/telemetry/heartbeat.js +49 -0
- package/dist/domain/telemetry/info.d.ts +9 -0
- package/dist/domain/telemetry/info.js +12 -0
- package/dist/domain/telemetry/init-answer.d.ts +12 -0
- package/dist/domain/telemetry/init-answer.js +42 -0
- package/dist/domain/telemetry/install-id.d.ts +5 -0
- package/dist/domain/telemetry/install-id.js +42 -0
- package/dist/domain/telemetry/normalize.d.ts +33 -0
- package/dist/domain/telemetry/normalize.js +88 -0
- package/dist/domain/telemetry/outbox.d.ts +18 -0
- package/dist/domain/telemetry/outbox.js +93 -0
- package/dist/domain/telemetry/panic-group.d.ts +4 -0
- package/dist/domain/telemetry/panic-group.js +51 -0
- package/dist/domain/telemetry/paths.d.ts +7 -0
- package/dist/domain/telemetry/paths.js +11 -0
- package/dist/domain/telemetry/redact.d.ts +18 -0
- package/dist/domain/telemetry/redact.js +109 -0
- package/dist/domain/telemetry/rollup-types.d.ts +81 -0
- package/dist/domain/telemetry/rollup-types.js +31 -0
- package/dist/domain/telemetry/rollup.d.ts +16 -0
- package/dist/domain/telemetry/rollup.js +102 -0
- package/dist/domain/telemetry/schema.d.ts +931 -0
- package/dist/domain/telemetry/schema.js +275 -0
- package/dist/domain/telemetry/service.d.ts +34 -0
- package/dist/domain/telemetry/service.js +146 -0
- package/dist/domain/telemetry/state.d.ts +17 -0
- package/dist/domain/telemetry/state.js +29 -0
- package/dist/domain/telemetry/turns.d.ts +17 -0
- package/dist/domain/telemetry/turns.js +176 -0
- package/dist/domain/telemetry/upgrade.d.ts +14 -0
- package/dist/domain/telemetry/upgrade.js +87 -0
- package/dist/domain/telemetry/uploader.d.ts +21 -0
- package/dist/domain/telemetry/uploader.js +82 -0
- package/dist/domain/telemetry/usage.d.ts +25 -0
- package/dist/domain/telemetry/usage.js +153 -0
- package/dist/domain/telemetry/web-report.d.ts +8 -0
- package/dist/domain/telemetry/web-report.js +15 -0
- package/dist/domain/ui-service/app-router.d.ts +69 -25
- package/dist/domain/ui-service/app-router.js +9 -2
- package/dist/domain/ui-service/input-schemas.d.ts +68 -4
- package/dist/domain/ui-service/input-schemas.js +9 -1
- package/dist/domain/ui-service/mutate/approvals.d.ts +3 -2
- package/dist/domain/ui-service/mutate/approvals.js +3 -2
- package/dist/domain/ui-service/mutate/plugin-packages.js +1 -1
- package/dist/domain/ui-service/mutate/telemetry.d.ts +5 -0
- package/dist/domain/ui-service/mutate/telemetry.js +6 -0
- package/dist/domain/ui-service/query/approvals.js +4 -3
- package/dist/domain/ui-service/query/machine-probe.d.ts +1 -1
- package/dist/domain/ui-service/query/machine-probe.js +3 -2
- package/dist/domain/ui-service/query/models.d.ts +3 -0
- package/dist/domain/ui-service/query/models.js +47 -30
- package/dist/domain/ui-service/query/plugin-source.js +4 -3
- package/dist/domain/ui-service/query/sessions.js +1 -0
- package/dist/domain/ui-service/query/telemetry.d.ts +3 -0
- package/dist/domain/ui-service/query/telemetry.js +4 -0
- package/dist/domain/ui-service/trpc.d.ts +8 -3
- package/dist/domain/ui-service/trpc.js +1 -1
- package/dist/domain/ui-service/types.d.ts +20 -2
- package/dist/domain/ui-service/ui-service.d.ts +33 -4
- package/dist/domain/ui-service/ui-service.js +19 -18
- package/dist/entry/app.js +20 -2
- package/dist/entry/cli-help.js +27 -14
- package/dist/entry/daemon.d.ts +1 -1
- package/dist/entry/daemon.js +86 -72
- package/dist/entry/init.d.ts +3 -0
- package/dist/entry/init.js +50 -28
- package/dist/entry/shutdown.js +3 -0
- package/dist/entry/signal-cli.js +8 -11
- package/dist/entry/start-ui-http.js +40 -18
- package/dist/entry/telemetry-wiring.d.ts +12 -0
- package/dist/entry/telemetry-wiring.js +56 -0
- package/dist/entry/ui-cli.d.ts +0 -11
- package/dist/entry/ui-cli.js +42 -33
- package/dist/events/event-types.d.ts +1 -4
- package/dist/orchestration/routing/message-router.js +2 -0
- package/dist/orchestration/routing/webhook.js +2 -0
- package/dist/orchestration/transcript-sink.d.ts +6 -0
- package/dist/orchestration/transcript-sink.js +17 -0
- package/dist/orchestration/waitpoint-ingress.js +3 -0
- package/dist/platform/ui-http/ui-auth-routes.d.ts +2 -0
- package/dist/platform/ui-http/ui-auth-routes.js +9 -2
- package/dist/platform/ui-http/ui-device-routes.d.ts +13 -0
- package/dist/platform/ui-http/ui-device-routes.js +81 -0
- package/dist/platform/ui-http/ui-devices.d.ts +24 -0
- package/dist/platform/ui-http/ui-devices.js +107 -0
- package/dist/platform/ui-http/ui-http-server.d.ts +10 -3
- package/dist/platform/ui-http/ui-http-server.js +11 -7
- package/dist/platform/ui-http/ui-pairing.d.ts +25 -0
- package/dist/platform/ui-http/ui-pairing.js +98 -0
- package/dist/store/gitignore-migration.d.ts +2 -0
- package/dist/store/gitignore-migration.js +16 -0
- package/dist/store/hook-registry.d.ts +1 -1
- package/dist/store/hook-registry.js +11 -6
- package/dist/store/session-registry-journal.js +3 -0
- package/dist/store/version-migrations.d.ts +5 -0
- package/dist/store/version-migrations.js +117 -80
- package/dist/tui/components/Dashboard.js +4 -3
- package/dist/tui/hooks/useDashboardData.js +1 -1
- package/package.json +3 -3
- package/web/dist/assets/{board-math-css-CB4GJ6qO.js → board-math-css-spk7yR6n.js} +1 -1
- package/web/dist/assets/index-BQ69u-92.css +1 -0
- package/web/dist/assets/{index-cIGFv27z.js → index-CKNLatCd.js} +1 -1
- package/web/dist/assets/index-CkzWfC98.js +525 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-CaSZPg_H.css +0 -1
- package/web/dist/assets/index-CzOR7Edh.js +0 -522
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { isTelemetryActive } from './gate.js';
|
|
2
|
+
import { admitCrash, wipeCrashLimits } from './crash-limits.js';
|
|
3
|
+
import { panicGroupKey } from './panic-group.js';
|
|
4
|
+
import { groupKeyOf, redactMessage, redactStack } from './redact.js';
|
|
5
|
+
import { recordTelemetryEvent, registerTelemetryHooks } from './service.js';
|
|
6
|
+
registerTelemetryHooks({ wipe: () => wipeCrashLimits() });
|
|
7
|
+
function errorNameOf(error) {
|
|
8
|
+
if (error instanceof Error)
|
|
9
|
+
return error.name || error.constructor?.name || 'Error';
|
|
10
|
+
return typeof error === 'object' && error !== null ? 'NonErrorObject' : `Non${typeof error}`;
|
|
11
|
+
}
|
|
12
|
+
/** Name, message and stack of whatever was thrown, before redaction. */
|
|
13
|
+
export function describeThrown(error) {
|
|
14
|
+
if (error instanceof Error) {
|
|
15
|
+
return { errorName: errorNameOf(error), message: error.message ?? '', stack: error.stack ?? '' };
|
|
16
|
+
}
|
|
17
|
+
return { errorName: errorNameOf(error), message: '', stack: '' };
|
|
18
|
+
}
|
|
19
|
+
/** Redact and shape a crash; the group key comes from the redacted stack. */
|
|
20
|
+
export function buildCrashEvent(input, suppressed = 0) {
|
|
21
|
+
const errorName = redactMessage(input.errorName).slice(0, 80) || 'Error';
|
|
22
|
+
const stack = redactStack(input.stack);
|
|
23
|
+
return {
|
|
24
|
+
type: 'crash',
|
|
25
|
+
at: (input.at ?? new Date()).toISOString(),
|
|
26
|
+
component: input.component,
|
|
27
|
+
kind: input.kind,
|
|
28
|
+
errorName,
|
|
29
|
+
message: redactMessage(input.message),
|
|
30
|
+
stack,
|
|
31
|
+
groupKey: groupKeyFor(input, errorName, stack),
|
|
32
|
+
uptimeS: input.uptimeS ?? null,
|
|
33
|
+
route: input.route?.slice(0, 80) ?? null,
|
|
34
|
+
buildStamp: input.buildStamp?.slice(0, 60) ?? null,
|
|
35
|
+
client: input.client ?? null,
|
|
36
|
+
exit: input.exit ?? null,
|
|
37
|
+
suppressed,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function childExitGroup(exit) {
|
|
41
|
+
return exit?.signal ? `ChildExit@${exit.signal}` : `ChildExit@code:${exit?.code ?? 'unknown'}`;
|
|
42
|
+
}
|
|
43
|
+
/** Child exits group by signal or code, native panics by their location (read from the unredacted
|
|
44
|
+
* report, then reduced to a source-relative file), everything else by its first own stack frame. */
|
|
45
|
+
function groupKeyFor(input, errorName, redactedStack) {
|
|
46
|
+
if (input.kind === 'childExit')
|
|
47
|
+
return childExitGroup(input.exit);
|
|
48
|
+
if (input.kind === 'panic')
|
|
49
|
+
return panicGroupKey(input.message, input.stack);
|
|
50
|
+
return groupKeyOf(errorName, redactedStack);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Record a crash: rate-limited, appended synchronously, uploaded within seconds when the
|
|
54
|
+
* service runs in this process. Never throws.
|
|
55
|
+
*/
|
|
56
|
+
export function captureCrash(input) {
|
|
57
|
+
try {
|
|
58
|
+
if (!isTelemetryActive())
|
|
59
|
+
return;
|
|
60
|
+
const draft = buildCrashEvent(input);
|
|
61
|
+
const admission = admitCrash(draft.groupKey);
|
|
62
|
+
if (!admission.send)
|
|
63
|
+
return;
|
|
64
|
+
recordTelemetryEvent({ ...draft, suppressed: admission.suppressed }, { urgent: true });
|
|
65
|
+
}
|
|
66
|
+
catch { /* crash reporting must never add a crash */ }
|
|
67
|
+
}
|
|
68
|
+
export function captureProcessCrash(component, kind, error) {
|
|
69
|
+
captureCrash({ component, kind, ...describeThrown(error), uptimeS: Math.round(process.uptime()) });
|
|
70
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { loadNameCatalog } from './normalize.js';
|
|
2
|
+
/** Queue every finished day as a `daily` event, then forget it locally. */
|
|
3
|
+
export declare function queueFinishedDays(now: number, loadCatalog?: typeof loadNameCatalog): Promise<void>;
|
|
4
|
+
/** Hook the rollup store into the service's persist / finalize / wipe moments. */
|
|
5
|
+
export declare function installDailyUpload(): void;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { toDailyEvent } from './daily.js';
|
|
2
|
+
import { loadNameCatalog } from './normalize.js';
|
|
3
|
+
import { dropRollupDay, finishedRollups, persistRollup, utcDay, wipeRollups } from './rollup.js';
|
|
4
|
+
import { recordTelemetryEvent, registerTelemetryHooks } from './service.js';
|
|
5
|
+
/** Queue every finished day as a `daily` event, then forget it locally. */
|
|
6
|
+
export async function queueFinishedDays(now, loadCatalog = loadNameCatalog) {
|
|
7
|
+
const days = finishedRollups(now);
|
|
8
|
+
if (days.length === 0)
|
|
9
|
+
return;
|
|
10
|
+
const catalog = await loadCatalog(utcDay(now));
|
|
11
|
+
for (const rollup of days) {
|
|
12
|
+
const event = toDailyEvent(rollup, catalog);
|
|
13
|
+
if (!event || recordTelemetryEvent(event))
|
|
14
|
+
dropRollupDay(rollup.day);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** Hook the rollup store into the service's persist / finalize / wipe moments. */
|
|
18
|
+
export function installDailyUpload() {
|
|
19
|
+
registerTelemetryHooks({ persist: persistRollup, finalize: (now) => queueFinishedDays(now), wipe: wipeRollups });
|
|
20
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type NameCatalog } from './normalize.js';
|
|
2
|
+
import type { RawRollup } from './rollup-types.js';
|
|
3
|
+
import { type DailyEvent } from './schema.js';
|
|
4
|
+
/** One finished day as an upload, or null when it does not fit the wire schema. */
|
|
5
|
+
export declare function toDailyEvent(rollup: RawRollup, catalog: NameCatalog): DailyEvent | null;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { normalizeModel, normalizeProvider, normalizeTool, toIdent } from './normalize.js';
|
|
2
|
+
import { emptyTurnRow } from './rollup-types.js';
|
|
3
|
+
import { bucketIndex, DailyEventSchema, emptyHistogram, FEATURE_COUNTERS, MESSAGE_CHANNELS, } from './schema.js';
|
|
4
|
+
function addInto(target, source) {
|
|
5
|
+
source.forEach((value, index) => { target[index] = (target[index] ?? 0) + value; });
|
|
6
|
+
}
|
|
7
|
+
function sumRecord(target, source) {
|
|
8
|
+
for (const [key, value] of Object.entries(source))
|
|
9
|
+
target[key] = (target[key] ?? 0) + value;
|
|
10
|
+
}
|
|
11
|
+
function mergeTurnRow(target, row) {
|
|
12
|
+
sumRecord(target.outcomes, row.outcomes);
|
|
13
|
+
sumRecord(target.failures, row.failures);
|
|
14
|
+
sumRecord(target.compactions, row.compactions);
|
|
15
|
+
sumRecord(target.tokens, row.tokens);
|
|
16
|
+
target.retries += row.retries;
|
|
17
|
+
target.fallbacks += row.fallbacks;
|
|
18
|
+
addInto(target.ttftMs, row.ttftMs);
|
|
19
|
+
addInto(target.durationS, row.durationS);
|
|
20
|
+
addInto(target.contextPctAtEnd, row.contextPctAtEnd);
|
|
21
|
+
}
|
|
22
|
+
/** Normalize each row's provider/model, merging rows that collapse onto the same name. */
|
|
23
|
+
function turnRows(rollup, catalog) {
|
|
24
|
+
const merged = new Map();
|
|
25
|
+
for (const row of Object.values(rollup.turns)) {
|
|
26
|
+
const { provider, customApi } = normalizeProvider(row.backend, row.provider, catalog);
|
|
27
|
+
const model = normalizeModel(row.backend, row.provider, row.model, catalog);
|
|
28
|
+
const key = [row.backend, provider, model, row.billing, customApi].join('|');
|
|
29
|
+
if (!merged.has(key))
|
|
30
|
+
merged.set(key, { ...emptyTurnRow(row.backend, provider, model, row.billing), customApi });
|
|
31
|
+
mergeTurnRow(merged.get(key), row);
|
|
32
|
+
}
|
|
33
|
+
return [...merged.values()].sort((a, b) => total(b) - total(a)).slice(0, 100);
|
|
34
|
+
}
|
|
35
|
+
function total(row) {
|
|
36
|
+
return row.outcomes.completed + row.outcomes.failed + row.outcomes.cancelled + row.outcomes.rateLimited;
|
|
37
|
+
}
|
|
38
|
+
function tools(rollup) {
|
|
39
|
+
const merged = new Map();
|
|
40
|
+
for (const [name, counts] of Object.entries(rollup.tools)) {
|
|
41
|
+
const key = normalizeTool(name);
|
|
42
|
+
const entry = merged.get(key) ?? { calls: 0, errors: 0 };
|
|
43
|
+
merged.set(key, { calls: entry.calls + counts.calls, errors: entry.errors + counts.errors });
|
|
44
|
+
}
|
|
45
|
+
return [...merged].map(([name, counts]) => ({ name, ...counts }))
|
|
46
|
+
.sort((a, b) => b.calls - a.calls).slice(0, 200);
|
|
47
|
+
}
|
|
48
|
+
function pick(source, keys) {
|
|
49
|
+
return Object.fromEntries(keys.filter((key) => source[key] > 0).map((key) => [key, source[key]]));
|
|
50
|
+
}
|
|
51
|
+
function identRecord(source) {
|
|
52
|
+
const out = {};
|
|
53
|
+
for (const [key, value] of Object.entries(source))
|
|
54
|
+
out[toIdent(key)] = (out[toIdent(key)] ?? 0) + value;
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
function turnsPerSession(sessionTurns) {
|
|
58
|
+
const histogram = emptyHistogram('turnsPerSession');
|
|
59
|
+
for (const turns of Object.values(sessionTurns))
|
|
60
|
+
histogram[bucketIndex('turnsPerSession', turns)] += 1;
|
|
61
|
+
return histogram;
|
|
62
|
+
}
|
|
63
|
+
function median(values) {
|
|
64
|
+
if (values.length === 0)
|
|
65
|
+
return 0;
|
|
66
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
67
|
+
return sorted[Math.floor(sorted.length / 2)];
|
|
68
|
+
}
|
|
69
|
+
function perf(rollup) {
|
|
70
|
+
const loop = rollup.perf.eventLoopP99s;
|
|
71
|
+
return {
|
|
72
|
+
startups: rollup.perf.startups.slice(-10).map(identRecord),
|
|
73
|
+
eventLoop: { windows: loop.length, p99MedianMs: median(loop), p99MaxMs: loop.length ? Math.max(...loop) : 0 },
|
|
74
|
+
web: rollup.perf.web,
|
|
75
|
+
sseReconnects: rollup.perf.sseReconnects,
|
|
76
|
+
remoteClientDisconnects: rollup.perf.remoteClientDisconnects,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** One finished day as an upload, or null when it does not fit the wire schema. */
|
|
80
|
+
export function toDailyEvent(rollup, catalog) {
|
|
81
|
+
const event = {
|
|
82
|
+
type: 'daily',
|
|
83
|
+
day: rollup.day,
|
|
84
|
+
turns: turnRows(rollup, catalog),
|
|
85
|
+
features: pick(rollup.features, FEATURE_COUNTERS),
|
|
86
|
+
messagesByChannel: pick(rollup.messagesByChannel, MESSAGE_CHANNELS),
|
|
87
|
+
uiOps: identRecord(rollup.uiOps),
|
|
88
|
+
tools: tools(rollup),
|
|
89
|
+
agent: {
|
|
90
|
+
userInterrupts: rollup.agent.userInterrupts,
|
|
91
|
+
superseded: rollup.agent.superseded,
|
|
92
|
+
turnsPerSession: turnsPerSession(rollup.agent.sessionTurns),
|
|
93
|
+
workers: rollup.agent.workers,
|
|
94
|
+
subagents: rollup.agent.subagents,
|
|
95
|
+
},
|
|
96
|
+
perf: perf(rollup),
|
|
97
|
+
errors: {
|
|
98
|
+
byModule: identRecord(rollup.errors.byModule),
|
|
99
|
+
samples: rollup.errors.samples.slice(0, 5).map((sample) => ({ ...sample, module: toIdent(sample.module) })),
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
const parsed = DailyEventSchema.safeParse(event);
|
|
103
|
+
return parsed.success ? parsed.data : null;
|
|
104
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Release CI writes this next to the compiled server; source builds have none. */
|
|
2
|
+
export declare const BUILD_INFO_FILE: string;
|
|
3
|
+
/**
|
|
4
|
+
* Where batches go: `CORTEX_TELEMETRY_ENDPOINT` (tests, self-hosted sinks), else the endpoint
|
|
5
|
+
* the release build recorded. Null means nothing is ever sent.
|
|
6
|
+
*/
|
|
7
|
+
export declare function resolveTelemetryEndpoint(env?: NodeJS.ProcessEnv, buildInfoFile?: string): string | null;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { INSTALL_ROOT } from '../../core/paths.js';
|
|
4
|
+
/** Release CI writes this next to the compiled server; source builds have none. */
|
|
5
|
+
export const BUILD_INFO_FILE = path.join(INSTALL_ROOT, 'dist', 'build-info.json');
|
|
6
|
+
let cachedBuildEndpoint;
|
|
7
|
+
function validEndpoint(raw) {
|
|
8
|
+
if (typeof raw !== 'string' || raw.trim() === '')
|
|
9
|
+
return null;
|
|
10
|
+
try {
|
|
11
|
+
const url = new URL(raw.trim());
|
|
12
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url.toString() : null;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function readBuildEndpoint(file) {
|
|
19
|
+
try {
|
|
20
|
+
const info = JSON.parse(readFileSync(file, 'utf8'));
|
|
21
|
+
return validEndpoint(info.telemetryEndpoint);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Where batches go: `CORTEX_TELEMETRY_ENDPOINT` (tests, self-hosted sinks), else the endpoint
|
|
29
|
+
* the release build recorded. Null means nothing is ever sent.
|
|
30
|
+
*/
|
|
31
|
+
export function resolveTelemetryEndpoint(env = process.env, buildInfoFile = BUILD_INFO_FILE) {
|
|
32
|
+
const override = validEndpoint(env.CORTEX_TELEMETRY_ENDPOINT);
|
|
33
|
+
if (override)
|
|
34
|
+
return override;
|
|
35
|
+
if (buildInfoFile !== BUILD_INFO_FILE)
|
|
36
|
+
return readBuildEndpoint(buildInfoFile);
|
|
37
|
+
if (cachedBuildEndpoint === undefined)
|
|
38
|
+
cachedBuildEndpoint = readBuildEndpoint(buildInfoFile);
|
|
39
|
+
return cachedBuildEndpoint;
|
|
40
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type TelemetryEnvelope } from './schema.js';
|
|
2
|
+
type InstallForm = TelemetryEnvelope['installForm'];
|
|
3
|
+
/** The desktop service sets CORTEX_NPM_PREFIX; a global npm layout is the npm form. */
|
|
4
|
+
export declare function detectInstallForm(env?: NodeJS.ProcessEnv, installRoot?: string): InstallForm;
|
|
5
|
+
export declare function buildEnvelope(channel: TelemetryEnvelope['channel'], now?: Date): TelemetryEnvelope;
|
|
6
|
+
export {};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import { getLocale } from '../../core/i18n.js';
|
|
3
|
+
import { INSTALL_ROOT } from '../../core/paths.js';
|
|
4
|
+
import { npmPrefixFromInstallRoot } from '../../core/utils.js';
|
|
5
|
+
import { CORTEX_VERSION } from '../../core/version.js';
|
|
6
|
+
import { getInstallId } from './install-id.js';
|
|
7
|
+
import { TELEMETRY_SCHEMA_VERSION } from './schema.js';
|
|
8
|
+
const KNOWN_OS = ['linux', 'darwin', 'win32', 'android'];
|
|
9
|
+
/** The desktop service sets CORTEX_NPM_PREFIX; a global npm layout is the npm form. */
|
|
10
|
+
export function detectInstallForm(env = process.env, installRoot = INSTALL_ROOT) {
|
|
11
|
+
if (env.CORTEX_NPM_PREFIX?.trim())
|
|
12
|
+
return 'desktop';
|
|
13
|
+
return npmPrefixFromInstallRoot(installRoot, '@cortex-agent/server') ? 'npm' : 'other';
|
|
14
|
+
}
|
|
15
|
+
function osName(platform) {
|
|
16
|
+
return KNOWN_OS.includes(platform) ? platform : 'other';
|
|
17
|
+
}
|
|
18
|
+
function majorOf(release) {
|
|
19
|
+
return (release.split('.')[0] ?? '').slice(0, 20);
|
|
20
|
+
}
|
|
21
|
+
export function buildEnvelope(channel, now = new Date()) {
|
|
22
|
+
return {
|
|
23
|
+
schema: TELEMETRY_SCHEMA_VERSION,
|
|
24
|
+
installId: getInstallId(),
|
|
25
|
+
sentAt: now.toISOString(),
|
|
26
|
+
version: CORTEX_VERSION.slice(0, 40),
|
|
27
|
+
channel,
|
|
28
|
+
installForm: detectInstallForm(),
|
|
29
|
+
os: osName(process.platform),
|
|
30
|
+
osRelease: majorOf(os.release()),
|
|
31
|
+
arch: process.arch.slice(0, 20),
|
|
32
|
+
nodeMajor: Number.parseInt(process.versions.node, 10),
|
|
33
|
+
uiLang: getLocale(),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** A stable group for one `log.error` call: the error's own frame, else its message shape. */
|
|
2
|
+
export declare function describeLogError(module: string, args: unknown[]): {
|
|
3
|
+
groupKey: string;
|
|
4
|
+
message: string;
|
|
5
|
+
};
|
|
6
|
+
/** The `log.error` sink: count per module, keep one redacted sample for up to five groups. */
|
|
7
|
+
export declare function recordErrorLog(module: string, args: unknown[]): void;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { groupKeyOf, redactMessage, redactStack } from './redact.js';
|
|
2
|
+
import { updateRollup } from './rollup.js';
|
|
3
|
+
const MAX_SAMPLES = 5;
|
|
4
|
+
function formatArg(arg) {
|
|
5
|
+
if (arg instanceof Error)
|
|
6
|
+
return `${arg.name}: ${arg.message}`;
|
|
7
|
+
if (typeof arg === 'string')
|
|
8
|
+
return arg;
|
|
9
|
+
try {
|
|
10
|
+
return JSON.stringify(arg) ?? String(arg);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return String(arg);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** A stable group for one `log.error` call: the error's own frame, else its message shape. */
|
|
17
|
+
export function describeLogError(module, args) {
|
|
18
|
+
const message = redactMessage(args.map(formatArg).join(' '));
|
|
19
|
+
const error = args.find((arg) => arg instanceof Error);
|
|
20
|
+
if (error?.stack) {
|
|
21
|
+
const key = groupKeyOf(error.name || 'Error', redactStack(error.stack));
|
|
22
|
+
if (!key.endsWith('@unknown'))
|
|
23
|
+
return { groupKey: `${module}:${key}`.slice(0, 200), message };
|
|
24
|
+
}
|
|
25
|
+
const shape = message.replace(/\d+/g, '#').slice(0, 120);
|
|
26
|
+
return { groupKey: `${module}:${shape}`.slice(0, 200), message };
|
|
27
|
+
}
|
|
28
|
+
function addSample(rollup, module, args) {
|
|
29
|
+
const { samples } = rollup.errors;
|
|
30
|
+
const { groupKey, message } = describeLogError(module, args);
|
|
31
|
+
const existing = samples.find((sample) => sample.groupKey === groupKey);
|
|
32
|
+
if (existing)
|
|
33
|
+
existing.count += 1;
|
|
34
|
+
else if (samples.length < MAX_SAMPLES)
|
|
35
|
+
samples.push({ module, groupKey, message, count: 1 });
|
|
36
|
+
}
|
|
37
|
+
/** The `log.error` sink: count per module, keep one redacted sample for up to five groups. */
|
|
38
|
+
export function recordErrorLog(module, args) {
|
|
39
|
+
updateRollup((rollup) => {
|
|
40
|
+
rollup.errors.byModule[module] = (rollup.errors.byModule[module] ?? 0) + 1;
|
|
41
|
+
addSample(rollup, module, args);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { FunnelEvent } from './schema.js';
|
|
2
|
+
type ServerStep = Extract<FunnelEvent['step'], `server_${string}` | 'provider_authed' | `first_${string}`>;
|
|
3
|
+
/** Report an onboarding step the first time this install reaches it; later calls are no-ops. */
|
|
4
|
+
export declare function recordFunnelStep(step: ServerStep, detail?: string | null): void;
|
|
5
|
+
export declare function resetFunnelCacheForTests(): void;
|
|
6
|
+
export {};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { recordTelemetryEvent } from './service.js';
|
|
2
|
+
import { readTelemetryState, updateTelemetryState } from './state.js';
|
|
3
|
+
const sentThisProcess = new Set();
|
|
4
|
+
/** Report an onboarding step the first time this install reaches it; later calls are no-ops. */
|
|
5
|
+
export function recordFunnelStep(step, detail = null) {
|
|
6
|
+
if (sentThisProcess.has(step))
|
|
7
|
+
return;
|
|
8
|
+
if (readTelemetryState().funnelSent.includes(step)) {
|
|
9
|
+
sentThisProcess.add(step);
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
const recorded = recordTelemetryEvent({
|
|
13
|
+
type: 'funnel', at: new Date().toISOString(), source: 'server', step, detail,
|
|
14
|
+
});
|
|
15
|
+
if (!recorded)
|
|
16
|
+
return;
|
|
17
|
+
sentThisProcess.add(step);
|
|
18
|
+
updateTelemetryState((state) => ({ ...state, funnelSent: [...new Set([...state.funnelSent, step])] }));
|
|
19
|
+
}
|
|
20
|
+
export function resetFunnelCacheForTests() {
|
|
21
|
+
sentThisProcess.clear();
|
|
22
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare const TELEMETRY_INACTIVE_REASONS: readonly ['setting', 'env', 'do-not-track', 'sealed', 'no-endpoint', 'dev'];
|
|
2
|
+
export type TelemetryInactiveReason = (typeof TELEMETRY_INACTIVE_REASONS)[number];
|
|
3
|
+
export interface TelemetryGateInput {
|
|
4
|
+
settingEnabled: boolean;
|
|
5
|
+
env: NodeJS.ProcessEnv;
|
|
6
|
+
/** Running from a source checkout (`CORTEX_REPO`, or a tree that still has `src/`). */
|
|
7
|
+
devCheckout: boolean;
|
|
8
|
+
endpoint: string | null;
|
|
9
|
+
}
|
|
10
|
+
export interface TelemetryGate {
|
|
11
|
+
active: boolean;
|
|
12
|
+
reason: TelemetryInactiveReason | null;
|
|
13
|
+
channel: 'release' | 'dev';
|
|
14
|
+
endpoint: string | null;
|
|
15
|
+
}
|
|
16
|
+
/** Pure decision; `telemetryGate()` feeds it the live inputs. */
|
|
17
|
+
export declare function evaluateTelemetryGate(input: TelemetryGateInput): TelemetryGate;
|
|
18
|
+
export declare function telemetryGate(env?: NodeJS.ProcessEnv): TelemetryGate;
|
|
19
|
+
export declare function isTelemetryActive(): boolean;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { existsSync, statSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { INSTALL_ROOT } from '../../core/paths.js';
|
|
4
|
+
import { getSettings } from '../../core/settings.js';
|
|
5
|
+
import { resolveTelemetryEndpoint } from './endpoint.js';
|
|
6
|
+
export const TELEMETRY_INACTIVE_REASONS = [
|
|
7
|
+
'setting', 'env', 'do-not-track', 'sealed', 'no-endpoint', 'dev',
|
|
8
|
+
];
|
|
9
|
+
function truthyFlag(raw) {
|
|
10
|
+
if (raw === undefined)
|
|
11
|
+
return false;
|
|
12
|
+
const value = raw.trim().toLowerCase();
|
|
13
|
+
return value !== '' && value !== '0' && value !== 'false' && value !== 'no' && value !== 'off';
|
|
14
|
+
}
|
|
15
|
+
/** Hard switches that win over the saved setting, in the order they are reported. */
|
|
16
|
+
function forcedOffReason(env) {
|
|
17
|
+
if (env.CORTEX_TELEMETRY?.trim() === '0')
|
|
18
|
+
return 'env';
|
|
19
|
+
if (truthyFlag(env.DO_NOT_TRACK))
|
|
20
|
+
return 'do-not-track';
|
|
21
|
+
if (env.CORTEX_CONFIG_IMMUTABLE === '1')
|
|
22
|
+
return 'sealed';
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
/** Pure decision; `telemetryGate()` feeds it the live inputs. */
|
|
26
|
+
export function evaluateTelemetryGate(input) {
|
|
27
|
+
const explicitOn = input.env.CORTEX_TELEMETRY?.trim() === '1';
|
|
28
|
+
const channel = input.devCheckout ? 'dev' : 'release';
|
|
29
|
+
const off = (reason) => ({ active: false, reason, channel, endpoint: input.endpoint });
|
|
30
|
+
const forced = forcedOffReason(input.env);
|
|
31
|
+
if (forced)
|
|
32
|
+
return off(forced);
|
|
33
|
+
if (!input.settingEnabled)
|
|
34
|
+
return off('setting');
|
|
35
|
+
if (input.devCheckout && !explicitOn)
|
|
36
|
+
return off('dev');
|
|
37
|
+
if (!input.endpoint)
|
|
38
|
+
return off('no-endpoint');
|
|
39
|
+
return { active: true, reason: null, channel, endpoint: input.endpoint };
|
|
40
|
+
}
|
|
41
|
+
let cachedDevCheckout;
|
|
42
|
+
/** `CORTEX_REPO` names an existing directory: the same test as the update checker's dev mode. */
|
|
43
|
+
function repoCheckoutConfigured() {
|
|
44
|
+
const repo = process.env.CORTEX_REPO;
|
|
45
|
+
try {
|
|
46
|
+
return !!repo && statSync(repo).isDirectory();
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Fixed for the life of the process; checked once (the gate runs on hot paths). */
|
|
53
|
+
function isDevCheckout() {
|
|
54
|
+
cachedDevCheckout ??= existsSync(path.join(INSTALL_ROOT, 'src', 'entry')) || repoCheckoutConfigured();
|
|
55
|
+
return cachedDevCheckout;
|
|
56
|
+
}
|
|
57
|
+
export function telemetryGate(env = process.env) {
|
|
58
|
+
return evaluateTelemetryGate({
|
|
59
|
+
settingEnabled: getSettings().telemetryEnabled,
|
|
60
|
+
env,
|
|
61
|
+
devCheckout: isDevCheckout(),
|
|
62
|
+
endpoint: resolveTelemetryEndpoint(env),
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
export function isTelemetryActive() {
|
|
66
|
+
return telemetryGate().active;
|
|
67
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AuthStatusSnapshot } from '../auth/auth-status.js';
|
|
2
|
+
import { type NameCatalog } from './normalize.js';
|
|
3
|
+
import type { HeartbeatEvent } from './schema.js';
|
|
4
|
+
/** The settings a heartbeat reports, by name; all booleans the user can see in Settings. */
|
|
5
|
+
export declare const HEARTBEAT_SETTINGS: readonly ['teamEnabled', 'serverAutoUpdate', 'serverUpdateDisable', 'autoResume', 'bgContinuation', 'streamDeltas', 'clientHotReloadEnabled', 'storeArchiveEnabled', 'providerUsageCollectionEnabled', 'claudeWindowWarmupEnabled', 'feishuSkillsInWeb', 'memoryIndexRegenEnabled'];
|
|
6
|
+
export interface HeartbeatSources {
|
|
7
|
+
authStatus: () => Promise<AuthStatusSnapshot | null>;
|
|
8
|
+
projects: () => number;
|
|
9
|
+
onlineDevices: () => Array<{
|
|
10
|
+
platform: string;
|
|
11
|
+
}>;
|
|
12
|
+
activeSessions24h: () => Promise<number>;
|
|
13
|
+
uptimeS: () => number;
|
|
14
|
+
settings: () => Record<string, unknown>;
|
|
15
|
+
catalog: () => Promise<NameCatalog>;
|
|
16
|
+
}
|
|
17
|
+
export declare function buildHeartbeat(sources: HeartbeatSources, now?: Date): Promise<HeartbeatEvent>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { normalizeProviderList, toIdent } from './normalize.js';
|
|
2
|
+
/** The settings a heartbeat reports, by name; all booleans the user can see in Settings. */
|
|
3
|
+
export const HEARTBEAT_SETTINGS = [
|
|
4
|
+
'teamEnabled', 'serverAutoUpdate', 'serverUpdateDisable', 'autoResume', 'bgContinuation',
|
|
5
|
+
'streamDeltas', 'clientHotReloadEnabled', 'storeArchiveEnabled', 'providerUsageCollectionEnabled',
|
|
6
|
+
'claudeWindowWarmupEnabled', 'feishuSkillsInWeb', 'memoryIndexRegenEnabled',
|
|
7
|
+
];
|
|
8
|
+
function usable(account) {
|
|
9
|
+
return account.state === 'logged-in' || account.state === 'expiring';
|
|
10
|
+
}
|
|
11
|
+
function claudeBilling(accounts) {
|
|
12
|
+
const claude = accounts.find((account) => account.backend === 'claude' && usable(account));
|
|
13
|
+
if (!claude)
|
|
14
|
+
return 'none';
|
|
15
|
+
return claude.authType === 'api_key' ? 'api' : 'plan';
|
|
16
|
+
}
|
|
17
|
+
function platformCounts(devices) {
|
|
18
|
+
const counts = {};
|
|
19
|
+
for (const { platform } of devices) {
|
|
20
|
+
const key = ['linux', 'darwin', 'win32'].includes(platform)
|
|
21
|
+
? platform : 'other';
|
|
22
|
+
counts[key] = (counts[key] ?? 0) + 1;
|
|
23
|
+
}
|
|
24
|
+
return counts;
|
|
25
|
+
}
|
|
26
|
+
function pickSettings(settings) {
|
|
27
|
+
return Object.fromEntries(HEARTBEAT_SETTINGS
|
|
28
|
+
.filter((key) => typeof settings[key] === 'boolean')
|
|
29
|
+
.map((key) => [toIdent(key), settings[key]]));
|
|
30
|
+
}
|
|
31
|
+
export async function buildHeartbeat(sources, now = new Date()) {
|
|
32
|
+
const snapshot = await sources.authStatus().catch(() => null);
|
|
33
|
+
const accounts = snapshot?.accounts.filter(usable) ?? [];
|
|
34
|
+
const devices = sources.onlineDevices();
|
|
35
|
+
const piNames = accounts.filter((account) => account.backend === 'pi').map((account) => account.provider);
|
|
36
|
+
return {
|
|
37
|
+
type: 'heartbeat',
|
|
38
|
+
at: now.toISOString(),
|
|
39
|
+
backends: [...new Set(accounts.map((account) => account.backend))],
|
|
40
|
+
claudeBilling: claudeBilling(accounts),
|
|
41
|
+
piProviders: normalizeProviderList(piNames, await sources.catalog()).slice(0, 60),
|
|
42
|
+
projects: sources.projects(),
|
|
43
|
+
onlineClients: devices.length,
|
|
44
|
+
clientPlatforms: platformCounts(devices),
|
|
45
|
+
activeSessions24h: await sources.activeSessions24h().catch(() => 0),
|
|
46
|
+
uptimeH: Math.round((sources.uptimeS() / 3600) * 100) / 100,
|
|
47
|
+
settings: pickSettings(sources.settings()),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type TelemetryInactiveReason } from './gate.js';
|
|
2
|
+
/** What the Privacy settings section shows (`telemetry.info`). */
|
|
3
|
+
export interface TelemetryInfo {
|
|
4
|
+
settingEnabled: boolean;
|
|
5
|
+
active: boolean;
|
|
6
|
+
inactiveReason: TelemetryInactiveReason | null;
|
|
7
|
+
installId: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function telemetryInfo(): TelemetryInfo;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { getSettings } from '../../core/settings.js';
|
|
2
|
+
import { telemetryGate } from './gate.js';
|
|
3
|
+
import { getInstallId } from './install-id.js';
|
|
4
|
+
export function telemetryInfo() {
|
|
5
|
+
const gate = telemetryGate();
|
|
6
|
+
return {
|
|
7
|
+
settingEnabled: getSettings().telemetryEnabled,
|
|
8
|
+
active: gate.active,
|
|
9
|
+
inactiveReason: gate.reason,
|
|
10
|
+
installId: getInstallId(),
|
|
11
|
+
};
|
|
12
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type InitTelemetryAnswer } from './schema.js';
|
|
2
|
+
/** The `telemetry` field of `cortex init --answers`, or undefined when absent or malformed. */
|
|
3
|
+
export declare function parseInitTelemetryAnswer(value: unknown): InitTelemetryAnswer | undefined;
|
|
4
|
+
/**
|
|
5
|
+
* Persist the init choice into the new home: `telemetryEnabled` in settings.json, and the
|
|
6
|
+
* caller's install id (the desktop shell's, so its setup events and the server's join up) unless
|
|
7
|
+
* this home already has one.
|
|
8
|
+
*/
|
|
9
|
+
export declare function applyInitTelemetry(answer: InitTelemetryAnswer, dirs: {
|
|
10
|
+
configDir: string;
|
|
11
|
+
storeDir: string;
|
|
12
|
+
}): void;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { adoptInstallId, isInstallId } from './install-id.js';
|
|
4
|
+
import { InitTelemetryAnswerSchema } from './schema.js';
|
|
5
|
+
/** The `telemetry` field of `cortex init --answers`, or undefined when absent or malformed. */
|
|
6
|
+
export function parseInitTelemetryAnswer(value) {
|
|
7
|
+
if (value === undefined)
|
|
8
|
+
return undefined;
|
|
9
|
+
const parsed = InitTelemetryAnswerSchema.safeParse(value);
|
|
10
|
+
return parsed.success ? parsed.data : undefined;
|
|
11
|
+
}
|
|
12
|
+
function readSettingsObject(file) {
|
|
13
|
+
if (!existsSync(file))
|
|
14
|
+
return {};
|
|
15
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'));
|
|
16
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
17
|
+
throw new Error(`${file} must contain a JSON object`);
|
|
18
|
+
}
|
|
19
|
+
return parsed;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Persist the init choice into the new home: `telemetryEnabled` in settings.json, and the
|
|
23
|
+
* caller's install id (the desktop shell's, so its setup events and the server's join up) unless
|
|
24
|
+
* this home already has one.
|
|
25
|
+
*/
|
|
26
|
+
export function applyInitTelemetry(answer, dirs) {
|
|
27
|
+
const settingsFile = path.join(dirs.configDir, 'settings.json');
|
|
28
|
+
const settings = readSettingsObject(settingsFile);
|
|
29
|
+
mkdirSync(dirs.configDir, { recursive: true });
|
|
30
|
+
writeFileSync(settingsFile, `${JSON.stringify({ ...settings, telemetryEnabled: answer.enabled }, null, 2)}\n`, 'utf8');
|
|
31
|
+
const idFile = path.join(dirs.storeDir, 'telemetry', 'install-id');
|
|
32
|
+
if (answer.installId && !hasInstallId(idFile))
|
|
33
|
+
adoptInstallId(answer.installId, idFile);
|
|
34
|
+
}
|
|
35
|
+
function hasInstallId(file) {
|
|
36
|
+
try {
|
|
37
|
+
return isInstallId(readFileSync(file, 'utf8').trim());
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare function isInstallId(value: unknown): value is string;
|
|
2
|
+
/** The random per-install id, created on first use. Carries no machine or user information. */
|
|
3
|
+
export declare function getInstallId(file?: string): string;
|
|
4
|
+
/** Take over an id generated elsewhere (the desktop shell hands its own to `cortex init`). */
|
|
5
|
+
export declare function adoptInstallId(id: string, file?: string): void;
|