@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
@@ -1,5 +1,6 @@
1
1
  import { ANTHROPIC_MODELS } from '../../../core/anthropic-models.js';
2
2
  import { anthropicModelDiscovery, anthropicModelIds, anthropicModelThinking, } from '../../../core/anthropic-model-discovery.js';
3
+ import { hasClaudeCredential } from '../../../core/claude-credentials.js';
3
4
  import { readGatewayYaml } from '../../../core/gateway-generator.js';
4
5
  import { defaultCustomProviderStores, listCustomProviders, GATEWAY_CONFIG_PATH, } from '../../pi-providers/index.js';
5
6
  import { piProviderDiscovery } from '../../../agent-adapter/pi/discovery.js';
@@ -8,7 +9,8 @@ import { THINKING_LEVELS_BY_BACKEND } from '../../agents/engine-selection.js';
8
9
  * The catalog is a UNION, never an intersection: a model must stay selectable for an endpoint the
9
10
  * host cannot currently enumerate (PI reports only providers with usable auth, and a scan can fail
10
11
  * outright). Every source therefore only ADDS — an endpoint known solely from gateway.yaml still
11
- * appears, with an empty model list, and the editor falls back to free text for it.
12
+ * appears, with an empty model list, and the editor falls back to free text for it. The one gate is
13
+ * the Claude backend itself: a host holding no Claude credential gets no Claude route at all.
12
14
  *
13
15
  * Deliberately its own query rather than a field of the high-frequency `config.get`: reading PI's
14
16
  * models loads the bundled SDK (~100 MB, see core/pi-sdk.ts), a cost only a caller that actually
@@ -62,47 +64,62 @@ class RouteBuilder {
62
64
  }
63
65
  }
