@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
@@ -1,44 +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
- return 'codex';
36
- }
37
- if (endpoint === 'anthropic') {
38
- // Non-standard Anthropic mode (e.g., deepseek-anthropic) — can use claude or pi
39
- // PI handles anthropic-compatible APIs better for custom providers
40
- return 'pi';
41
- }
42
23
  return 'pi';
43
24
  }
44
25
  /** Flatten all discovered endpoints into a list of (model, backend, mode) entries. */
@@ -51,65 +32,12 @@ function flattenModels(endpoints) {
51
32
  model,
52
33
  backend,
53
34
  mode: ep.mode,
54
- tier: classifyTier(model),
55
35
  endpoint: ep.endpoint,
56
36
  });
57
37
  }
58
38
  }
59
39
  return entries;
60
40
  }
61
- /** Pick the best model for a given tier and preferred endpoint. */
62
- function pickModel(models, tier, preferEndpoint) {
63
- // Prefer specific endpoint
64
- if (preferEndpoint) {
65
- const match = models.filter(m => m.tier === tier && m.endpoint === preferEndpoint);
66
- if (match.length > 0)
67
- return match[0];
68
- }
69
- // Fallback to any endpoint
70
- const any = models.filter(m => m.tier === tier);
71
- if (any.length > 0)
72
- return any[0];
73
- // Downgrade tier
74
- if (tier === 'max')
75
- return pickModel(models, 'mid', preferEndpoint);
76
- if (tier === 'mid')
77
- return pickModel(models, 'budget', preferEndpoint);
78
- return null;
79
- }
80
- /** Build a fallback chain for a given model.
81
- * Only includes models that are strictly lower-tier or from other endpoints. */
82
- function buildFallbackChain(primary, models) {
83
- const fallbacks = [];
84
- const tierOrder = { max: 0, mid: 1, budget: 2 };
85
- const primaryRank = tierOrder[primary.tier] ?? 1;
86
- // Same endpoint, strictly lower tier (not same or higher)
87
- const sameEndpoint = models.filter(m => m.endpoint === primary.endpoint
88
- && m.model !== primary.model
89
- && (tierOrder[m.tier] ?? 1) > primaryRank);
90
- sameEndpoint.sort((a, b) => (tierOrder[a.tier] ?? 1) - (tierOrder[b.tier] ?? 1));
91
- for (const m of sameEndpoint.slice(0, 2)) {
92
- fallbacks.push({ model: m.model, backend: m.backend, mode: m.mode });
93
- }
94
- // Cross-endpoint fallback (e.g., Claude → DeepSeek)
95
- const otherEndpoint = models.filter(m => m.endpoint !== primary.endpoint);
96
- otherEndpoint.sort((a, b) => (tierOrder[a.tier] ?? 1) - (tierOrder[b.tier] ?? 1));
97
- for (const m of otherEndpoint.slice(0, 2)) {
98
- fallbacks.push({ model: m.model, backend: m.backend, mode: m.mode });
99
- }
100
- return fallbacks;
101
- }
102
- /** Build profile entry from a ModelEntry, with optional extra config. */
103
- function makeProfileEntry(m, models, extraEnv, extraOption) {
104
- return {
105
- model: m.model,
106
- backend: m.backend,
107
- mode: m.mode,
108
- fallback: buildFallbackChain(m, models),
109
- ...(extraEnv ? { extraEnv } : {}),
110
- ...(extraOption ? { extraOption } : {}),
111
- };
112
- }
113
41
  /** Locate a ModelEntry by explicit (mode, model). Throws if not found. */
114
42
  function findModelEntry(models, choice, label) {
115
43
  const match = models.find(m => m.mode === choice.mode && m.model === choice.model);
@@ -118,73 +46,33 @@ function findModelEntry(models, choice, label) {
118
46
  }
119
47
  return match;
120
48
  }
