@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,59 +1,94 @@
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';
7
+ import { execSync } from 'child_process';
5
8
  import * as path from 'path';
6
9
  import * as os from 'os';
7
10
  import { createLogger } from './log.js';
8
11
  const log = createLogger('gateway-generator');
9
12
  // ─── Paths ─────────────────────────────────────────────────────────
10
13
  const CLAUDE_CREDENTIALS = path.join(os.homedir(), '.claude', '.credentials.json');
11
- const PI_MODELS = path.join(os.homedir(), '.pi', 'agent', 'models.json');
12
- const PI_AUTH = path.join(os.homedir(), '.pi', 'agent', 'auth.json');
13
- const PI_SETTINGS = path.join(os.homedir(), '.pi', 'agent', 'settings.json');
14
- // ─── Anthropic model tiers (by subscription type) ─────────────────
14
+ // ─── Anthropic Claude Code tier table (only used for Claude OAuth path) ─────
15
15
  /** Model names used in gateway model_fallbacks (API-level model IDs). */
16
16
  const ANTHROPIC_MODEL_TIERS = {
17
17
  max: ['claude-opus-4-7', 'claude-sonnet-4-6', 'claude-haiku-4-5'],
18
- pro: ['claude-sonnet-4-6', 'claude-haiku-4-5'],
18
+ pro: ['claude-opus-4-7', 'claude-sonnet-4-6', 'claude-haiku-4-5'],
19
19
  free: ['claude-haiku-4-5'],
20
20
  };