64
66
  export async function handleModelsCatalog(deps, _params, readers = {}) {
65
- const claudeModels = readers.claudeModels ?? (() => anthropicModelDiscovery.ensure());
66
- const piModels = readers.piModels ?? (() => piProviderDiscovery.ensureModels());
67
- const piPeek = readers.piPeek ?? (() => piProviderDiscovery.peekModels());
68
- const customProviders = readers.customProviders
69
- ?? (() => listCustomProviders(deps.customProviderStores ?? defaultCustomProviderStores()));
70
67
  const gatewayModes = (readers.gatewayModes ?? readGatewayModes)();
68
+ const claudeAvailable = (readers.claudeAvailable ?? (() => hasClaudeCredential()))();
71
69
  const builder = new RouteBuilder(gatewayModes);
72
- // Discovered ids UNIONED with the shipped table, never replacing it: a host with no credential
73
- // or no network keeps the list it always had. `source` stays 'builtin' because the route's
74
- // identity did not change — only how completely its models are known.
70
+ if (claudeAvailable)
71
+ await addClaudeRoute(builder, readers);
72
+ await addPiRoutes(builder, readers);
73
+ const customProviders = readers.customProviders
74
+ ?? (() => listCustomProviders(deps.customProviderStores ?? defaultCustomProviderStores()));
75
+ for (const provider of customProviders()) {
76
+ builder.add(provider.name, 'pi', 'custom', provider.models.map((model) => model.id));
77
+ }
78
+ for (const endpoint of Object.keys(gatewayModes)) {
79
+ if (endpoint !== CLAUDE_ENDPOINT)
80
+ builder.add(endpoint, 'pi', 'gateway', []);
81
+ else if (claudeAvailable)
82
+ builder.add(endpoint, 'claude', 'gateway', []);
83
+ }
84
+ const piPeek = readers.piPeek ?? (() => piProviderDiscovery.peekModels());
85
+ return {
86
+ routes: builder.build(),
87
+ piPending: piPeek().length === 0,
88
+ thinkingLevels: { claude: [...THINKING_LEVELS_BY_BACKEND.claude], pi: [...THINKING_LEVELS_BY_BACKEND.pi] },
89
+ };
90
+ }
91
+ /**
92
+ * Only a host holding a Claude credential gets the route, the way PI lists only providers with
93
+ * usable auth. Discovered ids are UNIONED with the shipped table, never replacing it: a logged-in
94
+ * host with no network keeps the list it always had. `source` stays 'builtin' because the route's
95
+ * identity did not change — only how completely its models are known.
96
+ */
97
+ async function addClaudeRoute(builder, readers) {
98
+ const claudeModels = readers.claudeModels ?? (() => anthropicModelDiscovery.ensure());
75
99
  const claude = await claudeModels();
76
100
  builder.add(CLAUDE_ENDPOINT, 'claude', 'builtin', anthropicModelIds(claude, ANTHROPIC_MODELS), anthropicModelThinking(claude));
77
- // `ensureModels()` waits out a COLD scan (bounded) and serves a warm cache at once: a picker's
78
- // whole purpose is the list, so an empty first answer would only become a spinner. A scan that
79
- // is still failing is not retried here — it left a backoff, and `piPending` reports the gap.
80
- const discovered = await piModels();
101
+ }
102
+ /**
103
+ * `ensureModels()` waits out a COLD scan (bounded) and serves a warm cache at once: a picker's
104
+ * whole purpose is the list, so an empty first answer would only become a spinner. A scan that is
105
+ * still failing is not retried here — it left a backoff, and `piPending` reports the gap.
106
+ */
107
+ async function addPiRoutes(builder, readers) {
108
+ const piModels = readers.piModels ?? (() => piProviderDiscovery.ensureModels());
81
109
  const byProvider = new Map();
82
110
  const thinkingByProvider = new Map();
83
- for (const pair of discovered) {
111
+ for (const pair of await piModels()) {
84
112
  const models = byProvider.get(pair.provider) ?? [];
85
113
  if (!models.includes(pair.model))
86
114
  models.push(pair.model);
87
115
  byProvider.set(pair.provider, models);
88
- if (pair.thinkingLevels) {
89
- const levels = thinkingByProvider.get(pair.provider) ?? {};
90
- levels[pair.model] = pair.thinkingLevels;
91
- thinkingByProvider.set(pair.provider, levels);
92
- }
116
+ if (!pair.thinkingLevels)
117
+ continue;
118
+ const levels = thinkingByProvider.get(pair.provider) ?? {};
119
+ levels[pair.model] = pair.thinkingLevels;
120
+ thinkingByProvider.set(pair.provider, levels);
93
121
  }
94
122
  for (const [provider, models] of byProvider) {
95
123
  builder.add(provider, 'pi', 'pi', models, thinkingByProvider.get(provider) ?? {});
96
124
  }
97
- for (const provider of customProviders()) {
98
- builder.add(provider.name, 'pi', 'custom', provider.models.map((model) => model.id));
99
- }
100
- for (const endpoint of Object.keys(gatewayModes)) {
101
- builder.add(endpoint, endpoint === CLAUDE_ENDPOINT ? 'claude' : 'pi', 'gateway', []);
102
- }
103
- return {
104
- routes: builder.build(),
105
- piPending: piPeek().length === 0,
106
- thinkingLevels: { claude: [...THINKING_LEVELS_BY_BACKEND.claude], pi: [...THINKING_LEVELS_BY_BACKEND.pi] },
107
- };
108
125
  }
@@ -2,7 +2,7 @@
2
2
  // mcpRead deliberately carries more than the catalog summary does — a form cannot round-trip a
3
3
  // command it was never given — but it stops at the same line the catalog does: env and header
4
4
  // VALUES never leave the server, only their key names.
5
- import { readMcpEnvelope, readSkillSource } from '../../plugins/authoring.js';
5
+ import { readMcpSource, readSkillSource } from '../../plugins/authoring.js';
6
6
  import { readPluginCatalogSnapshot, skillOrigin } from '../plugins-shared.js';
7
7
  function stringList(value) {
8
8
  return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : [];
@@ -46,11 +46,12 @@ export async function handlePluginsSkillFile(_deps, params) {
46
46
  }
47
47
  export function readMcpDrafts(pluginId) {
48
48
  const entry = readPluginCatalogSnapshot().byId.get(pluginId);
49
- const servers = Object.entries(readMcpEnvelope(pluginId))
49
+ const source = readMcpSource(pluginId);
50
+ const servers = Object.entries(source.servers)
50
51
  .map(([name, raw]) => draftServer(name, raw))
51
52
  .filter((server) => server !== null)
52
53
  .sort((left, right) => left.name.localeCompare(right.name));
53
- return { pluginId, supported: entry?.kind === 'portable', servers };
54
+ return { pluginId, supported: entry?.kind === 'portable', servers, baseHash: source.baseHash };
54
55
  }
55
56
  export async function handlePluginsMcpRead(_deps, params) {
56
57
  return readMcpDrafts(params.pluginId);
@@ -170,6 +170,7 @@ export async function handleSessionsList(deps, params) {
170
170
  unread: !s.teamLeadId && (s.origin === 'scheduled'
171
171
  ? (!s.lastReadAt || s.lastUsedAt > s.lastReadAt)
172
172
  : (!!s.lastReadAt && s.lastUsedAt > s.lastReadAt)),
173
+ lastReadAt: s.lastReadAt ?? null,
173
174
  };
174
175
  });
175
176
  // Title label-less sessions from their first user message so the left rail shows the conversation's
@@ -0,0 +1,3 @@
1
+ import { type TelemetryInfo } from '../../telemetry/info.js';
2
+ import type { QueryParams, UiServiceDeps } from '../types.js';
3
+ export declare function handleTelemetryInfo(_deps: UiServiceDeps, _params: QueryParams<'telemetry.info'>): Promise<TelemetryInfo>;
@@ -0,0 +1,4 @@
1
+ import { telemetryInfo } from '../../telemetry/info.js';
2
+ export async function handleTelemetryInfo(_deps, _params) {
3
+ return telemetryInfo();
4
+ }
@@ -1,3 +1,8 @@
1
+ import type { ClientKind } from '../telemetry/client-kind.js';
2
+ /** Built per request by the HTTP host; callers without a request (tests, TUI) pass `{}`. */
3
+ export interface UiRequestContext {
4
+ client?: ClientKind | null;
5
+ }
1
6
  /**
2
7
  * Keepalive for the SSE subscription that carries the whole UI's live state.
3
8
  *
@@ -33,14 +38,14 @@ export declare const UI_SSE_KEEPALIVE: {
33
38
  };
34
39
  };
35
40
  export declare const router: import("@trpc/server").TRPCRouterBuilder<{
36
- ctx: object;
41
+ ctx: UiRequestContext;
37
42
  meta: object;
38
43
  errorShape: import("@trpc/server").TRPCDefaultErrorShape;
39
44
  transformer: false;
40
45
  }>;
41
- export declare const publicProcedure: import("@trpc/server").TRPCProcedureBuilder<object, object, object, import("@trpc/server").TRPCUnsetMarker, import("@trpc/server").TRPCUnsetMarker, import("@trpc/server").TRPCUnsetMarker, import("@trpc/server").TRPCUnsetMarker, false>;
46
+ export declare const publicProcedure: import("@trpc/server").TRPCProcedureBuilder<UiRequestContext, object, object, import("@trpc/server").TRPCUnsetMarker, import("@trpc/server").TRPCUnsetMarker, import("@trpc/server").TRPCUnsetMarker, import("@trpc/server").TRPCUnsetMarker, false>;
42
47
  export declare const createCallerFactory: import("@trpc/server").TRPCRouterCallerFactory<{
43
- ctx: object;
48
+ ctx: UiRequestContext;
44
49
  meta: object;
45
50
  errorShape: import("@trpc/server").TRPCDefaultErrorShape;
46
51
  transformer: false;
@@ -29,7 +29,7 @@ export const UI_SSE_KEEPALIVE = {
29
29
  ping: { enabled: true, intervalMs: 15_000 },
30
30
  client: { reconnectAfterInactivityMs: 45_000 },
31
31
  };
32
- const t = initTRPC.create({
32
+ const t = initTRPC.context().create({
33
33
  sse: UI_SSE_KEEPALIVE,
34
34
  errorFormatter({ shape, path }) {
35
35
  if (path !== 'config.setPlatform')
@@ -53,6 +53,10 @@ import type { CustomProviderStores, CustomProviderView } from '../pi-providers/i
53
53
  export type { CustomProviderApi, CustomProviderModelSpec, CustomProviderView, } from '../pi-providers/index.js';
54
54
  import type { UsageSharingSettings } from '../costs/aistatus-config.js';
55
55
  export type { UsageSharingSettings } from '../costs/aistatus-config.js';
56
+ import type { TelemetryInfo } from '../telemetry/info.js';
57
+ export type { TelemetryInfo } from '../telemetry/info.js';
58
+ import type { ClientKind } from '../telemetry/client-kind.js';
59
+ export type { ClientKind } from '../telemetry/client-kind.js';
56
60
  export type { ProviderRateLimitPolicyOverride, ProviderRateLimitWindowPolicyOverride, ProviderRateLimits, } from '../../core/settings-spec.js';
57
61
  export type Ok<T> = {
58
62
  ok: true;
@@ -266,6 +270,9 @@ export interface SessionInfo {
266
270
  * it (`sessions.markRead` → registry lastReadAt). Legacy records with no lastReadAt are treated
267
271
  * as read (no unread flood on first deploy). */
268
272
  unread: boolean;
273
+ /** When the user last viewed the session (`sessions.markRead`); null when never. The chat finds
274
+ * the first reply that landed after it. Optional for rolling compatibility with older servers. */
275
+ lastReadAt?: string | null;
269
276
  }
