@cortex-agent/server 2026.5.23 → 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 (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 +153 -169
  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 +63 -21
  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
@@ -1,45 +1,25 @@
1
- // input: DiscoveredEndpoint[], profile-manager types, fs, path
1
+ // input: DiscoveredEndpoint[], explicit (mode, model) choices, optional fallback chains
2
2
  // output: generateProfiles / mergeProfilesJson / writeProfilesJson / listChoices
3
3
  // — produce profiles.json content from discovered models
4
- // pos: init-time profiles.json auto-generation. Names are unsuffixed (`plan`, `execute`);
5
- // users can override via explicit (mode, model) choices from `cortex init`.
4
+ // pos: init-time profiles.json auto-generation. Names are always 'plan' / 'execute' (no tier/provider
5
+ // suffix). User explicitly picks (mode, model) for each profile and optionally chooses fallback
6
+ // chains via interactive multi-select in `cortex init`. No tier classification, no auto-generated
7
+ // deepseek-pro / codex / etc. — PI is the source of model truth.
6
8
  import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
7
9
  import * as path from 'path';
8
10
  import * as os from 'os';
9
11
  import { createLogger } from './log.js';
10
12
  const log = createLogger('profile-generator');
11
- // ─── Model tier classification ────────────────────────────────────
12
- /** Determine model tier: "max", "mid", or "budget". */
13
- function classifyTier(model) {
14
- const lower = model.toLowerCase();
15
- if (lower.includes('opus') || lower.includes('pro') || lower.includes('gpt-5'))
16
- return 'max';
17
- if (lower.includes('sonnet') || lower.includes('flash') || lower.includes('mini'))
18
- return 'mid';
19
- if (lower.includes('haiku') || lower.includes('lite'))
20
- return 'budget';
21
- return 'mid'; // default
22
- }
23
13
  // ─── Endpoint → backend mapping ────────────────────────────────────
24
14
  /**
25
15
  * Determine the Cortex backend from endpoint and mode.
26
- * - anthropic endpoint with plan/api mode → claude
27
- * - openai endpoint → codex
28
- * - everything else → pi (or claude if anthropic endpoint)
16
+ * - anthropic endpoint with plan/api mode → claude (Claude Code CLI)
17
+ * - everything else → pi (PI agent CLI handles all other providers, including OAuth ones like openai-codex)
29
18
  */
30
19
  function resolveBackend(endpoint, mode) {
31
20
  if (endpoint === 'anthropic' && (mode === 'plan' || mode === 'api')) {
32
21
  return 'claude';
33
22
  }
34
- if (endpoint === 'openai') {
35
- // PI-discovered OpenAI models → use PI backend (not Codex)
36
- return 'pi';
37
- }
38
- if (endpoint === 'anthropic') {
39
- // Non-standard Anthropic mode (e.g., deepseek-anthropic) — can use claude or pi
40
- // PI handles anthropic-compatible APIs better for custom providers
41
- return 'pi';
42
- }
43
23
  return 'pi';
44
24
  }
45
25
  /** Flatten all discovered endpoints into a list of (model, backend, mode) entries. */
@@ -52,65 +32,12 @@ function flattenModels(endpoints) {
52
32
  model,
53
33
  backend,
54
34
  mode: ep.mode,
55
- tier: classifyTier(model),
56
35
  endpoint: ep.endpoint,
57
36
  });
58
37
  }
59
38
  }
60
39
  return entries;
61
40
  }