121
- /** Generate profiles for DeepSeek models (if available in discovered endpoints). */
122
- function generateDeepSeekProfiles(models) {
123
- const result = {};
124
- const deepseekModels = models.filter(m => m.model.toLowerCase().includes('deepseek'));
125
- for (const dm of deepseekModels) {
126
- const isFlash = dm.model.toLowerCase().includes('flash');
127
- const profileName = isFlash ? 'deepseek-flash' : 'deepseek-pro';
128
- const extraEnv = {};
129
- const extraOption = {};
130
- if (dm.backend === 'claude') {
131
- // Claude Code requires these for non-Anthropic providers
132
- extraEnv.CLAUDE_CODE_ATTRIBUTION_HEADER = '0';
133
- extraEnv.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = '1';
134
- extraEnv.CLAUDE_CODE_DISABLE_SESSION_METADATA = '1';
135
- }
136
- else if (dm.backend === 'pi' && !isFlash) {
137
- // DeepSeek pro with extended thinking via PI (only PI + DeepSeek non-flash)
138
- extraOption['--thinking'] = 'xhigh';
139
- }
140
- result[profileName] = {
141
- model: dm.model,
142
- backend: dm.backend,
143
- mode: dm.mode,
144
- ...(Object.keys(extraEnv).length > 0 ? { extraEnv } : {}),
145
- ...(Object.keys(extraOption).length > 0 ? { extraOption } : {}),
146
- };
147
- }
148
- return result;
149
- }
150
- /** Generate Codex profile if OpenAI models are available. */
151
- function generateCodexProfile(models) {
152
- const openaiModels = models.filter(m => m.endpoint === 'openai');
153
- if (openaiModels.length === 0)
154
- return {};
155
- const best = openaiModels.find(m => m.tier === 'max') || openaiModels[0];
156
- const fallbacks = [];
157
- // Fallback: Anthropic sonnet
158
- const claudeMid = models.find(m => m.endpoint === 'anthropic' && m.tier === 'mid');
159
- if (claudeMid) {
160
- fallbacks.push({ model: claudeMid.model, backend: claudeMid.backend, mode: 'plan' });
161
- }
49
+ /** Build a ProfileEntry from a ModelEntry (no fallback chain attached yet). */
50
+ function makeProfileEntry(m) {
162
51
  return {
163
- codex: {
164
- model: best.model,
165
- backend: 'codex',
166
- mode: 'plan',
167
- fallback: fallbacks.length > 0 ? fallbacks : undefined,
168
- },
52
+ model: m.model,
53
+ backend: m.backend,
54
+ mode: m.mode,
169
55
  };
170
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
+ }
171
66
  // ─── Choice listing (for init UI) ─────────────────────────────────
172
67
  /**
173
68
  * Flatten endpoints to a list of (mode, model) choices the user can pick from.
174
- * 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.
175
70
  */
176
71
  export function listChoices(endpoints) {
177
72
  const flat = flattenModels(endpoints);
178
- // Sort: anthropic+plan/api first (recommended for plan), then others.
179
- // Within each group, max-tier first.
180
- const tierOrder = { max: 0, mid: 1, budget: 2 };
181
- const isAnthropicNative = (m) => m.endpoint === 'anthropic' && (m.mode === 'plan' || m.mode === 'api');
182
73
  flat.sort((a, b) => {
183
- const aN = isAnthropicNative(a) ? 0 : 1;
184
- const bN = isAnthropicNative(b) ? 0 : 1;
185
- if (aN !== bN)
186
- return aN - bN;
187
- 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);
188
76
  });
189
77
  return flat.map(m => ({ mode: m.mode, model: m.model }));
190
78
  }