21
- /** Generate model_fallbacks: each model falls back to all lower-tier models. */
22
- function buildModelFallbacks(models) {
23
- const result = {};
24
- for (let i = 0; i < models.length; i++) {
25
- const fallbacks = models.slice(i + 1);
26
- if (fallbacks.length > 0) {
27
- result[models[i]] = fallbacks;
28
- }
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.
62
+ };
63
+ /** Try to read Claude Code credentials from macOS Keychain.
64
+ * On macOS, Claude Code stores OAuth tokens in Keychain (service "Claude Code-credentials"),
65
+ * not in ~/.claude/.credentials.json. Falls back gracefully on timeout/error. */
66
+ function readClaudeCredentialsDarwin() {
67
+ try {
68
+ const raw = execSync('security find-generic-password -s "Claude Code-credentials" -w', { timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
69
+ if (!raw)
70
+ return null;
71
+ return JSON.parse(raw);
72
+ }
73
+ catch {
74
+ return null; // Keychain locked, entry missing, or security not available
29
75
  }
30
- return result;
31
76
  }
32
- const KNOWN_PROVIDERS = {
33
- deepseek: {
34
- base_url: 'https://api.deepseek.com/anthropic',
35
- auth_style: 'anthropic',
36
- models: ['deepseek-v4-pro', 'deepseek-v4-flash'],
37
- },
38
- openai: {
39
- base_url: 'https://api.openai.com',
40
- auth_style: 'openai',
41
- models: ['gpt-5.4', 'gpt-5.4-mini'],
42
- },
43
- google: {
44
- base_url: 'https://generativelanguage.googleapis.com',
45
- auth_style: 'google',
46
- models: ['gemini-2.5-pro', 'gemini-2.5-flash'],
47
- },
48
- };
49
77
  /** Read and parse Claude Code credentials. Returns null if not logged in. */
50
78
  function scanClaudeCode() {
51
79
  try {
52
- if (!existsSync(CLAUDE_CREDENTIALS)) {
53
- log.info('Claude Code credentials not found — user may not be logged in');
54
- return null;
80
+ // macOS: try Keychain first, fall back to JSON file
81
+ let raw = null;
82
+ if (process.platform === 'darwin') {
83
+ raw = readClaudeCredentialsDarwin();
84
+ }
85
+ if (!raw) {
86
+ if (!existsSync(CLAUDE_CREDENTIALS)) {
87
+ log.info('Claude Code credentials not found — user may not be logged in');
88
+ return null;
89
+ }
90
+ raw = JSON.parse(readFileSync(CLAUDE_CREDENTIALS, 'utf-8'));
55
91
  }
56
- const raw = JSON.parse(readFileSync(CLAUDE_CREDENTIALS, 'utf-8'));
57
92
  const oauth = raw?.claudeAiOauth;
58
93
  if (!oauth?.accessToken) {
59
94
  log.info('Claude Code credentials exist but no OAuth token found');
@@ -69,91 +104,73 @@ function scanClaudeCode() {
69
104
  return null;
70
105
  }
71
106
  }
72
- /** Read and parse PI models.json + auth.json. Returns discovered providers. */
73
- function scanPI() {
74
- const providers = [];
75
- // Parse models.json for configured providers
76
- let modelsConfig = {};
77
- try {
78
- if (existsSync(PI_MODELS)) {
79
- modelsConfig = JSON.parse(readFileSync(PI_MODELS, 'utf-8'));
80
- }
81
- }
82
- catch (e) {
83
- log.warn(`Failed to read PI models.json: ${e.message}`);
84
- }
85
- // Parse auth.json for API keys
86
- let authConfig = {};
87
- try {
88
- if (existsSync(PI_AUTH)) {
89
- const raw = JSON.parse(readFileSync(PI_AUTH, 'utf-8'));
90
- for (const [name, entry] of Object.entries(raw)) {
91
- const e = entry;
92
- if (e?.key) {
93
- authConfig[name] = { name, key: e.key };
94
- }
95
- }
96
- }
97
- }
98
- catch (e) {
99
- log.warn(`Failed to read PI auth.json: ${e.message}`);
100
- }
101
- // Merge models.json providers
102
- const modelsProviders = modelsConfig?.providers || {};
103
- for (const [name, p] of Object.entries(modelsProviders)) {
104
- const prov = p;
105
- const models = (prov.models || []).map((m) => m.id || m);
106
- providers.push({
107
- name,
108
- baseUrl: prov.baseUrl || '',
109
- apiKey: prov.apiKey || authConfig[name]?.key || '',
110
- api: prov.api || 'anthropic-messages',
111
- models,
112
- });
113
- }
114
- // Add providers from auth.json that aren't in models.json yet
115
- for (const [name, auth] of Object.entries(authConfig)) {
116
- 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)
117
122
  continue;
118
- const known = KNOWN_PROVIDERS[name];
119
- if (!known) {
120
- 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)
121
128
  continue;
122
- }
123
- providers.push({
124
- name,
125
- baseUrl: known.base_url,
126
- apiKey: auth.key,
127
- api: known.auth_style === 'anthropic' ? 'anthropic-messages' : known.auth_style,
128
- models: known.models,
129
- });
129
+ const [provider, model] = parts;
130
+ if (provider === 'provider' && model === 'model')
131
+ continue; // header row
132
+ result.push({ provider, model });
130
133
  }
131
- return providers;
134
+ return result;
132
135
  }
133
- // ─── Discovery ─────────────────────────────────────────────────────
134
136
  /**
135
- * Determine the auth_style and api type from PI provider config.
136
- * 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.
137
142
  */
138
- function piApiToAuthStyle(api) {
139
- switch (api) {
140
- case 'anthropic-messages': return { auth_style: 'anthropic', endpoint: 'anthropic' };
141
- case 'openai': return { auth_style: 'openai', endpoint: 'openai' };
142
- 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 [];
143
162
  }
144
163
  }
145
- /** Check if a URL is a gateway URL (localhost:9880 or 127.0.0.1:9880). */
146
- function isGatewayUrl(url) {
147
- return url.includes('127.0.0.1:9880') || url.includes('localhost:9880');
148
- }
164
+ // ─── Discovery ─────────────────────────────────────────────────────
149
165
  /**
150
166
  * Scan Claude Code and PI configurations and return discovered endpoints.
151
167
  *
152
- * Rules:
153
- * - Claude Code plan mode: always generated (OAuth bearer passthrough, no managed keys).
154
- * - Claude Code api mode: generated only if ANTHROPIC_API_KEY env var is set (referenced via $ANTHROPIC_API_KEY).
155
- * - PI providers from auth.json: use known provider defaults.
156
- * - 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).
157
174
  */
158
175
  export function discoverEndpoints() {
159
176
  const endpoints = [];
@@ -161,7 +178,7 @@ export function discoverEndpoints() {
161
178
  const claude = scanClaudeCode();
162
179
  if (claude) {
163
180
  const models = ANTHROPIC_MODEL_TIERS[claude.subscriptionType || 'free'] || ANTHROPIC_MODEL_TIERS.free;
164
- // plan mode — OAuth bearer passthrough (no managed keys needed)
181
+ // plan mode — OAuth bearer passthrough
165
182
  endpoints.push({
166
183
  mode: 'plan',
167
184
  endpoint: 'anthropic',
@@ -170,9 +187,9 @@ export function discoverEndpoints() {
170
187
  keys: [],
171
188
  passthrough: true,
172
189
  models,
173
- modelFallbacks: {},
190
+ gatewayManaged: true,
174
191
  });
175
- // 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
176
193
  if (process.env.ANTHROPIC_API_KEY) {
177
194
  endpoints.push({
178
195
  mode: 'api',
@@ -182,36 +199,34 @@ export function discoverEndpoints() {
182
199
  keys: ['$ANTHROPIC_API_KEY'],
183
200
  passthrough: true,
184
201
  models,
185
- modelFallbacks: buildModelFallbacks(models),
202
+ gatewayManaged: true,
186
203
  });
187
204
  }
188
205
  }
189
- // ── PI → per-provider endpoints ──
190
- const piProviders = scanPI();
191
- for (const prov of piProviders) {
192
- // Skip providers whose base URL is already a gateway URL (already configured)
193
- if (isGatewayUrl(prov.baseUrl)) {
194
- 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')
195
220
  continue;
196
- }
197
- const { auth_style, endpoint } = piApiToAuthStyle(prov.api);
198
- const modeName = prov.name.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
199
- // Use env var reference for keys when possible, fall back to raw key from PI auth
200
- let keys = [];
201
- if (prov.apiKey) {
202
- // Check if this key matches a known env var to use reference
203
- const envRef = findEnvVarRef(prov.name, prov.apiKey);
204
- keys = envRef ? [envRef] : [prov.apiKey];
205
- }
206
221
  endpoints.push({
207
- mode: modeName,
208
- endpoint,
209
- base_url: prov.baseUrl,
210
- auth_style,
211
- keys,
212
- passthrough: false,
213
- models: prov.models,
214
- 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,
215
230
  });
216
231
  }
217
232
  return endpoints;
@@ -219,29 +234,19 @@ export function discoverEndpoints() {
219
234
  function capitalize(s) {
220
235
  return s.charAt(0).toUpperCase() + s.slice(1);
221
236
  }
222
- /** Try to match a raw API key to a known environment variable. */
223
- function findEnvVarRef(providerName, apiKey) {
224
- const envMap = {
225
- deepseek: 'DEEPSEEK_API_KEY',
226
- openai: 'OPENAI_API_KEY',
227
- google: 'GEMINI_API_KEY',
228
- openrouter: 'OPENROUTER_API_KEY',
229
- anthropic: 'ANTHROPIC_API_KEY',
230
- };
231
- const envVar = envMap[providerName];
232
- if (envVar && process.env[envVar] && process.env[envVar] === apiKey) {
233
- return `$${envVar}`;
234
- }
235
- return null;
236
- }
237
+ // ─── YAML Generation ───────────────────────────────────────────────
237
238
  /**
238
239
  * Generate gateway.yaml content from discovered endpoints.
239
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).
240
244
  */
241
245
  export function generateGatewayYaml(endpoints, defaultMode) {
242
- // 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")
243
248
  const byEndpoint = {};
244
- for (const ep of endpoints) {
249
+ for (const ep of renderable) {
245
250
  (byEndpoint[ep.endpoint] ||= []).push(ep);
246
251
  }
247
252
  const lines = [];
@@ -254,12 +259,12 @@ export function generateGatewayYaml(endpoints, defaultMode) {
254
259
  lines.push('#');
255
260
  lines.push('# Docs: https://aistatus.cc/docs');
256
261
  lines.push('');
257
- // Determine default mode
258
- const activeMode = defaultMode || endpoints[0]?.mode || 'api';
259
- // Collect all modes for the comment
260
- 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);
261
266
  lines.push(`port: 9880`);
262
- lines.push(`mode: ${activeMode} # active billing mode: ${allModes.join(' | ')}`);
267
+ lines.push(`mode: ${activeMode}${allModes.length > 0 ? ` # active billing mode: ${allModes.join(' | ')}` : ''}`);
263
268
  lines.push(`status_check: true`);
264
269
  for (const [epName, eps] of Object.entries(byEndpoint)) {
265
270
  lines.push('');
@@ -268,7 +273,7 @@ export function generateGatewayYaml(endpoints, defaultMode) {
268
273
  // Determine provider label for the comment
269
274
  const providerLabel = ep.mode === 'plan' ? 'Anthropic Claude (OAuth passthrough, billed via subscription)' :
270
275
  ep.mode === 'api' ? 'Anthropic Claude (API key, billed via API credits)' :
271
- `${capitalize(ep.mode)} (${ep.endpoint}-compatible API)`;
276
+ `${capitalize(ep.mode)} (PI-managed auth, routed through gateway)`;
272
277
  lines.push(` # ── ${providerLabel} ──`);
273
278
  lines.push(` ${ep.mode}:`);
274
279
  lines.push(` base_url: ${ep.base_url}`);
@@ -279,23 +284,24 @@ export function generateGatewayYaml(endpoints, defaultMode) {
279
284
  lines.push(` - ${key}`);
280
285
  }
281
286
  }
282
- if (ep.keys.length === 0) {
287
+ else {
283
288
  lines.push(` # No managed keys — ${ep.passthrough ? 'caller key passthrough' : 'waiting for key configuration'}`);
284
289
  }
285
290
  if (ep.passthrough && ep.keys.length > 0) {
286
291
  lines.push(` passthrough: true`);
287
292
  }
288
- if (Object.keys(ep.modelFallbacks).length > 0) {
289
- lines.push(` model_fallbacks:`);
290
- for (const [model, fallbacks] of Object.entries(ep.modelFallbacks)) {
291
- lines.push(` ${model}:`);
292
- for (const fb of fallbacks) {
293
- lines.push(` - ${fb}`);
294
- }
295
- }
296
- }
297
293
  }
298
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
+ }
299
305
  lines.push('');
300
306
  return lines.join('\n');
301
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
  /**