@cortex-agent/server 2026.5.22 → 2026.5.24-1

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 +179 -173
  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 +122 -62
  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) ──
@@ -573,50 +574,66 @@ async function collectSlackConfig(prefill) {
573
574
  ].join('\n'), 'Slack App Setup Guide');
574
575
  await promptCopyManifestToClipboard(SLACK_APP_MANIFEST);
575
576
  const hasPrefill = prefill && (prefill.signingSecret || prefill.appToken || prefill.botToken);
577
+ let signingSecret;
578
+ let appToken;
579
+ let botToken;
580
+ let adminChannelRaw;
576
581
  if (hasPrefill) {
577
- clack.log.info('Found existing Slack configuration — values are pre-filled. Press Enter to keep them, or type to replace.');
582
+ clack.log.info('Found existing Slack configuration. Press Enter to skip, or type anything to re-enter.');
583
+ const skip = await clack.text({
584
+ message: 'Skip Slack configuration? (Enter = skip, any key + Enter = re-enter)',
585
+ placeholder: 'Press Enter to skip',
586
+ defaultValue: '',
587
+ });
588
+ handleCancel(skip);
589
+ if (skip.trim() === '') {
590
+ // User pressed Enter — reuse prefill values.
591
+ signingSecret = prefill.signingSecret;
592
+ appToken = prefill.appToken;
593
+ botToken = prefill.botToken;
594
+ adminChannelRaw = prefill.adminChannel ?? '';
595
+ }
596
+ }
597
+ if (!signingSecret) {
598
+ signingSecret = await clack.password({
599
+ message: 'Step 1/4: SLACK_SIGNING_SECRET (from Basic Information):',
600
+ validate(value) {
601
+ if (!value)
602
+ return 'Signing secret is required.';
603
+ },
604
+ });
605
+ handleCancel(signingSecret);
606
+ appToken = await clack.password({
607
+ message: 'Step 2/4: SLACK_APP_TOKEN (App-Level Token, starts with xapp-):',
608
+ validate(value) {
609
+ if (!value)
610
+ return 'App token is required.';
611
+ if (!value.startsWith('xapp-'))
612
+ return 'Token should start with xapp-';
613
+ },
614
+ });
615
+ handleCancel(appToken);
616
+ botToken = await clack.password({
617
+ message: 'Step 3/4: SLACK_BOT_TOKEN (Bot User OAuth Token, starts with xoxb-):',
618
+ validate(value) {
619
+ if (!value)
620
+ return 'Bot token is required.';
621
+ if (!value.startsWith('xoxb-'))
622
+ return 'Token should start with xoxb-';
623
+ },
624
+ });
625
+ handleCancel(botToken);
626
+ adminChannelRaw = await clack.text({
627
+ message: 'Step 4/4: CORTEX_ADMIN_CHANNEL (optional — Slack channel ID for admin notifications):',
628
+ placeholder: 'e.g. C0123456789 or D0123456789 (leave blank to configure later)',
629
+ initialValue: prefill?.adminChannel,
630
+ });
631
+ handleCancel(adminChannelRaw);
578
632
  }
579
- const signingSecret = await clack.password({
580
- message: 'Step 1/4: SLACK_SIGNING_SECRET (from Basic Information):',
581
- initialValue: prefill?.signingSecret,
582
- validate(value) {
583
- if (!value)
584
- return 'Signing secret is required.';
585
- },
586
- });
587
- handleCancel(signingSecret);
588
- const appToken = await clack.password({
589
- message: 'Step 2/4: SLACK_APP_TOKEN (App-Level Token, starts with xapp-):',
590
- initialValue: prefill?.appToken,
591
- validate(value) {
592
- if (!value)
593
- return 'App token is required.';
594
- if (!value.startsWith('xapp-'))
595
- return 'Token should start with xapp-';
596
- },
597
- });
598
- handleCancel(appToken);
599
- const botToken = await clack.password({
600
- message: 'Step 3/4: SLACK_BOT_TOKEN (Bot User OAuth Token, starts with xoxb-):',
601
- initialValue: prefill?.botToken,
602
- validate(value) {
603
- if (!value)
604
- return 'Bot token is required.';
605
- if (!value.startsWith('xoxb-'))
606
- return 'Token should start with xoxb-';
607
- },
608
- });
609
- handleCancel(botToken);
610
- const adminChannelRaw = await clack.text({
611
- message: 'Step 4/4: CORTEX_ADMIN_CHANNEL (optional — Slack channel ID for admin notifications):',
612
- placeholder: 'e.g. C0123456789 or D0123456789 (leave blank to configure later)',
613
- initialValue: prefill?.adminChannel,
614
- });
615
- handleCancel(adminChannelRaw);
616
633
  return {
617
- botToken: botToken,
618
634
  signingSecret: signingSecret,
619
635
  appToken: appToken,
636
+ botToken: botToken,
620
637
  adminChannel: adminChannelRaw.trim() || undefined,
621
638
  };
