@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
@@ -1,6 +1,8 @@
1
- // input: fs, path, os, Claude credentials.json, PI models.json / auth.json
2
- // output: generateGatewayYaml() — scans Claude/PI local config, produces gateway.yaml content
3
- // pos: init-time gateway config auto-generation
1
+ // input: fs, path, os, Claude credentials.json, `pi --list-models` output
2
+ // output: discoverEndpoints / generateGatewayYaml / writeGatewayYaml / parsePiListModelsOutput
3
+ // — scans Claude OAuth + spawns pi --list-models, produces gateway.yaml content
4
+ // pos: init-time gateway config auto-generation. PI model metadata is owned by the PI agent
5
+ // (we shell out to `pi --list-models` rather than maintain provider/model whitelists).
4
6
  import { readFileSync, writeFileSync, copyFileSync, mkdirSync, existsSync } from 'fs';
5
7
  import { execSync } from 'child_process';
6
8
  import * as path from 'path';
@@ -9,43 +11,54 @@ import { createLogger } from './log.js';
9
11
  const log = createLogger('gateway-generator');
10
12
  // ─── Paths ─────────────────────────────────────────────────────────
11
13
  const CLAUDE_CREDENTIALS = path.join(os.homedir(), '.claude', '.credentials.json');
12
- const PI_MODELS = path.join(os.homedir(), '.pi', 'agent', 'models.json');
13
- const PI_AUTH = path.join(os.homedir(), '.pi', 'agent', 'auth.json');
14
- const PI_SETTINGS = path.join(os.homedir(), '.pi', 'agent', 'settings.json');
15
- // ─── Anthropic model tiers (by subscription type) ─────────────────
14
+ // ─── Anthropic Claude Code tier table (only used for Claude OAuth path) ─────
16
15
  /** Model names used in gateway model_fallbacks (API-level model IDs). */
17
16
  const ANTHROPIC_MODEL_TIERS = {
18
17
  max: ['claude-opus-4-7', 'claude-sonnet-4-6', 'claude-haiku-4-5'],
19
- pro: ['claude-sonnet-4-6', 'claude-haiku-4-5'],
18
+ pro: ['claude-opus-4-7', 'claude-sonnet-4-6', 'claude-haiku-4-5'],
20
19
  free: ['claude-haiku-4-5'],
21
20
  };
