@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,12 +1,18 @@
1
+ import * as path from 'node:path';
1
2
  import { formatError } from '../core/cli-utils.js';
3
+ import { createPairingStore, PAIRING_CODE_TTL_MS, PAIRING_FILE_NAME } from '../platform/ui-http/ui-pairing.js';
2
4
  import { getResolvedPaths } from './init.js';
3
5
  import { enableLocalUi } from './local-ui.js';
4
6
  import { getUiHelp } from './cli-help.js';
7
+ const SUBCOMMANDS = ['enable', 'pair'];
5
8
  /** Read the value following a flag, or undefined when the flag is absent. */
6
9
  function optionValue(args, flag) {
7
10
  const index = args.indexOf(flag);
8
11
  return index !== -1 && args[index + 1] ? args[index + 1] : undefined;
9
12
  }
13
+ function usageError(message, opts) {
14
+ return { exitCode: 1, stdout: '', stderr: formatError(message, opts) };
15
+ }
10
16
  /**
11
17
  * `cortex ui enable` — make this install reachable by the Cortex desktop app.
12
18
  *
@@ -18,42 +24,14 @@ function optionValue(args, flag) {
18
24
  * `changed` in the JSON output tells the caller whether a running daemon must be restarted: .env is
19
25
  * read at process start, so flipping it mid-flight has no effect until the server respawns.
20
26
  */
21
- export async function runUiCli(args) {
22
- if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
23
- const noSubcommand = args.length === 0;
24
- return noSubcommand
25
- ? {
26
- exitCode: 1,
27
- stdout: '',
28
- stderr: formatError("Missing subcommand for 'ui'.", {
29
- validValues: ['enable'],
30
- hint: 'cortex ui --help',
31
- }),
32
- }
33
- : { exitCode: 0, stdout: getUiHelp(), stderr: '' };
34
- }
35
- if (args[0] !== 'enable') {
36
- return {
37
- exitCode: 1,
38
- stdout: '',
39
- stderr: formatError(`Unknown subcommand: '${args[0]}'.`, {
40
- validValues: ['enable'],
41
- hint: 'cortex ui --help',
42
- }),
43
- };
44
- }
27
+ async function runEnable(args) {
45
28
  const asJson = args.includes('--json');
46
29
  const portRaw = optionValue(args, '--port');
47
30
  const port = portRaw === undefined ? undefined : Number(portRaw);
48
31
  if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) {
49
- return {
50
- exitCode: 1,
51
- stdout: '',
52
- stderr: formatError(`Invalid --port: '${portRaw}'.`, {
53
- validValues: ['an integer in 1-65535'],
54
- hint: 'cortex ui enable --port 3004',
55
- }),
56
- };
32
+ return usageError(`Invalid --port: '${portRaw}'.`, {
33
+ validValues: ['an integer in 1-65535'], hint: 'cortex ui enable --port 3004',
34
+ });
57
35
  }
58
36
  const paths = getResolvedPaths(optionValue(args, '--home'));
59
37
  try {
@@ -68,7 +46,7 @@ export async function runUiCli(args) {
68
46
  result.changed
69
47
  ? 'Configuration changed — restart the daemon to apply (cortex daemon restart).'
70
48
  : 'Already configured — no restart needed.',
71
- 'Connect the desktop app with the CORTEX_CLIENT_TOKEN from config/.env.',
49
+ 'Connect another app or browser with a one-time code from `cortex ui pair`.',
72
50
  ];
73
51
  return { exitCode: 0, stdout: `${lines.join('\n')}\n`, stderr: '' };
74
52
  }
@@ -76,3 +54,34 @@ export async function runUiCli(args) {
76
54
  return { exitCode: 1, stdout: '', stderr: error.message || String(error) };
77
55
  }
78
56
  }