62
- /** Pick the best model for a given tier and preferred endpoint. */
63
- function pickModel(models, tier, preferEndpoint) {
64
- // Prefer specific endpoint
65
- if (preferEndpoint) {
66
- const match = models.filter(m => m.tier === tier && m.endpoint === preferEndpoint);
67
- if (match.length > 0)
68
- return match[0];
69
- }
70
- // Fallback to any endpoint
71
- const any = models.filter(m => m.tier === tier);
72
- if (any.length > 0)
73
- return any[0];
74
- // Downgrade tier
75
- if (tier === 'max')
76
- return pickModel(models, 'mid', preferEndpoint);
77
- if (tier === 'mid')
78
- return pickModel(models, 'budget', preferEndpoint);
79
- return null;
80
- }
81
- /** Build a fallback chain for a given model.
82
- * Only includes models that are strictly lower-tier or from other endpoints. */
83
- function buildFallbackChain(primary, models) {
84
- const fallbacks = [];
85
- const tierOrder = { max: 0, mid: 1, budget: 2 };
86
- const primaryRank = tierOrder[primary.tier] ?? 1;
87
- // Same endpoint, strictly lower tier (not same or higher)
88
- const sameEndpoint = models.filter(m => m.endpoint === primary.endpoint
89
- && m.model !== primary.model
90
- && (tierOrder[m.tier] ?? 1) > primaryRank);
91
- sameEndpoint.sort((a, b) => (tierOrder[a.tier] ?? 1) - (tierOrder[b.tier] ?? 1));
92
- for (const m of sameEndpoint.slice(0, 2)) {
93
- fallbacks.push({ model: m.model, backend: m.backend, mode: m.mode });
94
- }
95
- // Cross-endpoint fallback (e.g., Claude → DeepSeek)
96
- const otherEndpoint = models.filter(m => m.endpoint !== primary.endpoint);
97
- otherEndpoint.sort((a, b) => (tierOrder[a.tier] ?? 1) - (tierOrder[b.tier] ?? 1));
98
- for (const m of otherEndpoint.slice(0, 2)) {
99
- fallbacks.push({ model: m.model, backend: m.backend, mode: m.mode });
100
- }
101
- return fallbacks;
102
- }
103
- /** Build profile entry from a ModelEntry, with optional extra config. */
104
- function makeProfileEntry(m, models, extraEnv, extraOption) {
105
- return {
106
- model: m.model,
107
- backend: m.backend,
108
- mode: m.mode,
109
- fallback: buildFallbackChain(m, models),
110
- ...(extraEnv ? { extraEnv } : {}),
111
- ...(extraOption ? { extraOption } : {}),
112
- };
113
- }
114
41
  /** Locate a ModelEntry by explicit (mode, model). Throws if not found. */
115
42
  function findModelEntry(models, choice, label) {
116
43
  const match = models.find(m => m.mode === choice.mode && m.model === choice.model);
@@ -119,73 +46,33 @@ function findModelEntry(models, choice, label) {
119
46
  }
120
47
  return match;
121
48
  }