22
- /** Generate model_fallbacks: each model falls back to all lower-tier models. */
23
- function buildModelFallbacks(models) {
24
- const result = {};
25
- for (let i = 0; i < models.length; i++) {
26
- const fallbacks = models.slice(i + 1);
27
- if (fallbacks.length > 0) {
28
- result[models[i]] = fallbacks;
29
- }
30
- }
31
- return result;
32
- }
33
- const KNOWN_PROVIDERS = {
34
- deepseek: {
35
- base_url: 'https://api.deepseek.com/anthropic',
36
- auth_style: 'anthropic',
37
- models: ['deepseek-v4-pro', 'deepseek-v4-flash'],
38
- },
39
- openai: {
40
- base_url: 'https://api.openai.com',
41
- auth_style: 'openai',
42
- models: ['gpt-5.4', 'gpt-5.4-mini'],
43
- },
44
- google: {
45
- base_url: 'https://generativelanguage.googleapis.com',
46
- auth_style: 'google',
47
- models: ['gemini-2.5-pro', 'gemini-2.5-flash'],
48
- },
21
+ // ─── PI provider → upstream URL lookup (manually maintained) ────────────────
22
+ /**
23
+ * Map a PI built-in provider name to its real upstream URL. Used by `generateGatewayYaml` so PI
24
+ * traffic can be routed through the gateway. Entries are sourced from PI source / docs.
25
+ *
26
+ * Providers absent from this table are still surfaced as cortex profiles, but no gateway endpoint
27
+ * is generated for them (gatewayManaged=false). PI will then either fail (if the cortex spawn path
28
+ * forces gateway routing) or direct-call the upstream (if the spawn path leaves models.json
29
+ * untouched for that provider). See `/home/fangxin/.cortex/plan/generic-wibbling-pine.md` stage E
30
+ * for the eventual full plumbing.
31
+ */
32
+ const PI_PROVIDER_UPSTREAM = {
33
+ // Anthropic-protocol providers (PI's `api: anthropic-messages`)
34
+ anthropic: { url: 'https://api.anthropic.com', auth_style: 'bearer' },
35
+ fireworks: { url: 'https://api.fireworks.ai/inference', auth_style: 'bearer' },
36
+ 'github-copilot': { url: 'https://api.individual.githubcopilot.com', auth_style: 'bearer' },
37
+ 'kimi-coding': { url: 'https://api.kimi.com/coding', auth_style: 'bearer' },
38
+ minimax: { url: 'https://api.minimax.io/anthropic', auth_style: 'bearer' },
39
+ 'minimax-cn': { url: 'https://api.minimaxi.com/anthropic', auth_style: 'bearer' },
40
+ opencode: { url: 'https://opencode.ai/zen', auth_style: 'bearer' },
41
+ 'vercel-ai-gateway': { url: 'https://ai-gateway.vercel.sh', auth_style: 'bearer' },
42
+ // OpenAI-completions / OpenAI-responses providers
43
+ cerebras: { url: 'https://api.cerebras.ai/v1', auth_style: 'bearer' },
44
+ deepseek: { url: 'https://api.deepseek.com', auth_style: 'bearer' },
45
+ groq: { url: 'https://api.groq.com/openai/v1', auth_style: 'bearer' },
46
+ huggingface: { url: 'https://router.huggingface.co/v1', auth_style: 'bearer' },
47
+ mistral: { url: 'https://api.mistral.ai', auth_style: 'bearer' },
48
+ openai: { url: 'https://api.openai.com/v1', auth_style: 'bearer' },
49
+ 'opencode-go': { url: 'https://opencode.ai/zen/go/v1', auth_style: 'bearer' },
50
+ openrouter: { url: 'https://openrouter.ai/api/v1', auth_style: 'bearer' },
51
+ xai: { url: 'https://api.x.ai/v1', auth_style: 'bearer' },
52
+ zai: { url: 'https://api.z.ai/api/coding/paas/v4', auth_style: 'bearer' },
53
+ // OAuth subscription providers (PI manages OAuth refresh; gateway transparently passthrough)
54
+ 'openai-codex': { url: 'https://chatgpt.com/backend-api', auth_style: 'bearer' },
55
+ 'google-gemini-cli': { url: 'https://cloudcode-pa.googleapis.com', auth_style: 'bearer' },
56
+ 'google-antigravity': { url: 'https://daily-cloudcode-pa.sandbox.googleapis.com', auth_style: 'bearer' },
57
+ // Other built-ins
58
+ google: { url: 'https://generativelanguage.googleapis.com/v1beta', auth_style: 'bearer' },
59
+ // amazon-bedrock / google-vertex / azure-openai-responses / cloudflare-workers-ai use
60
+ // env-driven URLs (region / account ID / resource name) — not safely templated here.
61
+ // Users wanting these through the gateway must edit gateway.yaml manually.
49
62
  };
50
63
  /** Try to read Claude Code credentials from macOS Keychain.
51
64
  * On macOS, Claude Code stores OAuth tokens in Keychain (service "Claude Code-credentials"),
@@ -91,91 +104,73 @@ function scanClaudeCode() {
91
104
  return null;
92
105
  }
93
106
  }
94
- /** Read and parse PI models.json + auth.json. Returns discovered providers. */
95
- function scanPI() {
96
- const providers = [];
97
- // Parse models.json for configured providers
98
- let modelsConfig = {};
99
- try {
100
- if (existsSync(PI_MODELS)) {
101
- modelsConfig = JSON.parse(readFileSync(PI_MODELS, 'utf-8'));
102
- }
103
- }
104
- catch (e) {
105
- log.warn(`Failed to read PI models.json: ${e.message}`);
106
- }
107
- // Parse auth.json for API keys
108
- let authConfig = {};
109
- try {
110
- if (existsSync(PI_AUTH)) {
111
- const raw = JSON.parse(readFileSync(PI_AUTH, 'utf-8'));
112
- for (const [name, entry] of Object.entries(raw)) {
113
- const e = entry;
114
- if (e?.key) {
115
- authConfig[name] = { name, key: e.key };
116
- }
117
- }
118
- }
119
- }
120
- catch (e) {
121
- log.warn(`Failed to read PI auth.json: ${e.message}`);
122
- }
123
- // Merge models.json providers
124
- const modelsProviders = modelsConfig?.providers || {};
125
- for (const [name, p] of Object.entries(modelsProviders)) {
126
- const prov = p;
127
- const models = (prov.models || []).map((m) => m.id || m);
128
- providers.push({
129
- name,
130
- baseUrl: prov.baseUrl || '',
131
- apiKey: prov.apiKey || authConfig[name]?.key || '',
132
- api: prov.api || 'anthropic-messages',
133
- models,
134
- });
135
- }
136
- // Add providers from auth.json that aren't in models.json yet
137
- for (const [name, auth] of Object.entries(authConfig)) {
138
- if (providers.some(p => p.name === name))
107
+ /**
108
+ * Parse the table output of `pi --list-models` into structured entries.
109
+ * Skips header row, blank lines, and the "No models available" fallback message.
110
+ *
111
+ * Example input:
112
+ * provider model context max-out thinking images
113
+ * anthropic claude-3-5-haiku-20241022 200K 8.2K no yes
114
+ * deepseek deepseek-v4-pro 1M 384K yes no
115
+ */
116
+ export function parsePiListModelsOutput(stdout) {
117
+ const lines = stdout.split('\n');
118
+ const result = [];
119
+ for (const raw of lines) {
120
+ const line = raw.trim();
121
+ if (!line)
139
122
  continue;
140
- const known = KNOWN_PROVIDERS[name];
141
- if (!known) {
142
- log.info(`PI auth key found for unknown provider "${name}" — skipping`);
123
+ if (line.startsWith('No models available'))
124
+ return [];
125
+ // PI uses 2+ spaces between columns for alignment
126
+ const parts = line.split(/\s{2,}/);
127
+ if (parts.length < 2)
143
128
  continue;
144
- }
145
- providers.push({
146
- name,
147
- baseUrl: known.base_url,
148
- apiKey: auth.key,
149
- api: known.auth_style === 'anthropic' ? 'anthropic-messages' : known.auth_style,
150
- models: known.models,
151
- });
129
+ const [provider, model] = parts;
130
+ if (provider === 'provider' && model === 'model')
131
+ continue; // header row
132
+ result.push({ provider, model });
152
133
  }
153
- return providers;
134
+ return result;
154
135
  }
155
- // ─── Discovery ─────────────────────────────────────────────────────
156
136
  /**
157
- * Determine the auth_style and api type from PI provider config.
158
- * PI's `api` field: "anthropic-messages" → auth_style "anthropic", "openai" → "openai"
137
+ * Discover PI providers and models by shelling out to `pi --list-models`.
138
+ * PI is the authoritative source of model metadata — cortex does not maintain a whitelist.
139
+ *
140
+ * Returns an empty array on any failure (PI not installed, timeout, parse error). The init flow
141
+ * should warn the user and tell them to `pi /login` first.
159
142
  */
160
- function piApiToAuthStyle(api) {
161
- switch (api) {
162
- case 'anthropic-messages': return { auth_style: 'anthropic', endpoint: 'anthropic' };
163
- case 'openai': return { auth_style: 'openai', endpoint: 'openai' };
164
- default: return { auth_style: 'bearer', endpoint: api };
143
+ function scanPIViaListModels() {
144
+ try {
145
+ // PI writes the table to stderr (not stdout) — merge via `2>&1` so we can parse it.
146
+ // Intentionally do NOT set PI_CODING_AGENT_DIR: discovery reads the user's real ~/.pi/agent/.
147
+ const stdout = execSync('pi --list-models 2>&1', {
148
+ timeout: 10_000,
149
+ encoding: 'utf-8',
150
+ });
151
+ return parsePiListModelsOutput(stdout);
152
+ }
153
+ catch (e) {
154
+ const err = e;
155
+ if (err.code === 'ENOENT') {
156
+ log.info('PI is not installed — skipping PI provider discovery');
157
+ }
158
+ else {
159
+ log.info(`pi --list-models failed (code=${err.code ?? err.status}): ${err.message ?? 'unknown error'}`);
160
+ }
161
+ return [];
165
162
  }
166
163
  }
167
- /** Check if a URL is a gateway URL (localhost:9880 or 127.0.0.1:9880). */
168
- function isGatewayUrl(url) {
169
- return url.includes('127.0.0.1:9880') || url.includes('localhost:9880');
170
- }
164
+ // ─── Discovery ─────────────────────────────────────────────────────
171
165
  /**
172
166
  * Scan Claude Code and PI configurations and return discovered endpoints.
173
167
  *
174
- * Rules:
175
- * - Claude Code plan mode: always generated (OAuth bearer passthrough, no managed keys).
176
- * - Claude Code api mode: generated only if ANTHROPIC_API_KEY env var is set (referenced via $ANTHROPIC_API_KEY).
177
- * - PI providers from auth.json: use known provider defaults.
178
- * - PI providers from models.json: skip if base URL is already a gateway URL (already configured).
168
+ * - Claude Code plan mode: always generated if logged in (OAuth bearer passthrough).
169
+ * - Claude Code api mode: generated only if ANTHROPIC_API_KEY env var is set.
170
+ * - PI providers: discovered via `pi --list-models`. Each provider becomes one endpoint with
171
+ * `mode = endpoint = provider name`. `gatewayManaged` is true only if the provider has a known
172
+ * upstream URL in PI_PROVIDER_UPSTREAM (otherwise profile is generated but gateway.yaml entry
173
+ * is skipped).
179
174
  */
180
175
  export function discoverEndpoints() {
181
176
  const endpoints = [];
@@ -183,7 +178,7 @@ export function discoverEndpoints() {
183
178
  const claude = scanClaudeCode();
184
179
  if (claude) {
185
180
  const models = ANTHROPIC_MODEL_TIERS[claude.subscriptionType || 'free'] || ANTHROPIC_MODEL_TIERS.free;
186
- // plan mode — OAuth bearer passthrough (no managed keys needed)
181
+ // plan mode — OAuth bearer passthrough
187
182
  endpoints.push({
188
183
  mode: 'plan',
189
184
  endpoint: 'anthropic',
@@ -192,9 +187,9 @@ export function discoverEndpoints() {
192
187
  keys: [],
193
188
  passthrough: true,
194
189
  models,
195
- modelFallbacks: {},
190
+ gatewayManaged: true,
196
191
  });
197
- // api mode — only if ANTHROPIC_API_KEY is set (referenced via env var, not raw token)
192
+ // api mode — only if ANTHROPIC_API_KEY is set
198
193
  if (process.env.ANTHROPIC_API_KEY) {
199
194
  endpoints.push({
200
195
  mode: 'api',
@@ -204,36 +199,34 @@ export function discoverEndpoints() {
204
199
  keys: ['$ANTHROPIC_API_KEY'],
205
200
  passthrough: true,
206
201
  models,
207
- modelFallbacks: buildModelFallbacks(models),
202
+ gatewayManaged: true,
208
203
  });
209
204
  }
210
205
  }
211
- // ── PI → per-provider endpoints ──
212
- const piProviders = scanPI();
213
- for (const prov of piProviders) {
214
- // Skip providers whose base URL is already a gateway URL (already configured)
215
- if (isGatewayUrl(prov.baseUrl)) {
216
- log.info(`PI provider "${prov.name}" already routes through gateway — skipping`);
206
+ // ── PI → per-provider endpoints (one mode per provider) ──
207
+ const piModels = scanPIViaListModels();
208
+ // Group models by provider name
209
+ const byProvider = new Map();
210
+ for (const { provider, model } of piModels) {
211
+ if (!byProvider.has(provider))
212
+ byProvider.set(provider, []);
213
+ byProvider.get(provider).push(model);
214
+ }
215
+ for (const [provider, models] of byProvider) {
216
+ const upstream = PI_PROVIDER_UPSTREAM[provider];
217
+ // anthropic is already covered by the Claude Code path above (with the user's OAuth subscription
218
+ // tier). If PI also reports anthropic, skip — Claude path is authoritative for plan mode.
219
+ if (provider === 'anthropic')
217
220
  continue;
218
- }
219
- const { auth_style, endpoint } = piApiToAuthStyle(prov.api);
220
- const modeName = prov.name.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
221
- // Use env var reference for keys when possible, fall back to raw key from PI auth
222
- let keys = [];
223
- if (prov.apiKey) {
224
- // Check if this key matches a known env var to use reference
225
- const envRef = findEnvVarRef(prov.name, prov.apiKey);
226
- keys = envRef ? [envRef] : [prov.apiKey];
227
- }
228
221
  endpoints.push({
229
- mode: modeName,
230
- endpoint,
231
- base_url: prov.baseUrl,
232
- auth_style,
233
- keys,
234
- passthrough: false,
235
- models: prov.models,
236
- modelFallbacks: {},
222
+ mode: provider,
223
+ endpoint: provider,
224
+ base_url: upstream?.url ?? '',
225
+ auth_style: upstream?.auth_style ?? 'bearer',
226
+ keys: [],
227
+ passthrough: true,
228
+ models,
229
+ gatewayManaged: !!upstream,
237
230
  });
238
231
  }
239
232
  return endpoints;
@@ -241,29 +234,19 @@ export function discoverEndpoints() {
241
234
  function capitalize(s) {
242
235
  return s.charAt(0).toUpperCase() + s.slice(1);
243
236
  }
244
- /** Try to match a raw API key to a known environment variable. */
245
- function findEnvVarRef(providerName, apiKey) {
246
- const envMap = {
247
- deepseek: 'DEEPSEEK_API_KEY',
248
- openai: 'OPENAI_API_KEY',
249
- google: 'GEMINI_API_KEY',
250
- openrouter: 'OPENROUTER_API_KEY',
251
- anthropic: 'ANTHROPIC_API_KEY',
252
- };
253
- const envVar = envMap[providerName];
254
- if (envVar && process.env[envVar] && process.env[envVar] === apiKey) {
255
- return `$${envVar}`;
256
- }
257
- return null;
258
- }
237
+ // ─── YAML Generation ───────────────────────────────────────────────
259
238
  /**
260
239
  * Generate gateway.yaml content from discovered endpoints.
261
240
  * Outputs a formatted YAML string with comments explaining each mode.
241
+ *
242
+ * Endpoints with gatewayManaged=false are skipped (their profile still exists in profiles.json,
243
+ * but gateway.yaml has no entry for them — PI traffic to those providers is currently direct).
262
244
  */
263
245
  export function generateGatewayYaml(endpoints, defaultMode) {
264
- // Group endpoints by endpoint name (e.g., "anthropic", "openai")
246
+ const renderable = endpoints.filter(e => e.gatewayManaged !== false);
247
+ // Group renderable endpoints by endpoint name (e.g., "anthropic", "deepseek")
265
248
  const byEndpoint = {};
266
- for (const ep of endpoints) {
249
+ for (const ep of renderable) {
267
250
  (byEndpoint[ep.endpoint] ||= []).push(ep);
268
251
  }
269
252
  const lines = [];
@@ -276,12 +259,12 @@ export function generateGatewayYaml(endpoints, defaultMode) {
276
259
  lines.push('#');
277
260
  lines.push('# Docs: https://aistatus.cc/docs');
278
261
  lines.push('');
279
- // Determine default mode
280
- const activeMode = defaultMode || endpoints[0]?.mode || 'api';
281
- // Collect all modes for the comment
282
- const allModes = endpoints.map(e => e.mode).filter((v, i, a) => a.indexOf(v) === i);
262
+ // Determine default mode (first renderable endpoint, falling back to all endpoints)
263
+ const activeMode = defaultMode || renderable[0]?.mode || endpoints[0]?.mode || 'api';
264
+ // Collect all renderable modes for the comment
265
+ const allModes = renderable.map(e => e.mode).filter((v, i, a) => a.indexOf(v) === i);
283
266
  lines.push(`port: 9880`);
284
- lines.push(`mode: ${activeMode} # active billing mode: ${allModes.join(' | ')}`);
267
+ lines.push(`mode: ${activeMode}${allModes.length > 0 ? ` # active billing mode: ${allModes.join(' | ')}` : ''}`);
285
268
  lines.push(`status_check: true`);
286
269
  for (const [epName, eps] of Object.entries(byEndpoint)) {
287
270
  lines.push('');
@@ -290,7 +273,7 @@ export function generateGatewayYaml(endpoints, defaultMode) {
290
273
  // Determine provider label for the comment
291
274
  const providerLabel = ep.mode === 'plan' ? 'Anthropic Claude (OAuth passthrough, billed via subscription)' :
292
275
  ep.mode === 'api' ? 'Anthropic Claude (API key, billed via API credits)' :
293
- `${capitalize(ep.mode)} (${ep.endpoint}-compatible API)`;
276
+ `${capitalize(ep.mode)} (PI-managed auth, routed through gateway)`;
294
277
  lines.push(` # ── ${providerLabel} ──`);
295
278
  lines.push(` ${ep.mode}:`);
296
279
  lines.push(` base_url: ${ep.base_url}`);
@@ -301,23 +284,24 @@ export function generateGatewayYaml(endpoints, defaultMode) {
301
284
  lines.push(` - ${key}`);
302
285
  }
303
286
  }
304
- if (ep.keys.length === 0) {
287
+ else {
305
288
  lines.push(` # No managed keys — ${ep.passthrough ? 'caller key passthrough' : 'waiting for key configuration'}`);
306
289
  }
307
290
  if (ep.passthrough && ep.keys.length > 0) {
308
291
  lines.push(` passthrough: true`);
309
292
  }
310
- if (Object.keys(ep.modelFallbacks).length > 0) {
311
- lines.push(` model_fallbacks:`);
312
- for (const [model, fallbacks] of Object.entries(ep.modelFallbacks)) {
313
- lines.push(` ${model}:`);
314
- for (const fb of fallbacks) {
315
- lines.push(` - ${fb}`);
316
- }
317
- }
318
- }
319
293
  }
320
294
  }
295
+ // Footer: list any PI providers we discovered but couldn't route (gatewayManaged=false)
296
+ const skipped = endpoints.filter(e => e.gatewayManaged === false);
297
+ if (skipped.length > 0) {
298
+ lines.push('');
299
+ lines.push('# Skipped (no known upstream URL in PI_PROVIDER_UPSTREAM):');
300
+ for (const s of skipped) {
301
+ lines.push(`# ${s.mode} (${s.models.length} model${s.models.length === 1 ? '' : 's'})`);
302
+ }
303
+ lines.push('# These providers appear in profiles.json but are not routed through this gateway.');
304
+ }
321
305
  lines.push('');
322
306
  return lines.join('\n');
323
307
  }
@@ -4,8 +4,8 @@
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import fs from 'node:fs/promises';
6
6
  import path from 'node:path';
7
- import { createLogger } from '../core/log.js';
8
- import { AsyncMutex } from '../core/async-mutex.js';
7
+ import { createLogger } from './log.js';
8
+ import { AsyncMutex } from './async-mutex.js';
9
9
  import { atomicWrite } from './atomic-write.js';
10
10
  const log = createLogger('json-repository');
11
11
  export class JsonRepository {
@@ -11,36 +11,35 @@ interface ProfilesFile {
11
11
  defaultProfile: string;
12
12
  profiles: Record<string, ProfileEntry>;
13
13
  }
14
- /** A (mode, model) pair the user can pick as the source for plan/execute. */
14
+ /** A (mode, model) pair the user can pick as the source for plan/execute or fallback. */
15
15
  export interface ModelChoice {
16
16
  mode: string;
17
17
  model: string;
18
18
  }
19
19
  export interface GenerateOpts {
20
- /** Explicit (mode, model) to use as the `plan` profile. Otherwise auto-inferred from anthropic max-tier. */
20
+ /** Explicit (mode, model) to use as the `plan` profile. Otherwise the first lexicographic choice. */
21
21
  planChoice?: ModelChoice;
22
- /** Explicit (mode, model) to use as the `execute` profile. Otherwise auto-inferred (non-Claude-Code mid-tier preferred). */
22
+ /** Explicit (mode, model) to use as the `execute` profile. Same default rule as planChoice. */
23
23
  executeChoice?: ModelChoice;
24
+ /** Ordered fallback chain for the `plan` profile. */
25
+ planFallback?: ModelChoice[];
26
+ /** Ordered fallback chain for the `execute` profile. */
27
+ executeFallback?: ModelChoice[];
24
28
  }
25
29
  /**
26
30
  * Flatten endpoints to a list of (mode, model) choices the user can pick from.
27
- * Ordered so Anthropic plan/api modes come first (recommended for `plan` profile).
31
+ * Strictly sorted by (mode ASC, model ASC) — no tier or provider preference.
28
32
  */
29
33
  export declare function listChoices(endpoints: DiscoveredEndpoint[]): ModelChoice[];
30
34
  /**
31
35
  * Generate a profiles.json object from discovered endpoints.
32
36
  *
33
- * Naming: outputs unsuffixed `plan` and `execute` (no provider suffix).
34
- *
35
- * Selection rules:
36
- * - plan: explicit `opts.planChoice` if provided, else max-tier Anthropic.
37
- * - execute: explicit `opts.executeChoice` if provided, else prefer non-Claude-Code
38
- * mid-tier (cost), fall back to Anthropic mid-tier, then max.
39
- *
40
- * Provider-specific profiles always layered on top:
41
- * - deepseek-flash / deepseek-pro: if DeepSeek models discovered. `--thinking xhigh`
42
- * only on PI backend non-flash (the only PI + DeepSeek combo that should get it).
43
- * - codex: if OpenAI models discovered.
37
+ * Generates exactly two profiles: `plan` and `execute`.
38
+ * - If `planChoice` is omitted, picks the first lexicographic (mode, model) tuple.
39
+ * - Same default rule for `execute`.
40
+ * - Fallback chains are taken verbatim from `planFallback` / `executeFallback` (no auto-derivation).
41
+ * - No tier classification, no auto-generated deepseek-pro / codex / etc. — users explicitly choose
42
+ * what they want via cortex init's interactive UI.
44
43
  */
45
44
  export declare function generateProfiles(endpoints: DiscoveredEndpoint[], opts?: GenerateOpts): ProfilesFile;
46
45
  /**