622
639
  }
@@ -1027,9 +1044,10 @@ function copyDefaults(paths, force) {
1027
1044
  safeCopy(path.join(DEFAULTS_DIR, 'context', 'scans', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'scans', 'CORTEX.md'), false, 'context/scans/CORTEX.md');
1028
1045
  safeCopy(path.join(DEFAULTS_DIR, 'context', 'ideas', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'ideas', 'CORTEX.md'), false, 'context/ideas/CORTEX.md');
1029
1046
  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
1047
+ // Config defaults — budget and session-hooks overwrite only with --force;
1048
+ // thread-templates are merged (new agents/templates added, existing preserved)
1031
1049
  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');
1050
+ mergeThreadTemplates(path.join(DEFAULTS_DIR, 'config', 'thread-templates.json'), path.join(paths.CONFIG_DIR, 'thread-templates.json'));
1033
1051
  safeCopy(path.join(DEFAULTS_DIR, 'config', 'session-hooks.json'), path.join(paths.CONFIG_DIR, 'session-hooks.json'), force, 'session-hooks.json');
1034
1052
  // Seed asset trees — per-file safeCopy semantics: new files always added, existing files
1035
1053
  // preserved unless force=true. These directories are referenced at runtime; without them
@@ -1127,9 +1145,11 @@ function detectExistingPlanOrExecute(configDir) {
1127
1145
  }
1128
1146
  }
1129
1147
  /**
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.
1148
+ * Interactively pick plan / execute (mode, model) from discovered endpoints, plus optional
1149
+ * fallback chains. Lists are sorted lexicographically; the first entry is pre-selected.
1150
+ *
1151
+ * Returns `overwrite: false` if the user declined to overwrite an existing profile — in that
1152
+ * case all *Choice / *Fallback fields are undefined.
1133
1153
  */