270
277
  export type InteractionKind = 'ask-user' | 'plan-approval';
271
278
  export type InteractionStatus = 'pending' | 'answered' | 'approved' | 'rejected' | 'expired' | 'cancelled';
@@ -1055,6 +1062,8 @@ export interface PluginsMcpRead {
1055
1062
  /** False when the plugin is legacy, where mcp.json is never loaded however it is written. */
1056
1063
  supported: boolean;
1057
1064
  servers: UiPluginMcpDraft[];
1065
+ /** Send back on save: a write from a stale read is refused as a conflict. */
1066
+ baseHash: string;
1058
1067
  }
1059
1068
  /** Secret maps are patches, not replacements: `null` keeps whatever is on disk under that key, a
1060
1069
  * string sets a new value, and an omitted key is dropped. That is what lets the browser edit a
@@ -1143,7 +1152,7 @@ export interface ApprovalInfo {
1143
1152
  id: string;
1144
1153
  title: string;
1145
1154
  /**
1146
- * Owning project from the `- **Project**:` bullet (need-approval skill template). `null` (honest
1155
+ * Owning project from the optional `- **Project**:` bullet on hand-written entries. `null` (honest
1147
1156
  * placeholder, never fabricated) for legacy entries and system-level operations — the UI renders
1148
1157
  * those as "global".
1149
1158
  */
