@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
@@ -80,6 +80,8 @@ import { DATA_DIR, CONFIG_DIR, INSTALL_ROOT, DAEMON_PID_FILE, DAEMON_CHILD_PID_F
80
80
  import { planFastInstall, applyFastInstall } from './fast-install.js';
81
81
  import { tryAcquireSingletonLock, releaseSingletonLock as releaseLock } from '../core/singleton-lock.js';
82
82
  import { ensureOwnBinsOnPath } from '../domain/system/own-bin-path.js';
83
+ import { captureProcessCrash } from '../domain/telemetry/crash.js';
84
+ import { CHILD_EXIT_ENV, encodeChildExit } from '../domain/telemetry/child-exit.js';
83
85
  import { finishRebuildStep, planRebuildProgress, settleRebuildProgress, startRebuildStep, writeRebuildProgress, } from '../core/rebuild-progress.js';
84
86
  // Load .env BEFORE reading any CORTEX_* env vars below. Mirrors app.ts §61 — the
85
87
  // daemon needs CORTEX_REPO (and potentially other vars) from .env, not just from
@@ -125,6 +127,7 @@ let pendingRebuild = null; // reason string if rebuild is deferred (busy or in-f
125
127
  let restarting = false; // true while restart() stop→start cycle is in progress
126
128
  let rebuilding = false; // true while runRebuildPipeline() is running
127
129
  let nextRestartReason = null; // forwarded to next child via CORTEX_RESTART_REASON
130
+ let nextChildExit = null; // forwarded via CORTEX_CHILD_EXIT (telemetry crash report)
128
131
  let watchMonitors = [];
129
132
  let rebuildProgress = null; // published pipeline state (file + child IPC)
130
133
  // Daemon logs are written by the centralized logger (src/core/log.ts)
@@ -144,15 +147,15 @@ function cancelPendingTimers() {
144
147
  rebuildTimer = null;
145
148
  }
146
149
  }
