@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,275 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anonymous product telemetry: the one wire contract shared by the server (producer), the
|
|
3
|
+
* Cloudflare ingest Worker (validator) and the public telemetry docs (which list every field).
|
|
4
|
+
*
|
|
5
|
+
* Imports nothing but zod so the Worker can bundle this file directly. Identifiers that come
|
|
6
|
+
* from user configuration (models, providers, tools, UI ops, log modules) are normalized by the
|
|
7
|
+
* server before upload; the Worker only checks their shape against `IDENT`.
|
|
8
|
+
*/
|
|
9
|
+
import { z } from 'zod';
|
|
10
|
+
export const TELEMETRY_SCHEMA_VERSION = 1;
|
|
11
|
+
/** Hard cap the Worker enforces on one request body. */
|
|
12
|
+
export const TELEMETRY_MAX_BATCH_BYTES = 64 * 1024;
|
|
13
|
+
export const TELEMETRY_MAX_EVENTS_PER_BATCH = 200;
|
|
14
|
+
/** Placeholders the normalizer substitutes for names outside the allowlists. */
|
|
15
|
+
export const TELEMETRY_OTHER = 'other';
|
|
16
|
+
export const TELEMETRY_CUSTOM = 'custom';
|
|
17
|
+
export const TELEMETRY_MCP_OTHER = 'mcp_other';
|
|
18
|
+
// ── Primitives ──────────────────────────────────────────
|
|
19
|
+
/** A normalized identifier: model, provider, tool, UI op, log module, migration name. */
|
|
20
|
+
export const IDENT = z.string().regex(/^[A-Za-z0-9._:/@[\]-]{1,80}$/);
|
|
21
|
+
const count = z.number().int().nonnegative();
|
|
22
|
+
const nonNegative = z.number().nonnegative();
|
|
23
|
+
const timestamp = z.iso.datetime();
|
|
24
|
+
const day = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
|
25
|
+
const version = z.string().max(40);
|
|
26
|
+
/** Redacted free text (error messages). */
|
|
27
|
+
const shortText = z.string().max(300);
|
|
28
|
+
/**
|
|
29
|
+
* Fixed histogram boundaries. A histogram is an array of `bounds.length + 1` counts: slot `i`
|
|
30
|
+
* counts values `<= bounds[i]`, the last slot counts everything above the final bound.
|
|
31
|
+
*/
|
|
32
|
+
export const TELEMETRY_BUCKETS = {
|
|
33
|
+
ttftMs: [500, 1_000, 2_000, 5_000, 10_000, 30_000, 60_000],
|
|
34
|
+
turnDurationS: [5, 15, 30, 60, 120, 300, 600, 1_800, 3_600],
|
|
35
|
+
contextPct: [10, 25, 50, 75, 90, 100],
|
|
36
|
+
turnsPerSession: [1, 2, 5, 10, 20, 50, 100],
|
|
37
|
+
webLoadMs: [200, 500, 1_000, 2_000, 5_000, 10_000],
|
|
38
|
+
};
|
|
39
|
+
function histogram(key) {
|
|
40
|
+
return z.array(count).length(TELEMETRY_BUCKETS[key].length + 1);
|
|
41
|
+
}
|
|
42
|
+
/** Slot index for `value` in the histogram named `key`. */
|
|
43
|
+
export function bucketIndex(key, value) {
|
|
44
|
+
const bounds = TELEMETRY_BUCKETS[key];
|
|
45
|
+
const slot = bounds.findIndex(bound => value <= bound);
|
|
46
|
+
return slot === -1 ? bounds.length : slot;
|
|
47
|
+
}
|
|
48
|
+
export function emptyHistogram(key) {
|
|
49
|
+
return new Array(TELEMETRY_BUCKETS[key].length + 1).fill(0);
|
|
50
|
+
}
|
|
51
|
+
// ── Envelope ────────────────────────────────────────────
|
|
52
|
+
export const TelemetryEnvelopeSchema = z.object({
|
|
53
|
+
schema: z.literal(TELEMETRY_SCHEMA_VERSION),
|
|
54
|
+
/** Random UUID generated once per install; carries no machine or user information. */
|
|
55
|
+
installId: z.uuid(),
|
|
56
|
+
sentAt: timestamp,
|
|
57
|
+
version,
|
|
58
|
+
channel: z.enum(['release', 'dev']),
|
|
59
|
+
installForm: z.enum(['desktop', 'npm', 'other']),
|
|
60
|
+
os: z.enum(['linux', 'darwin', 'win32', 'android', 'other']),
|
|
61
|
+
/** Major OS release only (e.g. "6", "10", "24"). */
|
|
62
|
+
osRelease: z.string().max(20),
|
|
63
|
+
arch: z.string().max(20),
|
|
64
|
+
/** Null when the sender is not Node (the desktop shell during setup). */
|
|
65
|
+
nodeMajor: z.number().int().nullable(),
|
|
66
|
+
uiLang: z.enum(['en', 'zh', 'other']),
|
|
67
|
+
});
|
|
68
|
+
// ── Crash ───────────────────────────────────────────────
|
|
69
|
+
export const CRASH_COMPONENTS = ['server', 'daemon', 'web', 'desktop', 'android'];
|
|
70
|
+
export const CRASH_KINDS = [
|
|
71
|
+
'uncaughtException', 'unhandledRejection', 'childExit', 'renderError', 'windowError', 'panic',
|
|
72
|
+
];
|
|
73
|
+
export const CLIENT_KINDS = ['desktop', 'android', 'browser'];
|
|
74
|
+
export const CrashEventSchema = z.object({
|
|
75
|
+
type: z.literal('crash'),
|
|
76
|
+
at: timestamp,
|
|
77
|
+
component: z.enum(CRASH_COMPONENTS),
|
|
78
|
+
kind: z.enum(CRASH_KINDS),
|
|
79
|
+
errorName: z.string().max(80),
|
|
80
|
+
message: shortText,
|
|
81
|
+
/** Redacted, at most 30 frames. */
|
|
82
|
+
stack: z.string().max(8_000),
|
|
83
|
+
/** Grouping key: error name + first Cortex-owned frame. */
|
|
84
|
+
groupKey: z.string().max(200),
|
|
85
|
+
uptimeS: nonNegative.nullable(),
|
|
86
|
+
/** Web only: route template such as `/session/:id`, never the concrete path. */
|
|
87
|
+
route: z.string().max(80).nullable(),
|
|
88
|
+
buildStamp: z.string().max(60).nullable(),
|
|
89
|
+
client: z.enum(CLIENT_KINDS).nullable(),
|
|
90
|
+
/** childExit only. */
|
|
91
|
+
exit: z.object({
|
|
92
|
+
code: z.number().int().nullable(),
|
|
93
|
+
signal: z.string().max(20).nullable(),
|
|
94
|
+
backoffMs: count,
|
|
95
|
+
}).nullable(),
|
|
96
|
+
/** Same-group crashes rate-limited away since the previous one of this group was sent. */
|
|
97
|
+
suppressed: count,
|
|
98
|
+
});
|
|
99
|
+
// ── Heartbeat ───────────────────────────────────────────
|
|
100
|
+
export const HeartbeatEventSchema = z.object({
|
|
101
|
+
type: z.literal('heartbeat'),
|
|
102
|
+
at: timestamp,
|
|
103
|
+
backends: z.array(z.enum(['claude', 'pi'])).max(2),
|
|
104
|
+
claudeBilling: z.enum(['plan', 'api', 'none']),
|
|
105
|
+
/** Normalized PI provider ids that have usable auth. */
|
|
106
|
+
piProviders: z.array(IDENT).max(60),
|
|
107
|
+
projects: count,
|
|
108
|
+
onlineClients: count,
|
|
109
|
+
clientPlatforms: z.partialRecord(z.enum(['linux', 'darwin', 'win32', 'other']), count),
|
|
110
|
+
activeSessions24h: count,
|
|
111
|
+
uptimeH: nonNegative,
|
|
112
|
+
/** A fixed handful of boolean settings chosen by the server (e.g. teamEnabled). */
|
|
113
|
+
settings: z.record(IDENT, z.boolean()),
|
|
114
|
+
});
|
|
115
|
+
// ── Upgrade / migration ─────────────────────────────────
|
|
116
|
+
export const UPGRADE_FAILURE_CLASSES = ['network', 'permission', 'npm', 'disk', 'timeout', 'other'];
|
|
117
|
+
export const UpgradeEventSchema = z.object({
|
|
118
|
+
type: z.literal('upgrade'),
|
|
119
|
+
at: timestamp,
|
|
120
|
+
from: version,
|
|
121
|
+
to: version,
|
|
122
|
+
method: z.enum(['auto', 'prompt', 'manual']),
|
|
123
|
+
/**
|
|
124
|
+
* installed / failed: the npm step's outcome. confirmed / unconfirmed: whether the next boot
|
|
125
|
+
* runs `to`. version-changed: a boot found a different version with no recorded upgrade.
|
|
126
|
+
*/
|
|
127
|
+
stage: z.enum(['installed', 'failed', 'confirmed', 'unconfirmed', 'version-changed']),
|
|
128
|
+
durationS: nonNegative.nullable(),
|
|
129
|
+
failure: z.object({ class: z.enum(UPGRADE_FAILURE_CLASSES), message: shortText }).nullable(),
|
|
130
|
+
});
|
|
131
|
+
export const MigrationFailureEventSchema = z.object({
|
|
132
|
+
type: z.literal('migration_failure'),
|
|
133
|
+
at: timestamp,
|
|
134
|
+
migration: IDENT,
|
|
135
|
+
errorClass: z.enum(['io', 'parse', 'permission', 'other']),
|
|
136
|
+
message: shortText,
|
|
137
|
+
});
|
|
138
|
+
// ── Onboarding funnel ───────────────────────────────────
|
|
139
|
+
/** Desktop-setup steps are sent by the native shell before any server exists. */
|
|
140
|
+
export const DESKTOP_SETUP_STEPS = [
|
|
141
|
+
'setup_started', 'server_installed', 'server_install_failed', 'init_completed', 'init_failed',
|
|
142
|
+
'daemon_started', 'daemon_start_failed',
|
|
143
|
+
];
|
|
144
|
+
export const SERVER_FUNNEL_STEPS = [
|
|
145
|
+
'server_init_completed', 'provider_authed', 'first_session', 'first_turn_completed',
|
|
146
|
+
'first_remote_client', 'first_worker', 'first_schedule',
|
|
147
|
+
];
|
|
148
|
+
export const SETUP_FAILURE_CLASSES = ['network', 'permission', 'disk', 'timeout', 'cancelled', 'other'];
|
|
149
|
+
export const FunnelEventSchema = z.object({
|
|
150
|
+
type: z.literal('funnel'),
|
|
151
|
+
at: timestamp,
|
|
152
|
+
source: z.enum(['desktop-setup', 'server']),
|
|
153
|
+
step: z.enum([...DESKTOP_SETUP_STEPS, ...SERVER_FUNNEL_STEPS]),
|
|
154
|
+
/** provider_authed: the backend; *_failed: one of SETUP_FAILURE_CLASSES; otherwise null. */
|
|
155
|
+
detail: IDENT.nullable(),
|
|
156
|
+
});
|
|
157
|
+
// ── Daily rollup ────────────────────────────────────────
|
|
158
|
+
export const TURN_FAILURE_CLASSES = ['auth', 'rate_limit', 'network', 'adapter_crash', 'timeout', 'other'];
|
|
159
|
+
export const TurnHealthRowSchema = z.object({
|
|
160
|
+
backend: z.enum(['claude', 'pi']),
|
|
161
|
+
provider: IDENT,
|
|
162
|
+
model: IDENT,
|
|
163
|
+
billing: z.enum(['plan', 'api']).nullable(),
|
|
164
|
+
/** API kind of a custom provider (e.g. openai-completions); null otherwise. */
|
|
165
|
+
customApi: IDENT.nullable(),
|
|
166
|
+
outcomes: z.object({ completed: count, failed: count, cancelled: count, rateLimited: count }),
|
|
167
|
+
failures: z.partialRecord(z.enum(TURN_FAILURE_CLASSES), count),
|
|
168
|
+
retries: count,
|
|
169
|
+
fallbacks: count,
|
|
170
|
+
ttftMs: histogram('ttftMs'),
|
|
171
|
+
durationS: histogram('turnDurationS'),
|
|
172
|
+
contextPctAtEnd: histogram('contextPct'),
|
|
173
|
+
compactions: z.object({ auto: count, manual: count }),
|
|
174
|
+
tokens: z.object({ input: count, output: count, cacheRead: count, cacheWrite: count }),
|
|
175
|
+
});
|
|
176
|
+
export const FEATURE_COUNTERS = [
|
|
177
|
+
'session_created', 'worker_spawned', 'subagent_run', 'board_opened', 'schedule_created',
|
|
178
|
+
'schedule_fired', 'waitpoint_created', 'waitpoint_signaled', 'browser_session', 'plan_submitted',
|
|
179
|
+
'plan_approved', 'plan_rejected', 'ask_user_asked', 'ask_user_answered', 'remote_client_connected',
|
|
180
|
+
];
|
|
181
|
+
export const MESSAGE_CHANNELS = ['desktop', 'android', 'browser', 'feishu', 'slack', 'tui', 'other'];
|
|
182
|
+
const outcomeCounts = z.object({ completed: count, failed: count, cancelled: count });
|
|
183
|
+
export const DailyEventSchema = z.object({
|
|
184
|
+
type: z.literal('daily'),
|
|
185
|
+
/** The UTC day the counts cover. */
|
|
186
|
+
day,
|
|
187
|
+
turns: z.array(TurnHealthRowSchema).max(100),
|
|
188
|
+
features: z.partialRecord(z.enum(FEATURE_COUNTERS), count),
|
|
189
|
+
messagesByChannel: z.partialRecord(z.enum(MESSAGE_CHANNELS), count),
|
|
190
|
+
/** Counts per UI mutation op name (`ui.mutate-invoked`). */
|
|
191
|
+
uiOps: z.record(IDENT, count),
|
|
192
|
+
tools: z.array(z.object({ name: IDENT, calls: count, errors: count })).max(200),
|
|
193
|
+
agent: z.object({
|
|
194
|
+
userInterrupts: count,
|
|
195
|
+
superseded: count,
|
|
196
|
+
turnsPerSession: histogram('turnsPerSession'),
|
|
197
|
+
workers: outcomeCounts,
|
|
198
|
+
subagents: outcomeCounts,
|
|
199
|
+
}),
|
|
200
|
+
perf: z.object({
|
|
201
|
+
/** One entry per boot that day (at most 10): phase name → milliseconds. */
|
|
202
|
+
startups: z.array(z.record(IDENT, nonNegative)).max(10),
|
|
203
|
+
eventLoop: z.object({ windows: count, p99MedianMs: nonNegative, p99MaxMs: nonNegative }),
|
|
204
|
+
web: z.object({
|
|
205
|
+
loads: count,
|
|
206
|
+
ttfbMs: histogram('webLoadMs'),
|
|
207
|
+
firstRenderMs: histogram('webLoadMs'),
|
|
208
|
+
interactiveMs: histogram('webLoadMs'),
|
|
209
|
+
}),
|
|
210
|
+
sseReconnects: count,
|
|
211
|
+
remoteClientDisconnects: count,
|
|
212
|
+
}),
|
|
213
|
+
errors: z.object({
|
|
214
|
+
/** `log.error` calls per logger module. */
|
|
215
|
+
byModule: z.record(IDENT, count),
|
|
216
|
+
samples: z.array(z.object({
|
|
217
|
+
module: IDENT,
|
|
218
|
+
groupKey: z.string().max(200),
|
|
219
|
+
message: shortText,
|
|
220
|
+
count,
|
|
221
|
+
})).max(5),
|
|
222
|
+
}),
|
|
223
|
+
});
|
|
224
|
+
// ── Batch ───────────────────────────────────────────────
|
|
225
|
+
export const TelemetryEventSchema = z.discriminatedUnion('type', [
|
|
226
|
+
CrashEventSchema,
|
|
227
|
+
HeartbeatEventSchema,
|
|
228
|
+
UpgradeEventSchema,
|
|
229
|
+
MigrationFailureEventSchema,
|
|
230
|
+
FunnelEventSchema,
|
|
231
|
+
DailyEventSchema,
|
|
232
|
+
]);
|
|
233
|
+
export const TelemetryBatchSchema = z.object({
|
|
234
|
+
envelope: TelemetryEnvelopeSchema,
|
|
235
|
+
events: z.array(TelemetryEventSchema).min(1).max(TELEMETRY_MAX_EVENTS_PER_BATCH),
|
|
236
|
+
});
|
|
237
|
+
// ── Web → server report (tRPC `telemetry.report`) ───────
|
|
238
|
+
// The web UI never talks to the Worker. It reports raw observations to its server, which
|
|
239
|
+
// redacts them, applies the master switch and folds them into crashes or the daily rollup.
|
|
240
|
+
// The client kind comes from the `x-cortex-client` request header, not from this payload.
|
|
241
|
+
export const WebTelemetryReportSchema = z.discriminatedUnion('kind', [
|
|
242
|
+
z.object({
|
|
243
|
+
kind: z.literal('crash'),
|
|
244
|
+
crashKind: z.enum(['renderError', 'windowError', 'unhandledRejection']),
|
|
245
|
+
errorName: z.string().max(200),
|
|
246
|
+
message: z.string().max(2_000),
|
|
247
|
+
stack: z.string().max(20_000),
|
|
248
|
+
route: z.string().max(80).nullable(),
|
|
249
|
+
buildStamp: z.string().max(60).nullable(),
|
|
250
|
+
uptimeS: nonNegative.nullable(),
|
|
251
|
+
}),
|
|
252
|
+
z.object({
|
|
253
|
+
/** A native shell panic recorded on a previous run, forwarded once on the next launch. */
|
|
254
|
+
kind: z.literal('native_crash'),
|
|
255
|
+
component: z.enum(['desktop', 'android']),
|
|
256
|
+
at: timestamp,
|
|
257
|
+
message: z.string().max(2_000),
|
|
258
|
+
stack: z.string().max(20_000),
|
|
259
|
+
appVersion: version,
|
|
260
|
+
}),
|
|
261
|
+
z.object({
|
|
262
|
+
kind: z.literal('load'),
|
|
263
|
+
ttfbMs: nonNegative.nullable(),
|
|
264
|
+
firstRenderMs: nonNegative.nullable(),
|
|
265
|
+
interactiveMs: nonNegative.nullable(),
|
|
266
|
+
}),
|
|
267
|
+
z.object({ kind: z.literal('sse_reconnect'), count: z.number().int().min(1).max(1_000) }),
|
|
268
|
+
]);
|
|
269
|
+
/** Request header the web UI sets on every server call so usage can be split by client. */
|
|
270
|
+
export const CLIENT_KIND_HEADER = 'x-cortex-client';
|
|
271
|
+
/** Init answers field (`cortex init --json`): the desktop shell passes its choice and id. */
|
|
272
|
+
export const InitTelemetryAnswerSchema = z.object({
|
|
273
|
+
enabled: z.boolean(),
|
|
274
|
+
installId: z.uuid().optional(),
|
|
275
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { HeartbeatEvent, TelemetryEvent } from './schema.js';
|
|
2
|
+
import { type FetchLike } from './uploader.js';
|
|
3
|
+
export interface TelemetryServiceOptions {
|
|
4
|
+
/** Builds the daily heartbeat; null skips this round. */
|
|
5
|
+
collectHeartbeat: () => Promise<HeartbeatEvent | null>;
|
|
6
|
+
fetchImpl?: FetchLike;
|
|
7
|
+
now?: () => number;
|
|
8
|
+
/** Delay after boot before the first heartbeat or rollup upload. */
|
|
9
|
+
firstDelayMs?: number;
|
|
10
|
+
}
|
|
11
|
+
/** Hooks other telemetry modules register for the moments the service drives. */
|
|
12
|
+
export interface TelemetryLifecycleHooks {
|
|
13
|
+
/** Persist in-memory aggregates (periodic tick and shutdown). */
|
|
14
|
+
persist?: () => void;
|
|
15
|
+
/** Turn completed days into outbox events. */
|
|
16
|
+
finalize?: (now: number) => void | Promise<void>;
|
|
17
|
+
/** Delete every local file the hook's module owns. */
|
|
18
|
+
wipe?: () => void;
|
|
19
|
+
}
|
|
20
|
+
export declare function registerTelemetryHooks(next: TelemetryLifecycleHooks): void;
|
|
21
|
+
/** Delete the outbox and every aggregate. The install id and state.json stay. */
|
|
22
|
+
export declare function wipeLocalTelemetry(): void;
|
|
23
|
+
/** Queue one event. Urgent events (crashes) trigger an upload within seconds. */
|
|
24
|
+
export declare function recordTelemetryEvent(event: TelemetryEvent, opts?: {
|
|
25
|
+
urgent?: boolean;
|
|
26
|
+
}): boolean;
|
|
27
|
+
/** Upload whatever the outbox holds. Never throws; concurrent calls share one attempt. */
|
|
28
|
+
export declare function flushTelemetry(): Promise<void>;
|
|
29
|
+
/** The periodic job: persist aggregates, then (after the boot delay) queue and upload. */
|
|
30
|
+
export declare function telemetryTick(): Promise<void>;
|
|
31
|
+
export declare function startTelemetry(options: TelemetryServiceOptions): void;
|
|
32
|
+
/** Shutdown: persist aggregates; queued events wait for the next boot. */
|
|
33
|
+
export declare function stopTelemetry(): void;
|
|
34
|
+
export declare function telemetryRunning(): boolean;
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { onSettingsChange } from '../../core/settings.js';
|
|
2
|
+
import { buildEnvelope } from './envelope.js';
|
|
3
|
+
import { telemetryGate, isTelemetryActive } from './gate.js';
|
|
4
|
+
import { appendToOutbox, settleOutbox, takeOutbox, wipeOutbox } from './outbox.js';
|
|
5
|
+
import { readTelemetryState, updateTelemetryState } from './state.js';
|
|
6
|
+
import { chunkEvents, postBatch, UploadBackoff } from './uploader.js';
|
|
7
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
8
|
+
const DEFAULT_FIRST_DELAY_MS = 10 * 60 * 1000;
|
|
9
|
+
const STARTUP_FLUSH_DELAY_MS = 30_000;
|
|
10
|
+
const URGENT_FLUSH_DELAY_MS = 2_000;
|
|
11
|
+
const hooks = [];
|
|
12
|
+
let backoff = new UploadBackoff();
|
|
13
|
+
let running = null;
|
|
14
|
+
let flushing = null;
|
|
15
|
+
let flushTimer = null;
|
|
16
|
+
let flushDueAt = 0;
|
|
17
|
+
export function registerTelemetryHooks(next) {
|
|
18
|
+
hooks.push(next);
|
|
19
|
+
}
|
|
20
|
+
function now() {
|
|
21
|
+
return running?.options.now?.() ?? Date.now();
|
|
22
|
+
}
|
|
23
|
+
function runHooks(pick) {
|
|
24
|
+
for (const hook of hooks) {
|
|
25
|
+
try {
|
|
26
|
+
pick(hook)?.();
|
|
27
|
+
}
|
|
28
|
+
catch { /* one module's failure never stops the others */ }
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** Delete the outbox and every aggregate. The install id and state.json stay. */
|
|
32
|
+
export function wipeLocalTelemetry() {
|
|
33
|
+
try {
|
|
34
|
+
wipeOutbox();
|
|
35
|
+
}
|
|
36
|
+
catch { /* best effort */ }
|
|
37
|
+
runHooks((hook) => hook.wipe);
|
|
38
|
+
}
|
|
39
|
+
/** Queue one event. Urgent events (crashes) trigger an upload within seconds. */
|
|
40
|
+
export function recordTelemetryEvent(event, opts = {}) {
|
|
41
|
+
if (!isTelemetryActive())
|
|
42
|
+
return false;
|
|
43
|
+
const appended = appendToOutbox(event);
|
|
44
|
+
if (appended && opts.urgent)
|
|
45
|
+
scheduleFlush(URGENT_FLUSH_DELAY_MS);
|
|
46
|
+
return appended;
|
|
47
|
+
}
|
|
48
|
+
/** Arm the flush timer; an earlier deadline (a crash during the startup delay) replaces a later one. */
|
|
49
|
+
function scheduleFlush(delayMs) {
|
|
50
|
+
const dueAt = now() + delayMs;
|
|
51
|
+
if (!running || (flushTimer && flushDueAt <= dueAt))
|
|
52
|
+
return;
|
|
53
|
+
if (flushTimer)
|
|
54
|
+
clearTimeout(flushTimer);
|
|
55
|
+
flushDueAt = dueAt;
|
|
56
|
+
flushTimer = setTimeout(() => {
|
|
57
|
+
flushTimer = null;
|
|
58
|
+
void flushTelemetry();
|
|
59
|
+
}, delayMs);
|
|
60
|
+
flushTimer.unref?.();
|
|
61
|
+
}
|
|
62
|
+
async function sendAll(gate, events) {
|
|
63
|
+
const batches = chunkEvents(events);
|
|
64
|
+
for (let i = 0; i < batches.length; i += 1) {
|
|
65
|
+
const envelope = buildEnvelope(gate.channel, new Date(now()));
|
|
66
|
+
const outcome = await postBatch(gate.endpoint, envelope, batches[i], running?.options.fetchImpl);
|
|
67
|
+
if (outcome === 'retry') {
|
|
68
|
+
backoff.failed();
|
|
69
|
+
return batches.slice(i).flat();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
backoff.succeeded();
|
|
73
|
+
return [];
|
|
74
|
+
}
|
|
75
|
+
async function doFlush() {
|
|
76
|
+
const gate = telemetryGate();
|
|
77
|
+
if (!gate.active || !gate.endpoint || !backoff.ready())
|
|
78
|
+
return;
|
|
79
|
+
const events = takeOutbox();
|
|
80
|
+
settleOutbox(events.length === 0 ? [] : await sendAll(gate, events));
|
|
81
|
+
}
|
|
82
|
+
/** Upload whatever the outbox holds. Never throws; concurrent calls share one attempt. */
|
|
83
|
+
export function flushTelemetry() {
|
|
84
|
+
flushing ??= doFlush().catch(() => undefined).finally(() => { flushing = null; });
|
|
85
|
+
return flushing;
|
|
86
|
+
}
|
|
87
|
+
async function queueHeartbeatIfDue() {
|
|
88
|
+
const last = Date.parse(readTelemetryState().lastHeartbeatAt ?? '') || 0;
|
|
89
|
+
if (!running || now() - last < DAY_MS)
|
|
90
|
+
return;
|
|
91
|
+
const heartbeat = await running.options.collectHeartbeat().catch(() => null);
|
|
92
|
+
if (!heartbeat || !recordTelemetryEvent(heartbeat))
|
|
93
|
+
return;
|
|
94
|
+
updateTelemetryState((state) => ({ ...state, lastHeartbeatAt: new Date(now()).toISOString() }));
|
|
95
|
+
}
|
|
96
|
+
async function finalizeAll(at) {
|
|
97
|
+
for (const hook of hooks) {
|
|
98
|
+
try {
|
|
99
|
+
await hook.finalize?.(at);
|
|
100
|
+
}
|
|
101
|
+
catch { /* the next tick retries */ }
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** The periodic job: persist aggregates, then (after the boot delay) queue and upload. */
|
|
105
|
+
export async function telemetryTick() {
|
|
106
|
+
if (!isTelemetryActive())
|
|
107
|
+
return wipeLocalTelemetry();
|
|
108
|
+
runHooks((hook) => hook.persist);
|
|
109
|
+
if (!running || now() - running.bootAt < firstDelayMs(running.options))
|
|
110
|
+
return;
|
|
111
|
+
await finalizeAll(now());
|
|
112
|
+
await queueHeartbeatIfDue();
|
|
113
|
+
await flushTelemetry();
|
|
114
|
+
}
|
|
115
|
+
function firstDelayMs(options) {
|
|
116
|
+
if (options.firstDelayMs !== undefined)
|
|
117
|
+
return options.firstDelayMs;
|
|
118
|
+
const fromEnv = Number.parseInt(process.env.CORTEX_TELEMETRY_FIRST_DELAY_S ?? '', 10);
|
|
119
|
+
return Number.isFinite(fromEnv) && fromEnv >= 0 ? fromEnv * 1000 : DEFAULT_FIRST_DELAY_MS;
|
|
120
|
+
}
|
|
121
|
+
function onSwitchChanged(changed) {
|
|
122
|
+
if (changed.includes('telemetryEnabled') && !isTelemetryActive())
|
|
123
|
+
wipeLocalTelemetry();
|
|
124
|
+
}
|
|
125
|
+
export function startTelemetry(options) {
|
|
126
|
+
if (running)
|
|
127
|
+
return;
|
|
128
|
+
running = { options, bootAt: options.now?.() ?? Date.now(), unsubscribe: onSettingsChange(onSwitchChanged) };
|
|
129
|
+
backoff = new UploadBackoff(() => now());
|
|
130
|
+
if (!isTelemetryActive())
|
|
131
|
+
return wipeLocalTelemetry();
|
|
132
|
+
scheduleFlush(STARTUP_FLUSH_DELAY_MS);
|
|
133
|
+
}
|
|
134
|
+
/** Shutdown: persist aggregates; queued events wait for the next boot. */
|
|
135
|
+
export function stopTelemetry() {
|
|
136
|
+
if (flushTimer)
|
|
137
|
+
clearTimeout(flushTimer);
|
|
138
|
+
flushTimer = null;
|
|
139
|
+
running?.unsubscribe();
|
|
140
|
+
running = null;
|
|
141
|
+
if (isTelemetryActive())
|
|
142
|
+
runHooks((hook) => hook.persist);
|
|
143
|
+
}
|
|
144
|
+
export function telemetryRunning() {
|
|
145
|
+
return running !== null;
|
|
146
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface PendingUpgrade {
|
|
2
|
+
from: string;
|
|
3
|
+
to: string;
|
|
4
|
+
method: 'auto' | 'prompt' | 'manual';
|
|
5
|
+
startedAt: string;
|
|
6
|
+
}
|
|
7
|
+
/** Small cross-boot facts; survives a telemetry wipe (it holds nothing worth deleting). */
|
|
8
|
+
export interface TelemetryState {
|
|
9
|
+
lastHeartbeatAt: string | null;
|
|
10
|
+
/** The version the previous boot ran, to spot upgrades no installer announced. */
|
|
11
|
+
lastVersion: string | null;
|
|
12
|
+
funnelSent: string[];
|
|
13
|
+
pendingUpgrade: PendingUpgrade | null;
|
|
14
|
+
}
|
|
15
|
+
export declare function readTelemetryState(file?: string): TelemetryState;
|
|
16
|
+
/** Read-modify-write; never throws (an unwritable home just forgets). */
|
|
17
|
+
export declare function updateTelemetryState(change: (state: TelemetryState) => TelemetryState, file?: string): TelemetryState;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { STATE_FILE } from './paths.js';
|
|
4
|
+
const EMPTY = {
|
|
5
|
+
lastHeartbeatAt: null, lastVersion: null, funnelSent: [], pendingUpgrade: null,
|
|
6
|
+
};
|
|
7
|
+
export function readTelemetryState(file = STATE_FILE) {
|
|
8
|
+
try {
|
|
9
|
+
const raw = JSON.parse(readFileSync(file, 'utf8'));
|
|
10
|
+
return {
|
|
11
|
+
...EMPTY,
|
|
12
|
+
...raw,
|
|
13
|
+
funnelSent: Array.isArray(raw.funnelSent) ? raw.funnelSent.filter((s) => typeof s === 'string') : [],
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return { ...EMPTY };
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** Read-modify-write; never throws (an unwritable home just forgets). */
|
|
21
|
+
export function updateTelemetryState(change, file = STATE_FILE) {
|
|
22
|
+
const next = change(readTelemetryState(file));
|
|
23
|
+
try {
|
|
24
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
25
|
+
writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`, 'utf8');
|
|
26
|
+
}
|
|
27
|
+
catch { /* best effort */ }
|
|
28
|
+
return next;
|
|
29
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { RunObserver, RunRequest } from '../runs/request.js';
|
|
2
|
+
import { type TURN_FAILURE_CLASSES } from './schema.js';
|
|
3
|
+
type FailureClass = (typeof TURN_FAILURE_CLASSES)[number];
|
|
4
|
+
type TerminalStatus = 'completed' | 'failed' | 'cancelled' | 'rate-limited';
|
|
5
|
+
export interface RunTerminalFacts {
|
|
6
|
+
status: TerminalStatus;
|
|
7
|
+
error?: Error;
|
|
8
|
+
durationS: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function classifyTurnFailure(message: string): FailureClass;
|
|
11
|
+
export interface RunTelemetry {
|
|
12
|
+
observer: RunObserver;
|
|
13
|
+
finish(facts: RunTerminalFacts): void;
|
|
14
|
+
}
|
|
15
|
+
/** Per-run collector: an observer for the run's events and a hook for its terminal state. */
|
|
16
|
+
export declare function createRunTelemetry(request: RunRequest): RunTelemetry;
|
|
17
|
+
export {};
|