@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.
Files changed (194) hide show
  1. package/README.md +10 -6
  2. package/defaults/context/projects/AGENTS.md +1 -1
  3. package/defaults/gitignore +3 -3
  4. package/defaults/hooks/new-session-hook.mjs +1 -1
  5. package/defaults/hooks/status-md-guard.mjs +6 -6
  6. package/defaults/plugins/cortex-system/plugin.json +1 -1
  7. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +16 -9
  8. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +2 -2
  9. package/defaults/rules/agents-md.md +1 -1
  10. package/defaults/rules/issues-md.md +1 -1
  11. package/defaults/rules/meta-conventions.md +3 -3
  12. package/defaults/rules/mission-md.md +1 -1
  13. package/defaults/rules/status-md.md +1 -1
  14. package/dist/agent-adapter/claude/bg-task-tracker.d.ts +3 -1
  15. package/dist/agent-adapter/claude/bg-task-tracker.js +6 -2
  16. package/dist/agent-adapter/claude/mcp-config.js +11 -0
  17. package/dist/agent-adapter/claude/turn-machine.d.ts +2 -1
  18. package/dist/agent-adapter/claude/turn-machine.js +8 -5
  19. package/dist/agent-adapter/continuation-phase.d.ts +6 -3
  20. package/dist/agent-adapter/continuation-phase.js +8 -3
  21. package/dist/agent-adapter/run-events.d.ts +4 -0
  22. package/dist/agent-adapter/types.d.ts +9 -2
  23. package/dist/build-info.json +1 -0
  24. package/dist/client-bundle/client.mjs +10 -5
  25. package/dist/client-bundle/manifest.json +2 -2
  26. package/dist/core/claude-credentials.d.ts +6 -0
  27. package/dist/core/claude-credentials.js +11 -0
  28. package/dist/core/gateway-generator.d.ts +17 -0
  29. package/dist/core/gateway-generator.js +42 -4
  30. package/dist/core/hook-bus.d.ts +1 -1
  31. package/dist/core/hook-bus.js +1 -8
  32. package/dist/core/locales/en.d.ts +1 -0
  33. package/dist/core/locales/slices/init.d.ts +1 -0
  34. package/dist/core/locales/slices/init.js +2 -0
  35. package/dist/core/log.d.ts +3 -0
  36. package/dist/core/log.js +18 -1
  37. package/dist/core/settings-spec.d.ts +5 -0
  38. package/dist/core/settings-spec.js +4 -0
  39. package/dist/core/types/agent-types.d.ts +3 -1
  40. package/dist/core/types/environment-types.d.ts +1 -6
  41. package/dist/domain/agents/environments/registry.js +3 -2
  42. package/dist/domain/agents/environments/schema.d.ts +3 -2
  43. package/dist/domain/agents/environments/schema.js +4 -3
  44. package/dist/domain/auth/auth-watch.js +48 -18
  45. package/dist/domain/mcp/tools/context.d.ts +0 -1
  46. package/dist/domain/mcp/tools/context.js +0 -1
  47. package/dist/domain/monitor/event-loop-monitor.d.ts +2 -0
  48. package/dist/domain/monitor/event-loop-monitor.js +5 -1
  49. package/dist/domain/plugins/authoring.d.ts +8 -1
  50. package/dist/domain/plugins/authoring.js +24 -9
  51. package/dist/domain/plugins/runtime-gc.d.ts +7 -0
  52. package/dist/domain/plugins/runtime-gc.js +52 -19
  53. package/dist/domain/plugins/runtime.js +2 -1
  54. package/dist/domain/remote/client-bootstrap.js +1 -1
  55. package/dist/domain/remote/client-manager.js +6 -1
  56. package/dist/domain/runs/retryable-errors.js +3 -1
  57. package/dist/domain/runs/service.d.ts +0 -9
  58. package/dist/domain/runs/service.js +29 -15
  59. package/dist/domain/scheduling/builtin-job-controller.d.ts +3 -1
  60. package/dist/domain/scheduling/builtin-job-controller.js +5 -2
  61. package/dist/domain/scheduling/builtin-jobs.js +7 -0
  62. package/dist/domain/scheduling/scheduler.js +14 -5
  63. package/dist/domain/system/server-update-check.js +2 -1
  64. package/dist/domain/telemetry/bus-collector.d.ts +3 -0
  65. package/dist/domain/telemetry/bus-collector.js +22 -0
  66. package/dist/domain/telemetry/child-exit.d.ts +11 -0
  67. package/dist/domain/telemetry/child-exit.js +36 -0
  68. package/dist/domain/telemetry/client-kind.d.ts +4 -0
  69. package/dist/domain/telemetry/client-kind.js +7 -0
  70. package/dist/domain/telemetry/crash-limits.d.ts +15 -0
  71. package/dist/domain/telemetry/crash-limits.js +50 -0
  72. package/dist/domain/telemetry/crash.d.ts +25 -0
  73. package/dist/domain/telemetry/crash.js +70 -0
  74. package/dist/domain/telemetry/daily-upload.d.ts +5 -0
  75. package/dist/domain/telemetry/daily-upload.js +20 -0
  76. package/dist/domain/telemetry/daily.d.ts +5 -0
  77. package/dist/domain/telemetry/daily.js +104 -0
  78. package/dist/domain/telemetry/endpoint.d.ts +7 -0
  79. package/dist/domain/telemetry/endpoint.js +40 -0
  80. package/dist/domain/telemetry/envelope.d.ts +6 -0
  81. package/dist/domain/telemetry/envelope.js +35 -0
  82. package/dist/domain/telemetry/error-digest.d.ts +7 -0
  83. package/dist/domain/telemetry/error-digest.js +43 -0
  84. package/dist/domain/telemetry/funnel.d.ts +6 -0
  85. package/dist/domain/telemetry/funnel.js +22 -0
  86. package/dist/domain/telemetry/gate.d.ts +19 -0
  87. package/dist/domain/telemetry/gate.js +67 -0
  88. package/dist/domain/telemetry/heartbeat.d.ts +17 -0
  89. package/dist/domain/telemetry/heartbeat.js +49 -0
  90. package/dist/domain/telemetry/info.d.ts +9 -0
  91. package/dist/domain/telemetry/info.js +12 -0
  92. package/dist/domain/telemetry/init-answer.d.ts +12 -0
  93. package/dist/domain/telemetry/init-answer.js +42 -0
  94. package/dist/domain/telemetry/install-id.d.ts +5 -0
  95. package/dist/domain/telemetry/install-id.js +42 -0
  96. package/dist/domain/telemetry/normalize.d.ts +33 -0
  97. package/dist/domain/telemetry/normalize.js +88 -0
  98. package/dist/domain/telemetry/outbox.d.ts +18 -0
  99. package/dist/domain/telemetry/outbox.js +93 -0
  100. package/dist/domain/telemetry/panic-group.d.ts +4 -0
  101. package/dist/domain/telemetry/panic-group.js +51 -0
  102. package/dist/domain/telemetry/paths.d.ts +7 -0
  103. package/dist/domain/telemetry/paths.js +11 -0
  104. package/dist/domain/telemetry/redact.d.ts +18 -0
  105. package/dist/domain/telemetry/redact.js +109 -0
  106. package/dist/domain/telemetry/rollup-types.d.ts +81 -0
  107. package/dist/domain/telemetry/rollup-types.js +31 -0
  108. package/dist/domain/telemetry/rollup.d.ts +16 -0
  109. package/dist/domain/telemetry/rollup.js +102 -0
  110. package/dist/domain/telemetry/schema.d.ts +931 -0
  111. package/dist/domain/telemetry/schema.js +275 -0
  112. package/dist/domain/telemetry/service.d.ts +34 -0
  113. package/dist/domain/telemetry/service.js +146 -0
  114. package/dist/domain/telemetry/state.d.ts +17 -0
  115. package/dist/domain/telemetry/state.js +29 -0
  116. package/dist/domain/telemetry/turns.d.ts +17 -0
  117. package/dist/domain/telemetry/turns.js +176 -0
  118. package/dist/domain/telemetry/upgrade.d.ts +14 -0
  119. package/dist/domain/telemetry/upgrade.js +87 -0
  120. package/dist/domain/telemetry/uploader.d.ts +21 -0
  121. package/dist/domain/telemetry/uploader.js +82 -0
  122. package/dist/domain/telemetry/usage.d.ts +25 -0
  123. package/dist/domain/telemetry/usage.js +153 -0
  124. package/dist/domain/telemetry/web-report.d.ts +8 -0
  125. package/dist/domain/telemetry/web-report.js +15 -0
  126. package/dist/domain/ui-service/app-router.d.ts +69 -25
  127. package/dist/domain/ui-service/app-router.js +9 -2
  128. package/dist/domain/ui-service/input-schemas.d.ts +68 -4
  129. package/dist/domain/ui-service/input-schemas.js +9 -1
  130. package/dist/domain/ui-service/mutate/approvals.d.ts +3 -2
  131. package/dist/domain/ui-service/mutate/approvals.js +3 -2
  132. package/dist/domain/ui-service/mutate/plugin-packages.js +1 -1
  133. package/dist/domain/ui-service/mutate/telemetry.d.ts +5 -0
  134. package/dist/domain/ui-service/mutate/telemetry.js +6 -0
  135. package/dist/domain/ui-service/query/approvals.js +4 -3
  136. package/dist/domain/ui-service/query/machine-probe.d.ts +1 -1
  137. package/dist/domain/ui-service/query/machine-probe.js +3 -2
  138. package/dist/domain/ui-service/query/models.d.ts +3 -0
  139. package/dist/domain/ui-service/query/models.js +47 -30
  140. package/dist/domain/ui-service/query/plugin-source.js +4 -3
  141. package/dist/domain/ui-service/query/sessions.js +1 -0
  142. package/dist/domain/ui-service/query/telemetry.d.ts +3 -0
  143. package/dist/domain/ui-service/query/telemetry.js +4 -0
  144. package/dist/domain/ui-service/trpc.d.ts +8 -3
  145. package/dist/domain/ui-service/trpc.js +1 -1
  146. package/dist/domain/ui-service/types.d.ts +20 -2
  147. package/dist/domain/ui-service/ui-service.d.ts +33 -4
  148. package/dist/domain/ui-service/ui-service.js +19 -18
  149. package/dist/entry/app.js +20 -2
  150. package/dist/entry/cli-help.js +27 -14
  151. package/dist/entry/daemon.d.ts +1 -1
  152. package/dist/entry/daemon.js +86 -72
  153. package/dist/entry/init.d.ts +3 -0
  154. package/dist/entry/init.js +50 -28
  155. package/dist/entry/shutdown.js +3 -0
  156. package/dist/entry/signal-cli.js +8 -11
  157. package/dist/entry/start-ui-http.js +40 -18
  158. package/dist/entry/telemetry-wiring.d.ts +12 -0
  159. package/dist/entry/telemetry-wiring.js +56 -0
  160. package/dist/entry/ui-cli.d.ts +0 -11
  161. package/dist/entry/ui-cli.js +42 -33
  162. package/dist/events/event-types.d.ts +1 -4
  163. package/dist/orchestration/routing/message-router.js +2 -0
  164. package/dist/orchestration/routing/webhook.js +2 -0
  165. package/dist/orchestration/transcript-sink.d.ts +6 -0
  166. package/dist/orchestration/transcript-sink.js +17 -0
  167. package/dist/orchestration/waitpoint-ingress.js +3 -0
  168. package/dist/platform/ui-http/ui-auth-routes.d.ts +2 -0
  169. package/dist/platform/ui-http/ui-auth-routes.js +9 -2
  170. package/dist/platform/ui-http/ui-device-routes.d.ts +13 -0
  171. package/dist/platform/ui-http/ui-device-routes.js +81 -0
  172. package/dist/platform/ui-http/ui-devices.d.ts +24 -0
  173. package/dist/platform/ui-http/ui-devices.js +107 -0
  174. package/dist/platform/ui-http/ui-http-server.d.ts +10 -3
  175. package/dist/platform/ui-http/ui-http-server.js +11 -7
  176. package/dist/platform/ui-http/ui-pairing.d.ts +25 -0
  177. package/dist/platform/ui-http/ui-pairing.js +98 -0
  178. package/dist/store/gitignore-migration.d.ts +2 -0
  179. package/dist/store/gitignore-migration.js +16 -0
  180. package/dist/store/hook-registry.d.ts +1 -1
  181. package/dist/store/hook-registry.js +11 -6
  182. package/dist/store/session-registry-journal.js +3 -0
  183. package/dist/store/version-migrations.d.ts +5 -0
  184. package/dist/store/version-migrations.js +117 -80
  185. package/dist/tui/components/Dashboard.js +4 -3
  186. package/dist/tui/hooks/useDashboardData.js +1 -1
  187. package/package.json +3 -3
  188. package/web/dist/assets/{board-math-css-CB4GJ6qO.js → board-math-css-spk7yR6n.js} +1 -1
  189. package/web/dist/assets/index-BQ69u-92.css +1 -0
  190. package/web/dist/assets/{index-cIGFv27z.js → index-CKNLatCd.js} +1 -1
  191. package/web/dist/assets/index-CkzWfC98.js +525 -0
  192. package/web/dist/index.html +2 -2
  193. package/web/dist/assets/index-CaSZPg_H.css +0 -1
  194. package/web/dist/assets/index-CzOR7Edh.js +0 -522