147
- export function buildChildProcessConfig(restartReason = null) {
150
+ export function buildChildProcessConfig(restartReason = null, childExit = null) {
148
151
  const stdio = ['pipe', 'ignore', 'ignore', 'ipc'];
149
152
  const env = { ...process.env };
150
- if (restartReason) {
153
+ delete env.CORTEX_RESTART_REASON;
154
+ delete env[CHILD_EXIT_ENV];
155
+ if (restartReason)
151
156
  env.CORTEX_RESTART_REASON = restartReason;
152
- }
153
- else {
154
- delete env.CORTEX_RESTART_REASON;
155
- }
157
+ if (childExit)
158
+ env[CHILD_EXIT_ENV] = childExit;
156
159
  return {
157
160
  cwd: DATA_DIR,
158
161
  windowsHide: true,
@@ -170,12 +173,14 @@ function startChild() {
170
173
  return;
171
174
  }
172
175
  const reasonForChild = nextRestartReason;
176
+ const childExit = nextChildExit;
173
177
  nextRestartReason = null;
178
+ nextChildExit = null;
174
179
  log.info(reasonForChild ? `Starting app.ts (reason: ${reasonForChild})...` : 'Starting app.ts...');
175
180
  childStartedAt = Date.now();
176
181
  childBusy = false;
177
182
  pendingRestart = null;
178
- child = fork(APP_ENTRY, [], buildChildProcessConfig(reasonForChild));
183
+ child = fork(APP_ENTRY, [], buildChildProcessConfig(reasonForChild, childExit));
179
184
  // Daemon only logs its own messages; app.ts handles its own output independently.
180
185
  log.info(`app.ts started — PID ${child.pid}`);
181
186
  // Persist child PID so CLI (daemon status / daemon restart --hard) can find it
@@ -184,70 +189,75 @@ function startChild() {
184
189
  }
185
190
  catch { }
186
191
  // IPC: app.ts tells us when it's busy/idle
187
- child.on('message', (msg) => {
188
- if (msg?.type === 'busy') {
189
- log.info(`IPC ← app.ts: busy`);
190
- childBusy = true;
191
- }
192
- else if (msg?.type === 'idle') {
193
- childBusy = false;
194
- const note = pendingRestart
195
- ? ` (pending restart: ${pendingRestart})`
196
- : pendingRebuild
197
- ? ` (pending rebuild: ${pendingRebuild})`
198
- : '';
199
- log.info(`IPC ← app.ts: idle${note}`);
200
- if (pendingRestart) {
201
- const reason = pendingRestart;
202
- pendingRestart = null;
203
- restart(reason);
204
- }
205
- else if (pendingRebuild) {
206
- const reason = pendingRebuild;
207
- pendingRebuild = null;
208
- runRebuildPipeline(reason);
209
- }
210
- }
211
- });
212
- child.on('exit', (code, signal) => {
213
- child = null;
214
- childBusy = false;
215
- // Clean up child PID file
216
- try {
217
- if (existsSync(DAEMON_CHILD_PID_FILE))
218
- unlinkSync(DAEMON_CHILD_PID_FILE);
219
- }
220
- catch { }
221
- if (shuttingDown) {
222
- log.info('app.ts exited (shutdown).');
223
- return;
224
- }
225
- // If restart() is driving the stop→start cycle, let it handle startChild()
226
- if (restarting) {
227
- if (signal)
228
- log.info(`app.ts stopped (signal ${signal}).`);
229
- return;
230
- }
231
- // Unexpected crash — schedule recovery with backoff
232
- const alive = Date.now() - childStartedAt;
233
- if (alive > HEALTHY_THRESHOLD)
234
- backoff = BACKOFF_INITIAL;
235
- const crashReason = signal ? `crash (signal ${signal})` : `crash (exit code ${code})`;
236
- if (signal) {
237
- log.info(`app.ts killed by signal ${signal}.`);
238
- }
239
- else {
240
- log.info(`app.ts exited with code ${code}.`);
241
- }
242
- log.info(`Restarting in ${backoff}ms...`);
243
- cancelPendingTimers();
244
- crashRecoveryTimer = setTimeout(() => {
245
- crashRecoveryTimer = null;
246
- nextRestartReason = crashReason;
247
- startChild();
248
- }, backoff);
249
- backoff = Math.min(backoff * 2, BACKOFF_MAX);
250
- });
192
+ child.on('message', onChildMessage);
193
+ child.on('exit', onChildExit);
194
+ }
195
+ function onChildIdle() {
196
+ childBusy = false;
197
+ const note = pendingRestart
198
+ ? ` (pending restart: ${pendingRestart})`
199
+ : pendingRebuild
200
+ ? ` (pending rebuild: ${pendingRebuild})`
201
+ : '';
202
+ log.info(`IPC ← app.ts: idle${note}`);
203
+ if (pendingRestart) {
204
+ const reason = pendingRestart;
205
+ pendingRestart = null;
206
+ restart(reason);
207
+ }
208
+ else if (pendingRebuild) {
209
+ const reason = pendingRebuild;
210
+ pendingRebuild = null;
211
+ runRebuildPipeline(reason);
212
+ }
213
+ }
214
+ function onChildMessage(msg) {
215
+ if (msg?.type === 'busy') {
216
+ log.info(`IPC ← app.ts: busy`);
217
+ childBusy = true;
218
+ }
219
+ else if (msg?.type === 'idle') {
220
+ onChildIdle();
221
+ }
222
+ }
223
+ function onChildExit(code, signal) {
224
+ child = null;
225
+ childBusy = false;
226
+ // Clean up child PID file
227
+ try {
228
+ if (existsSync(DAEMON_CHILD_PID_FILE))
229
+ unlinkSync(DAEMON_CHILD_PID_FILE);
230
+ }
231
+ catch { }
232
+ if (shuttingDown) {
233
+ log.info('app.ts exited (shutdown).');
234
+ return;
235
+ }
236
+ // If restart() is driving the stop→start cycle, let it handle startChild()
237
+ if (restarting) {
238
+ if (signal)
239
+ log.info(`app.ts stopped (signal ${signal}).`);
240
+ return;
241
+ }
242
+ scheduleCrashRecovery(code, signal);
243
+ }
244
+ /** Unexpected crash — schedule recovery with backoff. */
245
+ function scheduleCrashRecovery(code, signal) {
246
+ const alive = Date.now() - childStartedAt;
247
+ if (alive > HEALTHY_THRESHOLD)
248
+ backoff = BACKOFF_INITIAL;
249
+ const crashReason = signal ? `crash (signal ${signal})` : `crash (exit code ${code})`;
250
+ const crashFacts = encodeChildExit({ code, signal, uptimeMs: alive, backoffMs: backoff });
251
+ log.info(signal ? `app.ts killed by signal ${signal}.` : `app.ts exited with code ${code}.`);
252
+ log.info(`Restarting in ${backoff}ms...`);
253
+ cancelPendingTimers();
254
+ crashRecoveryTimer = setTimeout(() => {
255
+ crashRecoveryTimer = null;
256
+ nextRestartReason = crashReason;
257
+ nextChildExit = crashFacts;
258
+ startChild();
259
+ }, backoff);
260
+ backoff = Math.min(backoff * 2, BACKOFF_MAX);
251
261
  }
252
262
  function stopChild() {
253
263
  return new Promise((resolve) => {
@@ -875,9 +885,13 @@ function setupProcessErrorHandlers() {
875
885
  handlingError = false;
876
886
  }
877
887
  };
878
- process.on('uncaughtException', error => report('uncaughtException', error?.stack ?? error));
888
+ process.on('uncaughtException', error => {
889
+ report('uncaughtException', error?.stack ?? error);
890
+ captureProcessCrash('daemon', 'uncaughtException', error);
891
+ });
879
892
  process.on('unhandledRejection', reason => {
880
893
  report('unhandledRejection', reason instanceof Error ? reason.stack : reason);
894
+ captureProcessCrash('daemon', 'unhandledRejection', reason);
881
895
  });
882
896
  }
883
897
  function main() {
@@ -1,5 +1,6 @@
1
1
  export { isGitInstalled, ensureGitInstalled, getGitInstallHint } from './init-git.js';
2
2
  import type { ModelChoice } from '../core/models-generator.js';
3
+ import type { InitTelemetryAnswer } from '../domain/telemetry/schema.js';
3
4
  import { type UsageSharingUpdate } from '../domain/costs/aistatus-config.js';
4
5
  import { type Locale } from '../core/i18n.js';
5
6
  import { cmdFeishu } from './feishu-login.js';
@@ -43,6 +44,8 @@ export interface InitAnswers {
43
44
  feishuConfig?: FeishuInitConfig;
44
45
  /** Omitted when a scripted caller did not make an upload choice. */
45
46
  gatewayUsage?: GatewayUsageConfig;
47
+ /** Anonymous product telemetry choice; omitted keeps the default (on) and creates a fresh id. */
48
+ telemetry?: InitTelemetryAnswer;
46
49
  installService: boolean;
47
50
  /** Default model; omitted uses the discovery recommendation. */
48
51
  defaultChoice?: ModelChoice;
@@ -15,7 +15,9 @@ import { discoverEndpoints, writeMergedGatewayYaml, validateModelsAgainstGateway
15
15
  import { readExistingModels, writeModelsJson, listChoices, recommendedChoice } from '../core/models-generator.js';
16
16
  import { ENVIRONMENTS_DIRNAME, mergeDefaultEnvironments } from '../domain/agents/environments/index.js';
17
17
  import { createLogger } from '../core/log.js';
18
- import { INSTALL_ROOT, DEFAULTS_DIR } from '../core/paths.js';
18
+ import { INSTALL_ROOT, DEFAULTS_DIR, DATA_DIR } from '../core/paths.js';
19
+ import { applyInitTelemetry, parseInitTelemetryAnswer } from '../domain/telemetry/init-answer.js';
20
+ import { recordFunnelStep } from '../domain/telemetry/funnel.js';
19
21
  import { writeUsageSharing } from '../domain/costs/aistatus-config.js';
20
22
  import { t, setLocale, normalizeLocale, detectSystemLocale } from '../core/i18n.js';
21
23
  import { CLIENT_TOKEN_ENV } from '../core/auth.js';
@@ -119,6 +121,7 @@ export function parseInitAnswersJson(raw) {
119
121
  slackConfig: input.slackConfig,
120
122
  feishuConfig: input.feishuConfig,
121
123
  gatewayUsage,
124
+ telemetry: parseInitTelemetryAnswer(input.telemetry),
122
125
  installService: input.installService === true,
123
126
  defaultChoice: parseChoiceValue(input.defaultChoice),
124
127
  favorites: Array.isArray(input.favorites)
@@ -843,6 +846,7 @@ async function collectAnswersInteractive(paths) {
843
846
  handleCancel(email);
844
847
  gatewayUsage = { enabled: true, name: name, org: org, email: email };
845
848
  }
849
+ const telemetry = await askTelemetry();
846
850
  // Step 5: Service registration
847
851
  const wantService = await clack.confirm({
848
852
  message: t('init.serviceRegister.prompt'),
@@ -858,9 +862,15 @@ async function collectAnswersInteractive(paths) {
858
862
  slackConfig,
859
863
  feishuConfig,
860
864
  gatewayUsage,
865
+ telemetry,
861
866
  installService: wantService,
862
867
  };
863
868
  }
869
+ async function askTelemetry() {
870
+ const enabled = await clack.confirm({ message: t('init.telemetry.prompt'), initialValue: true });
871
+ handleCancel(enabled);
872
+ return { enabled: enabled };
873
+ }
864
874
  // ─── Non-interactive prompts (piped stdin) ───────────────────────
865
875
  async function collectAnswersNonInteractive() {
866
876
  const lines = [];
@@ -1185,6 +1195,38 @@ export async function runInit(options = {}) {
1185
1195
  emitter?.restore();
1186
1196
  }
1187
1197
  }
1198
+ function applySharingChoices(paths, answers, options) {
1199
+ if (answers.gatewayUsage)
1200
+ writeUsageSharing(answers.gatewayUsage, options.gatewayConfigDir);
1201
+ if (answers.telemetry) {
1202
+ applyInitTelemetry(answers.telemetry, { configDir: paths.CONFIG_DIR, storeDir: paths.STORE_DIR });
1203
+ }
1204
+ }
1205
+ async function detectAuthAndGateway(paths, answers, options, interactive, emitter) {
1206
+ const emit = (event) => emitter?.emit(event);
1207
+ const authBackends = await onboardInitAuth(interactive, event => {
1208
+ emit(event);
1209
+ if (!emitter && !interactive)
1210
+ process.stdout.write(`${JSON.stringify(event)}\n`);
1211
+ });
1212
+ if (interactive) {
1213
+ const configured = authBackends.length > 0
1214
+ && await runGatewaySetup(authBackends, paths, options.gatewayConfigDir, answers, true);
1215
+ emit({ step: 'gateway', state: configured ? 'ok' : 'skip' });
1216
+ return;
1217
+ }
1218
+ // Non-interactive: auto-detect silently, passing caller-supplied choices. A machine with no
1219
+ // backend logged in yet yields no endpoints — expected on a fresh desktop install, where the
1220
+ // user logs in from the workbench afterwards and the server syncs models from that login.
1221
+ try {
1222
+ const configured = await runGatewaySetup(answers.backends, paths, options.gatewayConfigDir, answers);
1223
+ emit({ step: 'gateway', state: configured ? 'ok' : 'skip', reason: configured ? undefined : 'no-backend-login' });
1224
+ }
1225
+ catch (e) {
1226
+ log.warn(`Gateway setup failed (non-interactive): ${e.message}`);
1227
+ emit({ step: 'gateway', state: 'skip', reason: e.message });
1228
+ }
1229
+ }
1188
1230
  export function writeInitConfigs(paths, answers, force) {
1189
1231
  // Opt-in retries never replace credentials, registry, or user configuration (even with --force).
1190
1232
  const overwrite = answers.localClient?.enabled ? false : force;
@@ -1214,10 +1256,8 @@ async function runInitSteps(paths, force, options, emitter) {
1214
1256
  // 4. Explicit client intent is durable before config writes; prepare never starts a process.
1215
1257
  await withInitLocalClient(paths, answers, () => writeInitConfigs(paths, answers, force), emit);
1216
1258
  emit({ step: 'config', state: 'ok' });
1217
- // 5. Gateway usage — omitted scripted answers preserve the existing user choice.
1218
- if (answers.gatewayUsage) {
1219
- writeUsageSharing(answers.gatewayUsage, options.gatewayConfigDir);
1220
- }
1259
+ // 5. Gateway usage and telemetry — omitted scripted answers preserve the existing choices.
1260
+ applySharingChoices(paths, answers, options);
1221
1261
  // 5b. Local Web UI endpoint — opt-in, driven by the desktop setup wizard. Must run after the
1222
1262
  // .env exists so the generated client token is the one the native app is handed back.
1223
1263
  let localUi = null;
@@ -1232,31 +1272,13 @@ async function runInitSteps(paths, force, options, emitter) {
1232
1272
  emit({ step: 'service', state: 'ok' });
1233
1273
  }
1234
1274
  // 7. Detect credentials automatically. Login/install is only offered here.
1235
- const authBackends = await onboardInitAuth(!!interactive, event => {
1236
- emit(event);
1237
- if (!emitter && !interactive)
1238
- process.stdout.write(`${JSON.stringify(event)}\n`);
1239
- });
1240
- if (interactive) {
1241
- const configured = authBackends.length > 0
1242
- && await runGatewaySetup(authBackends, paths, options.gatewayConfigDir, answers, true);
1243
- emit({ step: 'gateway', state: configured ? 'ok' : 'skip' });
1244
- }
1245
- else {
1246
- // Non-interactive: auto-detect silently, passing caller-supplied choices. A machine with no
1247
- // backend logged in yet yields no endpoints — expected on a fresh desktop install, where the
1248
- // user logs in from the workbench afterwards and the server syncs models from that login.
1249
- try {
1250
- const configured = await runGatewaySetup(answers.backends, paths, options.gatewayConfigDir, answers);
1251
- emit({ step: 'gateway', state: configured ? 'ok' : 'skip', reason: configured ? undefined : 'no-backend-login' });
1252
- }
1253
- catch (e) {
1254
- log.warn(`Gateway setup failed (non-interactive): ${e.message}`);
1255
- emit({ step: 'gateway', state: 'skip', reason: e.message });
1256
- }
1257
- }
1275
+ await detectAuthAndGateway(paths, answers, options, !!interactive, emitter);
1258
1276
  // 8. Done
1259
1277
  clack.outro(t('init.outro', { dataDir: paths.DATA_DIR }));
1278
+ // The funnel step goes to this process's own home only, and never against a fresh opt-out.
1279
+ if (answers.telemetry?.enabled !== false && path.resolve(paths.DATA_DIR) === path.resolve(DATA_DIR)) {
1280
+ recordFunnelStep('server_init_completed');
1281
+ }
1260
1282
  emit({
1261
1283
  step: 'result',
1262
1284
  state: 'ok',
@@ -5,6 +5,7 @@ import { CORTEX_VERSION } from '../core/version.js';
5
5
  import { flushAllRepositories } from '../core/json-repository.js';
6
6
  import { engines } from '../domain/runs/engines.js';
7
7
  import { stopBuiltinJobs } from '../domain/scheduling/builtin-jobs.js';
8
+ import { stopTelemetry } from '../domain/telemetry/service.js';
8
9
  import { stopClientManager } from '../domain/remote/client-manager.js';
9
10
  import { stopMachineRegistryWatcher } from '../domain/remote/machine-registry.js';
10
11
  import { stopAllDevicePorts } from '../domain/remote/device-port.js';
@@ -54,6 +55,8 @@ function drainSteps(h) {
54
55
  { name: 'claude window warm-up', run: stopClaudeWindowWarmup },
55
56
  // Pending WAL entries survive on disk for the next startup.
56
57
  { name: 'outbound drain loop', run: () => h.outboundQueue.stop() },
58
+ // After the engines closed, so turns cancelled by the shutdown are in the persisted rollup.
59
+ { name: 'telemetry', run: stopTelemetry },
57
60
  // SIGTERM landing between `writeFile(tmp)` and `rename(tmp, target)` in atomic-write.ts leaves
58
61
  // orphan .tmp.* siblings; the daemon gives 5s before SIGKILL, well over what this needs.
59
62
  { name: 'flush stores', run: () => Promise.allSettled([h.bus.close(), h.outboundQueue.flush(), flushAllRepositories()]) },
@@ -69,19 +69,16 @@ export function parseSignalArgs(argv) {
69
69
  }
70
70
  /** `--exit-code` is the ergonomic form: one flag turns `$?` into both a status and a message. */
71
71
  function resolveStatus(parsed) {
72
- if (parsed.exitCode !== null) {
73
- const code = Number.parseInt(parsed.exitCode, 10);
74
- if (!Number.isFinite(code)) {
75
- throw cliError(formatError(`--exit-code must be a number, got '${parsed.exitCode}'`));
76
- }
77
- const status = parsed.status ?? (code === 0 ? 'ok' : 'fail');
78
- return { status, message: parsed.message ?? `exit=${code}` };
72
+ if (parsed.status !== null && !STATUSES.includes(parsed.status)) {
73
+ throw cliError(formatError(`Invalid --status '${parsed.status}'`, { validValues: STATUSES }));
79
74
  }
80
- const status = parsed.status ?? 'ok';
81
- if (!STATUSES.includes(status)) {
82
- throw cliError(formatError(`Invalid --status '${status}'`, { validValues: STATUSES }));
75
+ if (parsed.exitCode === null)
76
+ return { status: parsed.status ?? 'ok', message: parsed.message };
77
+ const code = Number.parseInt(parsed.exitCode, 10);
78
+ if (!Number.isFinite(code)) {
79
+ throw cliError(formatError(`--exit-code must be a number, got '${parsed.exitCode}'`));
83
80
  }
84
- return { status, message: parsed.message };
81
+ return { status: parsed.status ?? (code === 0 ? 'ok' : 'fail'), message: parsed.message ?? `exit=${code}` };
85
82
  }
86
83
  function readData(spec) {
87
84
  if (spec === null)
@@ -1,10 +1,15 @@
1
1
  import * as path from 'node:path';
2
2
  import * as fs from 'node:fs';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { parseClientKind } from '../domain/telemetry/client-kind.js';
5
+ import { CLIENT_KIND_HEADER } from '../domain/telemetry/schema.js';
4
6
  import { createAppRouter } from '../domain/ui-service/app-router.js';
5
7
  import { createUiHttpServer, createAuthorizer } from '../platform/ui-http/ui-http-server.js';
6
8
  import { createUiSessionStore, DEFAULT_SESSION_TTL_MS } from '../platform/ui-http/ui-session.js';
7
9
  import { createUiAuthRoutes, createUiSessionProbeRoute, UI_LOGIN_PATH, UI_SESSION_PATH, } from '../platform/ui-http/ui-auth-routes.js';
10
+ import { createUiDeviceRoutes, UI_PAIR_PATH } from '../platform/ui-http/ui-device-routes.js';
11
+ import { createUiDeviceStore } from '../platform/ui-http/ui-devices.js';
12
+ import { createPairingStore, PAIRING_FILE_NAME } from '../platform/ui-http/ui-pairing.js';
8
13
  import { createOtaRoutes } from '../platform/ui-http/ui-ota.js';
9
14
  import { createAppUpdateRoutes } from '../platform/ui-http/app-update.js';
10
15
  import { isUpdateDevMode } from '../domain/system/server-update-check.js';
@@ -28,9 +33,11 @@ const log = createLogger('ui-http');
28
33
  const DEFAULT_UI_PORT = 3004;
29
34
  /** Where browser sessions survive a daemon restart. Written 0600 by the store. */
30
35
  const SESSIONS_FILE = path.join(STORE_DIR, 'ui-sessions.json');
36
+ /** Paired apps (token hashes). Written 0600 by the store. */
37
+ const DEVICES_FILE = path.join(STORE_DIR, 'ui-devices.json');
31
38
  /**
32
39
  * Token login is ON unless explicitly switched off — a browser reaching this server can log in by
33
- * pasting the clientToken once. Opting out (`CORTEX_UI_TOKEN_LOGIN=0`) removes the login routes and
40
+ * pasting the clientToken or a one-time pairing code, and an app can pair with a code. Opting out (`CORTEX_UI_TOKEN_LOGIN=0`) removes the login routes and
34
41
  * the cookie leg entirely, leaving the token header and (if configured) Cloudflare Access.
35
42
  *
36
43
  * Being on by default means every CORTEX_UI_HTTP deployment exposes a public POST /api/ui/login.
@@ -70,6 +77,32 @@ function defaultSpaDir() {
70
77
  return undefined;
71
78
  }
72
79
  }
80
+ /**
81
+ * Token login, pairing and paired apps behind one authorizer. The authorizer is handed to BOTH the
82
+ * gate and the public /api/ui/session probe, so "am I authenticated?" is answered by the same
83
+ * predicate that decides the next request — two copies would eventually disagree. With token login
84
+ * off, only the probe and the paired-app list remain — so the SPA can say "token login is off here"
85
+ * instead of showing a form that could never work.
86
+ */
87
+ function createUiAuth(env, getToken, verifyAccessJwt) {
88
+ const tokenLogin = isTokenLoginEnabled(env);
89
+ const devices = createUiDeviceStore({ file: DEVICES_FILE });
90
+ const matchDeviceToken = (token) => devices.match(token) !== undefined;
91
+ const sessionStore = tokenLogin ? createUiSessionStore({ file: SESSIONS_FILE, ttlMs: sessionTtlMs(env) }) : undefined;
92
+ const pairing = tokenLogin ? createPairingStore({ file: path.join(STORE_DIR, PAIRING_FILE_NAME) }) : undefined;
93
+ const verifySession = sessionStore ? (sid) => sessionStore.verify(sid) : undefined;
94
+ const authorize = createAuthorizer({ getToken, matchDeviceToken, verifySession, verifyAccessJwt });
95
+ const loginRoutes = sessionStore && pairing
96
+ ? createUiAuthRoutes({
97
+ store: sessionStore, getToken, authorize, ttlMs: sessionTtlMs(env), redeemCode: (code) => pairing.redeem(code),
98
+ })
99
+ : createUiSessionProbeRoute(authorize);
100
+ return {
101
+ authorize, matchDeviceToken, tokenLogin,
102
+ publicRoutes: tokenLogin ? [UI_LOGIN_PATH, UI_SESSION_PATH, UI_PAIR_PATH] : [UI_SESSION_PATH],
103
+ routes: { ...loginRoutes, ...createUiDeviceRoutes({ devices, pairing }) },
104
+ };
105
+ }
73
106
  /**
74
107
  * Build the AppRouter from the injected UiService and start the Web UI HTTP+SSE transport-host
75
108
  * on CORTEX_UI_PORT (default 3004), bound 127.0.0.1, behind the x-cortex-token gate, serving the
@@ -92,15 +125,8 @@ export function startUiHttpServer(opts) {
92
125
  // to token-only.
93
126
  const verifyAccessJwt = accessVerifierFromEnv(env);
94
127
  const getToken = opts.getToken ?? getClientToken;
95
- // Token login: one session store, one authorizer. The authorizer is handed to BOTH the gate and
96
- // the public /api/ui/session probe, so "am I authenticated?" is answered by the same predicate
97
- // that decides the next request — two copies would eventually disagree.
98
- const tokenLogin = isTokenLoginEnabled(env);
99
- const sessionStore = tokenLogin
100
- ? createUiSessionStore({ file: SESSIONS_FILE, ttlMs: sessionTtlMs(env) })
101
- : undefined;
102
- const verifySession = sessionStore ? (sid) => sessionStore.verify(sid) : undefined;
103
- const authorize = createAuthorizer({ getToken, verifySession, verifyAccessJwt });
128
+ const auth = createUiAuth(env, getToken, verifyAccessJwt);
129
+ const { authorize, tokenLogin } = auth;
104
130
  // The agent's browser, live in the app: session list, takeover, typed text, and the stream itself.
105
131
  const browserStream = createBrowserStream({
106
132
  listSessions: listBrowserSessions, streamPort, setTakeover, isTakenOver, insertText,
@@ -113,20 +139,16 @@ export function startUiHttpServer(opts) {
113
139
  return createUiHttpServer({
114
140
  router,
115
141
  getToken,
142
+ matchDeviceToken: auth.matchDeviceToken,
116
143
  port,
117
144
  host: '127.0.0.1',
118
145
  spaDir,
119
146
  corsOrigins,
120
147
  authorize,
121
- // Reachable without a credential: the login endpoint and the boolean probe. Everything else,
122
- // including logout, goes through the gate.
123
- publicRoutes: tokenLogin ? [UI_LOGIN_PATH, UI_SESSION_PATH] : [UI_SESSION_PATH],
148
+ createContext: (req) => ({ client: parseClientKind(req.headers[CLIENT_KIND_HEADER]) }),
149
+ publicRoutes: auth.publicRoutes,
124
150
  customRoutes: {
125
- // Browser token login. When disabled, only the probe remains — so the SPA can say "token
126
- // login is off here" instead of showing a form that could never work.
127
- ...(sessionStore
128
- ? createUiAuthRoutes({ store: sessionStore, getToken, authorize, ttlMs: sessionTtlMs(env) })
129
- : createUiSessionProbeRoute(authorize)),
151
+ ...auth.routes,
130
152
  // Composer uploads, workspace downloads and board assets.
131
153
  ...createFileRoutes({
132
154
  attachmentsDir: path.join(WORKSPACE_DIR, 'attachments'),
@@ -0,0 +1,12 @@
1
+ import { stopTelemetry } from '../domain/telemetry/service.js';
2
+ import type { EventBus } from '../events/event-bus.js';
3
+ /** Early in boot: everything that must see the boot itself. All of it is local until upload. */
4
+ export declare function installEarlyTelemetry(): void;
5
+ /** Feature and web signals; called once the event bus exists. */
6
+ export declare function installTelemetryCollectors(bus: EventBus): void;
7
+ /** The event-loop monitor's window observer. */
8
+ export declare const telemetryEventLoopObserver: (reading: {
9
+ p99Ms: number;
10
+ }) => void;
11
+ export declare function startTelemetryService(): void;
12
+ export { stopTelemetry as stopTelemetryService };
@@ -0,0 +1,56 @@
1
+ // Composition of the telemetry service: the heartbeat's data sources live all over the domain
2
+ // layer, so they are gathered here rather than imported by domain/telemetry itself.
3
+ import { setErrorLogSink } from '../core/log.js';
4
+ import { getSettings } from '../core/settings.js';
5
+ import { getAuthStatus } from '../domain/auth/auth-status.js';
6
+ import { projectStore } from '../domain/projects/index.js';
7
+ import { getOnlineDevices } from '../domain/remote/client-manager.js';
8
+ import { buildHeartbeat } from '../domain/telemetry/heartbeat.js';
9
+ import { loadNameCatalog } from '../domain/telemetry/normalize.js';
10
+ import { startTelemetry, stopTelemetry } from '../domain/telemetry/service.js';
11
+ import { captureChildExitFromEnv } from '../domain/telemetry/child-exit.js';
12
+ import { installDailyUpload } from '../domain/telemetry/daily-upload.js';
13
+ import { recordErrorLog } from '../domain/telemetry/error-digest.js';
14
+ import { subscribeTelemetryToBus } from '../domain/telemetry/bus-collector.js';
15
+ import { recordFunnelStep } from '../domain/telemetry/funnel.js';
16
+ import { installWebReportSink, recordEventLoopLag } from '../domain/telemetry/usage.js';
17
+ import { onLoginSuccess } from '../domain/auth/login-flow.js';
18
+ import { confirmUpgradeAtBoot } from '../domain/telemetry/upgrade.js';
19
+ import { sessionStore } from '../store/session-registry-repo.js';
20
+ const DAY_MS = 24 * 60 * 60 * 1000;
21
+ async function activeSessions24h() {
22
+ const since = Date.now() - DAY_MS;
23
+ const recent = await sessionStore.listRecentSessions(10_000);
24
+ return recent.filter((session) => Date.parse(session.lastUsedAt ?? '') >= since).length;
25
+ }
26
+ function heartbeatSources() {
27
+ return {
28
+ authStatus: () => getAuthStatus(),
29
+ projects: () => projectStore.list().length,
30
+ onlineDevices: () => getOnlineDevices(),
31
+ activeSessions24h,
32
+ uptimeS: () => process.uptime(),
33
+ settings: () => getSettings(),
34
+ catalog: () => loadNameCatalog(new Date().toISOString().slice(0, 10)),
35
+ };
36
+ }
37
+ /** Early in boot: everything that must see the boot itself. All of it is local until upload. */
38
+ export function installEarlyTelemetry() {
39
+ installDailyUpload();
40
+ setErrorLogSink(recordErrorLog);
41
+ captureChildExitFromEnv();
42
+ confirmUpgradeAtBoot();
43
+ }
44
+ /** Feature and web signals; called once the event bus exists. */
45
+ export function installTelemetryCollectors(bus) {
46
+ subscribeTelemetryToBus(bus);
47
+ installWebReportSink();
48
+ onLoginSuccess((event) => recordFunnelStep('provider_authed', event.backend));
49
+ }
50
+ /** The event-loop monitor's window observer. */
51
+ export const telemetryEventLoopObserver = (reading) => recordEventLoopLag(reading.p99Ms);
52
+ export function startTelemetryService() {
53
+ const sources = heartbeatSources();
54
+ startTelemetry({ collectHeartbeat: () => buildHeartbeat(sources) });
55
+ }
56
+ export { stopTelemetry as stopTelemetryService };
@@ -1,13 +1,2 @@
1
1
  import { type CliResult } from '../core/cli-utils.js';
2
- /**
3
- * `cortex ui enable` — make this install reachable by the Cortex desktop app.
4
- *
5
- * The native shell needs three things that a plain `cortex init` leaves off (the endpoint is
6
- * opt-in): the Web UI HTTP transport switched on, a port, and the shell's own origins allowed for
7
- * CORS. This wraps all three plus token generation into one idempotent command, so both the desktop
8
- * setup wizard and an operator repairing an older install use the same path.
9
- *
10
- * `changed` in the JSON output tells the caller whether a running daemon must be restarted: .env is
11
- * read at process start, so flipping it mid-flight has no effect until the server respawns.
12
- */
13
2
  export declare function runUiCli(args: string[]): Promise<CliResult>;