122
- /** Generate profiles for DeepSeek models (if available in discovered endpoints). */
123
- function generateDeepSeekProfiles(models) {
124
- const result = {};
125
- const deepseekModels = models.filter(m => m.model.toLowerCase().includes('deepseek'));
126
- for (const dm of deepseekModels) {
127
- const isFlash = dm.model.toLowerCase().includes('flash');
128
- const profileName = isFlash ? 'deepseek-flash' : 'deepseek-pro';
129
- const extraEnv = {};
130
- const extraOption = {};
131
- if (dm.backend === 'claude') {
132
- // Claude Code requires these for non-Anthropic providers
133
- extraEnv.CLAUDE_CODE_ATTRIBUTION_HEADER = '0';
134
- extraEnv.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = '1';
135
- extraEnv.CLAUDE_CODE_DISABLE_SESSION_METADATA = '1';
136
- }
137
- else if (dm.backend === 'pi' && !isFlash) {
138
- // DeepSeek pro with extended thinking via PI (only PI + DeepSeek non-flash)
139
- extraOption['--thinking'] = 'xhigh';
140
- }
141
- result[profileName] = {
142
- model: dm.model,
143
- backend: dm.backend,
144
- mode: dm.mode,
145
- ...(Object.keys(extraEnv).length > 0 ? { extraEnv } : {}),
146
- ...(Object.keys(extraOption).length > 0 ? { extraOption } : {}),
147
- };
148
- }
149
- return result;
150
- }
151
- /** Generate Codex profile if OpenAI models are available. */
152
- function generateCodexProfile(models) {
153
- const openaiModels = models.filter(m => m.endpoint === 'openai');
154
- if (openaiModels.length === 0)
155
- return {};
156
- const best = openaiModels.find(m => m.tier === 'max') || openaiModels[0];
157
- const fallbacks = [];
158
- // Fallback: Anthropic sonnet
159
- const claudeMid = models.find(m => m.endpoint === 'anthropic' && m.tier === 'mid');
160
- if (claudeMid) {
161
- fallbacks.push({ model: claudeMid.model, backend: claudeMid.backend, mode: 'plan' });
162
- }
49
+ /** Build a ProfileEntry from a ModelEntry (no fallback chain attached yet). */
50
+ function makeProfileEntry(m) {
163
51
  return {
164
- codex: {
165
- model: best.model,
166
- backend: 'pi',
167
- mode: best.mode,
168
- fallback: fallbacks.length > 0 ? fallbacks : undefined,
169
- },
52
+ model: m.model,
53
+ backend: m.backend,
54
+ mode: m.mode,
170
55
  };
171
56
  }
57
+ /** Build fallback entries from explicit user choices. Throws if any choice can't be resolved. */
58
+ function resolveFallbackChain(models, fallback, label) {
59
+ if (!fallback || fallback.length === 0)
60
+ return undefined;
61
+ return fallback.map((choice, i) => {
62
+ const m = findModelEntry(models, choice, `${label} fallback[${i}]`);
63
+ return makeProfileEntry(m);
64
+ });
65
+ }
172
66
  // ─── Choice listing (for init UI) ─────────────────────────────────
173
67
  /**
174
68
  * Flatten endpoints to a list of (mode, model) choices the user can pick from.
175
- * Ordered so Anthropic plan/api modes come first (recommended for `plan` profile).
69
+ * Strictly sorted by (mode ASC, model ASC) — no tier or provider preference.
176
70
  */
177
71
  export function listChoices(endpoints) {
178
72
  const flat = flattenModels(endpoints);
179
- // Sort: anthropic+plan/api first (recommended for plan), then others.
180
- // Within each group, max-tier first.
181
- const tierOrder = { max: 0, mid: 1, budget: 2 };
182
- const isAnthropicNative = (m) => m.endpoint === 'anthropic' && (m.mode === 'plan' || m.mode === 'api');
183
73
  flat.sort((a, b) => {
184
- const aN = isAnthropicNative(a) ? 0 : 1;
185
- const bN = isAnthropicNative(b) ? 0 : 1;
186
- if (aN !== bN)
187
- return aN - bN;
188
- return (tierOrder[a.tier] ?? 1) - (tierOrder[b.tier] ?? 1);
74
+ const cmp = a.mode.localeCompare(b.mode);
75
+ return cmp !== 0 ? cmp : a.model.localeCompare(b.model);
189
76
  });
190
77
  return flat.map(m => ({ mode: m.mode, model: m.model }));
191
78
  }
@@ -193,17 +80,12 @@ export function listChoices(endpoints) {
193
80
  /**
194
81
  * Generate a profiles.json object from discovered endpoints.
195
82
  *
196
- * Naming: outputs unsuffixed `plan` and `execute` (no provider suffix).
197
- *
198
- * Selection rules:
199
- * - plan: explicit `opts.planChoice` if provided, else max-tier Anthropic.
200
- * - execute: explicit `opts.executeChoice` if provided, else prefer non-Claude-Code
201
- * mid-tier (cost), fall back to Anthropic mid-tier, then max.
202
- *
203
- * Provider-specific profiles always layered on top:
204
- * - deepseek-flash / deepseek-pro: if DeepSeek models discovered. `--thinking xhigh`
205
- * only on PI backend non-flash (the only PI + DeepSeek combo that should get it).
206
- * - codex: if OpenAI models discovered.
83
+ * Generates exactly two profiles: `plan` and `execute`.
84
+ * - If `planChoice` is omitted, picks the first lexicographic (mode, model) tuple.
85
+ * - Same default rule for `execute`.
86
+ * - Fallback chains are taken verbatim from `planFallback` / `executeFallback` (no auto-derivation).
87
+ * - No tier classification, no auto-generated deepseek-pro / codex / etc. — users explicitly choose
88
+ * what they want via cortex init's interactive UI.
207
89
  */
208
90
  export function generateProfiles(endpoints, opts = {}) {
209
91
  const models = flattenModels(endpoints);
@@ -216,32 +98,26 @@ export function generateProfiles(endpoints, opts = {}) {
216
98
  },
217
99
  };
218
100
  }
219
- const profiles = {};
220
- const anthropicModels = models.filter(m => m.endpoint === 'anthropic' && (m.mode === 'plan' || m.mode === 'api'));
221
- // ── plan ──
222
- const planEntry = opts.planChoice
223
- ? findModelEntry(models, opts.planChoice, 'planChoice')
224
- : pickModel(anthropicModels, 'max');
225
- if (planEntry) {
226
- profiles.plan = makeProfileEntry(planEntry, models);
227
- }
228
- // ── execute ──
229
- let executeEntry;
230
- if (opts.executeChoice) {
231
- executeEntry = findModelEntry(models, opts.executeChoice, 'executeChoice');
232
- }
233
- else {
234
- // Prefer mid-tier non-Anthropic-native models for cost savings
235
- const nonClaudeMid = models.find(m => m.tier === 'mid' && !(m.endpoint === 'anthropic' && (m.mode === 'plan' || m.mode === 'api')));
236
- executeEntry = nonClaudeMid || pickModel(anthropicModels, 'mid') || pickModel(anthropicModels, 'max');
237
- }
238
- if (executeEntry) {
239
- profiles.execute = makeProfileEntry(executeEntry, models);
240
- }
241
- // ── Provider-specific profiles ──
242
- Object.assign(profiles, generateDeepSeekProfiles(models));
243
- Object.assign(profiles, generateCodexProfile(models));
244
- return { defaultProfile: 'plan', profiles };
101
+ // Lexicographic default: first choice in listChoices order
102
+ const sorted = listChoices(endpoints);
103
+ const defaultChoice = sorted[0];
104
+ const planEntry = findModelEntry(models, opts.planChoice ?? defaultChoice, 'planChoice');
105
+ const executeEntry = findModelEntry(models, opts.executeChoice ?? defaultChoice, 'executeChoice');
106
+ const planFallback = resolveFallbackChain(models, opts.planFallback, 'planChoice');
107
+ const executeFallback = resolveFallbackChain(models, opts.executeFallback, 'executeChoice');
108
+ const planProfile = makeProfileEntry(planEntry);
109
+ if (planFallback)
110
+ planProfile.fallback = planFallback;
111
+ const executeProfile = makeProfileEntry(executeEntry);
112
+ if (executeFallback)
113
+ executeProfile.fallback = executeFallback;
114
+ return {
115
+ defaultProfile: 'plan',
116
+ profiles: {
117
+ plan: planProfile,
118
+ execute: executeProfile,
119
+ },
120
+ };
245
121
  }