1134
1154
  async function pickPlanExecuteInteractive(endpoints, configDir) {
1135
1155
  // If existing profiles.json has plan/execute, ask before overwriting
@@ -1146,34 +1166,67 @@ async function pickPlanExecuteInteractive(endpoints, configDir) {
1146
1166
  const choices = listChoices(endpoints);
1147
1167
  if (choices.length === 0)
1148
1168
  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;
1169
+ const formatValue = (c) => `${c.mode}:${c.model}`;
1170
+ const parseValue = (v) => {
1171
+ const colonIdx = v.indexOf(':');
1172
+ return { mode: v.substring(0, colonIdx), model: v.substring(colonIdx + 1) };
1173
+ };
1156
1174
  const options = choices.map(c => ({
1157
- value: `${c.mode}:${c.model}`,
1175
+ value: formatValue(c),
1158
1176
  label: `${c.mode} / ${c.model}`,
1159
1177
  }));
1178
+ // Default = first lexicographic entry (no tier inference).
1179
+ const firstChoiceValue = formatValue(choices[0]);
1160
1180
  const planSel = await clack.select({
1161
1181
  message: 'Pick model for the `plan` profile (used by executor agents — planner, doc-writer, coder, etc.):',
1162
1182
  options,
1163
- initialValue: planDefault,
1183
+ initialValue: firstChoiceValue,
1164
1184
  });
1165
1185
  handleCancel(planSel);
1166
1186
  const execSel = await clack.select({
1167
1187
  message: 'Pick model for the `execute` profile (used by reviewer agents — reviewer, doc-reviewer, coder-reviewer, etc.):',
1168
1188
  options,
1169
- initialValue: executeDefault,
1189
+ initialValue: firstChoiceValue,
1170
1190
  });
1171
1191
  handleCancel(execSel);
1172
- const [planMode, planModel] = planSel.split(':');
1173
- const [execMode, execModel] = execSel.split(':');
1192
+ const planChoice = parseValue(planSel);
1193
+ const execChoice = parseValue(execSel);
1194
+ // ── Fallback selection (multi-select, ordered) ──
1195
+ // Build fallback options excluding the primary choice. If no candidates remain (e.g. only
1196
+ // one discovered model), skip the prompt entirely.
1197
+ const planFallbackOptions = options.filter(o => o.value !== planSel);
1198
+ const execFallbackOptions = options.filter(o => o.value !== execSel);
1199
+ let planFallback;
1200
+ if (planFallbackOptions.length > 0) {
1201
+ const sel = await clack.multiselect({
1202
+ message: 'Pick fallback models for `plan` (in order, space to toggle, enter to confirm, leave empty for no fallback):',
1203
+ options: planFallbackOptions,
1204
+ required: false,
1205
+ initialValues: [],
1206
+ });
1207
+ handleCancel(sel);
1208
+ const arr = sel;
1209
+ if (arr.length > 0)
1210
+ planFallback = arr.map(parseValue);
1211
+ }
1212
+ let executeFallback;
1213
+ if (execFallbackOptions.length > 0) {
1214
+ const sel = await clack.multiselect({
1215
+ message: 'Pick fallback models for `execute` (in order, space to toggle, enter to confirm, leave empty for no fallback):',
1216
+ options: execFallbackOptions,
1217
+ required: false,
1218
+ initialValues: [],
1219
+ });
1220
+ handleCancel(sel);
1221
+ const arr = sel;
1222
+ if (arr.length > 0)
1223
+ executeFallback = arr.map(parseValue);
1224
+ }
1174
1225
  return {
1175
- planChoice: { mode: planMode, model: planModel },
1176
- executeChoice: { mode: execMode, model: execModel },
1226
+ planChoice,
1227
+ executeChoice: execChoice,
1228
+ planFallback,
1229
+ executeFallback,
1177
1230
  overwrite: true,
1178
1231
  };
1179
1232
  }
@@ -1193,20 +1246,25 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1193
1246
  const yamlContent = generateGatewayYaml(endpoints);
1194
1247
  const gatewayPath = writeGatewayYaml(yamlContent, gatewayConfigDir);
1195
1248
  clack.log.success(`Gateway config written to ${gatewayPath}`);
1196
- // Resolve plan/execute choices + overwrite intent.
1249
+ // Resolve plan/execute choices + fallback chains + overwrite intent.
1197
1250
  let planChoice = answers?.planChoice;
1198
1251
  let executeChoice = answers?.executeChoice;
1252
+ let planFallback;
1253
+ let executeFallback;
1199
1254
  let overwrite;
1200
1255
  if (processStdin.isTTY) {
1201
1256
  // Interactive: prompt for selection (with overwrite confirmation if needed)
1202
1257
  const picked = await pickPlanExecuteInteractive(endpoints, paths.CONFIG_DIR);
1203
1258
  planChoice = picked.planChoice ?? planChoice;
1204
1259
  executeChoice = picked.executeChoice ?? executeChoice;
1260
+ planFallback = picked.planFallback;
1261
+ executeFallback = picked.executeFallback;
1205
1262
  overwrite = picked.overwrite;
1206
1263
  }
1207
1264
  else {
1208
- // Non-interactive: stdin already provided choices (or empty → auto-infer).
1209
- // Always overwrite — scripted (re)install assumes the operator knows the intent.
1265
+ // Non-interactive: stdin already provided choices (or empty → lex-first default).
1266
+ // Fallback chains are not configurable via stdin in this iteration — extend the stdin
1267
+ // protocol if scripted installs need fallback.
1210
1268
  overwrite = true;
1211
1269
  }
1212
1270
  // Generate profiles.json
@@ -1214,11 +1272,13 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1214
1272
  outputDir: paths.CONFIG_DIR,
1215
1273
  planChoice,
1216
1274
  executeChoice,
1275
+ planFallback,
1276
+ executeFallback,
1217
1277
  overwrite,
1218
1278
  });
1219
1279
  clack.log.success(`Profiles written to ${profilesPath}`);
1220
1280
  // Show profile summary (reflects what was actually generated, not what was merged)
1221
- const profiles = generateProfiles(endpoints, { planChoice, executeChoice });
1281
+ const profiles = generateProfiles(endpoints, { planChoice, executeChoice, planFallback, executeFallback });
1222
1282
  const profileNames = Object.keys(profiles.profiles).join(', ');
1223
1283
  clack.log.info(`Generated profiles: ${profileNames} (default: ${profiles.defaultProfile})`);
1224
1284
  }
@@ -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;