@cortex-agent/server 2026.5.22 → 2026.5.24

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 (56) hide show
  1. package/defaults/config/thread-templates.json +13 -0
  2. package/dist/agent-adapter/pi/adapter.js +56 -7
  3. package/dist/agent-adapter/pi/agent-dir.d.ts +41 -4
  4. package/dist/agent-adapter/pi/agent-dir.js +101 -16
  5. package/dist/agent-adapter/pi/spawn-args.d.ts +4 -0
  6. package/dist/agent-adapter/pi/spawn-args.js +6 -3
  7. package/dist/agent-adapter/types.d.ts +7 -0
  8. package/dist/core/gateway-generator.d.ts +27 -14
  9. package/dist/core/gateway-generator.js +178 -172
  10. package/dist/{store → core}/json-repository.js +2 -2
  11. package/dist/core/profile-generator.d.ts +14 -15
  12. package/dist/core/profile-generator.js +52 -173
  13. package/dist/domain/agents/facade.js +6 -0
  14. package/dist/domain/system/server-update-check.d.ts +17 -0
  15. package/dist/domain/system/server-update-check.js +130 -0
  16. package/dist/domain/system/update-prompt.d.ts +8 -0
  17. package/dist/domain/system/update-prompt.js +5 -0
  18. package/dist/domain/system/update-state.d.ts +9 -0
  19. package/dist/domain/system/update-state.js +25 -0
  20. package/dist/domain/threads/template-loader.d.ts +10 -0
  21. package/dist/domain/threads/template-loader.js +71 -1
  22. package/dist/entry/app.js +24 -2
  23. package/dist/entry/init.js +67 -23
  24. package/dist/orchestration/agent-runner.js +3 -4
  25. package/dist/orchestration/interactions/update-prompt-slack.d.ts +6 -0
  26. package/dist/orchestration/interactions/update-prompt-slack.js +95 -0
  27. package/dist/orchestration/lifecycle.js +3 -4
  28. package/dist/platform/adapter.d.ts +4 -0
  29. package/dist/platform/adapter.js +1 -1
  30. package/dist/platform/adapters/feishu.d.ts +1 -0
  31. package/dist/platform/adapters/feishu.js +7 -0
  32. package/dist/platform/adapters/slack-project-conduits.js +1 -1
  33. package/dist/platform/adapters/slack.d.ts +1 -0
  34. package/dist/platform/adapters/slack.js +8 -0
  35. package/dist/platform/index.js +1 -1
  36. package/dist/platform/testing.d.ts +1 -0
  37. package/dist/platform/testing.js +7 -0
  38. package/dist/store/conversation-ledger-repo.js +1 -1
  39. package/dist/store/cost-repo.js +2 -2
  40. package/dist/store/execution-repo.js +1 -1
  41. package/dist/store/outbound-queue.js +1 -1
  42. package/dist/store/profile-repo.js +1 -1
  43. package/dist/store/project-dir-repo.d.ts +0 -5
  44. package/dist/store/project-dir-repo.js +4 -15
  45. package/dist/store/schedule-repo.js +1 -1
  46. package/dist/store/session-registry-repo.js +6 -2
  47. package/dist/store/session-repo.js +1 -1
  48. package/dist/store/thread-repo.js +1 -1
  49. package/dist/store/version-migrations.d.ts +22 -0
  50. package/dist/store/version-migrations.js +200 -0
  51. package/package.json +2 -2
  52. package/dist/store/channel-repo.d.ts +0 -27
  53. package/dist/store/channel-repo.js +0 -64
  54. /package/dist/{store → core}/atomic-write.d.ts +0 -0
  55. /package/dist/{store → core}/atomic-write.js +0 -0
  56. /package/dist/{store → core}/json-repository.d.ts +0 -0
package/dist/entry/app.js CHANGED
@@ -16,13 +16,13 @@ import * as executionRegistry from '../domain/executions/registry.js';
16
16
  import { initHookBridge } from '../orchestration/routing/hook-bridge.js';
17
17
  import { registerCommands } from '../orchestration/routing/commands/index.js';
18
18
  import { taskStore } from '../domain/tasks/store.js';
19
- import { channelRepo } from '../store/channel-repo.js';
20
19
  import { projectDirRepo } from '../store/project-dir-repo.js';
21
20
  import { projectStore } from '../domain/projects/index.js';
22
21
  import { sendStartupDmIfConfigured } from './startup-notify.js';
23
22
  import { startGateway, stopGateway } from '../domain/costs/gateway-manager.js';
24
23
  import { startClientManager, stopClientManager, startAllRemoteClients } from '../domain/remote/client-manager.js';
25
24
  import { checkAndUpdateClients, formatUpdateSlackMessage } from '../domain/remote/client-hot-reload.js';
25
+ import { checkServerUpdate } from '../domain/system/server-update-check.js';
26
26
  import { threadStore } from '../store/thread-repo.js';
27
27
  import { sessionRepo } from '../store/session-repo.js';
28
28
  import { conversationLedger } from '../store/conversation-ledger-repo.js';
