@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
@@ -28,24 +28,24 @@ const FLAT_MODE = 'default';
28
28
  * forces gateway routing) or direct-call the upstream (if the spawn path leaves models.json
29
29
  * untouched for that provider). Full provider plumbing remains future work.
30
30
  */
31
- const PI_PROVIDER_UPSTREAM = {
31
+ export const PI_PROVIDER_UPSTREAM = {
32
32
  // Anthropic-protocol providers (PI's `api: anthropic-messages`)
33
33
  anthropic: { url: 'https://api.anthropic.com', auth_style: 'bearer' },
34
34
  fireworks: { url: 'https://api.fireworks.ai/inference', auth_style: 'bearer' },
35
35
  'github-copilot': { url: 'https://api.individual.githubcopilot.com', auth_style: 'bearer' },
36
- 'kimi-coding': { url: 'https://api.kimi.com/coding', auth_style: 'bearer' },
37
36
  minimax: { url: 'https://api.minimax.io/anthropic', auth_style: 'bearer' },
38
37
  'minimax-cn': { url: 'https://api.minimaxi.com/anthropic', auth_style: 'bearer' },
39
- opencode: { url: 'https://opencode.ai/zen', auth_style: 'bearer' },
38
+ opencode: { url: 'https://opencode.ai/inference', auth_style: 'bearer' },
40
39
  'vercel-ai-gateway': { url: 'https://ai-gateway.vercel.sh', auth_style: 'bearer' },
41
40
  // OpenAI-completions / OpenAI-responses providers
42
41
  cerebras: { url: 'https://api.cerebras.ai/v1', auth_style: 'bearer' },
43
42
  deepseek: { url: 'https://api.deepseek.com', auth_style: 'bearer' },
44
43
  groq: { url: 'https://api.groq.com/openai/v1', auth_style: 'bearer' },
45
44
  huggingface: { url: 'https://router.huggingface.co/v1', auth_style: 'bearer' },
45
+ 'kimi-coding': { url: 'https://api.kimi.com/coding/v1', auth_style: 'bearer' },
46
46
  mistral: { url: 'https://api.mistral.ai', auth_style: 'bearer' },
47
47
  openai: { url: 'https://api.openai.com/v1', auth_style: 'bearer' },
48
- 'opencode-go': { url: 'https://opencode.ai/zen/go/v1', auth_style: 'bearer' },
48
+ 'opencode-go': { url: 'https://opencode.ai/inference/go/v1', auth_style: 'bearer' },
49
49
  openrouter: { url: 'https://openrouter.ai/api/v1', auth_style: 'bearer' },
50
50
  xai: { url: 'https://api.x.ai/v1', auth_style: 'bearer' },
51
51
  zai: { url: 'https://api.z.ai/api/coding/paas/v4', auth_style: 'bearer' },
@@ -59,6 +59,44 @@ const PI_PROVIDER_UPSTREAM = {
59
59
  // env-driven URLs (region / account ID / resource name) — not safely templated here.
60
60
  // Users wanting these through the gateway must edit gateway.yaml manually.
61
61
  };
62
+ /**
63
+ * Upstream URLs the table above held for a PI provider before PI moved it (PI 1.3.0). A stored
64
+ * route still on one of these is the route Cortex wrote, not a hand-pointed relay, so it follows
65
+ * the provider to its current upstream; mergeGatewayConfig never rewrites an existing route.
66
+ */
67
+ const RETIRED_PI_UPSTREAMS = {
68
+ 'kimi-coding': ['https://api.kimi.com/coding'],
69
+ opencode: ['https://opencode.ai/zen'],
70
+ 'opencode-go': ['https://opencode.ai/zen/go/v1'],
71
+ };
72
+ /** Point every stored route still on a retired PI upstream at the current one; returns how many moved. */
73
+ export function refreshRetiredPiUpstreams(endpoints) {
74
+ let moved = 0;
75
+ for (const [provider, retired] of Object.entries(RETIRED_PI_UPSTREAMS)) {
76
+ for (const route of Object.values(endpoints[provider] ?? {})) {
77
+ if (!retired.includes(route.base_url))
78
+ continue;
79
+ route.base_url = PI_PROVIDER_UPSTREAM[provider].url;
80
+ moved += 1;
81
+ }
82
+ }
83
+ return moved;
84
+ }
85
+ /** Rewrite gateway.yaml (backing it up first) when a stored route is on a retired PI upstream. */
86
+ export function migrateRetiredPiUpstreams(configPath = path.join(AISTATUS_DIR, 'gateway.yaml')) {
87
+ const parsed = readGatewayYaml(configPath);
88
+ if (!parsed)
89
+ return 0;
90
+ const moved = refreshRetiredPiUpstreams(parsed.endpoints);
91
+ if (moved === 0)
92
+ return 0;
93
+ copyFileSync(configPath, `${configPath}.bak`);
94
+ atomicWriteSync(configPath, serializeGatewayYaml({
95
+ endpoints: parsed.endpoints, top: parsed.top, preservedCustom: [], droppedFromDiscovery: [],
96
+ }));
97
+ log.info(`Moved ${moved} gateway route(s) off retired PI upstream URLs in ${configPath}`);
98
+ return moved;
99
+ }
62
100
  /** The ascending thinking-level ladder PI's own selector walks. */
63
101
  const PI_THINKING_LADDER = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
64
102
  /**
@@ -5,7 +5,7 @@ export type HookSpec = {
5
5
  command: string;
6
6
  args?: string[];
7
7
  timeoutMs: number;
8
- result?: 'hook-result' | 'stdout-as-prompt' | 'none';
8
+ result?: 'stdout-as-prompt' | 'none';
9
9
  };
10
10
  export type HookEmitResult = {
11
11
  id: string;
@@ -43,14 +43,7 @@ function failure(id, error) {
43
43
  return { id, error: message };
44
44
  }
45
45
  function parsedResult(hook, stdout) {
46
- switch (hook.result) {
47
- case 'hook-result':
48
- return { id: hook.id, result: JSON.parse(stdout) };
49
- case 'stdout-as-prompt':
50
- return { id: hook.id, result: stdout.trim() };
51
- default:
52
- return { id: hook.id };
53
- }
46
+ return hook.result === 'stdout-as-prompt' ? { id: hook.id, result: stdout.trim() } : { id: hook.id };
54
47
  }
55
48
  function interpretResult(hook, stdout, stderr) {
56
49
  const result = parsedResult(hook, stdout);
@@ -554,6 +554,7 @@ export declare const en: {
554
554
  'usageSharing.issue.name-required': 'A name is required to join the leaderboard.';
555
555
  'usageSharing.issue.email-invalid': 'A valid email is required to join the leaderboard.';
556
556
  'init.serviceRegister.prompt': 'Register Cortex as a system service (auto-start on boot)?';
557
+ 'init.telemetry.prompt': 'Send anonymous usage and crash statistics to help improve Cortex? (never your prompts, files or names; can be turned off in Settings)';
557
558
  'init.gatewaySetup.overwritePrompt': 'An existing default model was found. Replace it with a new selection?';
558
559
  'init.gatewaySetup.defaultPrompt': 'Pick the default model:';
559
560
  'init.gatewaySetup.favoritesPrompt': 'Pick favorite models (space to toggle; the default model is always included):';
@@ -119,6 +119,7 @@ export declare const initEn: {
119
119
  readonly 'usageSharing.issue.name-required': 'A name is required to join the leaderboard.';
120
120
  readonly 'usageSharing.issue.email-invalid': 'A valid email is required to join the leaderboard.';
121
121
  readonly 'init.serviceRegister.prompt': 'Register Cortex as a system service (auto-start on boot)?';
122
+ readonly 'init.telemetry.prompt': 'Send anonymous usage and crash statistics to help improve Cortex? (never your prompts, files or names; can be turned off in Settings)';
122
123
  readonly 'init.gatewaySetup.overwritePrompt': 'An existing default model was found. Replace it with a new selection?';
123
124
  readonly 'init.gatewaySetup.defaultPrompt': 'Pick the default model:';
124
125
  readonly 'init.gatewaySetup.favoritesPrompt': 'Pick favorite models (space to toggle; the default model is always included):';
@@ -178,6 +178,7 @@ export const initEn = {
178
178
  'usageSharing.issue.email-invalid': 'A valid email is required to join the leaderboard.',
179
179
  // ── Service registration prompt ──
180
180
  'init.serviceRegister.prompt': 'Register Cortex as a system service (auto-start on boot)?',
181
+ 'init.telemetry.prompt': 'Send anonymous usage and crash statistics to help improve Cortex? (never your prompts, files or names; can be turned off in Settings)',
181
182
  // ── Gateway & model auto-setup ──
182
183
  'init.gatewaySetup.overwritePrompt': 'An existing default model was found. Replace it with a new selection?',
183
184
  'init.gatewaySetup.defaultPrompt': 'Pick the default model:',
@@ -392,6 +393,7 @@ export const initZh = {
392
393
  'usageSharing.issue.email-invalid': '加入排行榜需要填写有效的邮箱。',
393
394
  // ── Service registration prompt ──
394
395
  'init.serviceRegister.prompt': '将 Cortex 注册为系统服务(开机自启)?',
396
+ 'init.telemetry.prompt': '发送匿名使用与崩溃统计,帮助改进 Cortex?(不含对话、文件或名称;可随时在设置中关闭)',
395
397
  // ── Gateway & model auto-setup ──
396
398
  'init.gatewaySetup.overwritePrompt': '检测到已有默认模型,是否用新的选择替换?',
397
399
  'init.gatewaySetup.defaultPrompt': '选择默认模型:',
@@ -10,4 +10,7 @@ export interface Logger {
10
10
  error(...args: unknown[]): void;
11
11
  debug(...args: unknown[]): void;
12
12
  }
13
+ /** Observer of every `log.error` call (the telemetry error digest). Set once by the app. */
14
+ export type ErrorLogSink = (module: string, args: unknown[]) => void;
15
+ export declare function setErrorLogSink(sink: ErrorLogSink | null): void;
13
16
  export declare function createLogger(mod: string): Logger;
package/dist/core/log.js CHANGED
@@ -114,6 +114,23 @@ function formatArg(a) {
114
114
  }
115
115
  return String(a);
116
116
  }
117
+ let errorSink = null;
118
+ let inErrorSink = false;
119
+ export function setErrorLogSink(sink) {
120
+ errorSink = sink;
121
+ }
122
+ function notifyErrorSink(mod, args) {
123
+ if (!errorSink || inErrorSink)
124
+ return;
125
+ inErrorSink = true;
126
+ try {
127
+ errorSink(mod, args);
128
+ }
129
+ catch { /* an observer never breaks logging */ }
130
+ finally {
131
+ inErrorSink = false;
132
+ }
133
+ }
117
134
  // ── Core write ──────────────────────────────────────────
118
135
  function writeConsole(level, prefix, args) {
119
136
  if (processLogPolicy.consoleToStderr)
@@ -148,7 +165,7 @@ export function createLogger(mod) {
148
165
  return {
149
166
  info: (...args) => write('INFO', mod, args),
150
167
  warn: (...args) => write('WARN', mod, args),
151
- error: (...args) => write('ERROR', mod, args),
168
+ error: (...args) => { write('ERROR', mod, args); notifyErrorSink(mod, args); },
152
169
  debug: (...args) => { if (isDebugMode())
153
170
  write('DEBUG', mod, args); },
154
171
  };
@@ -27,6 +27,7 @@ export interface Settings {
27
27
  serverAutoUpdate: boolean;
28
28
  clientHotReloadEnabled: boolean;
29
29
  teamEnabled: boolean;
30
+ telemetryEnabled: boolean;
30
31
  feishuSkillsInWeb: boolean;
31
32
  waitpointSweepMs: number;
32
33
  waitpointTtlMs: number;
@@ -186,6 +187,10 @@ export declare const SETTINGS_SPEC: {
186
187
  default: true;
187
188
  legacyParse: (raw: string) => raw is "1";
188
189
  };
190
+ telemetryEnabled: {
191
+ type: "boolean";
192
+ default: true;
193
+ };
189
194
  waitpointSweepMs: {
190
195
  envVar: string;
191
196
  type: "number";
@@ -165,6 +165,10 @@ export const SETTINGS_SPEC = {
165
165
  default: true,
166
166
  legacyParse: (raw) => raw === '1',
167
167
  },
168
+ // Anonymous product telemetry (domain/telemetry). CORTEX_TELEMETRY is deliberately not a legacy
169
+ // variable of this key: the gate reads it directly as a hard switch, so `CORTEX_TELEMETRY=0` in
170
+ // .env must stay in .env rather than be migrated away (an existing key here would win over it).
171
+ telemetryEnabled: { type: 'boolean', default: true },
168
172
  waitpointSweepMs: {
169
173
  envVar: 'CORTEX_WAITPOINT_SWEEP_MS',
170
174
  type: 'number',
@@ -37,7 +37,9 @@ export type SystemTurnOrigin =
37
37
  /** A worker's pending question or plan was forwarded to its lead. */
38
38
  | 'worker-question'
39
39
  /** A schedule fired and opened its run with the prompt the user wrote for it. */
40
- | 'scheduled';
40
+ | 'scheduled'
41
+ /** Finished `run_in_background` work re-invoked the model with no turn in flight. */
42
+ | 'background-task';
41
43
  export interface AuthNoticeAction {
42
44
  kind: 'auth-login';
43
45
  noticeId: string;
@@ -8,8 +8,7 @@ import type { McpComposition } from '../../agent-adapter/types.js';
8
8
  export type AgentSettingSource = 'user' | 'project' | 'local';
9
9
  /** The environment fields an agent definition owns. Every default equals the behaviour an agent that
10
10
  * declares none of them already had, so adding the block to a definition changes nothing by itself.
11
- * Mixed into {@link AgentDefinition} and {@link ResolvedEnvironment}; `delegable` sits on the
12
- * definition alone because it describes what the agent is rather than how one use of it runs. */
11
+ * Mixed into {@link AgentDefinition} and {@link ResolvedEnvironment}. */
13
12
  export interface AgentEnvironment {
14
13
  loadRules?: boolean;
15
14
  disableHooks?: boolean;
@@ -20,7 +19,6 @@ export interface AgentEnvironment {
20
19
  export interface AgentDefinition extends AgentEnvironment {
21
20
  name: string;
22
21
  description?: string;
23
- persistSession?: boolean;
24
22
  directive?: string;
25
23
  systemPrompt?: string;
26
24
  promptTemplate?: string;
@@ -31,9 +29,6 @@ export interface AgentDefinition extends AgentEnvironment {
31
29
  disabledPlugins?: string[];
32
30
  mcpComposition?: McpComposition;
33
31
  mcpToolAllowlist?: string[];
34
- /** Whether this template may be named as a subagent delegation target. Declared now so a
35
- * definition can carry the intent; nothing reads it yet. */
36
- delegable?: boolean;
37
32
  }
38
33
  /** An environment resolved for one run: its definition without the catalog-only fields, with the
39
34
  * MCP allowlist canonicalized. */
@@ -5,7 +5,7 @@ import { createSnapshotWatchMonitor } from '../../../core/resilient-watch.js';
5
5
  import { ENVIRONMENTS_DIR } from './paths.js';
6
6
  import { environmentPluginDirs } from '../../plugins/builtin.js';
7
7
  import { fsRefResolver, resolveFileRef } from './file-refs.js';
8
- import { validateEnvironment } from './schema.js';
8
+ import { RETIRED_ENVIRONMENT_KEYS, validateEnvironment } from './schema.js';
9
9
  const log = createLogger('environments');
10
10
  /** Definitions with retired engine fields removed (no `file:` refs resolved), keyed by file name. */
11
11
  let definitions = {};
@@ -42,7 +42,8 @@ function readDefinitions(dir) {
42
42
  log.warn(`Skipping environment ${file}: name field "${def?.name}" ≠ filename`);
43
43
  continue;
44
44
  }
45
- delete def.profile;
45
+ for (const key of ['profile', ...RETIRED_ENVIRONMENT_KEYS])
46
+ delete def[key];
46
47
  out[name] = def;
47
48
  }
48
49
  return out;
@@ -36,7 +36,6 @@ export declare const environmentSchema: z.ZodObject<{
36
36
  projectContext: z.ZodOptional<z.ZodBoolean>;
37
37
  name: z.ZodString;
38
38
  description: z.ZodOptional<z.ZodString>;
39
- persistSession: z.ZodOptional<z.ZodBoolean>;
40
39
  directive: z.ZodOptional<z.ZodString>;
41
40
  systemPrompt: z.ZodOptional<z.ZodString>;
42
41
  promptTemplate: z.ZodOptional<z.ZodString>;
@@ -50,8 +49,10 @@ export declare const environmentSchema: z.ZodObject<{
50
49
  none: "none";
51
50
  }>>;
52
51
  mcpToolAllowlist: z.ZodOptional<z.ZodArray<z.ZodString>>;
53
- delegable: z.ZodOptional<z.ZodBoolean>;
54
52
  }, z.core.$strip>;
53
+ /** Fields older files may still carry. They no longer do anything: accepted without a warning and
54
+ * dropped on load. */
55
+ export declare const RETIRED_ENVIRONMENT_KEYS: readonly ['persistSession', 'delegable'];
55
56
  /** Zod issues as anchored validation issues. */
56
57
  export declare function zodIssues(result: z.ZodSafeParseResult<unknown>): Issue[];
57
58
  export declare function unknownKeyWarnings(body: Record<string, unknown>, known: ReadonlySet<string>): Issue[];
@@ -15,7 +15,6 @@ export const environmentFieldsShape = {
15
15
  export const environmentSchema = z.object({
16
16
  name: z.string().min(1),
17
17
  description: z.string().optional(),
18
- persistSession: z.boolean().optional(),
19
18
  directive: z.string().optional(),
20
19
  systemPrompt: z.string().optional(),
21
20
  promptTemplate: z.string().optional(),
@@ -26,11 +25,13 @@ export const environmentSchema = z.object({
26
25
  disabledPlugins: z.array(z.string()).optional(),
27
26
  mcpComposition: z.enum(['direct', 'none']).optional(),
28
27
  mcpToolAllowlist: z.array(z.string()).optional(),
29
- delegable: z.boolean().optional(),
30
28
  ...environmentFieldsShape,
31
29
  });
30
+ /** Fields older files may still carry. They no longer do anything: accepted without a warning and
31
+ * dropped on load. */
32
+ export const RETIRED_ENVIRONMENT_KEYS = ['persistSession', 'delegable'];
32
33
  // Keys the schema knows about. Anything else is a warning, never an error.
33
- const ENVIRONMENT_KEYS = new Set(Object.keys(environmentSchema.shape));
34
+ const ENVIRONMENT_KEYS = new Set([...Object.keys(environmentSchema.shape), ...RETIRED_ENVIRONMENT_KEYS]);
34
35
  function formatPath(segments) {
35
36
  let out = '';
36
37
  for (const seg of segments) {
@@ -14,6 +14,38 @@ const AUTH_KIND_KEYS = {
14
14
  function pairKey(event) {
15
15
  return `${event.backend}:${event.provider}`;
16
16
  }
17
+ /** One reminder per pair and channel every 24h; a null channel (internal run) is its own bucket. */
18
+ class ReminderLedger {
19
+ now;
20
+ byPair = new Map();
21
+ constructor(now) {
22
+ this.now = now;
23
+ }
24
+ fresh(reminder) {
25
+ return reminder !== undefined && this.now() - reminder.notifiedAt < REMINDER_INTERVAL_MS;
26
+ }
27
+ anyRecent(pair) {
28
+ return [...(this.byPair.get(pair)?.values() ?? [])].some(reminder => this.fresh(reminder));
29
+ }
30
+ /** Reserve before async delivery so concurrent events cannot create a retry storm. */
31
+ reserve(pair, channel) {
32
+ const channels = this.byPair.get(pair) ?? new Map();
33
+ if (this.fresh(channels.get(channel)))
34
+ return null;
35
+ const attempt = Symbol(pair);
36
+ channels.set(channel, { notifiedAt: this.now(), attempt });
37
+ this.byPair.set(pair, channels);
38
+ return attempt;
39
+ }
40
+ release(pair, channel, attempt) {
41
+ const channels = this.byPair.get(pair);
42
+ if (channels?.get(channel)?.attempt === attempt)
43
+ channels.delete(channel);
44
+ }
45
+ clear(pair) {
46
+ this.byPair.delete(pair);
47
+ }
48
+ }
17
49
  let recentNotificationQuery = () => false;
18
50
  export function wasAuthRecentlyNotified(backend, provider) {
19
51
  return recentNotificationQuery(backend, provider);
@@ -91,14 +123,21 @@ async function postPlatformNotice(adapter, event, text, action, buildAction) {
91
123
  ...(event.sessionId !== null ? { sessionId: event.sessionId } : {}),
92
124
  }, platformContent(text, button));
93
125
  }
126
+ /** Internal runs have no conversation: the notice and its login button go to the admin channel. */
127
+ async function emitAdminNotice(adapter, notice, action, buildAction) {
128
+ const button = action && buildAction ? buildAction(action, '', notice.text) : null;
129
+ const { richBlocks } = platformContent(notice.text, button);
130
+ await emitSystemNotice(adapter, { ...notice, level: 'error', richBlocks });
131
+ }
94
132
  async function deliverNotice(bus, adapter, event, dependencies) {
95
133
  const web = event.channel?.startsWith('web:') ?? false;
96
134
  const snapshot = await readSnapshot(dependencies.readStatus ?? getAuthStatus);
97
- const action = event.channel ? resolveAction(event, snapshot) : null;
98
- const actionable = !!action && (web || !!dependencies.buildPlatformAction);
135
+ const action = resolveAction(event, snapshot);
136
+ // The admin notice's Web toast cannot carry the button, so its text keeps the manual guidance.
137
+ const actionable = !!action && event.channel !== null && (web || !!dependencies.buildPlatformAction);
99
138
  const notice = buildNotice(event, findAccount(snapshot, event), actionable);
100
139
  if (event.channel === null) {
101
- await emitSystemNotice(adapter, { ...notice, level: 'error' });
140
+ await emitAdminNotice(adapter, notice, action, dependencies.buildPlatformAction);
102
141
  }
103
142
  else if (web) {
104
143
  publishWebNotice(bus, event, notice.text, action);
@@ -109,28 +148,19 @@ async function deliverNotice(bus, adapter, event, dependencies) {
109
148
  }
110
149
  export function registerAuthWatch(bus, adapter, dependencies = {}) {
111
150
  // A restart may repeat one reminder; keeping this local avoids shared mutable publisher state.
112
- const reminders = new Map();
113
- const now = dependencies.now ?? Date.now;
114
- const wasRecentlyNotified = (backend, provider) => {
115
- const previous = reminders.get(pairKey({ backend, provider }))?.notifiedAt;
116
- return previous !== undefined && now() - previous < REMINDER_INTERVAL_MS;
117
- };
118
- recentNotificationQuery = wasRecentlyNotified;
151
+ const reminders = new ReminderLedger(dependencies.now ?? Date.now);
152
+ recentNotificationQuery = (backend, provider) => reminders.anyRecent(pairKey({ backend, provider }));
119
153
  bus.subscribe('auth.required', (event) => {
120
154
  const key = pairKey(event);
121
- const current = now();
122
- if (wasRecentlyNotified(event.backend, event.provider))
155
+ const attempt = reminders.reserve(key, event.channel);
156
+ if (!attempt)
123
157
  return;
124
- // Reserve before async delivery so concurrent events cannot create a retry storm.
125
- const attempt = Symbol(key);
126
- reminders.set(key, { notifiedAt: current, attempt });
127
158
  void deliverNotice(bus, adapter, event, dependencies).catch(() => {
128
- if (reminders.get(key)?.attempt === attempt)
129
- reminders.delete(key);
159
+ reminders.release(key, event.channel, attempt);
130
160
  log.error(`Failed to deliver authentication notice for ${key}`);
131
161
  });
132
162
  });
133
163
  bus.subscribe('auth.recovered', (event) => {
134
- reminders.delete(pairKey(event));
164
+ reminders.clear(pairKey(event));
135
165
  });
136
166
  }
@@ -24,7 +24,6 @@ export interface CortexToolContext {
24
24
  subagentClaudeModels: SubagentModelOption[];
25
25
  scheduleTaskId: string | null;
26
26
  callbackSource: string | null;
27
- branchMachine: string | null;
28
27
  /** Daemon webhook root, e.g. `http://127.0.0.1:3001`. */
29
28
  webhookBaseUrl: string;
30
29
  /** Shared secret for the daemon webhook gate (`x-cortex-token`). Empty when unavailable. */
@@ -37,7 +37,6 @@ export function toolContextFromEnv(env = process.env) {
37
37
  subagentClaudeModels: decodeSubagentModels(env.CORTEX_SUBAGENT_CLAUDE_MODELS),
38
38
  scheduleTaskId: optional(env.CORTEX_SCHEDULE_TASK_ID),
39
39
  callbackSource: optional(env.CORTEX_CALLBACK_SOURCE),
40
- branchMachine: optional(env.CORTEX_BRANCH_MACHINE),
41
40
  webhookBaseUrl: `http://127.0.0.1:${positiveInt(env.WEBHOOK_PORT, DEFAULT_WEBHOOK_PORT)}`,
42
41
  webhookToken: env.CORTEX_WEBHOOK_TOKEN || '',
43
42
  slackBotToken: optional(env.SLACK_BOT_TOKEN),
@@ -18,6 +18,8 @@ export interface EventLoopMonitorOptions {
18
18
  intervalMs?: number;
19
19
  /** Test seam: supplies the histogram instead of `monitorEventLoopDelay`. */
20
20
  createHistogram?: () => EventLoopDelayHistogram;
21
+ /** Observer of each closed window (telemetry). */
22
+ onReading?: (reading: EventLoopLagReading) => void;
21
23
  }
22
24
  /**
23
25
  * Close the current window: read the percentiles, log them, and reset the histogram.
@@ -43,7 +43,11 @@ export function startEventLoopMonitor(options = {}) {
43
43
  _intervalMs = options.intervalMs ?? DEFAULT_SAMPLE_INTERVAL_MS;
44
44
  _histogram = (options.createHistogram ?? (() => monitorEventLoopDelay({ resolution: RESOLUTION_MS })))();
45
45
  _histogram.enable();
46
- _timer = setInterval(() => { sampleEventLoopLagOnce(); }, _intervalMs);
46
+ _timer = setInterval(() => {
47
+ const reading = sampleEventLoopLagOnce();
48
+ if (reading)
49
+ options.onReading?.(reading);
50
+ }, _intervalMs);
47
51
  // The daemon's lifetime is owned by its servers, never by this metric timer.
48
52
  if (typeof _timer.unref === 'function')
49
53
  _timer.unref();
@@ -33,7 +33,14 @@ export declare function removePlugin(id: string): void;
33
33
  /** Give a legacy plugin the root manifest that portable discovery needs, reusing the legacy
34
34
  * manifest's own fields. The legacy file is left in place. */
35
35
  export declare function convertToPortable(id: string): void;
36
+ export interface McpSource {
37
+ servers: Record<string, unknown>;
38
+ /** Hash of the mcp.json bytes in effect; an absent file hashes as empty. */
39
+ baseHash: string;
40
+ }
36
41
  /** The raw envelope, secrets included. Only the ui-service redaction layer may see this — it must
37
42
  * never be returned to a browser unfiltered (that is the whole point of PLUGIN_MCP_RUNTIME). */
43
+ export declare function readMcpSource(pluginId: string): McpSource;
38
44
  export declare function readMcpEnvelope(pluginId: string): Record<string, unknown>;
39
- export declare function writeMcpEnvelope(pluginId: string, servers: Record<string, unknown>): void;
45
+ /** Optimistic concurrency, same contract as writeSkillSource. */
46
+ export declare function writeMcpEnvelope(pluginId: string, servers: Record<string, unknown>, baseHash: string): void;
@@ -273,15 +273,23 @@ export function convertToPortable(id) {
273
273
  body.description = legacy.description;
274
274
  atomicWriteSync(containedTarget(root), `${JSON.stringify(body, null, 2)}\n`);
275
275
  }
276
- function readJson(filePath) {
276
+ function parseJsonObject(text) {
277
277
  try {
278
- const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
278
+ const parsed = JSON.parse(text);
279
279
  return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
280
280
  }
281
281
  catch {
282
282
  return null;
283
283
  }
284
284
  }
285
+ function readJson(filePath) {
286
+ try {
287
+ return parseJsonObject(fs.readFileSync(filePath, 'utf8'));
288
+ }
289
+ catch {
290
+ return null;
291
+ }
292
+ }
285
293
  /** The mcp.json in effect: the user's when their layer has one, otherwise the built-in plugin's. */
286
294
  function effectiveMcpFile(pluginId) {
287
295
  assertName('plugin id', pluginId);
@@ -294,19 +302,26 @@ function effectiveMcpFile(pluginId) {
294
302
  }
295
303
  /** The raw envelope, secrets included. Only the ui-service redaction layer may see this — it must
296
304
  * never be returned to a browser unfiltered (that is the whole point of PLUGIN_MCP_RUNTIME). */
297
- export function readMcpEnvelope(pluginId) {
305
+ export function readMcpSource(pluginId) {
298
306
  const file = effectiveMcpFile(pluginId);
299
307
  if (!file)
300
- return {};
301
- const parsed = readJson(file);
308
+ return { servers: {}, baseHash: sha256('') };
309
+ const text = fs.readFileSync(file, 'utf8');
310
+ const parsed = parseJsonObject(text);
302
311
  if (!parsed)
303
312
  throw fail('invalid-args', `'${pluginId}/mcp.json' is not valid JSON`);
304
313
  const servers = parsed.mcpServers;
305
- return servers && typeof servers === 'object' && !Array.isArray(servers)
306
- ? servers
307
- : {};
314
+ const valid = servers && typeof servers === 'object' && !Array.isArray(servers);
315
+ return { servers: valid ? servers : {}, baseHash: sha256(text) };
308
316
  }
309
- export function writeMcpEnvelope(pluginId, servers) {
317
+ export function readMcpEnvelope(pluginId) {
318
+ return readMcpSource(pluginId).servers;
319
+ }
320
+ /** Optimistic concurrency, same contract as writeSkillSource. */
321
+ export function writeMcpEnvelope(pluginId, servers, baseHash) {
322
+ if (readMcpSource(pluginId).baseHash !== baseHash) {
323
+ throw fail('conflict', `'${pluginId}/mcp.json' changed on disk`);
324
+ }
310
325
  const envelope = { $schema: AGENT_PLUGIN_V1_MCP_SCHEMA_URL, mcpServers: servers };
311
326
  const parsed = portableMcpSchema.safeParse(envelope);
312
327
  if (!parsed.success) {
@@ -6,5 +6,12 @@ export declare function markInUse(directory: string): void;
6
6
  * directory a later spawn still wants is rebuilt at the same path. Returns what was removed.
7
7
  */
8
8
  export declare function sweepStaleRuntimeDirs(backendDir: string, inUse: ReadonlySet<string>, now?: number): string[];
9
+ /**
10
+ * Remove Claude MCP and remote-proxy configs under `runtimeDir` that nothing has touched for
11
+ * {@link STALE_AFTER_MS}. Every Claude spawn and every pooled-session reuse check rewrites or touches
12
+ * the files it resolves, and an idle Claude process exits within the hour, so a file this old is
13
+ * used by no running process. A later spawn that wants it writes it again at the same path.
14
+ */
15
+ export declare function sweepStaleClaudeMcpFiles(runtimeDir: string, now?: number): string[];
9
16
  /** Test hook: forget the per-directory sweep throttle. */
10
17
  export declare function _resetSweepThrottle(): void;