@cortex-agent/server 2026.5.23 → 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 (53) hide show
  1. package/dist/agent-adapter/pi/adapter.js +56 -7
  2. package/dist/agent-adapter/pi/agent-dir.d.ts +41 -4
  3. package/dist/agent-adapter/pi/agent-dir.js +101 -16
  4. package/dist/agent-adapter/pi/spawn-args.d.ts +4 -0
  5. package/dist/agent-adapter/pi/spawn-args.js +6 -3
  6. package/dist/agent-adapter/types.d.ts +7 -0
  7. package/dist/core/gateway-generator.d.ts +27 -14
  8. package/dist/core/gateway-generator.js +154 -170
  9. package/dist/{store → core}/json-repository.js +2 -2
  10. package/dist/core/profile-generator.d.ts +14 -15
  11. package/dist/core/profile-generator.js +52 -174
  12. package/dist/domain/agents/facade.js +6 -0
  13. package/dist/domain/system/server-update-check.d.ts +17 -0
  14. package/dist/domain/system/server-update-check.js +130 -0
  15. package/dist/domain/system/update-prompt.d.ts +8 -0
  16. package/dist/domain/system/update-prompt.js +5 -0
  17. package/dist/domain/system/update-state.d.ts +9 -0
  18. package/dist/domain/system/update-state.js +25 -0
  19. package/dist/entry/app.js +24 -2
  20. package/dist/entry/init.js +118 -60
  21. package/dist/orchestration/agent-runner.js +3 -4
  22. package/dist/orchestration/interactions/update-prompt-slack.d.ts +6 -0
  23. package/dist/orchestration/interactions/update-prompt-slack.js +95 -0
  24. package/dist/orchestration/lifecycle.js +3 -4
  25. package/dist/platform/adapter.d.ts +4 -0
  26. package/dist/platform/adapter.js +1 -1
  27. package/dist/platform/adapters/feishu.d.ts +1 -0
  28. package/dist/platform/adapters/feishu.js +7 -0
  29. package/dist/platform/adapters/slack-project-conduits.js +1 -1
  30. package/dist/platform/adapters/slack.d.ts +1 -0
  31. package/dist/platform/adapters/slack.js +8 -0
  32. package/dist/platform/index.js +1 -1
  33. package/dist/platform/testing.d.ts +1 -0
  34. package/dist/platform/testing.js +7 -0
  35. package/dist/store/conversation-ledger-repo.js +1 -1
  36. package/dist/store/cost-repo.js +2 -2
  37. package/dist/store/execution-repo.js +1 -1
  38. package/dist/store/outbound-queue.js +1 -1
  39. package/dist/store/profile-repo.js +1 -1
  40. package/dist/store/project-dir-repo.d.ts +0 -5
  41. package/dist/store/project-dir-repo.js +4 -15
  42. package/dist/store/schedule-repo.js +1 -1
  43. package/dist/store/session-registry-repo.js +6 -2
  44. package/dist/store/session-repo.js +1 -1
  45. package/dist/store/thread-repo.js +1 -1
  46. package/dist/store/version-migrations.d.ts +22 -0
  47. package/dist/store/version-migrations.js +200 -0
  48. package/package.json +2 -2
  49. package/dist/store/channel-repo.d.ts +0 -27
  50. package/dist/store/channel-repo.js +0 -64
  51. /package/dist/{store → core}/atomic-write.d.ts +0 -0
  52. /package/dist/{store → core}/atomic-write.js +0 -0
  53. /package/dist/{store → core}/json-repository.d.ts +0 -0
@@ -574,50 +574,66 @@ async function collectSlackConfig(prefill) {
574
574
  ].join('\n'), 'Slack App Setup Guide');
575
575
  await promptCopyManifestToClipboard(SLACK_APP_MANIFEST);
576
576
  const hasPrefill = prefill && (prefill.signingSecret || prefill.appToken || prefill.botToken);
577
+ let signingSecret;
578
+ let appToken;
579
+ let botToken;
580
+ let adminChannelRaw;
577
581
  if (hasPrefill) {
578
- 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);
579
632
  }
580
- const signingSecret = await clack.password({
581
- message: 'Step 1/4: SLACK_SIGNING_SECRET (from Basic Information):',
582
- initialValue: prefill?.signingSecret,
583
- validate(value) {
584
- if (!value)
585
- return 'Signing secret is required.';
586
- },
587
- });
588
- handleCancel(signingSecret);
589
- const appToken = await clack.password({
590
- message: 'Step 2/4: SLACK_APP_TOKEN (App-Level Token, starts with xapp-):',
591
- initialValue: prefill?.appToken,
592
- validate(value) {
593
- if (!value)
594
- return 'App token is required.';
595
- if (!value.startsWith('xapp-'))
596
- return 'Token should start with xapp-';
597
- },
598
- });
599
- handleCancel(appToken);
600
- const botToken = await clack.password({
601
- message: 'Step 3/4: SLACK_BOT_TOKEN (Bot User OAuth Token, starts with xoxb-):',
602
- initialValue: prefill?.botToken,
603
- validate(value) {
604
- if (!value)
605
- return 'Bot token is required.';
606
- if (!value.startsWith('xoxb-'))
607
- return 'Token should start with xoxb-';
608
- },
609
- });
610
- handleCancel(botToken);
611
- const adminChannelRaw = await clack.text({
612
- message: 'Step 4/4: CORTEX_ADMIN_CHANNEL (optional — Slack channel ID for admin notifications):',
613
- placeholder: 'e.g. C0123456789 or D0123456789 (leave blank to configure later)',
614
- initialValue: prefill?.adminChannel,
615
- });
616
- handleCancel(adminChannelRaw);
617
633
  return {
618
- botToken: botToken,
619
634
  signingSecret: signingSecret,
620
635
  appToken: appToken,
636
+ botToken: botToken,
621
637
  adminChannel: adminChannelRaw.trim() || undefined,
622
638
  };