246
122
  // ─── File I/O ─────────────────────────────────────────────────────
247
123
  /**
@@ -299,6 +175,8 @@ export function writeProfilesJson(endpoints, optsOrOutputDir) {
299
175
  const generated = generateProfiles(endpoints, {
300
176
  planChoice: opts.planChoice,
301
177
  executeChoice: opts.executeChoice,
178
+ planFallback: opts.planFallback,
179
+ executeFallback: opts.executeFallback,
302
180
  });
303
181
  const merged = mergeProfilesJson(generated, opts.outputDir, opts.overwrite ?? false);
304
182
  const configDir = opts.outputDir || path.join(os.homedir(), '.cortex', 'config');
@@ -6,6 +6,7 @@ import { resolveProfileConfig } from './profile-manager.js';
6
6
  import { recordCost } from '../costs/cost-tracker.js';
7
7
  import { configureEnvForMode, isRetryableResult, isRetryableError } from './config.js';
8
8
  import { isModeRateLimited, isThrottled } from '../costs/rate-limit-throttle.js';
9
+ import { GATEWAY_URL } from '../costs/gateway-manager.js';
9
10
  import { createLogger } from '../../core/log.js';
10
11
  import { loadCortexRules } from '../memory/rules-loader.js';
11
12
  const log = createLogger('facade');
@@ -46,6 +47,11 @@ function buildSpawnConfig(options, config, anthropicBaseUrl) {
46
47
  isUserInitiated: !!options.isUserInitiated,
47
48
  rawTools: typeof options.tools === 'string' ? options.tools : undefined,
48
49
  anthropicBaseUrl,
50
+ // PI-specific routing: provider name (= profile mode) + gateway base URL. PI adapter writes
51
+ // a multi-provider models.json (writeProvidersConfig) so every PI provider lands on the
52
+ // gateway. Claude / codex adapters ignore these fields.
53
+ piProvider: config.backend === 'pi' && config.mode ? config.mode : undefined,
54
+ piGatewayBaseUrl: config.backend === 'pi' ? GATEWAY_URL : undefined,
49
55
  cortexContext: hasContext ? ctx : undefined,
50
56
  appendSystemPrompt,
51
57
  };
@@ -0,0 +1,17 @@
1
+ import type { UpdateChoice, UpdatePrompt } from './update-prompt.js';
2
+ import { type UpdateState } from './update-state.js';
3
+ export declare function compareCalVer(a: string, b: string): number;
4
+ export declare function isUpdateDevMode(): boolean;
5
+ export interface CheckServerUpdateDeps {
6
+ prompt: UpdatePrompt;
7
+ getLatest?: () => string | null;
8
+ spawnInstall?: () => void;
9
+ loadState?: () => UpdateState | null;
10
+ saveState?: (s: UpdateState) => void;
11
+ now?: () => string;
12
+ }
13
+ export interface CheckServerUpdateResult {
14
+ action: UpdateChoice | null;
15
+ latestVersion: string | null;
16
+ }
17
+ export declare function checkServerUpdate(deps: CheckServerUpdateDeps): Promise<CheckServerUpdateResult>;
@@ -0,0 +1,130 @@
1
+ // input: UpdatePrompt interface, UpdateState I/O, CORTEX_VERSION, child_process
2
+ // output: compareCalVer, isUpdateDevMode, checkServerUpdate
3
+ // pos: DR-0013 core checker — npm registry version check + prompt + dispatch
4
+ import * as fs from 'node:fs';
5
+ import { execSync, spawn } from 'node:child_process';
6
+ import { CORTEX_VERSION } from '../../core/version.js';
7
+ import { loadUpdateState, saveUpdateState } from './update-state.js';
8
+ // ── CalVer comparison: YYYY.M.D[-N] ──────────────────────────────
9
+ // Supports an optional suffix (e.g. 2026.5.23-1) for hotfix releases.
10
+ // Default suffix is 0 when absent. Compare element-wise (year, month, day, suffix)
11
+ // to avoid string-ordering pitfalls across digit boundaries.
12
+ export function compareCalVer(a, b) {
13
+ const parse = (v) => {
14
+ const parts = v.split('.');
15
+ const year = Number(parts[0]);
16
+ const month = Number(parts[1]);
17
+ const daySuffix = parts[2]?.split('-') ?? ['0'];
18
+ const day = Number(daySuffix[0]);
19
+ const suffix = Number(daySuffix[1] ?? '0');
20
+ return [year, month, day, suffix];
21
+ };
22
+ const [ay, am, ad, asfx] = parse(a);
23
+ const [by, bm, bd, bsfx] = parse(b);
24
+ if (ay !== by)
25
+ return ay - by;
26
+ if (am !== bm)
27
+ return am - bm;
28
+ if (ad !== bd)
29
+ return ad - bd;
30
+ return asfx - bsfx;
31
+ }
32
+ // ── Dev mode detection ──────────────────────────────────────────
33
+ // In dev mode (CORTEX_REPO set), server auto-update is skipped entirely
34
+ // because the developer manages the install directly.
35
+ export function isUpdateDevMode() {
36
+ const repo = process.env.CORTEX_REPO;
37
+ if (!repo)
38
+ return false;
39
+ try {
40
+ return fs.existsSync(repo) && fs.statSync(repo).isDirectory();
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }
46
+ // ── Default implementations ─────────────────────────────────────
47
+ function defaultGetLatest() {
48
+ try {
49
+ const result = execSync('npm view @cortex-agent/server version', {
50
+ encoding: 'utf8',
51
+ timeout: 15000,
52
+ stdio: 'pipe',
53
+ }).trim();
54
+ return result || null;
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ }
60
+ function defaultSpawnInstall() {
61
+ const child = spawn('npm', ['install', '-g', '@cortex-agent/server@latest'], {
62
+ detached: true,
63
+ stdio: 'ignore',
64
+ cwd: '/tmp',
65
+ });
66
+ child.unref();
67
+ }
68
+ function defaultNow() {
69
+ return new Date().toISOString();
70
+ }
71
+ // ── Main check-and-prompt flow ──────────────────────────────────
72
+ export async function checkServerUpdate(deps) {
73
+ // 1. Enable toggle: auto-update is off by default, opt-in via env var
74
+ if (process.env.CORTEX_SERVER_UPDATE_ENABLE !== '1') {
75
+ return { action: null, latestVersion: null };
76
+ }
77
+ // 2. Dev mode: skip entirely
78
+ if (isUpdateDevMode()) {
79
+ return { action: null, latestVersion: null };
80
+ }
81
+ const getLatest = deps.getLatest ?? defaultGetLatest;
82
+ const spawnInstall = deps.spawnInstall ?? defaultSpawnInstall;
83
+ const loadState = deps.loadState ?? loadUpdateState;
84
+ const saveState = deps.saveState ?? saveUpdateState;
85
+ const now = deps.now ?? defaultNow;
86
+ // 2. Fetch latest version
87
+ const latestVersion = getLatest();
88
+ if (latestVersion === null) {
89
+ return { action: null, latestVersion: null };
90
+ }
91
+ // 3. Latest <= local: no update needed
92
+ if (compareCalVer(latestVersion, CORTEX_VERSION) <= 0) {
93
+ return { action: null, latestVersion };
94
+ }
95
+ // 4. Check if this version was skipped
96
+ const state = loadState() ?? {};
97
+ if (state.skippedVersion === latestVersion) {
98
+ return { action: null, latestVersion };
99
+ }
100
+ // 5. Record check time and prompt
101
+ const timestamp = now();
102
+ saveState({
103
+ ...state,
104
+ lastCheckedAt: timestamp,
105
+ lastPromptedVersion: latestVersion,
106
+ });
107
+ const choice = await deps.prompt.ask({ latestVersion });
108
+ // 6. Dispatch user choice
109
+ if (choice === 'apply') {
110
+ saveState({
111
+ ...state,
112
+ skippedVersion: undefined,
113
+ lastCheckedAt: timestamp,
114
+ lastPromptedVersion: latestVersion,
115
+ });
116
+ spawnInstall();
117
+ return { action: 'apply', latestVersion };
118
+ }
119
+ if (choice === 'skip') {
120
+ saveState({
121
+ ...state,
122
+ skippedVersion: latestVersion,
123
+ lastCheckedAt: timestamp,
124
+ lastPromptedVersion: latestVersion,
125
+ });
126
+ return { action: 'skip', latestVersion };
127
+ }
128
+ // cancel / null: no state mutation beyond what was already saved
129
+ return { action: choice, latestVersion };
130
+ }
@@ -0,0 +1,8 @@
1
+ export type UpdateChoice = 'apply' | 'skip' | 'cancel';
2
+ export interface UpdatePrompt {
3
+ /** Present an update prompt to the user.
4
+ * Returns the user's choice, or null if the prompt was dismissed (timeout / superseded). */
5
+ ask(spec: {
6
+ latestVersion: string;
7
+ }): Promise<UpdateChoice | null>;
8
+ }
@@ -0,0 +1,5 @@
1
+ // input: nothing (pure types module)
2
+ // output: UpdateChoice type + UpdatePrompt interface
3
+ // pos: Platform-agnostic interface for server update prompts
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ export {};
@@ -0,0 +1,9 @@
1
+ export interface UpdateState {
2
+ skippedVersion?: string;
3
+ lastCheckedAt?: string;
4
+ lastPromptedVersion?: string;
5
+ }
6
+ export declare function loadUpdateState(): UpdateState | null;
7
+ export declare function saveUpdateState(state: UpdateState): void;
8
+ /** Test-only: redirect file path to an isolated temp location. */
9
+ export declare function _testSetStateFile(p: string): void;
@@ -0,0 +1,25 @@
1
+ // input: STORE_DIR constant
2
+ // output: loadUpdateState / saveUpdateState for update-state.json
3
+ // pos: DR-0013 server auto-update skipped version persistence
4
+ import * as fs from 'fs';
5
+ import * as path from 'path';
6
+ import { STORE_DIR } from '../../core/utils.js';
7
+ // Mutable for test isolation — tests override this via _testSetStateFile
8
+ let stateFilePath = path.join(STORE_DIR, 'update-state.json');
9
+ export function loadUpdateState() {
10
+ try {
11
+ return JSON.parse(fs.readFileSync(stateFilePath, 'utf8'));
12
+ }
13
+ catch {
14
+ return null;
15
+ }
16
+ }
17
+ export function saveUpdateState(state) {
18
+ const dir = path.dirname(stateFilePath);
19
+ fs.mkdirSync(dir, { recursive: true });
20
+ fs.writeFileSync(stateFilePath, JSON.stringify(state, null, 2));
21
+ }
22
+ /** Test-only: redirect file path to an isolated temp location. */
23
+ export function _testSetStateFile(p) {
24
+ stateFilePath = p;
25
+ }
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.