@@ -192,17 +80,12 @@ export function listChoices(endpoints) {
192
80
  /**
193
81
  * Generate a profiles.json object from discovered endpoints.
194
82
  *
195
- * Naming: outputs unsuffixed `plan` and `execute` (no provider suffix).
196
- *
197
- * Selection rules:
198
- * - plan: explicit `opts.planChoice` if provided, else max-tier Anthropic.
199
- * - execute: explicit `opts.executeChoice` if provided, else prefer non-Claude-Code
200
- * mid-tier (cost), fall back to Anthropic mid-tier, then max.
201
- *
202
- * Provider-specific profiles always layered on top:
203
- * - deepseek-flash / deepseek-pro: if DeepSeek models discovered. `--thinking xhigh`
204
- * only on PI backend non-flash (the only PI + DeepSeek combo that should get it).
205
- * - 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.
206
89
  */
207
90
  export function generateProfiles(endpoints, opts = {}) {
208
91
  const models = flattenModels(endpoints);
@@ -215,32 +98,26 @@ export function generateProfiles(endpoints, opts = {}) {
215
98
  },
216
99
  };
217
100
  }
218
- const profiles = {};
219
- const anthropicModels = models.filter(m => m.endpoint === 'anthropic' && (m.mode === 'plan' || m.mode === 'api'));
220
- // ── plan ──
221
- const planEntry = opts.planChoice
222
- ? findModelEntry(models, opts.planChoice, 'planChoice')
223
- : pickModel(anthropicModels, 'max');
224
- if (planEntry) {
225
- profiles.plan = makeProfileEntry(planEntry, models);
226
- }
227
- // ── execute ──
228
- let executeEntry;
229
- if (opts.executeChoice) {
230
- executeEntry = findModelEntry(models, opts.executeChoice, 'executeChoice');
231
- }
232
- else {
233
- // Prefer mid-tier non-Anthropic-native models for cost savings
234
- const nonClaudeMid = models.find(m => m.tier === 'mid' && !(m.endpoint === 'anthropic' && (m.mode === 'plan' || m.mode === 'api')));
235
- executeEntry = nonClaudeMid || pickModel(anthropicModels, 'mid') || pickModel(anthropicModels, 'max');
236
- }
237
- if (executeEntry) {
238
- profiles.execute = makeProfileEntry(executeEntry, models);
239
- }
240
- // ── Provider-specific profiles ──
241
- Object.assign(profiles, generateDeepSeekProfiles(models));
242
- Object.assign(profiles, generateCodexProfile(models));
243
- 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
+ };
244
121
  }
245
122
  // ─── File I/O ─────────────────────────────────────────────────────
246
123
  /**
@@ -298,6 +175,8 @@ export function writeProfilesJson(endpoints, optsOrOutputDir) {
298
175
  const generated = generateProfiles(endpoints, {
299
176
  planChoice: opts.planChoice,
300
177
  executeChoice: opts.executeChoice,
178
+ planFallback: opts.planFallback,
179
+ executeFallback: opts.executeFallback,
301
180
  });
302
181
  const merged = mergeProfilesJson(generated, opts.outputDir, opts.overwrite ?? false);
303
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
+ }
@@ -7,6 +7,16 @@ export declare function resolveFileRef(field: string, value: string | undefined)
7
7
  /** Resolve a plugin directory path. Absolute paths are returned as-is;
8
8
  * relative paths are resolved against DATA_DIR (plugins live under DATA_DIR/plugins/). */
9
9
  export declare function resolvePluginDir(dir: string): string;
10
+ /**
11
+ * Merge defaults thread-templates.json into the user's config.
12
+ * - Agents/templates not in user config → added from defaults.
13
+ * - Agents/templates already in user config → preserved as-is (never overwritten).
14
+ * - If user config doesn't exist → copy defaults in full.
15
+ * - Malformed user config → replace with defaults.
16
+ *
17
+ * @returns true if the user config file was written, false if no changes were needed.
18
+ */
19
+ export declare function mergeThreadTemplates(defaultsPath: string, userConfigPath: string): boolean;
10
20
  export declare function loadConfig(): {
11
21
  agents: Record<string, AgentDefinition>;
12
22
  templates: Record<string, ThreadTemplate>;
@@ -1,7 +1,7 @@
1
1
  // Thread template config loading and hot-reload.
2
2
  // input: DATA_DIR/thread-templates.json, prompts/ directory
3
3
  // output: loadConfig / startConfigWatcher / stopConfigWatcher / getTemplate / getAgent / listTemplates / listAgents / resolvePluginDir
4
- import { readFileSync, existsSync, watch } from 'fs';
4
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, watch } from 'fs';
5
5
  import * as path from 'path';