623
639
  }
@@ -1129,9 +1145,11 @@ function detectExistingPlanOrExecute(configDir) {
1129
1145
  }
1130
1146
  }
1131
1147
  /**
1132
- * Interactively pick plan / execute (mode, model) from discovered endpoints.
1133
- * Pre-selects auto-inferred defaults. Returns undefined for either choice if the user
1134
- * 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.
1135
1153
  */
1136
1154
  async function pickPlanExecuteInteractive(endpoints, configDir) {
1137
1155
  // If existing profiles.json has plan/execute, ask before overwriting
@@ -1148,34 +1166,67 @@ async function pickPlanExecuteInteractive(endpoints, configDir) {
1148
1166
  const choices = listChoices(endpoints);
1149
1167
  if (choices.length === 0)
1150
1168
  return { overwrite: true };
1151
- const autoDefaults = generateProfiles(endpoints).profiles;
1152
- const planDefault = autoDefaults.plan
1153
- ? `${autoDefaults.plan.mode}:${autoDefaults.plan.model}`
1154
- : `${choices[0].mode}:${choices[0].model}`;
1155
- const executeDefault = autoDefaults.execute
1156
- ? `${autoDefaults.execute.mode}:${autoDefaults.execute.model}`
1157
- : 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
+ };
1158
1174
  const options = choices.map(c => ({
1159
- value: `${c.mode}:${c.model}`,
1175
+ value: formatValue(c),
1160
1176
  label: `${c.mode} / ${c.model}`,
1161
1177
  }));
1178
+ // Default = first lexicographic entry (no tier inference).
1179
+ const firstChoiceValue = formatValue(choices[0]);
1162
1180
  const planSel = await clack.select({
1163
1181
  message: 'Pick model for the `plan` profile (used by executor agents — planner, doc-writer, coder, etc.):',
1164
1182
  options,
1165
- initialValue: planDefault,
1183
+ initialValue: firstChoiceValue,
1166
1184
  });
1167
1185
  handleCancel(planSel);
1168
1186
  const execSel = await clack.select({
1169
1187
  message: 'Pick model for the `execute` profile (used by reviewer agents — reviewer, doc-reviewer, coder-reviewer, etc.):',
1170
1188
  options,
1171
- initialValue: executeDefault,
1189
+ initialValue: firstChoiceValue,
1172
1190
  });
1173
1191
  handleCancel(execSel);
1174
- const [planMode, planModel] = planSel.split(':');
1175
- 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
+ }
1176
1225
  return {
1177
- planChoice: { mode: planMode, model: planModel },
1178
- executeChoice: { mode: execMode, model: execModel },
1226
+ planChoice,
1227
+ executeChoice: execChoice,
1228
+ planFallback,
1229
+ executeFallback,
1179
1230
  overwrite: true,
1180
1231
  };
1181
1232
  }
@@ -1195,20 +1246,25 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1195
1246
  const yamlContent = generateGatewayYaml(endpoints);
1196
1247
  const gatewayPath = writeGatewayYaml(yamlContent, gatewayConfigDir);
1197
1248
  clack.log.success(`Gateway config written to ${gatewayPath}`);
1198
- // Resolve plan/execute choices + overwrite intent.
1249
+ // Resolve plan/execute choices + fallback chains + overwrite intent.
1199
1250
  let planChoice = answers?.planChoice;
1200
1251
  let executeChoice = answers?.executeChoice;
1252
+ let planFallback;
1253
+ let executeFallback;
1201
1254
  let overwrite;
1202
1255
  if (processStdin.isTTY) {
1203
1256
  // Interactive: prompt for selection (with overwrite confirmation if needed)
1204
1257
  const picked = await pickPlanExecuteInteractive(endpoints, paths.CONFIG_DIR);
1205
1258
  planChoice = picked.planChoice ?? planChoice;
1206
1259
  executeChoice = picked.executeChoice ?? executeChoice;
1260
+ planFallback = picked.planFallback;
1261
+ executeFallback = picked.executeFallback;
1207
1262
  overwrite = picked.overwrite;
1208
1263
  }
1209
1264
  else {
1210
- // Non-interactive: stdin already provided choices (or empty → auto-infer).
1211
- // 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.
1212
1268
  overwrite = true;
1213
1269
  }
1214
1270
  // Generate profiles.json
@@ -1216,11 +1272,13 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1216
1272
  outputDir: paths.CONFIG_DIR,
1217
1273
  planChoice,
1218
1274
  executeChoice,
1275
+ planFallback,
1276
+ executeFallback,
1219
1277
  overwrite,
1220
1278
  });
1221
1279
  clack.log.success(`Profiles written to ${profilesPath}`);
1222
1280
  // Show profile summary (reflects what was actually generated, not what was merged)
1223
- const profiles = generateProfiles(endpoints, { planChoice, executeChoice });
1281
+ const profiles = generateProfiles(endpoints, { planChoice, executeChoice, planFallback, executeFallback });
1224
1282
  const profileNames = Object.keys(profiles.profiles).join(', ');
1225
1283
  clack.log.info(`Generated profiles: ${profileNames} (default: ${profiles.defaultProfile})`);
1226
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;
@@ -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();