57
+ /**
58
+ * `cortex ui pair` — mint a one-time pairing code for a new app or browser. It goes into the same
59
+ * file the running server redeems from, so the server needs no restart.
60
+ */
61
+ async function runPair(args) {
62
+ const paths = getResolvedPaths(optionValue(args, '--home'));
63
+ const store = createPairingStore({ file: path.join(paths.STORE_DIR, PAIRING_FILE_NAME) });
64
+ const { code, expiresAt } = store.create();
65
+ if (args.includes('--json')) {
66
+ return { exitCode: 0, stdout: `${JSON.stringify({ ok: true, code, expiresAt }, null, 2)}\n`, stderr: '' };
67
+ }
68
+ const lines = [
69
+ `Pairing code: ${code}`,
70
+ `Valid for ${PAIRING_CODE_TTL_MS / 60_000} minutes, once.`,
71
+ 'Enter it with this server\'s address in the Cortex app, or on the browser sign-in page.',
72
+ ];
73
+ return { exitCode: 0, stdout: `${lines.join('\n')}\n`, stderr: '' };
74
+ }
75
+ const RUNNERS = { enable: runEnable, pair: runPair };
76
+ export async function runUiCli(args) {
77
+ if (args.length === 0) {
78
+ return usageError("Missing subcommand for 'ui'.", { validValues: SUBCOMMANDS, hint: 'cortex ui --help' });
79
+ }
80
+ if (args.includes('--help') || args.includes('-h'))
81
+ return { exitCode: 0, stdout: getUiHelp(), stderr: '' };
82
+ const runner = Object.hasOwn(RUNNERS, args[0]) ? RUNNERS[args[0]] : undefined;
83
+ if (!runner) {
84
+ return usageError(`Unknown subcommand: '${args[0]}'.`, { validValues: SUBCOMMANDS, hint: 'cortex ui --help' });
85
+ }
86
+ return runner(args);
87
+ }
@@ -225,10 +225,6 @@ export type CortexEvent = {
225
225
  type: 'llm.active-count-delta';
226
226
  ts: string;
227
227
  delta: number;
228
- } | {
229
- type: 'scheduler.tick';
230
- ts: string;
231
- jobKey: string;
232
228
  } | {
233
229
  type: 'rate-limit.changed';
234
230
  ts: string;
@@ -241,6 +237,7 @@ export type CortexEvent = {
241
237
  ok: boolean;
242
238
  code?: string;
243
239
  } | null;
240
+ client?: 'desktop' | 'android' | 'browser' | null;
244
241
  } | {
245
242
  type: 'event-bus.handler-failed';
246
243
  ts: string;
@@ -1,5 +1,6 @@
1
1
  import { createLogger } from '../../core/log.js';
2
2
  import { extractForwardedContent } from '../status-helpers.js';
3
+ import { countMessage, platformChannel } from '../../domain/telemetry/usage.js';
3
4
  const log = createLogger('app');
4
5
  import { orchestrator } from '../orchestrator.js';
5
6
  const COMMAND_MENTION_TOKEN = /(^|\s+)(?:<@[^>\s]+>|@[^\s@]+)(?=\s|$)/g;
@@ -19,6 +20,7 @@ async function routeIncomingMessage(message, adapter, dispatchCommand) {
19
20
  if (!userMessage && !hasFiles && !forwardedContent)
20
21
  return;
21
22
  const channel = message.ref.conduit;
23
+ countMessage(platformChannel(channel));
22
24
  const threadAnchorId = message.ref.threadId || null;
23
25
  const commandMessage = normalizeCommandMentions(userMessage?.trim());
24
26
  if (dispatchCommand(commandMessage, channel, adapter, threadAnchorId))
@@ -1,4 +1,5 @@
1
1
  import { createLogger } from '../../core/log.js';
2
+ import { recordWebhookCall } from '../../domain/telemetry/usage.js';
2
3
  import { getSettings } from '../../core/settings.js';
3
4
  import { AUTH_HEADER, getWebhookToken, timingSafeEqualStr } from '../../core/auth.js';
4
5
  import * as http from 'http';
@@ -91,6 +92,7 @@ function jsonRoute(handler) {
91
92
  res.end('Bad JSON');
92
93
  return;
93
94
  }
95
+ recordWebhookCall(req.url, data);
94
96
  try {
95
97
  await handler(data, res);
96
98
  }
@@ -34,6 +34,12 @@ export interface TranscriptSinkDeps extends ToolImageDeps {
34
34
  appendSubagentEnd: (sessionId: string, opts: Parameters<typeof conversationHistory.appendSubagentEnd>[1]) => Promise<void>;
35
35
  appendAssistant: (sessionId: string, opts: Parameters<typeof conversationHistory.appendAssistant>[1]) => Promise<void>;
36
36
  appendThinking: (sessionId: string, opts: Parameters<typeof conversationHistory.appendThinking>[1]) => Promise<void>;
37
+ appendUser: (sessionId: string, opts: Parameters<typeof conversationHistory.appendUser>[1]) => Promise<void>;
38
+ /** Open a ledger turn beside a system turn's history row: rewind maps the two by position. */
39
+ beginLedgerTurn: (channel: string, opts: {
40
+ userMessageTs: string;
41
+ userMessageText: string;
42
+ }) => Promise<void>;
37
43
  setTodos: (sessionId: string, snapshot: TodoSnapshot) => void;
38
44
  publishMessage: typeof publishSessionMessage;
39
45
  publishTodos: typeof publishSessionTodos;
@@ -1,6 +1,7 @@
1
1
  import { createLogger } from '../core/log.js';
2
2
  import { sessionTodos } from '../core/session-todos.js';
3
3
  import { conversationHistory, summarizeToolInputForHistory, toolDeviceForHistory } from '../store/conversation-history-repo.js';
4
+ import { conversationLedger } from '../store/conversation-ledger-repo.js';
4
5
  import { sessionStore } from '../store/session-registry-repo.js';
5
6
  import { subagentSpawnFromAttribution, subagentSpawnsFromToolCall } from '../core/subagent-spawn.js';
6
7
  import { teamActionFromToolCall } from '../core/team-action.js';
@@ -50,6 +51,8 @@ const DEFAULT_DEPS = {
50
51
  appendSubagentEnd: (sessionId, opts) => conversationHistory.appendSubagentEnd(sessionId, opts),
51
52
  appendAssistant: (sessionId, opts) => conversationHistory.appendAssistant(sessionId, opts),
52
53
  appendThinking: (sessionId, opts) => conversationHistory.appendThinking(sessionId, opts),
54
+ appendUser: (sessionId, opts) => conversationHistory.appendUser(sessionId, opts),
55
+ beginLedgerTurn: async (channel, opts) => { await conversationLedger.beginTurn(channel, opts); },
53
56
  setTodos: (sessionId, snapshot) => sessionTodos.set(sessionId, snapshot),
54
57
  publishMessage: publishSessionMessage,
55
58
  publishTodos: publishSessionTodos,
@@ -63,6 +66,7 @@ const DEFAULT_DEPS = {
63
66
  /** The event kinds this sink writes as transcript rows (context usage is stored beside them). */
64
67
  const ROW_EVENT_TYPES = new Set([
65
68
  'assistant_text', 'assistant_thinking', 'tool_use', 'tool_result', 'todo_update', 'subagent_end', 'context_usage',
69
+ 'background_wake',
66
70
  ]);
67
71
  /** A background-phase event this sink would write: what a hold or the injection ledger forwards. */
68
72
  export function isBackgroundRowEvent(event) {
@@ -145,6 +149,16 @@ export function createTranscriptSink(opts) {
145
149
  subagentId: parentToolUseId, subagentEnded: status,
146
150
  });
147
151
  }
152
+ /** Finished background tasks woke the agent: a system turn, so the chat starts a new reply at it
153
+ * instead of folding the woken turn into the previous one. The history row is queued before
154
+ * anything the woken turn writes; a channel with no ledger simply has no rewind to keep aligned. */
155
+ function persistBackgroundWake(summaries) {
156
+ const ts = new Date().toISOString();
157
+ const text = summaries.join('\n');
158
+ recordHistory(deps.appendUser(sessionId, { text, ts, systemOrigin: 'background-task' }));
159
+ recordHistory(deps.beginLedgerTurn(channel, { userMessageTs: `bg-wake:${ts}`, userMessageText: text }));
160
+ deps.publishMessage({ sessionId, channel, role: 'user', text, ts, systemOrigin: 'background-task' });
161
+ }
148
162
  function persistThinking(text, blockId) {
149
163
  if (blockId)
150
164
  opts.flushDelta?.(blockId);
@@ -225,6 +239,9 @@ export function createTranscriptSink(opts) {
225
239
  case 'assistant_thinking':
226
240
  persistThinking(event.text, event.blockId);
227
241
  return;
242
+ case 'background_wake':
243
+ persistBackgroundWake(event.summaries);
244
+ return;
228
245
  case 'assistant_text':
229
246
  persistAssistant(event.text, event.blockId, event.noticeLevel, event.noticeAction, event.subagent, event.phase);
230
247
  return;
@@ -5,6 +5,7 @@
5
5
  // free.
6
6
  // - spool ingestion: a file dropped in the spool dir is equivalent to a POST, which is how
7
7
  // a machine with no curl (or no route to the daemon) still reports.
8
+ import { countFeature } from '../domain/telemetry/usage.js';
8
9
  import fs from 'node:fs/promises';
9
10
  import path from 'node:path';
10
11
  import { createLogger } from '../core/log.js';
@@ -72,6 +73,8 @@ export async function ingestSignal(input, deps = productionIngestDeps) {
72
73
  if (outcome.kind === 'accepted' && outcome.fired) {
73
74
  scheduleWaitpointDelivery(outcome.waitpoint, deps.notifier);
74
75
  }
76
+ if (outcome.kind === 'accepted')
77
+ countFeature('waitpoint_signaled');
75
78
  return outcome;
76
79
  }
77
80
  const SPOOL_DISPOSITION = {
@@ -23,6 +23,8 @@ export interface UiAuthRouteDeps {
23
23
  authorize: (req: http.IncomingMessage) => Promise<boolean>;
24
24
  /** Session lifetime, mirrored into the cookie's Max-Age. */
25
25
  ttlMs: number;
26
+ /** Consume a one-time pairing code (ui-pairing.ts). Absent → only the client token signs in. */
27
+ redeemCode?: (code: string) => boolean;
26
28
  }
27
29
  /**
28
30
  * Whether this request arrived over a channel where a `Secure` cookie will actually be stored:
@@ -4,6 +4,7 @@
4
4
  import { timingSafeEqualStr } from '../../core/auth.js';
5
5
  import { createLogger } from '../../core/log.js';
6
6
  import { readJsonBody, sendError, sendJson, sendMethodNotAllowed } from './http-json.js';
7
+ import { normalizePairingCode } from './ui-pairing.js';
7
8
  import { parseCookie } from './ui-session.js';
8
9
  const log = createLogger('ui-http');
9
10
  /** Cookie carrying the opaque session id. Name is stable — the SPA never reads it (HttpOnly). */
@@ -55,6 +56,12 @@ export function sessionCookie(sid, maxAgeSec, secure) {
55
56
  export function sessionIdFrom(req) {
56
57
  return parseCookie(req.headers.cookie, UI_SESSION_COOKIE);
57
58
  }
59
+ /** A typed pairing code is spent on the code store; anything else must be the client token. */
60
+ function acceptsLogin(deps, presented) {
61
+ if (deps.redeemCode && normalizePairingCode(presented))
62
+ return deps.redeemCode(presented);
63
+ return timingSafeEqualStr(deps.getToken(), presented);
64
+ }
58
65
  /**
59
66
  * The three token-login routes. `/api/ui/login` and `/api/ui/session` MUST be registered as public
60
67
  * routes on the server (a browser with no credential has to be able to reach them); `/api/ui/logout`
@@ -72,9 +79,9 @@ export function createUiAuthRoutes(deps) {
72
79
  if (!body)
73
80
  return;
74
81
  const presented = typeof body.token === 'string' ? body.token.trim() : '';
75
- if (!timingSafeEqualStr(deps.getToken(), presented)) {
82
+ if (!acceptsLogin(deps, presented)) {
76
83
  await new Promise((resolve) => setTimeout(resolve, LOGIN_FAILURE_DELAY_MS));
77
- log.warn('ui login rejected: wrong token');
84
+ log.warn('ui login rejected: wrong token or pairing code');
78
85
  return sendError(res, 401, 'invalid-token', 'Invalid token');
79
86
  }
80
87
  const sid = deps.store.create();
@@ -0,0 +1,13 @@
1
+ import type { CustomRouteHandler } from './ui-http-server.js';
2
+ import type { UiDeviceStore } from './ui-devices.js';
3
+ import type { PairingStore } from './ui-pairing.js';
4
+ export declare const UI_PAIR_PATH = "/api/ui/pair";
5
+ export declare const UI_PAIRING_CODE_PATH = "/api/ui/pairing-code";
6
+ export declare const UI_DEVICES_PATH = "/api/ui/devices";
7
+ export declare const UI_DEVICE_REVOKE_PATH = "/api/ui/devices/revoke";
8
+ export interface UiDeviceRouteDeps {
9
+ devices: UiDeviceStore;
10
+ /** Absent when token login is off. */
11
+ pairing?: PairingStore;
12
+ }
13
+ export declare function createUiDeviceRoutes(deps: UiDeviceRouteDeps): Record<string, CustomRouteHandler>;
@@ -0,0 +1,81 @@
1
+ // Pairing and paired-device routes.
2
+ //
3
+ // POST /api/ui/pair PUBLIC {code, name} → {token}: an app trades a pairing code for its
4
+ // own device token.
5
+ // POST /api/ui/pairing-code gated → {code, expiresAt}: a signed-in UI mints a code.
6
+ // GET /api/ui/devices gated → {devices, pairing}: paired apps, `current` marking the caller.
7
+ // POST /api/ui/devices/revoke gated {id}: the device's token stops working at once.
8
+ //
9
+ // Pairing (the first two) exists only while browser token login is on; with it off the server has
10
+ // no public door at all, and the list only offers revoking what was paired before.
11
+ import { AUTH_HEADER } from '../../core/auth.js';
12
+ import { createLogger } from '../../core/log.js';
13
+ import { readJsonBody, sendError, sendJson, sendMethodNotAllowed } from './http-json.js';
14
+ import { LOGIN_FAILURE_DELAY_MS } from './ui-auth-routes.js';
15
+ const log = createLogger('ui-http');
16
+ export const UI_PAIR_PATH = '/api/ui/pair';
17
+ export const UI_PAIRING_CODE_PATH = '/api/ui/pairing-code';
18
+ export const UI_DEVICES_PATH = '/api/ui/devices';
19
+ export const UI_DEVICE_REVOKE_PATH = '/api/ui/devices/revoke';
20
+ function presentedToken(req) {
21
+ const v = req.headers[AUTH_HEADER];
22
+ return Array.isArray(v) ? v[0] : v;
23
+ }
24
+ function pairRoute(devices, pairing) {
25
+ return async (req, res) => {
26
+ if (req.method !== 'POST')
27
+ return sendMethodNotAllowed(res, 'POST');
28
+ const body = await readJsonBody(req, res);
29
+ if (!body)
30
+ return;
31
+ const code = typeof body.code === 'string' ? body.code : '';
32
+ if (!pairing.redeem(code)) {
33
+ await new Promise((resolve) => setTimeout(resolve, LOGIN_FAILURE_DELAY_MS));
34
+ log.warn('app pairing rejected: wrong or expired code');
35
+ return sendError(res, 401, 'invalid-code', 'Invalid or expired pairing code');
36
+ }
37
+ const { device, token } = devices.issue(typeof body.name === 'string' ? body.name : '');
38
+ log.info(`app paired: ${device.name} (${device.id})`);
39
+ sendJson(res, 200, { ok: true, data: { token, device } });
40
+ };
41
+ }
42
+ function pairingCodeRoute(pairing) {
43
+ return async (req, res) => {
44
+ if (req.method !== 'POST')
45
+ return sendMethodNotAllowed(res, 'POST');
46
+ sendJson(res, 200, { ok: true, data: pairing.create() }, { 'Cache-Control': 'no-store' });
47
+ };
48
+ }
49
+ function listRoute(deps) {
50
+ return async (req, res) => {
51
+ if (req.method !== 'GET')
52
+ return sendMethodNotAllowed(res, 'GET');
53
+ const current = deps.devices.match(presentedToken(req))?.id;
54
+ const devices = deps.devices.list().map((d) => ({ ...d, current: d.id === current }));
55
+ sendJson(res, 200, { ok: true, data: { devices, pairing: !!deps.pairing } }, { 'Cache-Control': 'no-store' });
56
+ };
57
+ }
58
+ function revokeRoute(devices) {
59
+ return async (req, res) => {
60
+ if (req.method !== 'POST')
61
+ return sendMethodNotAllowed(res, 'POST');
62
+ const body = await readJsonBody(req, res);
63
+ if (!body)
64
+ return;
65
+ const id = typeof body.id === 'string' ? body.id : '';
66
+ if (!devices.revoke(id))
67
+ return sendError(res, 404, 'not-found', 'No such device');
68
+ log.info(`paired app revoked: ${id}`);
69
+ sendJson(res, 200, { ok: true });
70
+ };
71
+ }
72
+ export function createUiDeviceRoutes(deps) {
73
+ const pairingRoutes = deps.pairing
74
+ ? { [UI_PAIR_PATH]: pairRoute(deps.devices, deps.pairing), [UI_PAIRING_CODE_PATH]: pairingCodeRoute(deps.pairing) }
75
+ : {};
76
+ return {
77
+ ...pairingRoutes,
78
+ [UI_DEVICES_PATH]: listRoute(deps),
79
+ [UI_DEVICE_REVOKE_PATH]: revokeRoute(deps.devices),
80
+ };
81
+ }
@@ -0,0 +1,24 @@
1
+ /** Last-use times move on every request; disk sees them at most this often per device. */
2
+ export declare const DEVICE_SEEN_PERSIST_MS: number;
3
+ export interface UiDevice {
4
+ id: string;
5
+ name: string;
6
+ createdAt: number;
7
+ lastSeenAt: number;
8
+ }
9
+ export interface UiDeviceStore {
10
+ /** Register a device and return its token. The token is never retrievable again. */
11
+ issue(name: string): {
12
+ device: UiDevice;
13
+ token: string;
14
+ };
15
+ /** The device a presented token belongs to, recording the use. */
16
+ match(token: string | undefined): UiDevice | undefined;
17
+ list(): UiDevice[];
18
+ /** False when no such device exists. */
19
+ revoke(id: string): boolean;
20
+ }
21
+ export declare function createUiDeviceStore(opts?: {
22
+ file?: string;
23
+ now?: () => number;
24
+ }): UiDeviceStore;
@@ -0,0 +1,107 @@
1
+ // Per-device app tokens. A desktop or mobile app that pairs with a code gets its own token, sent as
2
+ // `x-cortex-token` exactly like the shared client token, so the app needs no other change. Each one
3
+ // can be revoked alone; the shared client token stays with cortex-client devices.
4
+ //
5
+ // Only a SHA-256 of each token is stored. The server is the only writer, so the file is read once.
6
+ import * as crypto from 'crypto';
7
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'fs';
8
+ import * as path from 'path';
9
+ import { timingSafeEqualStr } from '../../core/auth.js';
10
+ import { createLogger } from '../../core/log.js';
11
+ const log = createLogger('ui-http');
12
+ /** Last-use times move on every request; disk sees them at most this often per device. */
13
+ export const DEVICE_SEEN_PERSIST_MS = 10 * 60 * 1000;
14
+ const NAME_MAX = 60;
15
+ const NAME_FALLBACK = 'App';
16
+ function hashToken(token) {
17
+ return crypto.createHash('sha256').update(token).digest('hex');
18
+ }
19
+ function cleanName(name) {
20
+ const trimmed = name.trim().slice(0, NAME_MAX);
21
+ return trimmed || NAME_FALLBACK;
22
+ }
23
+ function isStoredDevice(value) {
24
+ const d = value;
25
+ return typeof d?.id === 'string' && typeof d.name === 'string' && typeof d.tokenHash === 'string'
26
+ && typeof d.createdAt === 'number' && typeof d.lastSeenAt === 'number';
27
+ }
28
+ function load(file) {
29
+ if (!file)
30
+ return [];
31
+ try {
32
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
33
+ return Array.isArray(parsed?.devices) ? parsed.devices.filter(isStoredDevice) : [];
34
+ }
35
+ catch {
36
+ return []; // absent or corrupt → no paired devices; the apps pair again
37
+ }
38
+ }
39
+ function publicView(d) {
40
+ return { id: d.id, name: d.name, createdAt: d.createdAt, lastSeenAt: d.lastSeenAt };
41
+ }
42
+ export function createUiDeviceStore(opts = {}) {
43
+ const now = opts.now ?? (() => Date.now());
44
+ const devices = load(opts.file);
45
+ /** lastSeenAt as last written, per device id. */
46
+ const persistedSeen = new Map(devices.map((d) => [d.id, d.lastSeenAt]));
47
+ const persist = () => {
48
+ if (!opts.file)
49
+ return;
50
+ try {
51
+ mkdirSync(path.dirname(opts.file), { recursive: true });
52
+ const tmp = `${opts.file}.tmp`;
53
+ writeFileSync(tmp, JSON.stringify({ devices }), { mode: 0o600 });
54
+ renameSync(tmp, opts.file);
55
+ for (const d of devices)
56
+ persistedSeen.set(d.id, d.lastSeenAt);
57
+ }
58
+ catch (e) {
59
+ log.warn(`could not persist paired devices: ${e.message}`);
60
+ }
61
+ };
62
+ // Constant-time walk over every hash, as the session store does: the set is a handful of apps.
63
+ const find = (token) => {
64
+ const hash = hashToken(token);
65
+ let hit;
66
+ for (const d of devices)
67
+ if (timingSafeEqualStr(d.tokenHash, hash))
68
+ hit = d;
69
+ return hit;
70
+ };
71
+ return {
72
+ issue(name) {
73
+ const t = now();
74
+ const token = crypto.randomBytes(32).toString('hex');
75
+ const device = {
76
+ id: crypto.randomBytes(6).toString('hex'), name: cleanName(name),
77
+ createdAt: t, lastSeenAt: t, tokenHash: hashToken(token),
78
+ };
79
+ devices.push(device);
80
+ persist();
81
+ return { device: publicView(device), token };
82
+ },
83
+ match(token) {
84
+ if (!token)
85
+ return undefined;
86
+ const device = find(token);
87
+ if (!device)
88
+ return undefined;
89
+ device.lastSeenAt = now();
90
+ if (device.lastSeenAt - (persistedSeen.get(device.id) ?? 0) >= DEVICE_SEEN_PERSIST_MS)
91
+ persist();
92
+ return publicView(device);
93
+ },
94
+ list() {
95
+ return devices.map(publicView);
96
+ },
97
+ revoke(id) {
98
+ const index = devices.findIndex((d) => d.id === id);
99
+ if (index < 0)
100
+ return false;
101
+ devices.splice(index, 1);
102
+ persistedSeen.delete(id);
103
+ persist();
104
+ return true;
105
+ },
106
+ };
107
+ }
@@ -7,6 +7,8 @@ export interface UiHttpServerOptions {
7
7
  router: AnyRouter;
8
8
  /** Accessor for the bearer token the server accepts (wiring passes getClientToken). */
9
9
  getToken: () => string;
10
+ /** Paired apps' own tokens, accepted wherever the client token is (including the port forward). */
11
+ matchDeviceToken?: DeviceTokenMatcher;
10
12
  /** TCP port to listen on (0 = ephemeral, useful in tests). */
11
13
  port: number;
12
14
  /** Host to bind. Defaults to 127.0.0.1 (loopback only — exposure is via a tunnel). */
@@ -28,9 +30,9 @@ export interface UiHttpServerOptions {
28
30
  */
29
31
  customRoutes?: Record<string, CustomRouteHandler>;
30
32
  /**
31
- * Custom-route paths served WITHOUT the auth gate. Only the login and session-probe routes belong
32
- * here: a browser that holds no credential yet must be able to reach them, and each answers with
33
- * nothing more than a boolean or a 401.
33
+ * Custom-route paths served WITHOUT the auth gate. Only the login, app-pairing and session-probe
34
+ * routes belong here: a browser or app that holds no credential yet must be able to reach them,
35
+ * and each answers with nothing more than a boolean, a credential for a valid secret, or a 401.
34
36
  */
35
37
  publicRoutes?: string[];
36
38
  /**
@@ -39,6 +41,8 @@ export interface UiHttpServerOptions {
39
41
  * predicate the gate uses, instead of a second copy that could drift.
40
42
  */
41
43
  authorize: Authorizer;
44
+ /** Per-request tRPC context built from the incoming request; defaults to `{}`. */
45
+ createContext?: (req: http.IncomingMessage) => object;
42
46
  /**
43
47
  * Mount the TCP-over-WebSocket port forward on `/forward` (desktop shell → a loopback service on
44
48
  * this host). Defaults to on; `CORTEX_PORT_FORWARD=0` at the call site turns it off.
@@ -64,6 +68,8 @@ export interface UiHttpServer {
64
68
  server: http.Server;
65
69
  close: () => Promise<void>;
66
70
  }
71
+ /** Whether a presented `x-cortex-token` belongs to a paired app (ui-devices.ts). */
72
+ export type DeviceTokenMatcher = (token: string | undefined) => boolean;
67
73
  /** Decides whether one request may pass the gate. Async only because the JWT leg is. */
68
74
  export type Authorizer = (req: http.IncomingMessage) => Promise<boolean>;
69
75
  /**
@@ -76,6 +82,7 @@ export type Authorizer = (req: http.IncomingMessage) => Promise<boolean>;
76
82
  */
77
83
  export declare function createAuthorizer(opts: {
78
84
  getToken: () => string;
85
+ matchDeviceToken?: DeviceTokenMatcher;
79
86
  verifySession?: (sid: string | undefined) => boolean;
80
87
  verifyAccessJwt?: AccessJwtVerifier;
81
88
  }): Authorizer;
@@ -17,7 +17,8 @@ const CORS_ALLOW_METHODS = 'GET, POST, OPTIONS';
17
17
  // `x-session-id` / `x-file-name` are the custom headers the file-upload route reads; the app's
18
18
  // upload is cross-origin (webview `cortexui://localhost` → server), so its CORS preflight fails
19
19
  // unless these are allow-listed alongside the auth token and content-type.
20
- const CORS_ALLOW_HEADERS = `${AUTH_HEADER}, content-type, x-session-id, x-file-name`;
20
+ // `x-cortex-client` names the app (desktop / android / browser) on every tRPC call.
21
+ const CORS_ALLOW_HEADERS = `${AUTH_HEADER}, content-type, x-session-id, x-file-name, x-cortex-client`;
21
22
  const CORS_MAX_AGE = '86400'; // 24 h preflight cache
22
23
  /**
23
24
  * Largest tRPC request body. The big legitimate payloads are a pasted message (`sessions.send`,
@@ -27,11 +28,14 @@ const CORS_MAX_AGE = '86400'; // 24 h preflight cache
27
28
  const TRPC_MAX_BODY_BYTES = 16 * 1024 * 1024;
28
29
  /** Methods that never change state. Everything else is checked against the request's Origin. */
29
30
  const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
30
- /** Bearer gate for a tRPC request: constant-time compare of the accepted token vs the header. */
31
- function isAuthorized(req, getToken) {
31
+ /**
32
+ * Bearer gate: the shared client token (constant-time compare) or, when a matcher is wired, a
33
+ * paired app's own token.
34
+ */
35
+ function isAuthorized(req, getToken, matchDeviceToken) {
32
36
  const provided = req.headers[AUTH_HEADER];
33
37
  const headerVal = Array.isArray(provided) ? provided[0] : provided;
34
- return timingSafeEqualStr(getToken(), headerVal);
38
+ return timingSafeEqualStr(getToken(), headerVal) || matchDeviceToken?.(headerVal) === true;
35
39
  }
36
40
  /**
37
41
  * Cloudflare Access path: verify the `Cf-Access-Jwt-Assertion` JWT the edge injects. Returns false
@@ -57,7 +61,7 @@ async function isAccessAuthorized(req, verifyAccessJwt) {
57
61
  */
58
62
  export function createAuthorizer(opts) {
59
63
  return async (req) => {
60
- if (isAuthorized(req, opts.getToken))
64
+ if (isAuthorized(req, opts.getToken, opts.matchDeviceToken))
61
65
  return true;
62
66
  if (opts.verifySession?.(sessionIdFrom(req)))
63
67
  return true;
@@ -174,7 +178,7 @@ export function createUiHttpServer(opts) {
174
178
  const server = createHTTPServer({
175
179
  router: opts.router,
176
180
  basePath: TRPC_BASE_PATH,
177
- createContext: () => ({}),
181
+ createContext: ({ req }) => opts.createContext?.(req) ?? {},
178
182
  maxBodySize: TRPC_MAX_BODY_BYTES,
179
183
  // Runs BEFORE the tRPC handler. tRPC paths are auth-gated here; everything else is the SPA stub.
180
184
  middleware: async (req, res, next) => {
@@ -263,7 +267,7 @@ export function createUiHttpServer(opts) {
263
267
  server.on('upgrade', (req, socket, head) => {
264
268
  const pathname = (req.url ?? '').split('?')[0];
265
269
  if (forward && pathname === FORWARD_PATH) {
266
- if (!isAuthorized(req, opts.getToken)) {
270
+ if (!isAuthorized(req, opts.getToken, opts.matchDeviceToken)) {
267
271
  log.warn(`forward auth rejected: ${req.url}`);
268
272
  socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
269
273
  socket.destroy();
@@ -0,0 +1,25 @@
1
+ /** Outstanding codes, under the store dir — shared by the server and `cortex ui pair`. */
2
+ export declare const PAIRING_FILE_NAME = "ui-pairing.json";
3
+ /** How long a code stays redeemable. */
4
+ export declare const PAIRING_CODE_TTL_MS: number;
5
+ /**
6
+ * Wrong guesses tolerated before every outstanding code is voided. With 40 bits per code this caps
7
+ * an online guesser's odds at roughly 20 in 10^12 per minted code.
8
+ */
9
+ export declare const PAIRING_MAX_FAILURES = 20;
10
+ export interface PairingCode {
11
+ /** Display form, `XXXX-XXXX`. */
12
+ code: string;
13
+ expiresAt: number;
14
+ }
15
+ export interface PairingStore {
16
+ create(): PairingCode;
17
+ /** Consume a live code. True at most once per code; every miss counts toward the failure cap. */
18
+ redeem(input: string): boolean;
19
+ }
20
+ /** Canonical form of a typed code, or null when the input cannot be a pairing code at all. */
21
+ export declare function normalizePairingCode(input: string): string | null;
22
+ export declare function createPairingStore(opts: {
23
+ file: string;
24
+ now?: () => number;
25
+ }): PairingStore;