6
6
  import { CONFIG_DIR, DATA_DIR, PROMPTS_DIR } from '../../core/utils.js';
7
7
  import { createLogger } from '../../core/log.js';
@@ -66,6 +66,76 @@ export function resolvePluginDir(dir) {
66
66
  return dir;
67
67
  return path.join(DATA_DIR, dir);
68
68
  }
69
+ // --- Config merging (init) ---
70
+ /**
71
+ * Merge defaults thread-templates.json into the user's config.
72
+ * - Agents/templates not in user config → added from defaults.
73
+ * - Agents/templates already in user config → preserved as-is (never overwritten).
74
+ * - If user config doesn't exist → copy defaults in full.
75
+ * - Malformed user config → replace with defaults.
76
+ *
77
+ * @returns true if the user config file was written, false if no changes were needed.
78
+ */
79
+ export function mergeThreadTemplates(defaultsPath, userConfigPath) {
80
+ // 1. Read defaults
81
+ let defaults;
82
+ try {
83
+ const raw = readFileSync(defaultsPath, 'utf8');
84
+ defaults = JSON.parse(raw);
85
+ }
86
+ catch (e) {
87
+ log.warn(`Cannot read default thread-templates.json from ${defaultsPath}: ${e.message}`);
88
+ return false;
89
+ }
90
+ const defaultAgents = defaults.agents || {};
91
+ const defaultTemplates = defaults.templates || {};
92
+ // 2. User config doesn't exist yet — copy defaults as-is
93
+ if (!existsSync(userConfigPath)) {
94
+ const dir = path.dirname(userConfigPath);
95
+ if (!existsSync(dir))
96
+ mkdirSync(dir, { recursive: true });
97
+ writeFileSync(userConfigPath, JSON.stringify(defaults, null, 2) + '\n', 'utf8');
98
+ log.info('thread-templates.json created from defaults');
99
+ return true;
100
+ }
101
+ // 3. Parse existing user config
102
+ let userConfig;
103
+ try {
104
+ const raw = readFileSync(userConfigPath, 'utf8');
105
+ userConfig = JSON.parse(raw);
106
+ }
107
+ catch (e) {
108
+ log.warn(`Failed to parse existing thread-templates.json (${e.message}), falling back to defaults`);
109
+ writeFileSync(userConfigPath, JSON.stringify(defaults, null, 2) + '\n', 'utf8');
110
+ return true;
111
+ }
112
+ const userAgents = { ...(userConfig.agents || {}) };
113
+ const userTemplates = { ...(userConfig.templates || {}) };
114
+ let changed = false;
115
+ // 4. Add new agents from defaults that don't exist in user config
116
+ for (const [name, agent] of Object.entries(defaultAgents)) {
117
+ if (!userAgents[name]) {
118
+ userAgents[name] = agent;
119
+ log.info(`Added new agent to thread-templates.json: ${name}`);
120
+ changed = true;
121
+ }
122
+ }
123
+ // 5. Add new templates from defaults that don't exist in user config
124
+ for (const [name, template] of Object.entries(defaultTemplates)) {
125
+ if (!userTemplates[name]) {
126
+ userTemplates[name] = template;
127
+ log.info(`Added new template to thread-templates.json: ${name}`);
128
+ changed = true;
129
+ }
130
+ }
131
+ // 6. Only write if something changed
132
+ if (changed) {
133
+ const merged = { agents: userAgents, templates: userTemplates };
134
+ writeFileSync(userConfigPath, JSON.stringify(merged, null, 2) + '\n', 'utf8');
135
+ log.info('thread-templates.json merged with defaults');
136
+ }
137
+ return changed;
138
+ }
69
139
  // --- Config loading ---
70
140
  export function loadConfig() {
71
141
  try {