@@ -9,6 +9,10 @@ const SWEEP_INTERVAL_MS = 60 * 60 * 1000;
9
9
  /** Only names this runtime creates (`safeNativeComposite` prefixes): projections and their temp
10
10
  * dirs are `plugin_*`, snapshot descriptors are `skill_*`. Anything else is left alone. */
11
11
  const OWNED_NAME = /^(plugin|skill)_/;
12
+ /** Claude MCP configs and remote-proxy configs are content-addressed `<sha256>.json` files; an
13
+ * interrupted write leaves its `.tmp.*` sibling behind. */
14
+ const OWNED_MCP_FILE = /^[0-9a-f]{64}\.json(?:\.tmp\..+)?$/;
15
+ const CLAUDE_MCP_DIRS = ['claude-mcp', 'claude-mcp-proxies'];
12
16
  const lastSweep = new Map();
13
17
  /** Mark a reused projection or snapshot as live, so a sweep in this or another process keeps it. */
14
18
  export function markInUse(directory) {
@@ -20,48 +24,77 @@ export function markInUse(directory) {
20
24
  // A failed touch only makes the directory eligible for a sweep, which rebuilds it on demand.
21
25
  }
22
26
  }
23
- function ownedChildren(parent) {
27
+ function ownedChildren(parent, owned) {
24
28
  try {
25
- return fs.readdirSync(parent).filter((name) => OWNED_NAME.test(name)).map((name) => path.join(parent, name));
29
+ return fs.readdirSync(parent).filter((name) => owned.test(name)).map((name) => path.join(parent, name));
26
30
  }
27
31
  catch {
28
32
  return [];
29
33
  }
30
34
  }
31
- function isStale(directory, now) {
35
+ function isStale(entry, now, isKind) {
32
36
  try {
33
- const stat = fs.lstatSync(directory);
34
- return stat.isDirectory() && now - stat.mtimeMs >= STALE_AFTER_MS;
37
+ const stat = fs.lstatSync(entry);
38
+ return isKind(stat) && now - stat.mtimeMs >= STALE_AFTER_MS;
35
39
  }
36
40
  catch {
37
41
  return false;
38
42
  }
39
43
  }
40
- /**
41
- * Remove projections and skill snapshots under `backendDir` that the current spawn does not use and
42
- * that nothing has touched for {@link STALE_AFTER_MS}. Every one is content-addressed, so a removed
43
- * directory a later spawn still wants is rebuilt at the same path. Returns what was removed.
44
- */
45
- export function sweepStaleRuntimeDirs(backendDir, inUse, now = Date.now()) {
46
- if (now - (lastSweep.get(backendDir) ?? 0) < SWEEP_INTERVAL_MS)
47
- return [];
48
- lastSweep.set(backendDir, now);
44
+ /** True when `key` was swept within the last interval; otherwise records this sweep. */
45
+ function throttled(key, now) {
46
+ if (now - (lastSweep.get(key) ?? 0) < SWEEP_INTERVAL_MS)
47
+ return true;
48
+ lastSweep.set(key, now);
49
+ return false;
50
+ }
51
+ function removeStale(entries, inUse, now, isKind) {
49
52
  const removed = [];
50
- for (const directory of [...ownedChildren(backendDir), ...ownedChildren(path.join(backendDir, 'skill-snapshots'))]) {
51
- if (inUse.has(directory) || !isStale(directory, now))
53
+ for (const entry of entries) {
54
+ if (inUse.has(entry) || !isStale(entry, now, isKind))
52
55
  continue;
53
56
  try {
54
- fs.rmSync(directory, { recursive: true, force: true });
55
- removed.push(directory);
57
+ fs.rmSync(entry, { recursive: true, force: true });
58
+ removed.push(entry);
56
59
  }
57
60
  catch (error) {
58
- log.warn(`Could not remove stale plugin runtime dir ${directory}: ${error.message}`);
61
+ log.warn(`Could not remove stale plugin runtime entry ${entry}: ${error.message}`);
59
62
  }
60
63
  }
64
+ return removed;
65
+ }
66
+ /**
67
+ * Remove projections and skill snapshots under `backendDir` that the current spawn does not use and
68
+ * that nothing has touched for {@link STALE_AFTER_MS}. Every one is content-addressed, so a removed
69
+ * directory a later spawn still wants is rebuilt at the same path. Returns what was removed.
70
+ */
71
+ export function sweepStaleRuntimeDirs(backendDir, inUse, now = Date.now()) {
72
+ if (throttled(backendDir, now))
73
+ return [];
74
+ const entries = [
75
+ ...ownedChildren(backendDir, OWNED_NAME),
76
+ ...ownedChildren(path.join(backendDir, 'skill-snapshots'), OWNED_NAME),
77
+ ];
78
+ const removed = removeStale(entries, inUse, now, (stat) => stat.isDirectory());
61
79
  if (removed.length > 0)
62
80
  log.info(`Removed ${removed.length} stale plugin runtime dir(s) under ${backendDir}`);
63
81
  return removed;
64
82
  }
83
+ /**
84
+ * Remove Claude MCP and remote-proxy configs under `runtimeDir` that nothing has touched for
85
+ * {@link STALE_AFTER_MS}. Every Claude spawn and every pooled-session reuse check rewrites or touches
86
+ * the files it resolves, and an idle Claude process exits within the hour, so a file this old is
87
+ * used by no running process. A later spawn that wants it writes it again at the same path.
88
+ */
89
+ export function sweepStaleClaudeMcpFiles(runtimeDir, now = Date.now()) {
90
+ if (throttled(path.join(runtimeDir, CLAUDE_MCP_DIRS[0]), now))
91
+ return [];
92
+ const entries = CLAUDE_MCP_DIRS.flatMap((dir) => ownedChildren(path.join(runtimeDir, dir), OWNED_MCP_FILE));
93
+ const removed = removeStale(entries, new Set(), now, (stat) => stat.isFile());
94
+ if (removed.length > 0)
95
+ log.info(`Removed ${removed.length} stale Claude MCP config(s) under ${runtimeDir}`);
96
+ return removed;
97
+ }
65
98
  /** Test hook: forget the per-directory sweep throttle. */
66
99
  export function _resetSweepThrottle() {
67
100
  lastSweep.clear();
@@ -9,7 +9,7 @@ import { loadPluginCatalog } from './catalog.js';
9
9
  import { defaultBuiltinPluginsDir, listBuiltinPluginIds } from './builtin.js';
10
10
  import { pluginMcpRuntime, portableNamespace, skillRoot, } from './catalog-types.js';
11
11
  import { listImmediateChildNames, realPath } from './fs-helpers.js';
12
- import { markInUse, sweepStaleRuntimeDirs } from './runtime-gc.js';
12
+ import { markInUse, sweepStaleClaudeMcpFiles, sweepStaleRuntimeDirs } from './runtime-gc.js';
13
13
  import { safeClaudeManifestVersion, safeNativeComposite } from '../../core/native-name.js';
14
14
  import { buildProjectedSkillTree, copyProjectedSkillTree, validateProjectedSkillTree, } from './skill-projection.js';
15
15
  const log = createLogger('plugin-runtime');
@@ -546,6 +546,7 @@ export function resolvePluginRuntime(options) {
546
546
  const portable = collectPortableDetails(classified.portableSelections, options.backend, runtimeDir, portableMcpEnabled(options.mcpComposition));
547
547
  warnLegacySkillCollisions(portable.skillClaims, classified.selectedLegacySkills);
548
548
  sweepStaleRuntimeDirs(path.join(runtimeDir, options.backend), directoriesInUse(portable.details));
549
+ sweepStaleClaudeMcpFiles(runtimeDir);
549
550
  const resolved = resolvedRuntime(options.backend, classified.items, portable.details);
550
551
  return withWarnings(resolved, [...classified.warnings, ...portable.warnings]);
551
552
  }
@@ -22,7 +22,7 @@ if (!serverHost) {
22
22
  }
23
23
  const serverPort = getArg('--server-port') || '3002';
24
24
  if (!sshHost) {
25
- log.error(`Usage: node --import tsx src/client-bootstrap.ts --host user@host --device-name NAME [options]
25
+ log.error(`Usage (from agent-server/): node --import tsx src/domain/remote/client-bootstrap.ts --host user@host --device-name NAME [options]
26
26
 
27
27
  Options:
28
28
  --host <user@host> SSH target (required)
@@ -5,6 +5,7 @@ import { AUTH_HEADER, getClientToken, timingSafeEqualStr } from '../../core/auth
5
5
  import { createLogger } from '../../core/log.js';
6
6
  import { claimStream, parseStreamId, cancelStreamsFor } from './reverse-stream.js';
7
7
  import { emitCortexEvent } from '../../core/hook-bus.js';
8
+ import { recordRemoteClientConnected, recordRemoteClientDisconnected } from '../telemetry/usage.js';
8
9
  const log = createLogger('client-manager');
9
10
  let updateHooks = null;
10
11
  function setClientUpdateHooks(hooks) { updateHooks = hooks; }
@@ -16,10 +17,13 @@ const pendingCommands = new Map();
16
17
  let wss = null;
17
18
  let heartbeatCheckInterval = null;
18
19
  let clientManagerPort = null;
20
+ const SHUTDOWN_REASON = 'Server shutting down';
19
21
  const HEARTBEAT_TIMEOUT_MS = 15_000; // 3 missed 5s heartbeats
20
22
  const DEFAULT_COMMAND_TIMEOUT_MS = 120_000; // 2 min for bash
21
23
  const FILE_COMMAND_TIMEOUT_MS = 30_000; // 30s for file operations
22
24
  function emitDisconnected(device, reason) {
25
+ if (reason !== SHUTDOWN_REASON)
26
+ recordRemoteClientDisconnected();
23
27
  const payload = reason ? { device, reason } : { device };
24
28
  void emitCortexEvent('cortex:client.disconnected', payload).catch(() => { });
25
29
  }
@@ -94,6 +98,7 @@ function registerHelloDevice(ws, msg, remoteAddress) {
94
98
  connectedAt: new Date(), lastHeartbeat: new Date(), bundleHash, ws,
95
99
  });
96
100
  log.info(`Device connected: ${device} (${platform})`);
101
+ recordRemoteClientConnected();
97
102
  void emitCortexEvent('cortex:client.connected', { device }).catch(() => { });
98
103
  applyReportedGpuCount(device, typeof msg.gpuCount === 'number' ? msg.gpuCount : null);
99
104
  try {
@@ -247,7 +252,7 @@ async function stopClientManager() {
247
252
  info.ws.close(1001, 'Server shutting down');
248
253
  }
249
254
  catch { }
250
- emitDisconnected(info.device, 'Server shutting down');
255
+ emitDisconnected(info.device, SHUTDOWN_REASON);
251
256
  }
252
257
  devices.clear();
253
258
  const server = wss;
@@ -11,6 +11,7 @@ const PERMANENT_PROVIDER_ERROR = /(?:invalid[_ ]request|forbidden|not found|requ
11
11
  const TRANSIENT_HTTP_STATUS = /(?:^(?:error\s*)?(?:408|500|502|503|504)\b|\bhttp(?: status)?\s*[:=]?\s*(?:408|500|502|503|504)\b|\bstatus(?: code)?\s*[:=]?\s*(?:408|500|502|503|504)\b)/i;
12
12
  const TRANSIENT_TRANSPORT_ERROR = /(?:fetch failed|econnreset|econnrefused|etimedout|eai_again|enotfound|socket hang up|connection (?:reset|refused|terminated|error)|upstream connection error|temporary failure in name resolution|(?:request|connection|connect|network|socket|tls|upstream).*tim(?:ed? out|eout))/i;
13
13
  const TRANSIENT_PROVIDER_GUIDANCE = /\byou can retry your request\b/i;
14
+ const TRANSIENT_MACHINE_ERROR = /\b(?:ENOSPC|EMFILE|ENFILE|EAGAIN)\b/i;
14
15
  export function isRetryableError(error) {
15
16
  const message = error?.message;
16
17
  if (!message || classifyAuthError(message) || PERMANENT_PROVIDER_ERROR.test(message))
@@ -18,5 +19,6 @@ export function isRetryableError(error) {
18
19
  return isApiRateLimitError(message)
19
20
  || TRANSIENT_HTTP_STATUS.test(message)
20
21
  || TRANSIENT_TRANSPORT_ERROR.test(message)
21
- || TRANSIENT_PROVIDER_GUIDANCE.test(message);
22
+ || TRANSIENT_PROVIDER_GUIDANCE.test(message)
23
+ || TRANSIENT_MACHINE_ERROR.test(message);
22
24
  }
@@ -1,12 +1,3 @@
1
1
  import { type AgentRun } from './run.js';
2
2
  import type { RunObserver, RunRequest } from './request.js';
3
- /**
4
- * Start one agent run: open its execution record, register it for cancellation, and return the
5
- * `AgentRun` that owns the rest of the lifecycle. This is the single entry point every surface is
6
- * meant to call.
7
- *
8
- * The run opens one attempt on its pooled engine session and feeds every signal through
9
- * one `RunEvent` stream. `teardownExecution` and the registry removal happen exactly once, from
10
- * the run's terminal handler.
11
- */
12
3
  export declare function startRun(request: RunRequest, observers: RunObserver[]): AgentRun;
@@ -2,6 +2,7 @@ import { runRegistry } from '../../core/run-registry.js';
2
2
  import { sessionBenchmarkMaxOutputTokens } from '../benchmark/session-evidence.js';
3
3
  import * as executionRegistry from '../executions/registry.js';
4
4
  import { AgentRunImpl } from './run.js';
5
+ import { createRunTelemetry } from '../telemetry/turns.js';
5
6
  /**
6
7
  * Start one agent run: open its execution record, register it for cancellation, and return the
7
8
  * `AgentRun` that owns the rest of the lifecycle. This is the single entry point every surface is
@@ -11,13 +12,14 @@ import { AgentRunImpl } from './run.js';
11
12
  * one `RunEvent` stream. `teardownExecution` and the registry removal happen exactly once, from
12
13
  * the run's terminal handler.
13
14
  */
14
- export function startRun(request, observers) {
15
- if (request.benchmark?.evidenceContext && request.session.sessionId) {
16
- request = { ...request, benchmarkMaxOutputTokens: request.benchmarkMaxOutputTokens
17
- ?? sessionBenchmarkMaxOutputTokens(request.session.sessionId) };
18
- }
19
- const startedAt = Date.now();
20
- const execution = executionRegistry.startLocalExecution({
15
+ function withBenchmarkCap(request) {
16
+ if (!request.benchmark?.evidenceContext || !request.session.sessionId)
17
+ return request;
18
+ return { ...request, benchmarkMaxOutputTokens: request.benchmarkMaxOutputTokens
19
+ ?? sessionBenchmarkMaxOutputTokens(request.session.sessionId) };
20
+ }
21
+ function openExecution(request) {
22
+ return executionRegistry.startLocalExecution({
21
23
  kind: request.context.executionKind,
22
24
  channel: request.context.channel,
23
25
  project: request.context.project,
@@ -29,19 +31,31 @@ export function startRun(request, observers) {
29
31
  label: request.prompt.text.substring(0, 60),
30
32
  scheduleTaskId: request.context.scheduleTaskId || null,
31
33
  });
34
+ }
35
+ function closeExecution(executionId, info) {
36
+ const { status, result, spend, error, durationS } = info;
37
+ executionRegistry.teardownExecution({
38
+ executionId, status, result, spend,
39
+ error: error ? { message: error.message } : null,
40
+ durationS,
41
+ });
42
+ runRegistry.remove(executionId);
43
+ }
44
+ export function startRun(request, observers) {
45
+ request = withBenchmarkCap(request);
46
+ const startedAt = Date.now();
47
+ const execution = openExecution(request);
48
+ // Anonymous product telemetry: one more observer, and the terminal facts (no-op when off).
49
+ const telemetry = createRunTelemetry(request);
32
50
  const run = new AgentRunImpl({
33
51
  request,
34
- observers,
52
+ observers: [...observers, telemetry.observer],
35
53
  executionId: execution.id,
36
54
  registry: runRegistry,
37
55
  startedAt,
38
- onTerminal: ({ status, result, spend, error, durationS }) => {
39
- executionRegistry.teardownExecution({
40
- executionId: execution.id, status, result, spend,
41
- error: error ? { message: error.message } : null,
42
- durationS,
43
- });
44
- runRegistry.remove(execution.id);
56
+ onTerminal: (info) => {
57
+ closeExecution(execution.id, info);
58
+ telemetry.finish(info);
45
59
  },
46
60
  });
47
61
  run.start();
@@ -2,7 +2,9 @@ export type BuiltinJobMode = 'serial' | 'detached';
2
2
  export interface BuiltinJobDefinition {
3
3
  name: string;
4
4
  enabledKey: string;
5
- intervalKey: string;
5
+ /** Setting that holds the interval; `fixedIntervalMs` instead for a job with no such setting. */
6
+ intervalKey?: string;
7
+ fixedIntervalMs?: number;
6
8
  mode: BuiltinJobMode;
7
9
  run: () => void | Promise<void>;
8
10
  }
@@ -1,3 +1,6 @@
1
+ function jobInterval(job, settings) {
2
+ return job.fixedIntervalMs ?? settings[job.intervalKey ?? ''];
3
+ }
1
4
  function clearJobTimer(state) {
2
5
  if (!state.timer)
3
6
  return;
@@ -39,7 +42,7 @@ class JobController {
39
42
  const state = this.states.get(job.name);
40
43
  const wasEnabled = state.enabled;
41
44
  const nextEnabled = settings[job.enabledKey] === true;
42
- const nextInterval = settings[job.intervalKey];
45
+ const nextInterval = jobInterval(job, settings);
43
46
  const intervalChanged = nextInterval !== state.intervalMs;
44
47
  state.enabled = nextEnabled;
45
48
  state.intervalMs = nextInterval;
@@ -63,7 +66,7 @@ class JobController {
63
66
  const settings = this.options.getSettings();
64
67
  if (!this.started || settings[job.enabledKey] !== true)
65
68
  return;
66
- state.intervalMs = settings[job.intervalKey];
69
+ state.intervalMs = jobInterval(job, settings);
67
70
  if (job.mode === 'serial')
68
71
  this.runSerial(job);
69
72
  else
@@ -3,6 +3,7 @@ import { getSettings, onSettingsChange } from '../../core/settings.js';
3
3
  import { usageService } from '../costs/usage-service.js';
4
4
  import { createBuiltinJobController } from './builtin-job-controller.js';
5
5
  import { regenAll } from '../memory/index-regen.js';
6
+ import { telemetryTick } from '../telemetry/service.js';
6
7
  const log = createLogger('builtin-jobs');
7
8
  let controller = null;
8
9
  function buildJobs() {
@@ -17,6 +18,12 @@ function buildJobs() {
17
18
  intervalKey: 'memoryIndexRegenIntervalMs', mode: 'serial',
18
19
  run: async () => { regenAll(); },
19
20
  },
21
+ {
22
+ // Persists the day's telemetry aggregates and uploads what is due (heartbeat, finished
23
+ // days, retries). The tick itself checks the full gate (env, sealed home, endpoint).
24
+ name: 'telemetry', enabledKey: 'telemetryEnabled', fixedIntervalMs: 5 * 60 * 1000, mode: 'serial',
25
+ run: telemetryTick,
26
+ },
20
27
  ];
21
28
  }
22
29
  export function startBuiltinJobs() {
@@ -1,4 +1,5 @@
1
1
  import { watch } from 'fs';
2
+ import { countFeature, recordScheduleCreated } from '../telemetry/usage.js';
2
3
  import { runShell } from '../../core/exec-async.js';
3
4
  import { t } from '../../core/i18n.js';
4
5
  import { Icons } from '../../core/icons.js';
@@ -136,6 +137,8 @@ class Scheduler {
136
137
  this._scheduleTask(task);
137
138
  }
138
139
  this._reportReload(added, removed.length, updated);
140
+ // Tasks another process (the CLI) wrote; ones this scheduler added are already armed.
141
+ recordScheduleCreated(added);
139
142
  }
140
143
  _reportReload(added, removed, updated) {
141
144
  if (!added && !removed && !updated)
@@ -146,6 +149,7 @@ class Scheduler {
146
149
  async add(spec) {
147
150
  const { task } = await addSchedule(this._repo, spec);
148
151
  this._scheduleTask(task);
152
+ recordScheduleCreated();
149
153
  return task;
150
154
  }
151
155
  // Remove a task by id. Returns true if found and removed.
@@ -270,11 +274,6 @@ class Scheduler {
270
274
  // Internal: invoke the runner for a task
271
275
  async _runTask(task) {
272
276
  log.info(`Firing task ${task.id} (${task.type}, dispatch=${task.dispatchType || 'llm'}, model=${task.selection?.model || 'default'}, project=${task.projectId}): "${task.message}"`);
273
- void emitCortexEvent('cortex:schedule.fired', {
274
- scheduleId: task.id,
275
- name: task.message,
276
- project: task.projectId,
277
- }).catch(() => { });
278
277
  try {
279
278
  await this._dispatchTask(task);
280
279
  }
@@ -284,6 +283,7 @@ class Scheduler {
284
283
  }
285
284
  async _dispatchTask(task) {
286
285
  if (!task.dispatchType) {
286
+ emitScheduleFired(task);
287
287
  await this.runner({
288
288
  message: `[Scheduled Task] ${task.message}`,
289
289
  projectId: task.projectId,
@@ -297,7 +297,16 @@ class Scheduler {
297
297
  log.warn(`Skipping task ${task.id}: unregistered dispatch type "${task.dispatchType}"`);
298
298
  return;
299
299
  }
300
+ emitScheduleFired(task);
300
301
  await handler({ channel: task.projectId, scheduleTaskId: task.id });
301
302
  }
302
303
  }
304
+ function emitScheduleFired(task) {
305
+ countFeature('schedule_fired');
306
+ void emitCortexEvent('cortex:schedule.fired', {
307
+ scheduleId: task.id,
308
+ name: task.id,
309
+ project: task.projectId,
310
+ }).catch(() => { });
311
+ }
303
312
  export { Scheduler };
@@ -6,6 +6,7 @@ import { runFile } from '../../core/exec-async.js';
6
6
  import { npmInvocation, withServerNpmPrefix } from '../../core/utils.js';
7
7
  import { loadUpdateState, saveUpdateState } from './update-state.js';
8
8
  import { ALWAYS_IDLE, createIdleInstaller } from './server-update-install.js';
9
+ import { trackInstall } from '../telemetry/upgrade.js';
9
10
  // ── Dev mode detection ──────────────────────────────────────────
10
11
  // In dev mode (CORTEX_REPO set), server auto-update is skipped entirely
11
12
  // because the developer manages the install directly.
@@ -75,7 +76,7 @@ export function createServerUpdateCoordinator(deps) {
75
76
  return new ServerUpdateCoordinator({
76
77
  prompt: deps.prompt,
77
78
  getLatest: deps.getLatest ?? defaultGetLatest,
78
- installWhenIdle: deps.installWhenIdle ?? createIdleInstaller(deps.idle ?? ALWAYS_IDLE, runNpmInstall),
79
+ installWhenIdle: deps.installWhenIdle ?? createIdleInstaller(deps.idle ?? ALWAYS_IDLE, trackInstall(runNpmInstall)),
79
80
  loadState: deps.loadState ?? loadUpdateState,
80
81
  saveState: deps.saveState ?? saveUpdateState,
81
82
  now: deps.now ?? defaultNow,
@@ -0,0 +1,3 @@
1
+ import type { EventBus } from '../../events/event-bus.js';
2
+ /** Fold the event bus's feature signals into the daily rollup. Returns the unsubscribe. */
3
+ export declare function subscribeTelemetryToBus(bus: EventBus): () => void;
@@ -0,0 +1,22 @@
1
+ import { countFeature, recordUiMutation } from './usage.js';
2
+ /** Fold the event bus's feature signals into the daily rollup. Returns the unsubscribe. */
3
+ export function subscribeTelemetryToBus(bus) {
4
+ const unsubscribers = [
5
+ bus.subscribe('ui.mutate-invoked', (event) => recordUiMutation(event.op, event.result?.ok === true, event.client)),
6
+ bus.subscribe('plan.submitted', (event) => { if (!event.dryRun)
7
+ countFeature('plan_submitted'); }),
8
+ bus.subscribe('ask-user.requested', (event) => { if (!event.dryRun)
9
+ countFeature('ask_user_asked'); }),
10
+ bus.subscribe('ask-user.answered', () => countFeature('ask_user_answered')),
11
+ bus.subscribe('session.interaction', (event) => {
12
+ if (event.kind !== 'plan-approval')
13
+ return;
14
+ if (event.status === 'approved')
15
+ countFeature('plan_approved');
16
+ if (event.status === 'rejected')
17
+ countFeature('plan_rejected');
18
+ }),
19
+ ];
20
+ return () => { for (const subscription of unsubscribers)
21
+ subscription.unsubscribe(); };
22
+ }
@@ -0,0 +1,11 @@
1
+ /** The daemon hands the next app process the facts of the previous one's unexpected exit. */
2
+ export declare const CHILD_EXIT_ENV = "CORTEX_CHILD_EXIT";
3
+ export interface ChildExitInfo {
4
+ code: number | null;
5
+ signal: string | null;
6
+ uptimeMs: number;
7
+ backoffMs: number;
8
+ }
9
+ export declare function encodeChildExit(info: ChildExitInfo): string;
10
+ /** At boot: report the crash the daemon recovered from, if any. */
11
+ export declare function captureChildExitFromEnv(env?: NodeJS.ProcessEnv): void;
@@ -0,0 +1,36 @@
1
+ import { captureCrash } from './crash.js';
2
+ /** The daemon hands the next app process the facts of the previous one's unexpected exit. */
3
+ export const CHILD_EXIT_ENV = 'CORTEX_CHILD_EXIT';
4
+ export function encodeChildExit(info) {
5
+ return JSON.stringify(info);
6
+ }
7
+ function decode(raw) {
8
+ if (!raw)
9
+ return null;
10
+ try {
11
+ const value = JSON.parse(raw);
12
+ if (typeof value.uptimeMs !== 'number' || typeof value.backoffMs !== 'number')
13
+ return null;
14
+ const code = Number.isInteger(value.code) ? value.code : null;
15
+ const signal = typeof value.signal === 'string' ? value.signal.slice(0, 20) : null;
16
+ return { code, signal, uptimeMs: Math.max(0, value.uptimeMs), backoffMs: Math.max(0, Math.round(value.backoffMs)) };
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ }
22
+ /** At boot: report the crash the daemon recovered from, if any. */
23
+ export function captureChildExitFromEnv(env = process.env) {
24
+ const info = decode(env[CHILD_EXIT_ENV]);
25
+ if (!info)
26
+ return;
27
+ captureCrash({
28
+ component: 'server',
29
+ kind: 'childExit',
30
+ errorName: 'ChildExit',
31
+ message: info.signal ? `signal ${info.signal}` : `exit code ${info.code ?? 'unknown'}`,
32
+ stack: '',
33
+ uptimeS: Math.round(info.uptimeMs / 1000),
34
+ exit: { code: info.code, signal: info.signal, backoffMs: info.backoffMs },
35
+ });
36
+ }
@@ -0,0 +1,4 @@
1
+ import { CLIENT_KINDS } from './schema.js';
2
+ export type ClientKind = (typeof CLIENT_KINDS)[number];
3
+ /** The `x-cortex-client` request header, or null when absent or unrecognized. */
4
+ export declare function parseClientKind(header: string | string[] | undefined): ClientKind | null;
@@ -0,0 +1,7 @@
1
+ import { CLIENT_KINDS } from './schema.js';
2
+ /** The `x-cortex-client` request header, or null when absent or unrecognized. */
3
+ export function parseClientKind(header) {
4
+ const raw = Array.isArray(header) ? header[0] : header;
5
+ const value = raw?.trim().toLowerCase();
6
+ return CLIENT_KINDS.includes(value ?? '') ? value : null;
7
+ }
@@ -0,0 +1,15 @@
1
+ export declare const CRASH_GROUP_INTERVAL_MS: number;
2
+ export declare const CRASH_DAILY_LIMIT = 20;
3
+ export declare const CRASH_LIMITS_FILE: string;
4
+ export interface CrashAdmission {
5
+ send: boolean;
6
+ /** Same-group crashes held back since the last one sent (reported on this one). */
7
+ suppressed: number;
8
+ }
9
+ /**
10
+ * One crash per group per hour, twenty per install per UTC day. Held-back crashes are only
11
+ * counted, and the count rides on the next crash of that group that goes out. Synchronous: the
12
+ * caller may be a process about to exit.
13
+ */
14
+ export declare function admitCrash(groupKey: string, now?: number, file?: string): CrashAdmission;
15
+ export declare function wipeCrashLimits(file?: string): void;
@@ -0,0 +1,50 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { TELEMETRY_DIR } from './paths.js';
4
+ export const CRASH_GROUP_INTERVAL_MS = 60 * 60 * 1000;
5
+ export const CRASH_DAILY_LIMIT = 20;
6
+ export const CRASH_LIMITS_FILE = path.join(TELEMETRY_DIR, 'crash-limits.json');
7
+ function read(file, day) {
8
+ try {
9
+ const state = JSON.parse(readFileSync(file, 'utf8'));
10
+ if (state.day === day && state.groups && typeof state.sentToday === 'number')
11
+ return state;
12
+ return { day, sentToday: 0, groups: state.groups ?? {} };
13
+ }
14
+ catch {
15
+ return { day, sentToday: 0, groups: {} };
16
+ }
17
+ }
18
+ function write(file, state, now) {
19
+ for (const [key, group] of Object.entries(state.groups)) {
20
+ if (now - group.lastSentAt > 24 * CRASH_GROUP_INTERVAL_MS && group.suppressed === 0)
21
+ delete state.groups[key];
22
+ }
23
+ try {
24
+ mkdirSync(path.dirname(file), { recursive: true });
25
+ writeFileSync(file, JSON.stringify(state), 'utf8');
26
+ }
27
+ catch { /* an unwritable home only loses the limiter */ }
28
+ }
29
+ /**
30
+ * One crash per group per hour, twenty per install per UTC day. Held-back crashes are only
31
+ * counted, and the count rides on the next crash of that group that goes out. Synchronous: the
32
+ * caller may be a process about to exit.
33
+ */
34
+ export function admitCrash(groupKey, now = Date.now(), file = CRASH_LIMITS_FILE) {
35
+ const state = read(file, new Date(now).toISOString().slice(0, 10));
36
+ const group = state.groups[groupKey] ?? { lastSentAt: 0, suppressed: 0 };
37
+ const tooSoon = now - group.lastSentAt < CRASH_GROUP_INTERVAL_MS;
38
+ if (tooSoon || state.sentToday >= CRASH_DAILY_LIMIT) {
39
+ state.groups[groupKey] = { ...group, suppressed: group.suppressed + 1 };
40
+ write(file, state, now);
41
+ return { send: false, suppressed: group.suppressed + 1 };
42
+ }
43
+ state.groups[groupKey] = { lastSentAt: now, suppressed: 0 };
44
+ state.sentToday += 1;
45
+ write(file, state, now);
46
+ return { send: true, suppressed: group.suppressed };
47
+ }
48
+ export function wipeCrashLimits(file = CRASH_LIMITS_FILE) {
49
+ rmSync(file, { force: true });
50
+ }
@@ -0,0 +1,25 @@
1
+ import type { ClientKind } from './client-kind.js';
2
+ import type { CrashEvent } from './schema.js';
3
+ export interface CrashInput {
4
+ component: CrashEvent['component'];
5
+ kind: CrashEvent['kind'];
6
+ errorName: string;
7
+ message: string;
8
+ stack: string;
9
+ uptimeS?: number | null;
10
+ route?: string | null;
11
+ buildStamp?: string | null;
12
+ client?: ClientKind | null;
13
+ exit?: CrashEvent['exit'];
14
+ at?: Date;
15
+ }
16
+ /** Name, message and stack of whatever was thrown, before redaction. */
17
+ export declare function describeThrown(error: unknown): Pick<CrashInput, 'errorName' | 'message' | 'stack'>;
18
+ /** Redact and shape a crash; the group key comes from the redacted stack. */
19
+ export declare function buildCrashEvent(input: CrashInput, suppressed?: number): CrashEvent;
20
+ /**
21
+ * Record a crash: rate-limited, appended synchronously, uploaded within seconds when the
22
+ * service runs in this process. Never throws.
23
+ */
24
+ export declare function captureCrash(input: CrashInput): void;
25
+ export declare function captureProcessCrash(component: 'server' | 'daemon', kind: 'uncaughtException' | 'unhandledRejection', error: unknown): void;