@@ -43,9 +43,11 @@ import { initScheduledRunner, createScheduler, setSchedulerRef, setBus, setInter
43
43
  import { buildInteractiveCallbacks } from '../orchestration/agent-runner.js';
44
44
  import { registerInteractionHandlers, initInteractionHandlers } from '../orchestration/interactions/interaction-handlers.js';
45
45
  import { CommandActionRouter } from '../orchestration/interactions/command-action-router.js';
46
+ import { createSlackUpdatePrompt } from '../orchestration/interactions/update-prompt-slack.js';
46
47
  import { registerMessageHandler } from '../orchestration/routing/message-router.js';
47
48
  import { initRateLimitThrottle } from '../domain/costs/rate-limit-throttle.js';
48
49
  import { scheduleRepo } from '../store/schedule-repo.js';
50
+ import { runMigrations } from '../store/version-migrations.js';
49
51
  import { costRepo } from '../store/cost-repo.js';
50
52
  import { profileRepo, startProfileWatcher, setAdminNotifier as setProfileNotifier } from '../store/profile-repo.js';
51
53
  import { sessionStore } from '../store/session-registry-repo.js';
@@ -104,6 +106,8 @@ const dispatchCommand = registerCommands({
104
106
  getExecutionStatusReport: buildExecutionStatusReport,
105
107
  commandRouter,
106
108
  });
109
+ // DR-0013: wire Slack update prompt BEFORE bindToAdapter (router has no unregister API)
110
+ const updatePrompt = createSlackUpdatePrompt(adapter, commandRouter);
107
111
  // Bind command action handlers (buttons, modals) to the platform adapter
108
112
  commandRouter.bindToAdapter(adapter);
109
113
  const handleMessageEdit = createEditHandler({
@@ -144,7 +148,7 @@ process.on('SIGTERM', async () => {
144
148
  // `writeFile(tmp)` and `rename(tmp, target)` in atomic-write.ts leaves orphan .tmp.* siblings.
145
149
  // Daemon gives 5s before SIGKILL — well over the time needed to flush a few MB of JSON.
146
150
  try {
147
- await Promise.allSettled([bus.close(), oq.flush(), threadStore.flush(), sessionRepo.flush(), conversationLedger.flush(), taskStore.flush(), executionRepo.flush(), channelRepo.flush(), projectDirRepo.flush(), scheduleRepo.flush(), costRepo.flush(), profileRepo.flush(), sessionStore.flush()]);
151
+ await Promise.allSettled([bus.close(), oq.flush(), threadStore.flush(), sessionRepo.flush(), conversationLedger.flush(), taskStore.flush(), executionRepo.flush(), projectDirRepo.flush(), scheduleRepo.flush(), costRepo.flush(), profileRepo.flush(), sessionStore.flush()]);
148
152
  }
149
153
  catch { }
150
154
  await stopGateway();
@@ -154,6 +158,7 @@ process.on('SIGTERM', async () => {
154
158
  (async () => {
155
159
  cleanupLogs();
156
160
  ensureMcpConfig();
161
+ await runMigrations();
157
162
  // DR-0012 §3.6: clean up orphan TUI tmux sessions from a previous agent-server lifetime.
158
163
  // We can't re-adopt them (sessionKey↔tmux mapping was never persisted) so the honest move
159
164
  // is to kill any leftovers — otherwise a later session that reuses the same sessionId will
@@ -223,6 +228,23 @@ process.on('SIGTERM', async () => {
223
228
  }
224
229
  await startAllRemoteClients();
225
230
  }, 2000);
231
+ // DR-0013: server auto-update — first check after 60s, then every 24h
232
+ setTimeout(async () => {
233
+ try {
234
+ await checkServerUpdate({ prompt: updatePrompt });
235
+ }
236
+ catch (e) {
237
+ log.error(`Server auto-update check failed: ${e.message}`);
238
+ }
239
+ }, 60_000);
240
+ setInterval(async () => {
241
+ try {
242
+ await checkServerUpdate({ prompt: updatePrompt });
243
+ }
244
+ catch (e) {
245
+ log.error(`Server auto-update check failed: ${e.message}`);
246
+ }
247
+ }, 24 * 60 * 60 * 1000);
226
248
  await scheduler.start();
227
249
  // One-time migration: resume tasks left paused by the old scheduler-based rate-limit mechanism.
228
250
  // The new provider-aware rate-limit-throttle no longer pauses tasks via the scheduler guard.
@@ -19,6 +19,7 @@ import * as yaml from 'yaml';
19
19
  import { buildFullConfig, buildCoreConfig, buildTuiConfig } from '../core/config-generator.js';
20
20
  import { discoverEndpoints, generateGatewayYaml, writeGatewayYaml } from '../core/gateway-generator.js';
21
21
  import { generateProfiles, writeProfilesJson, listChoices } from '../core/profile-generator.js';
22
+ import { mergeThreadTemplates } from '../domain/threads/index.js';
22
23
  import { createLogger } from '../core/log.js';
23
24
  import { INSTALL_ROOT, DEFAULTS_DIR } from '../core/utils.js';
24
25
  // ─── Path computation (DATA_DIR resolved locally to support --home override) ──
@@ -1027,9 +1028,10 @@ function copyDefaults(paths, force) {
1027
1028
  safeCopy(path.join(DEFAULTS_DIR, 'context', 'scans', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'scans', 'CORTEX.md'), false, 'context/scans/CORTEX.md');
1028
1029
  safeCopy(path.join(DEFAULTS_DIR, 'context', 'ideas', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'ideas', 'CORTEX.md'), false, 'context/ideas/CORTEX.md');
1029
1030
  safeCopy(path.join(DEFAULTS_DIR, 'context', 'user', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'user', 'CORTEX.md'), false, 'context/user/CORTEX.md');
1030
- // Config defaults — overwrite only with --force
1031
+ // Config defaults — budget and session-hooks overwrite only with --force;
1032
+ // thread-templates are merged (new agents/templates added, existing preserved)
1031
1033
  safeCopy(path.join(DEFAULTS_DIR, 'config', 'budget.json'), path.join(paths.CONFIG_DIR, 'budget.json'), force, 'budget.json');
1032
- safeCopy(path.join(DEFAULTS_DIR, 'config', 'thread-templates.json'), path.join(paths.CONFIG_DIR, 'thread-templates.json'), force, 'thread-templates.json');
1034
+ mergeThreadTemplates(path.join(DEFAULTS_DIR, 'config', 'thread-templates.json'), path.join(paths.CONFIG_DIR, 'thread-templates.json'));
1033
1035
  safeCopy(path.join(DEFAULTS_DIR, 'config', 'session-hooks.json'), path.join(paths.CONFIG_DIR, 'session-hooks.json'), force, 'session-hooks.json');
1034
1036
  // Seed asset trees — per-file safeCopy semantics: new files always added, existing files
1035
1037
  // preserved unless force=true. These directories are referenced at runtime; without them
@@ -1127,9 +1129,11 @@ function detectExistingPlanOrExecute(configDir) {
1127
1129
  }
1128
1130
  }
1129
1131
  /**
1130
- * Interactively pick plan / execute (mode, model) from discovered endpoints.
1131
- * Pre-selects auto-inferred defaults. Returns undefined for either choice if the user
1132
- * declined to overwrite an existing profile.
1132
+ * Interactively pick plan / execute (mode, model) from discovered endpoints, plus optional
1133
+ * fallback chains. Lists are sorted lexicographically; the first entry is pre-selected.
1134
+ *
1135
+ * Returns `overwrite: false` if the user declined to overwrite an existing profile — in that
1136
+ * case all *Choice / *Fallback fields are undefined.
1133
1137
  */
1134
1138
  async function pickPlanExecuteInteractive(endpoints, configDir) {
1135
1139
  // If existing profiles.json has plan/execute, ask before overwriting
@@ -1146,34 +1150,67 @@ async function pickPlanExecuteInteractive(endpoints, configDir) {
1146
1150
  const choices = listChoices(endpoints);
1147
1151
  if (choices.length === 0)
1148
1152
  return { overwrite: true };
1149
- const autoDefaults = generateProfiles(endpoints).profiles;
1150
- const planDefault = autoDefaults.plan
1151
- ? `${autoDefaults.plan.mode}:${autoDefaults.plan.model}`
1152
- : `${choices[0].mode}:${choices[0].model}`;
1153
- const executeDefault = autoDefaults.execute
1154
- ? `${autoDefaults.execute.mode}:${autoDefaults.execute.model}`
1155
- : planDefault;
1153
+ const formatValue = (c) => `${c.mode}:${c.model}`;
1154
+ const parseValue = (v) => {
1155
+ const colonIdx = v.indexOf(':');
1156
+ return { mode: v.substring(0, colonIdx), model: v.substring(colonIdx + 1) };
1157
+ };
1156
1158
  const options = choices.map(c => ({
1157
- value: `${c.mode}:${c.model}`,
1159
+ value: formatValue(c),
1158
1160
  label: `${c.mode} / ${c.model}`,
1159
1161
  }));
1162
+ // Default = first lexicographic entry (no tier inference).
1163
+ const firstChoiceValue = formatValue(choices[0]);
1160
1164
  const planSel = await clack.select({
1161
1165
  message: 'Pick model for the `plan` profile (used by executor agents — planner, doc-writer, coder, etc.):',
1162
1166
  options,
1163
- initialValue: planDefault,
1167
+ initialValue: firstChoiceValue,
1164
1168
  });
1165
1169
  handleCancel(planSel);
1166
1170
  const execSel = await clack.select({
1167
1171
  message: 'Pick model for the `execute` profile (used by reviewer agents — reviewer, doc-reviewer, coder-reviewer, etc.):',
1168
1172
  options,
1169
- initialValue: executeDefault,
1173
+ initialValue: firstChoiceValue,
1170
1174
  });
1171
1175
  handleCancel(execSel);
1172
- const [planMode, planModel] = planSel.split(':');
1173
- const [execMode, execModel] = execSel.split(':');
1176
+ const planChoice = parseValue(planSel);
1177
+ const execChoice = parseValue(execSel);
1178
+ // ── Fallback selection (multi-select, ordered) ──
1179
+ // Build fallback options excluding the primary choice. If no candidates remain (e.g. only
1180
+ // one discovered model), skip the prompt entirely.
1181
+ const planFallbackOptions = options.filter(o => o.value !== planSel);
1182
+ const execFallbackOptions = options.filter(o => o.value !== execSel);
1183
+ let planFallback;
1184
+ if (planFallbackOptions.length > 0) {
1185
+ const sel = await clack.multiselect({
1186
+ message: 'Pick fallback models for `plan` (in order, space to toggle, enter to confirm, leave empty for no fallback):',
1187
+ options: planFallbackOptions,
1188
+ required: false,
1189
+ initialValues: [],
1190
+ });
1191
+ handleCancel(sel);
1192
+ const arr = sel;
1193
+ if (arr.length > 0)
1194
+ planFallback = arr.map(parseValue);
1195
+ }
1196
+ let executeFallback;
1197
+ if (execFallbackOptions.length > 0) {
1198
+ const sel = await clack.multiselect({
1199
+ message: 'Pick fallback models for `execute` (in order, space to toggle, enter to confirm, leave empty for no fallback):',
1200
+ options: execFallbackOptions,
1201
+ required: false,
1202
+ initialValues: [],
1203
+ });
1204
+ handleCancel(sel);
1205
+ const arr = sel;
1206
+ if (arr.length > 0)
1207
+ executeFallback = arr.map(parseValue);
1208
+ }
1174
1209
  return {
1175
- planChoice: { mode: planMode, model: planModel },
1176
- executeChoice: { mode: execMode, model: execModel },
1210
+ planChoice,
1211
+ executeChoice: execChoice,
1212
+ planFallback,
1213
+ executeFallback,
1177
1214
  overwrite: true,
1178
1215
  };
1179
1216
  }
@@ -1193,20 +1230,25 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1193
1230
  const yamlContent = generateGatewayYaml(endpoints);
1194
1231
  const gatewayPath = writeGatewayYaml(yamlContent, gatewayConfigDir);
1195
1232
  clack.log.success(`Gateway config written to ${gatewayPath}`);
1196
- // Resolve plan/execute choices + overwrite intent.
1233
+ // Resolve plan/execute choices + fallback chains + overwrite intent.
1197
1234
  let planChoice = answers?.planChoice;
1198
1235
  let executeChoice = answers?.executeChoice;
1236
+ let planFallback;
1237
+ let executeFallback;
1199
1238
  let overwrite;
1200
1239
  if (processStdin.isTTY) {
1201
1240
  // Interactive: prompt for selection (with overwrite confirmation if needed)
1202
1241
  const picked = await pickPlanExecuteInteractive(endpoints, paths.CONFIG_DIR);
1203
1242
  planChoice = picked.planChoice ?? planChoice;
1204
1243
  executeChoice = picked.executeChoice ?? executeChoice;
1244
+ planFallback = picked.planFallback;
1245
+ executeFallback = picked.executeFallback;
1205
1246
  overwrite = picked.overwrite;
1206
1247
  }
1207
1248
  else {
1208
- // Non-interactive: stdin already provided choices (or empty → auto-infer).
1209
- // Always overwrite — scripted (re)install assumes the operator knows the intent.
1249
+ // Non-interactive: stdin already provided choices (or empty → lex-first default).
1250
+ // Fallback chains are not configurable via stdin in this iteration — extend the stdin
1251
+ // protocol if scripted installs need fallback.
1210
1252
  overwrite = true;
1211
1253
  }
1212
1254
  // Generate profiles.json
@@ -1214,11 +1256,13 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1214
1256
  outputDir: paths.CONFIG_DIR,
1215
1257
  planChoice,
1216
1258
  executeChoice,
1259
+ planFallback,
1260
+ executeFallback,
1217
1261
  overwrite,
1218
1262
  });
1219
1263
  clack.log.success(`Profiles written to ${profilesPath}`);
1220
1264
  // Show profile summary (reflects what was actually generated, not what was merged)
1221
- const profiles = generateProfiles(endpoints, { planChoice, executeChoice });
1265
+ const profiles = generateProfiles(endpoints, { planChoice, executeChoice, planFallback, executeFallback });
1222
1266
  const profileNames = Object.keys(profiles.profiles).join(', ');
1223
1267
  clack.log.info(`Generated profiles: ${profileNames} (default: ${profiles.defaultProfile})`);
1224
1268
  }
@@ -19,7 +19,6 @@ const log = createLogger('agent-runner');
19
19
  import { createToolTrace } from '../platform/index.js';
20
20
  import { setStreamingCallback, clearStreamingCallback, publishPlanSubmitted, publishAskUserRequested } from './routing/hook-bridge.js';
21
21
  import { maybeNotifyCodexLowUsage } from '../domain/costs/codex-usage-monitor.js';
22
- import { projectDirRepo } from '../store/project-dir-repo.js';
23
22
  import { getAgent, createDefaultThread } from '../domain/threads/index.js';
24
23
  import { runThread } from '../domain/threads/runner.js';
25
24
  import { downloadFiles as downloadPlatformFiles } from './routing/file-handler.js';
@@ -55,7 +54,7 @@ export class AgentRunner {
55
54
  const downloadedFiles = await downloadFiles(message.files, hasFiles, adapter);
56
55
  const startTime = Date.now();
57
56
  const sessionId = await getSessionAsync(channel, resolveBackendForChannel(channel));
58
- const sessionName = await resolveSessionName(sessionId, channel, userMessage);
57
+ const sessionName = await resolveSessionName(sessionId, channel, userMessage, adapter);
59
58
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: sessionId ?? '' };
60
59
  // 1. Orchestration side effects (keep — ledger, status, hook-bridge)
61
60
  const statusText = buildUserProcessingMessage({ startTime, profileName: getActiveProfile(channel), sessionName, sessionId });
@@ -159,13 +158,13 @@ async function handleDefaultAgentResult({ result, channel, adapter, statusMsg, s
159
158
  await handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger: 'user', sessionName, threadTs, userMessageTs: messageTs, onAssistantMessage: callbacks.onAssistantMsg });
160
159
  // NOTE: createAutoThread removed — thread was created pre-execution via createDefaultThread
161
160
  }
162
- async function resolveSessionName(sessionId, channel, userMessage) {
161
+ async function resolveSessionName(sessionId, channel, userMessage, adapter) {
163
162
  if (sessionId) {
164
163
  const existing = await sessionStore.lookupBySessionId(sessionId);
165
164
  if (existing)
166
165
  return existing;
167
166
  const name = await sessionStore.generateSessionName();
168
- const channelProject = await projectDirRepo.getChannelProject(channel);
167
+ const channelProject = await adapter.resolveInboundProject(channel);
169
168
  await sessionStore.registerSession(name, { sessionId, channel, backend: resolveBackendForChannel(channel), kind: 'local', label: userMessage?.substring(0, 60), profileName: getActiveProfile(channel), projectId: channelProject ?? 'general' });
170
169
  return name;
171
170
  }
@@ -0,0 +1,6 @@
1
+ import type { PlatformAdapter } from '../../platform/index.js';
2
+ import type { CommandActionRouter } from '../interactions/command-action-router.js';
3
+ import type { UpdatePrompt } from '../../domain/system/update-prompt.js';
4
+ export declare function createSlackUpdatePrompt(adapter: PlatformAdapter, router: CommandActionRouter, opts?: {
5
+ timeoutMs?: number;
6
+ }): UpdatePrompt;
@@ -0,0 +1,95 @@
1
+ // input: @platform/index.js + @orch/interactions/command-action-router.js + @domain/system/update-prompt.js
2
+ // output: createSlackUpdatePrompt(adapter, router, opts?) => UpdatePrompt
3
+ // pos: Slack-specific UpdatePrompt implementation — pre-registers three actionIds on router,
4
+ // posts interactive message to system-notice, resolves ask() promise on button click.
5
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
+ const DEFAULT_TIMEOUT_MS = 86_400_000; // 24h
7
+ // --- Factory ---
8
+ export function createSlackUpdatePrompt(adapter, router, opts) {
9
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
10
+ let pending = null;
11
+ let timerHandle;
12
+ // --- Internal helpers ---
13
+ const clearPending = () => {
14
+ if (timerHandle !== undefined) {
15
+ clearTimeout(timerHandle);
16
+ timerHandle = undefined;
17
+ }
18
+ pending = null;
19
+ };
20
+ const resolveText = (choice, version) => {
21
+ switch (choice) {
22
+ case 'apply':
23
+ return `Installing @cortex-agent/server@${version}... daemon will restart shortly.`;
24
+ case 'skip':
25
+ return `Skipped version ${version}.`;
26
+ case 'cancel':
27
+ return `Update cancelled. Will check again at next interval.`;
28
+ }
29
+ };
30
+ // --- Build click handlers ---
31
+ const buildHandler = (choice) => {
32
+ return async (ctx) => {
33
+ if (!pending)
34
+ return; // stale click — no pending prompt
35
+ const p = pending;
36
+ const version = p.latestVersion;
37
+ clearPending();
38
+ p.resolve(choice);
39
+ if (ctx.messageRef) {
40
+ await adapter.updateMessage(ctx.messageRef, { text: resolveText(choice, version) }).catch(() => { });
41
+ }
42
+ };
43
+ };
44
+ // --- Pre-register three actionIds on router ---
45
+ router.registerCommand('update', {
46
+ actions: [
47
+ { actionId: 'apply', handler: buildHandler('apply') },
48
+ { actionId: 'skip', handler: buildHandler('skip') },
49
+ { actionId: 'cancel', handler: buildHandler('cancel') },
50
+ ],
51
+ });
52
+ // --- Button templates (value filled in at ask time) ---
53
+ const buttonTemplates = [
54
+ { type: 'button', text: 'Update', actionId: 'cmd:update:apply', value: '', style: 'primary' },
55
+ { type: 'button', text: 'Skip this version', actionId: 'cmd:update:skip', value: '' },
56
+ { type: 'button', text: 'Cancel', actionId: 'cmd:update:cancel', value: '', style: 'danger' },
57
+ ];
58
+ // --- Return the UpdatePrompt implementation ---
59
+ return {
60
+ async ask(spec) {
61
+ // Resolve any existing pending prompt
62
+ if (pending) {
63
+ const old = pending;
64
+ clearPending();
65
+ old.resolve(null);
66
+ if (old.messageRef) {
67
+ await adapter.updateMessage(old.messageRef, { text: 'Superseded by a newer update prompt.' }).catch(() => { });
68
+ }
69
+ }
70
+ // Stamp version onto buttons
71
+ const versionedButtons = buttonTemplates.map(b => ({ ...b, value: spec.latestVersion }));
72
+ // Post interactive message to admin DM
73
+ const messageRef = await adapter.postInteractive({ type: 'system-notice' }, {
74
+ text: `Cortex Server v${spec.latestVersion} is available. Update now?`,
75
+ richBlocks: [
76
+ { type: 'section', text: `Cortex Server v${spec.latestVersion} is available.` },
77
+ { type: 'actions', elements: versionedButtons },
78
+ ],
79
+ actions: versionedButtons,
80
+ });
81
+ // Create new pending promise
82
+ return new Promise((resolve) => {
83
+ pending = { resolve, messageRef, latestVersion: spec.latestVersion };
84
+ timerHandle = setTimeout(() => {
85
+ if (!pending || pending.resolve !== resolve)
86
+ return; // already handled
87
+ const ref = pending.messageRef;
88
+ clearPending();
89
+ resolve(null);
90
+ adapter.updateMessage(ref, { text: 'Update prompt timed out.' }).catch(() => { });
91
+ }, timeoutMs).unref();
92
+ });
93
+ },
94
+ };
95
+ }
@@ -17,7 +17,6 @@ import * as executionRegistry from '../domain/executions/registry.js';
17
17
  import * as askUserQuestion from './interactions/ask-user-question.js';
18
18
  import { runAgent, getClaudeMode, getActiveProfile, resolveBackendForChannel } from '../domain/agents/index.js';
19
19
  import { projectStore } from '../domain/projects/index.js';
20
- import { projectDirRepo } from '../store/project-dir-repo.js';
21
20
  import { setStreamingCallback, clearStreamingCallback } from './routing/hook-bridge.js';
22
21
  import { maybeNotifyCodexLowUsage } from '../domain/costs/codex-usage-monitor.js';
23
22
  import { normalizeSkillCommandPrefix } from '../domain/memory/skill-scanner.js';
@@ -113,7 +112,7 @@ export async function handleAgentError({ error, channel, adapter, statusMsg, sta
113
112
  await sealStatus(adapter, statusMsg, supersededText, buildSealedStatusActionBlocks(supersededText, { channel, sessionName, isDm: true }));
114
113
  return;
115
114
  }
116
- await persistErrorSession(resolvedSessionId, sessionName, channel);
115
+ await persistErrorSession(resolvedSessionId, sessionName, channel, adapter);
117
116
  if (userMessageTs)
118
117
  await conversationLedger.completeTurn(channel, userMessageTs, { executionId });
119
118
  if (error?.cancelled) {
@@ -135,7 +134,7 @@ export async function handleAgentError({ error, channel, adapter, statusMsg, sta
135
134
  await adapter.postMessage(errorDest, { text: `Error: ${error.message}` }, threadTs ? { threadId: threadTs } : undefined);
136
135
  }
137
136
  }
138
- async function persistErrorSession(resolvedSessionId, sessionName, channel) {
137
+ async function persistErrorSession(resolvedSessionId, sessionName, channel, adapter) {
139
138
  if (!resolvedSessionId)
140
139
  return;
141
140
  const backend = resolveBackendForChannel(channel);
@@ -145,7 +144,7 @@ async function persistErrorSession(resolvedSessionId, sessionName, channel) {
145
144
  return;
146
145
  const existing = await sessionStore.lookupBySessionId(resolvedSessionId);
147
146
  if (!existing) {
148
- await sessionStore.registerSession(sessionName, { sessionId: resolvedSessionId, channel, backend, kind: 'local', profileName: getActiveProfile(channel), projectId: (await projectDirRepo.getChannelProject(channel)) ?? 'general' });
147
+ await sessionStore.registerSession(sessionName, { sessionId: resolvedSessionId, channel, backend, kind: 'local', profileName: getActiveProfile(channel), projectId: (await adapter.resolveInboundProject(channel)) ?? 'general' });
149
148
  }
150
149
  }
151
150
  // --- AskUserQuestion resume ---
@@ -29,4 +29,8 @@ export interface PlatformAdapter {
29
29
  unbindProjectConduit(projectId: string): Promise<void>;
30
30
  /** Get all registered project→conduit mappings. */
31
31
  getProjectConduits(): Promise<Record<string, string>>;
32
+ /** Inverse lookup: given an inbound conduit (e.g., a Slack channel id), return
33
+ * the project it is currently bound to, or null if unbound. Used by the
34
+ * orchestration layer to attach inbound messages to their project. */
35
+ resolveInboundProject(conduit: string): Promise<string | null>;
32
36
  }
@@ -1,5 +1,5 @@
1
1
  // input: ./types.js platform-agnostic message types
2
- // output: PlatformAdapter interface (21 methods: 17 core + openOutputStream + 3 conduit methods)
2
+ // output: PlatformAdapter interface (22 methods: 17 core + openOutputStream + 4 conduit methods)
3
3
  // pos: Single abstraction boundary between core modules and messaging platform
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  export {};
@@ -43,6 +43,7 @@ export declare class FeishuAdapter implements PlatformAdapter {
43
43
  bindProjectConduit(projectId: string, conduitHint: string): Promise<void>;
44
44
  unbindProjectConduit(projectId: string): Promise<void>;
45
45
  getProjectConduits(): Promise<Record<string, string>>;
46
+ resolveInboundProject(conduit: string): Promise<string | null>;
46
47
  /**
47
48
  * Resolve a Destination to a concrete Feishu chat_id + kind label.
48
49
  * Returns channel=null for destinations that should be silently dropped
@@ -265,6 +265,13 @@ export class FeishuAdapter {
265
265
  async getProjectConduits() {
266
266
  return { ...this._feishuConduits };
267
267
  }
268
+ async resolveInboundProject(conduit) {
269
+ for (const [project, ch] of Object.entries(this._feishuConduits)) {
270
+ if (ch === conduit)
271
+ return project;
272
+ }
273
+ return null;
274
+ }
268
275
  /**
269
276
  * Resolve a Destination to a concrete Feishu chat_id + kind label.
270
277
  * Returns channel=null for destinations that should be silently dropped
@@ -3,7 +3,7 @@
3
3
  // pos: File-backed project→conduit mapping, same path as channel-registry.json
4
4
  // for backward compatibility with existing bindings.
5
5
  import * as path from 'path';
6
- import { JsonRepository } from '../../store/json-repository.js';
6
+ import { JsonRepository } from '../../core/json-repository.js';
7
7
  import { STORE_DIR } from '../../core/paths.js';
8
8
  const CHANNEL_REGISTRY_FILE = path.join(STORE_DIR, 'channel-registry.json');
9
9
  export class SlackProjectConduitsStore {
@@ -84,6 +84,7 @@ export declare class SlackAdapter implements PlatformAdapter {
84
84
  bindProjectConduit(projectId: string, conduitHint: string): Promise<void>;
85
85
  unbindProjectConduit(projectId: string): Promise<void>;
86
86
  getProjectConduits(): Promise<Record<string, string>>;
87
+ resolveInboundProject(conduit: string): Promise<string | null>;
87
88
  private _conduitsStore;
88
89
  private _getConduitsStore;
89
90
  /**
@@ -509,6 +509,14 @@ export class SlackAdapter {
509
509
  async getProjectConduits() {
510
510
  return this._getConduitsStore().getAll();
511
511
  }
512
+ async resolveInboundProject(conduit) {
513
+ const conduits = await this._getConduitsStore().getAll();
514
+ for (const [project, ch] of Object.entries(conduits)) {
515
+ if (ch === conduit)
516
+ return project;
517
+ }
518
+ return null;
519
+ }
512
520
  _conduitsStore = null;
513
521
  _getConduitsStore() {
514
522
  if (!this._conduitsStore) {
@@ -1,4 +1,4 @@
1
- // input: adapter + types + virtual-message + adapters/*
1
+ // input: adapter + types + output-stream + adapters/*
2
2
  // output: Re-export full family of PlatformAdapter public APIs
3
3
  // pos: Public API export of the Platform abstraction
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
@@ -108,6 +108,7 @@ export declare class MockAdapter implements PlatformAdapter {
108
108
  bindProjectConduit(projectId: string, conduitHint: string): Promise<void>;
109
109
  unbindProjectConduit(projectId: string): Promise<void>;
110
110
  getProjectConduits(): Promise<Record<string, string>>;
111
+ resolveInboundProject(conduit: string): Promise<string | null>;
111
112
  /** Simulate an inbound message for testing event handlers. */
112
113
  simulateMessage(channel: string, text: string, opts?: {
113
114
  senderId?: string;
@@ -186,6 +186,13 @@ export class MockAdapter {
186
186
  async getProjectConduits() {
187
187
  return Object.fromEntries(this._projectConduits);
188
188
  }
189
+ async resolveInboundProject(conduit) {
190
+ for (const [project, ch] of this._projectConduits) {
191
+ if (ch === conduit)
192
+ return project;
193
+ }
194
+ return null;
195
+ }
189
196
  // --- Test helpers ---
190
197
  /** Simulate an inbound message for testing event handlers. */
191
198
  async simulateMessage(channel, text, opts) {
@@ -3,7 +3,7 @@
3
3
  // pos: Claude session turns to Slack message mapping persistence (based on JsonRepository, AsyncMutex serialized)
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import * as path from 'path';
6
- import { JsonRepository } from './json-repository.js';
6
+ import { JsonRepository } from '../core/json-repository.js';
7
7
  import { STORE_DIR } from '../core/paths.js';
8
8
  const LEDGER_FILE = path.join(STORE_DIR, 'conversation-ledger.json');
9
9
  function nowIso() {
@@ -5,8 +5,8 @@
5
5
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
6
  import * as path from 'path';
7
7
  import fs from 'node:fs/promises';
8
- import { JsonRepository } from './json-repository.js';
9
- import { atomicWrite } from './atomic-write.js';
8
+ import { JsonRepository } from '../core/json-repository.js';
9
+ import { atomicWrite } from '../core/atomic-write.js';
10
10
  import { AsyncMutex } from '../core/async-mutex.js';
11
11
  import { STORE_DIR, CONFIG_DIR } from '../core/paths.js';
12
12
  const NINETY_DAYS_MS = 90 * 24 * 60 * 60 * 1000;
@@ -5,7 +5,7 @@
5
5
  // >>> If I am updated, update my header comment and CORTEX.md <<<
6
6
  import * as path from 'path';
7
7
  import { readFileSync } from 'fs';
8
- import { JsonRepository } from './json-repository.js';
8
+ import { JsonRepository } from '../core/json-repository.js';
9
9
  import { createLogger } from '../core/log.js';
10
10
  import { AsyncMutex } from '../core/async-mutex.js';
11
11
  import { STORE_DIR } from '../core/paths.js';
@@ -7,7 +7,7 @@ import path from 'node:path';
7
7
  import { randomUUID } from 'node:crypto';
8
8
  import { createLogger } from '../core/log.js';
9
9
  import { AsyncMutex } from '../core/async-mutex.js';
10
- import { atomicWrite } from './atomic-write.js';
10
+ import { atomicWrite } from '../core/atomic-write.js';
11
11
  const log = createLogger('outbound-queue');
12
12
  import { STORE_DIR } from '../core/paths.js';
13
13
  const DEFAULT_TTL_MS = 30 * 60 * 1000; // 30 minutes
@@ -11,7 +11,7 @@
11
11
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
12
12
  import { readFileSync, watch, existsSync } from 'fs';
13
13
  import * as path from 'path';
14
- import { JsonRepository } from './json-repository.js';
14
+ import { JsonRepository } from '../core/json-repository.js';
15
15
  import { CONFIG_DIR } from '../core/paths.js';
16
16
  import { createLogger } from '../core/log.js';
17
17
  const log = createLogger('profile-repo');
@@ -1,20 +1,15 @@
1
- import { ChannelRepo } from './channel-repo.js';
2
1
  /** Shape of project-dirs.json: `{"projectName": {"machineName": "dirPath", ...}, ...}` */
3
2
  export type ProjectDirsData = Record<string, Record<string, string>>;
4
3
  interface ProjectDirRepoOptions {
5
4
  filePath?: string;
6
- channelRepoOverride?: ChannelRepo;
7
5
  }
8
6
  export declare class ProjectDirRepo {
9
7
  private readonly _repo;
10
- private readonly _channelRepo;
11
8
  constructor(opts?: ProjectDirRepoOptions);
12
9
  getProjectDir(project: string, machine: string): Promise<string | null>;
13
10
  setProjectDir(project: string, machine: string, dirPath: string): Promise<void>;
14
11
  removeProjectDir(project: string, machine: string): Promise<void>;
15
12
  getAllProjectDirs(): Promise<Record<string, Record<string, string>>>;
16
- /** Reverse-lookup: channelId → project name (via channel-registry.json). */
17
- getChannelProject(channelId: string): Promise<string | null>;
18
13
  /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
19
14
  flush(): Promise<void>;
20
15
  }
@@ -1,22 +1,20 @@
1
- // input: project-dirs.json (+ channel-registry.json for reverse lookup)
2
- // output: ProjectDirRepo (async getProjectDir / setProjectDir / removeProjectDir / getAllProjectDirs / getChannelProject)
1
+ // input: project-dirs.json
2
+ // output: ProjectDirRepo (async getProjectDir / setProjectDir / removeProjectDir / getAllProjectDirs)
3
3
  // pos: Project-device code directory mapping persistence layer. Based on JsonRepository abstraction, AsyncMutex serializes reads/writes of project-dirs.json.
4
+ // Channel→project reverse lookup used to live here (getChannelProject); it now lives on PlatformAdapter as resolveInboundProject.
4
5
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
6
  import * as path from 'path';
6
- import { JsonRepository } from './json-repository.js';
7
+ import { JsonRepository } from '../core/json-repository.js';
7
8
  import { STORE_DIR } from '../core/paths.js';
8
- import { channelRepo } from './channel-repo.js';
9
9
  const PROJECT_DIRS_FILE = path.join(STORE_DIR, 'project-dirs.json');
10
10
  export class ProjectDirRepo {
11
11
  _repo;
12
- _channelRepo;
13
12
  constructor(opts = {}) {
14
13
  this._repo = new JsonRepository({
15
14
  filePath: opts.filePath ?? PROJECT_DIRS_FILE,
16
15
  defaultValue: () => ({}),
17
16
  migrate: (raw) => (typeof raw === 'object' && raw !== null ? raw : ({})),
18
17
  });
19
- this._channelRepo = opts.channelRepoOverride ?? channelRepo;
20
18
  }
21
19
  async getProjectDir(project, machine) {
22
20
  const data = await this._repo.read();
@@ -43,15 +41,6 @@ export class ProjectDirRepo {
43
41
  async getAllProjectDirs() {
44
42
  return { ...(await this._repo.read()) };
45
43
  }
46
- /** Reverse-lookup: channelId → project name (via channel-registry.json). */
47
- async getChannelProject(channelId) {
48
- const channelReg = await this._channelRepo.getAllRegistrations();
49
- for (const [project, ch] of Object.entries(channelReg)) {
50
- if (ch === channelId)
51
- return project;
52
- }
53
- return null;
54
- }
55
44
  /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
56
45
  flush() {
57
46
  return this._repo.flush();