@@ -1371,6 +1380,7 @@ export interface QueryReturnMap {
1371
1380
  'auth.flowState': LoginFlowState | null;
1372
1381
  'auth.customProviders': CustomProviderView[];
1373
1382
  'usageSharing.get': UsageSharingSettings;
1383
+ 'telemetry.info': TelemetryInfo;
1374
1384
  'models.catalog': ModelCatalogSnapshot;
1375
1385
  'hooks.list': HooksOverview;
1376
1386
  'machines.list': MachineInfo[];
@@ -1442,6 +1452,9 @@ export interface MutateReturnMap {
1442
1452
  'auth.upsertCustomProvider': CustomProviderView;
1443
1453
  'auth.removeCustomProvider': AuthRemoveCustomProviderReturn;
1444
1454
  'usageSharing.set': UsageSharingSettings;
1455
+ 'telemetry.report': {
1456
+ ok: true;
1457
+ };
1445
1458
  'hooks.create': HooksCreateReturn;
1446
1459
  'hooks.update': HooksUpdateReturn;
1447
1460
  'hooks.setEnabled': HooksSetEnabledReturn;
@@ -1477,9 +1490,14 @@ export type QueryParams<S extends QueryScope> = QueryParamMap[S];
1477
1490
  export type QueryReturn<S extends QueryScope> = QueryReturnMap[S];
1478
1491
  export type MutateArgs<O extends MutateOp> = MutateArgsMap[O];
1479
1492
  export type MutateReturn<O extends MutateOp> = MutateReturnMap[O];
1493
+ /** Per-request facts the transport knows and handlers may use; never part of the op's args. */
1494
+ export interface UiCallContext {
1495
+ /** Which app sent the request (`x-cortex-client`), null for unknown callers. */
1496
+ client: ClientKind | null;
1497
+ }
1480
1498
  export interface UiService {
1481
1499
  query<S extends QueryScope>(scope: S, params: QueryParams<S>): Promise<Result<QueryReturn<S>>>;
1482
- mutate<O extends MutateOp>(op: O, args: MutateArgs<O>): Promise<Result<MutateReturn<O>>>;
1500
+ mutate<O extends MutateOp>(op: O, args: MutateArgs<O>, ctx?: UiCallContext): Promise<Result<MutateReturn<O>>>;
1483
1501
  subscribe(filter: SubscribeFilter): AsyncIterable<UiEvent> & {
1484
1502
  close(): void;
1485
1503
  };
@@ -1,4 +1,4 @@
1
- import type { UiServiceDeps, UiService, QueryScope, MutateOp, Result, QueryParams, QueryReturn, MutateArgs, MutateReturn } from './types.js';
1
+ import type { UiServiceDeps, UiService, QueryScope, MutateOp, Result, QueryParams, QueryReturn, MutateArgs, MutateReturn, UiCallContext } from './types.js';
2
2
  import { handleSystemCheckUpdate } from './mutate/system.js';
3
3
  /** One handler per query scope; a missing or mistyped handler fails compilation. */
4
4
  export type QueryHandlerMap = {
@@ -6,7 +6,7 @@ export type QueryHandlerMap = {
6
6
  };
7
7
  /** One handler per mutate op; a missing or mistyped handler fails compilation. */
8
8
  export type MutateHandlerMap = {
9
- [O in MutateOp]: (deps: UiServiceDeps, args: MutateArgs<O>) => Promise<Result<MutateReturn<O>>>;
9
+ [O in MutateOp]: (deps: UiServiceDeps, args: MutateArgs<O>, ctx: UiCallContext) => Promise<Result<MutateReturn<O>>>;
10
10
  };
11
11
  export declare const queryHandlers: {
12
12
  'projects.list': (deps: UiServiceDeps) => Promise<import("./types.js").ProjectConduitInfo[]>;
@@ -81,6 +81,7 @@ export declare const queryHandlers: {
81
81
  }) => Promise<import("./types.js").LoginFlowState>;
82
82
  'auth.customProviders': (deps: UiServiceDeps, params: Record<string, never>) => Promise<import("./types.js").CustomProviderView[]>;
83
83
  'usageSharing.get': (deps: UiServiceDeps, params: Record<string, never>) => Promise<import("./types.js").UsageSharingSettings>;
84
+ 'telemetry.info': (deps: UiServiceDeps, params: Record<string, never>) => Promise<import("./types.js").TelemetryInfo>;
84
85
  'models.catalog': (deps: UiServiceDeps, params: Record<string, never>) => Promise<import("./types.js").ModelCatalogSnapshot>;
85
86
  'hooks.list': (deps: UiServiceDeps, params: Record<string, never>) => Promise<import("./types.js").HooksOverview>;
86
87
  'machines.list': (deps: UiServiceDeps, params: Record<string, never>) => Promise<import("./types.js").MachineInfo[]>;
@@ -366,6 +367,33 @@ export declare const mutateHandlers: {
366
367
  org?: string;
367
368
  email?: string;
368
369
  }) => Promise<Result<import("./types.js").UsageSharingSettings>>;
370
+ 'telemetry.report': (deps: UiServiceDeps, args: {
371
+ kind: "crash";
372
+ crashKind: "renderError" | "unhandledRejection" | "windowError";
373
+ errorName: string;
374
+ message: string;
375
+ stack: string;
376
+ route?: string;
377
+ buildStamp?: string;
378
+ uptimeS?: number;
379
+ } | {
380
+ kind: "native_crash";
381
+ component: "android" | "desktop";
382
+ at: string;
383
+ message: string;
384
+ stack: string;
385
+ appVersion: string;
386
+ } | {
387
+ kind: "load";
388
+ ttfbMs?: number;
389
+ firstRenderMs?: number;
390
+ interactiveMs?: number;
391
+ } | {
392
+ kind: "sse_reconnect";
393
+ count: number;
394
+ }, ctx: UiCallContext) => Promise<Result<{
395
+ ok: true;
396
+ }>>;
369
397
  'hooks.create': (deps: UiServiceDeps, args: {
370
398
  event: string;
371
399
  matcher?: string;
@@ -375,7 +403,7 @@ export declare const mutateHandlers: {
375
403
  timeoutSec?: number;
376
404
  backends?: ("claude" | "pi")[];
377
405
  requiresTool?: string;
378
- result?: "hook-result" | "none" | "stdout-as-prompt";
406
+ result?: "none" | "stdout-as-prompt";
379
407
  enabled?: boolean;
380
408
  id: string;
381
409
  }) => Promise<Result<import("./types.js").HooksCreateReturn>>;
@@ -388,7 +416,7 @@ export declare const mutateHandlers: {
388
416
  timeoutSec?: number;
389
417
  backends?: ("claude" | "pi")[];
390
418
  requiresTool?: string;
391
- result?: "hook-result" | "none" | "stdout-as-prompt";
419
+ result?: "none" | "stdout-as-prompt";
392
420
  enabled?: boolean;
393
421
  id: string;
394
422
  }) => Promise<Result<import("./types.js").HooksUpdateReturn>>;
@@ -476,6 +504,7 @@ export declare const mutateHandlers: {
476
504
  env?: Record<string, string>;
477
505
  headers?: Record<string, string>;
478
506
  }[];
507
+ baseHash: string;
479
508
  }) => Promise<Result<import("./types.js").PluginsMcpRead>>;
480
509
  'environments.validate': (deps: UiServiceDeps, args: {
481
510
  name: string;
@@ -15,6 +15,8 @@ import { handleConfigGet } from './query/config.js';
15
15
  import { handleAuthFlowState, handleAuthStatus } from './query/auth.js';
16
16
  import { handleCustomProvidersList } from './query/custom-providers.js';
17
17
  import { handleUsageSharingGet } from './query/usage-sharing.js';
18
+ import { handleTelemetryInfo } from './query/telemetry.js';
19
+ import { handleTelemetryReport } from './mutate/telemetry.js';
18
20
  import { handleModelsCatalog } from './query/models.js';
19
21
  import { handleHooksList } from './query/hooks.js';
20
22
  import { handleMachinesList } from './query/machines.js';
@@ -71,6 +73,7 @@ export const queryHandlers = {
71
73
  'auth.flowState': (deps, params) => handleAuthFlowState(params, deps.authLogin?.getState),
72
74
  'auth.customProviders': (deps, params) => handleCustomProvidersList(deps, params),
73
75
  'usageSharing.get': (deps, params) => handleUsageSharingGet(deps, params),
76
+ 'telemetry.info': (deps, params) => handleTelemetryInfo(deps, params),
74
77
  'models.catalog': (deps, params) => handleModelsCatalog(deps, params),
75
78
  'hooks.list': (deps, params) => handleHooksList(deps, params),
76
79
  'machines.list': (deps, params) => handleMachinesList(deps, params),
@@ -135,6 +138,7 @@ export const mutateHandlers = {
135
138
  'auth.upsertCustomProvider': (deps, args) => handleCustomProviderUpsert(deps, args),
136
139
  'auth.removeCustomProvider': (deps, args) => handleCustomProviderRemove(deps, args),
137
140
  'usageSharing.set': (deps, args) => handleUsageSharingSet(deps, args),
141
+ 'telemetry.report': (deps, args, ctx) => handleTelemetryReport(deps, args, ctx),
138
142
  'hooks.create': (deps, args) => handleHooksCreate(deps, args),
139
143
  'hooks.update': (deps, args) => handleHooksUpdate(deps, args),
140
144
  'hooks.setEnabled': (deps, args) => handleHooksSetEnabled(deps, args),
@@ -171,6 +175,7 @@ const AUDIT_REDACTORS = {
171
175
  'auth.respondPrompt': ({ flowId }) => ({ flowId }),
172
176
  'auth.upsertCustomProvider': ({ apiKey: _upstreamKey, ...safe }) => safe,
173
177
  'usageSharing.set': ({ enabled }) => ({ enabled }),
178
+ 'telemetry.report': ({ kind }) => ({ kind }),
174
179
  };
175
180
  function dropNoteText({ text: _privateText, ...safe }) {
176
181
  return safe;
@@ -183,6 +188,7 @@ export function redactMutationAuditArgs(op, args) {
183
188
  const redact = AUDIT_REDACTORS[op] ?? (op.startsWith('notes.') ? dropNoteText : undefined);
184
189
  return redact ? redact(args) : args;
185
190
  }
191
+ const NO_CALL_CONTEXT = { client: null };
186
192
  export function createUiService(deps) {
187
193
  const assistantSnapshots = new AssistantSnapshots(deps.bus);
188
194
  return {
@@ -200,32 +206,27 @@ export function createUiService(deps) {
200
206
  return { ok: false, code, message: err?.message || String(err) };
201
207
  }
202
208
  },
203
- async mutate(op, args) {
209
+ async mutate(op, args, ctx = NO_CALL_CONTEXT) {
204
210
  const handler = mutateHandlers[op];
205
211
  if (!handler) {
206
212
  return { ok: false, code: 'invalid-args', message: `Unknown mutate op: ${op}` };
207
213
  }
214
+ let result;
208
215
  try {
209
- const result = await handler(deps, args);
210
- // Publish audit event before returning
211
- deps.bus.publish({
212
- type: 'ui.mutate-invoked',
213
- op,
214
- args: redactMutationAuditArgs(op, args),
215
- result: result.ok ? { ok: true } : { ok: false, code: result.code },
216
- });
217
- return result;
216
+ result = await handler(deps, args, ctx);
218
217
  }
219
218
  catch (err) {
220
- const errResult = { ok: false, code: 'internal', message: err?.message || String(err) };
221
- deps.bus.publish({
222
- type: 'ui.mutate-invoked',
223
- op,
224
- args: redactMutationAuditArgs(op, args),
225
- result: { ok: false, code: 'internal' },
226
- });
227
- return errResult;
219
+ result = { ok: false, code: 'internal', message: err?.message || String(err) };
228
220
  }
221
+ // Publish audit event before returning
222
+ deps.bus.publish({
223
+ type: 'ui.mutate-invoked',
224
+ op,
225
+ args: redactMutationAuditArgs(op, args),
226
+ result: result.ok ? { ok: true } : { ok: false, code: result.code },
227
+ client: ctx.client,
228
+ });
229
+ return result;
229
230
  },
230
231
  subscribe(filter) {
231
232
  return createSubscription(deps.bus, filter, assistantSnapshots);
package/dist/entry/app.js CHANGED
@@ -26,6 +26,10 @@ import { startClaudeWindowWarmup } from '../orchestration/claude-window-warmup.j
26
26
  import { projectStore } from '../domain/projects/index.js';
27
27
  import { sendStartupDmIfConfigured } from './startup-notify.js';
28
28
  import { installSigtermShutdown } from './shutdown.js';
29
+ import { installEarlyTelemetry, installTelemetryCollectors, startTelemetryService, telemetryEventLoopObserver, } from './telemetry-wiring.js';
30
+ import { markBootPhase, recordStartup } from '../domain/telemetry/usage.js';
31
+ import { captureProcessCrash } from '../domain/telemetry/crash.js';
32
+ import { recordMigrationFailure } from '../domain/telemetry/upgrade.js';
29
33
  import { buildUiService } from './ui-service-wiring.js';
30
34
  import { startPlatformAdapters } from './platform-connect.js';
31
35
  import { subscribeDaemonNotices } from './daemon-notice.js';
@@ -235,9 +239,13 @@ else {
235
239
  process.exit(1);
236
240
  }
237
241
  process.on('exit', () => releaseSingletonLock(APP_PID_FILE));
242
+ // Error digest, the crash the daemon just recovered from, and upgrade confirmation: before the
243
+ // migrations, so their failures are counted too.
244
+ installEarlyTelemetry();
238
245
  // Cross-file migrations must finish before adapters, ports, and background services
239
246
  // become externally visible. Provider-state extraction runs before schedule cleanup.
240
- await runMigrations();
247
+ await runMigrations({ onMigrationFailure: recordMigrationFailure });
248
+ markBootPhase('migrations');
241
249
  reloadAgentState();
242
250
  await migrateBuiltinJobSchedules();
243
251
  // Before any Claude spawn: a fresh Cortex Claude config dir takes its model/effort/context
@@ -257,6 +265,7 @@ process.on('unhandledRejection', (reason) => {
257
265
  _inExceptionHandler = true;
258
266
  try {
259
267
  log.error(`unhandledRejection: ${reason instanceof Error ? reason.stack : String(reason)}`);
268
+ captureProcessCrash('server', 'unhandledRejection', reason);
260
269
  }
261
270
  catch { /* swallow secondary failure */ }
262
271
  finally {
@@ -269,6 +278,7 @@ process.on('uncaughtException', (err) => {
269
278
  _inExceptionHandler = true;
270
279
  try {
271
280
  log.error(`uncaughtException: ${err?.stack ?? err}`);
281
+ captureProcessCrash('server', 'uncaughtException', err);
272
282
  }
273
283
  catch { /* swallow secondary failure */ }
274
284
  finally {
@@ -278,6 +288,7 @@ process.on('uncaughtException', (err) => {
278
288
  // --- EventBus + logger ---
279
289
  const bus = new EventBus();
280
290
  createEventLogger(bus);
291
+ installTelemetryCollectors(bus);
281
292
  initAuthEvents(bus);
282
293
  // A login only becomes useful once the models it unlocks are routable, and that mapping is derived
283
294
  // by scanning local backend state. Re-derive it whenever a login lands, so a user who authenticates
@@ -372,7 +383,7 @@ scheduler.setAdminNotifier(notifyAdmin);
372
383
  // awaited sequence (initRateLimitRecovery).
373
384
  initDiskMonitor(adapter);
374
385
  // Agent sessions run in this process, so a stalled loop degrades all of them at once.
375
- startEventLoopMonitor();
386
+ startEventLoopMonitor({ onReading: telemetryEventLoopObserver });
376
387
  const commandRouter = new CommandActionRouter();
377
388
  const dispatchCommand = registerCommands({
378
389
  scheduler,
@@ -427,6 +438,7 @@ installSigtermShutdown(shutdownHandles);
427
438
  // An in-process execution dies with the server, so stale it immediately — otherwise a
428
439
  // 'running' dispatch record poisons a dispatch concurrency slot until the reconciler's next tick.
429
440
  await executionRegistry.markMissingRunningExecutionsStale();
441
+ markBootPhase('executions');
430
442
  // A server restart closes every in-process injection window. Commit any durable orphan before
431
443
  // the UI transport starts so the first transcript snapshot cannot expose a forever-pending row.
432
444
  const recoveredPending = await recoverPendingInjections().catch((error) => {
@@ -457,10 +469,12 @@ installSigtermShutdown(shutdownHandles);
457
469
  catch (e) {
458
470
  log.warn(`CORTEX_UI_HTTP is set but the Web UI transport failed to load: ${e.message}`);
459
471
  }
472
+ markBootPhase('uiHttp');
460
473
  // Binds the TUI gateway; Slack/Feishu connect in the background with bounded retries, and a
461
474
  // platform that fails or stalls ends in a system notice rather than a stalled boot. Nothing below
462
475
  // needs their sockets: every outbound post, including the notices, goes through their HTTP APIs.
463
476
  shutdownHandles.platformConnections = await startPlatformAdapters(adapter);
477
+ markBootPhase('platforms');
464
478
  // Let the supervisor reach the operator through us — it has no platform adapter of its own.
465
479
  subscribeDaemonNotices(adapter);
466
480
  void sendStartupDmIfConfigured(adapter, {
@@ -530,6 +544,7 @@ installSigtermShutdown(shutdownHandles);
530
544
  retentionController.start();
531
545
  // M1: Initialize project registry (scaffolds general/, scans PROJECTS_DIR, starts fs.watch watcher)
532
546
  await projectStore.initialize();
547
+ markBootPhase('projects');
533
548
  startGateway();
534
549
  prewarmPiBackend();
535
550
  startClientManager(parseInt(process.env.CORTEX_CLIENT_PORT || '3002', 10), process.env.CORTEX_CLIENT_HOST);
@@ -547,6 +562,7 @@ installSigtermShutdown(shutdownHandles);
547
562
  const dailyUpdateCheck = setInterval(() => { void runUpdateCheck(); }, 24 * 60 * 60 * 1000);
548
563
  dailyUpdateCheck.unref?.();
549
564
  await scheduler.start();
565
+ markBootPhase('scheduler');
550
566
  // Daily store archival: move week-old terminal execution records to data/archive/*.jsonl.
551
567
  // Keeps the hot stores small — their full-map sync stringify on every persist is the main
552
568
  // event-loop stall source when they grow to multi-MB.
@@ -578,6 +594,7 @@ installSigtermShutdown(shutdownHandles);
578
594
  // Waitpoints: drains the signal spool, ages out expired waitpoints and retries any wake whose
579
595
  // delivery failed. Every in-memory fast path dies with the process; this does not.
580
596
  startWaitpointSweep();
597
+ startTelemetryService();
581
598
  startBuiltinJobs();
582
599
  void emitCortexEvent('cortex:server.start', {
583
600
  version: CORTEX_VERSION,
@@ -590,5 +607,6 @@ installSigtermShutdown(shutdownHandles);
590
607
  : 'provider setup required';
591
608
  log.info(`Cortex agent is running (${adapter.name}) — ${selectionSummary}`
592
609
  + ` · boot ${Math.round(performance.now())}ms (imports ${importsMs}ms)`);
610
+ recordStartup(importsMs);
593
611
  syncTerminalCommand();
594
612
  })();
@@ -4,18 +4,29 @@ export function getInitHelp() {
4
4
  return [
5
5
  'Initialize Cortex data directory',
6
6
  '',
7
- 'Usage: cortex init [--home <path>] [--gateway-config-dir <path>]',
7
+ 'Usage: cortex init [--home <path>] [--gateway-config-dir <path>] [--force] [--answers <file>] [--json]',
8
8
  '',
9
- 'Creates the CORTEX_HOME directory structure, prompts for backends,',
10
- 'interaction platform (Slack / Feishu), gateway usage, and system service.',
11
- 'Generates .env with platform tokens, copies default configs, and',
12
- 'auto-generates mcp-config.json and agent-state.json.',
9
+ 'Creates the CORTEX_HOME directory structure and asks for the language, interaction',
10
+ 'platform (Slack / Feishu), machine name, usage reporting and system service.',
11
+ 'Writes .env, copies default configs and generates mcp-config*.json, machines.json',
12
+ 'and agent-state.json. It then detects provider logins, offers to log in, and sets',
13
+ 'up gateway routes, the default model and favorites.',
13
14
  '',
14
15
  'Options:',
15
- ' --home <path> Set CORTEX_HOME (default: $CORTEX_HOME or ~/.cortex/)',
16
+ ' --home <path> Set CORTEX_HOME (default: $CORTEX_HOME or ~/.cortex/)',
16
17
  ' --gateway-config-dir <path> Gateway config output directory (default: ~/.aistatus/)',
17
- ' --force Overwrite existing configs (.env, budget.json, agent-state.json, etc.)',
18
- ' --help, -h Show this help',
18
+ ' --force Overwrite existing configs (.env, budget.json, agent-state.json, etc.)',
19
+ ' --answers <file> Read answers from a JSON file instead of prompting; omitted fields use defaults',
20
+ ' --json Print NDJSON progress events on stdout and send human output to stderr',
21
+ ' --help, -h Show this help',
22
+ '',
23
+ 'With --answers or --json, init does not prompt or start provider login; it reports',
24
+ 'credential status and can finish before any provider is set up.',
25
+ '',
26
+ 'Examples:',
27
+ ' cortex init',
28
+ ' cortex init --home /data/cortex',
29
+ ' cortex init --answers answers.json --json',
19
30
  ].join('\n');
20
31
  }
21
32
  export function getSetupGatewayHelp() {
@@ -53,21 +64,23 @@ export function getTuiHelp() {
53
64
  export function getUiHelp() {
54
65
  return formatHelp({
55
66
  name: 'cortex ui',
56
- description: 'Manage the local Web UI endpoint used by the Cortex desktop app',
57
- usage: 'cortex ui enable [--port <port>] [--home <path>] [--json]',
67
+ description: 'Manage the Web UI endpoint used by the Cortex apps and browsers',
68
+ usage: 'cortex ui <enable|pair> [--port <port>] [--home <path>] [--json]',
58
69
  commands: [
59
70
  { name: 'enable', description: 'Turn on the loopback Web UI endpoint and print how to reach it' },
71
+ { name: 'pair', description: 'Print a one-time pairing code (10 minutes) for a new app or browser' },
60
72
  ],
61
73
  options: [
62
- { flag: '--port <port>', description: 'TCP port to serve the Web UI on', default: '3004' },
63
- { flag: '--home <path>', description: 'CORTEX_HOME to configure', default: '$CORTEX_HOME or ~/.cortex' },
64
- { flag: '--json', description: 'Print the endpoint, token and change state as JSON' },
74
+ { flag: '--port <port>', description: 'enable: TCP port to serve the Web UI on', default: 'the configured CORTEX_UI_PORT, else 3004' },
75
+ { flag: '--home <path>', description: 'CORTEX_HOME to use', default: '$CORTEX_HOME or ~/.cortex' },
76
+ { flag: '--json', description: 'Print the result as JSON (enable: endpoint, token, change state; pair: code, expiry)' },
65
77
  { flag: '--help, -h', description: 'Show this help' },
66
78
  ],
67
79
  examples: [
68
- { description: 'Enable the endpoint on the default port', command: 'cortex ui enable' },
80
+ { description: 'Enable the endpoint, keeping the configured port', command: 'cortex ui enable' },
69
81
  { description: 'Serve on another port', command: 'cortex ui enable --port 4000' },
70
82
  { description: 'Machine-readable output for the desktop setup flow', command: 'cortex ui enable --json' },
83
+ { description: 'Get a code to connect a phone or another computer', command: 'cortex ui pair' },
71
84
  ],
72
85
  });
73
86
  }
@@ -68,7 +68,7 @@
68
68
  * rebuild pipeline; in production mode it just respawns app.js.
69
69
  */
70
70
  import { type RebuildProgress, type RebuildStepName } from '../core/rebuild-progress.js';
71
- export declare function buildChildProcessConfig(restartReason?: string | null): {
71
+ export declare function buildChildProcessConfig(restartReason?: string | null, childExit?: string | null): {
72
72
  cwd: string;
73
73
  windowsHide: boolean;
74
74
  stdio: ("ignore" | "ipc" | "pipe")[];