@cortex-agent/server 2026.5.22 → 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 (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 +178 -172
  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 +67 -23
  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
@@ -6,6 +6,7 @@
6
6
  "profile": "__active__",
7
7
  "persistSession": true,
8
8
  "promptTemplate": "{{input}}\n\nWrite your final reply to {{artifactPath}}.",
9
+ "systemPrompt": "file:direct.md",
9
10
  "tools": "Agent,AskUserQuestion,Bash,Edit,EnterPlanMode,ExitPlanMode,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
10
11
  "pluginDirs": [
11
12
  "plugins/cortex-common",
@@ -20,6 +21,7 @@
20
21
  "profile": "__active__",
21
22
  "persistSession": true,
22
23
  "promptTemplate": "{{input}}",
24
+ "systemPrompt": "file:direct.md",
23
25
  "tools": "Agent,AskUserQuestion,Bash,Edit,EnterPlanMode,ExitPlanMode,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
24
26
  "pluginDirs": [
25
27
  "plugins/cortex-common",
@@ -50,6 +52,7 @@
50
52
  "persistSession": false,
51
53
  "directive": "",
52
54
  "promptTemplate": "{{input}}\n\n{{previousOutput}}",
55
+ "systemPrompt": "file:worker.md",
53
56
  "tools": "Agent,Bash,Edit,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
54
57
  "pluginDirs": [
55
58
  "plugins/cortex-common",
@@ -64,6 +67,7 @@
64
67
  "profile": "__active__",
65
68
  "persistSession": false,
66
69
  "promptTemplate": "{{input}}",
70
+ "systemPrompt": "file:worker.md",
67
71
  "tools": "Agent,Bash,Edit,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
68
72
  "pluginDirs": [
69
73
  "plugins/cortex-common",
@@ -78,6 +82,7 @@
78
82
  "profile": "plan",
79
83
  "persistSession": true,
80
84
  "promptTemplate": "Write your plan to {{artifactPath}}.\n\nUser request:\n{{input}}",
85
+ "systemPrompt": "file:worker.md",
81
86
  "tools": "Agent,Bash,Edit,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
82
87
  "pluginDirs": [
83
88
  "plugins/cortex-common",
@@ -91,6 +96,7 @@
91
96
  "persistSession": true,
92
97
  "directive": "You are a strict reviewer. Evaluate the plan for correctness, completeness, and feasibility.",
93
98
  "promptTemplate": "Read the content in {{artifactPath}} and perform a review. Append your review to the ## Review section at the end of the file. If the content passes, write [APPROVED] at the end of the review. Otherwise provide specific suggestions for improvement.",
99
+ "systemPrompt": "file:worker.md",
94
100
  "tools": "Agent,Bash,Edit,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
95
101
  "pluginDirs": [
96
102
  "plugins/cortex-common",
@@ -104,6 +110,7 @@
104
110
  "persistSession": false,
105
111
  "directive": "file:plan-reviewer.md",
106
112
  "promptTemplate": "Execute the plan-phase audit per the plan-reviewer directive.\n\nTask / context (must declare plan path, phase under review, and where the phase's artifacts live):\n{{input}}\n\n---\n\nWrite the review to {{artifactPath}}. Walk every acceptance criterion of the phase explicitly (met / partially met / not met with a citation). End the artifact with a single line in the exact form: `Verdict: Approve | Revise | Reject` (one word, no modifiers).",
113
+ "systemPrompt": "file:worker.md",
107
114
  "tools": "Agent,Bash,Edit,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
108
115
  "pluginDirs": [
109
116
  "plugins/cortex-common",
@@ -117,6 +124,7 @@
117
124
  "persistSession": false,
118
125
  "directive": "file:plan-executor.md",
119
126
  "promptTemplate": "Translate Plan Reviewer's verdict into operations per the plan-executor directive.\n\nPlan Reviewer's report (previous step):\n{{previousOutput}}\n\n---\n\nOriginal task / context:\n{{input}}\n\n---\n\nReviewer's full artifact is at {{artifactPath}} \u2014 read it end-to-end first, extract the `Verdict:` word, then run the matching branch (Approve / Revise / Reject). All new tasks MUST carry `template:plan-gate` and full metadata; gate tasks always start `PLAN-GATE: `. Do NOT modify the plan file's structure or acceptance criteria.",
127
+ "systemPrompt": "file:worker.md",
120
128
  "tools": "Agent,Bash,Edit,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
121
129
  "pluginDirs": [
122
130
  "plugins/cortex-stage-gate"
@@ -129,6 +137,7 @@
129
137
  "persistSession": false,
130
138
  "directive": "file:milestone-reviewer.md",
131
139
  "promptTemplate": "Execute the milestone adversarial audit per the milestone-reviewer directive.\n\nTask / context:\n{{input}}\n\n---\n\nWrite the review to {{artifactPath}}. Cover every dimension the milestone's success criteria can be judged on. Each issue must carry a citation and a Blocker / Nice-to-have label. Do NOT issue a Director-style verdict \u2014 that belongs to Director.",
140
+ "systemPrompt": "file:worker.md",
132
141
  "tools": "Agent,Bash,Edit,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
133
142
  "pluginDirs": [
134
143
  "plugins/cortex-common",
@@ -142,6 +151,7 @@
142
151
  "persistSession": false,
143
152
  "directive": "file:director.md",
144
153
  "promptTemplate": "Execute the milestone verdict per the director directive.\n\nMilestone Reviewer's report (previous step):\n{{previousOutput}}\n\n---\n\nOriginal task / context:\n{{input}}\n\n---\n\nReviewer's full artifact is at {{artifactPath}} \u2014 read it end-to-end first. Write your analysis and the final `Verdict:` line back to the same artifact. Artifact MUST agree on verdict word and top reasons.",
154
+ "systemPrompt": "file:worker.md",
145
155
  "tools": "Agent,Bash,Edit,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
146
156
  "pluginDirs": [
147
157
  "plugins/cortex-common",
@@ -155,6 +165,7 @@
155
165
  "persistSession": false,
156
166
  "directive": "file:milestone-executor.md",
157
167
  "promptTemplate": "Translate Director's verdict into operations per the milestone-executor directive.\n\nDirector's analysis (previous step):\n{{previousOutput}}\n\n---\n\nOriginal task / context:\n{{input}}\n\n---\n\nDirector's full artifact is at {{artifactPath}} \u2014 read it end-to-end first and extract the `Verdict:` word. Then execute the matching branch (Proceed / Iterate / Pivot / Abort) per directive.",
168
+ "systemPrompt": "file:worker.md",
158
169
  "tools": "Agent,Bash,Edit,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
159
170
  "pluginDirs": [
160
171
  "plugins/cortex-stage-gate"
@@ -166,6 +177,7 @@
166
177
  "profile": "plan",
167
178
  "persistSession": true,
168
179
  "directive": "file:doc-writer.md",
180
+ "systemPrompt": "file:worker.md",
169
181
  "entryStage": "write",
170
182
  "stages": {
171
183
  "write": {
@@ -190,6 +202,7 @@
190
202
  "profile": "execute",
191
203
  "persistSession": true,
192
204
  "directive": "file:doc-reviewer.md",
205
+ "systemPrompt": "file:worker.md",
193
206
  "promptTemplate": "Audit Doc Writer's project-file changes (changes by other agents in the same files may appear \u2014 ignore those):\n{{modifiedFiles}}\n\nOriginal task:\n{{input}}\n\nApply the doc-reviewer directive and append your review to {{artifactPath}} under `## Review (iteration N)`. End the section with `[APPROVED]` if no Blockers remain; otherwise list the Blockers so Doc Writer can revise.",
194
207
  "tools": "Agent,Bash,Edit,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
195
208
  "pluginDirs": [
@@ -2,7 +2,7 @@
2
2
  // output: PIAdapter + PISession + switch_session API
3
3
  // pos: PI CLI session pool and AgentAdapter implementation
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
- import { spawn as defaultSpawn } from 'child_process';
5
+ import { spawn as defaultSpawn, execSync } from 'child_process';
6
6
  import { mkdirSync } from 'fs';
7
7
  import * as path from 'path';
8
8
  import { DATA_DIR, INSTALL_ROOT } from '../../core/utils.js';
@@ -11,12 +11,44 @@ import { CAPABILITIES_BY_BACKEND } from '../capabilities.js';
11
11
  import { buildSpawnArgs } from './spawn-args.js';
12
12
  import { createLineSplitter, encodeCommand } from './framing.js';
13
13
  import { piRpcLineToNormalized, createPIEventParserState } from './event-parser.js';
14
- import { PI_AGENT_DIR, PI_SESSIONS_DIR, writeAnthropicBaseUrl } from './agent-dir.js';
14
+ import { PI_AGENT_DIR, PI_SESSIONS_DIR, writeProvidersConfig, ensureAuthVisible } from './agent-dir.js';
15
+ import { parsePiListModelsOutput } from '../../core/gateway-generator.js';
15
16
  import { buildPrompt } from '../normalize/prompt-builder.js';
16
17
  const log = createLogger('pi-adapter');
17
18
  function buildPromptText(msg) {
18
19
  return buildPrompt(msg.text, msg.attachments ?? []);
19
20
  }
21
+ /**
22
+ * Discover unique PI provider names by shelling out to `pi --list-models`. Called at spawn time
23
+ * so the multi-provider models.json reflects whatever the user has currently authenticated to.
24
+ *
25
+ * PI writes the table to stderr — merge via 2>&1. Returns empty array on any failure (PI not
26
+ * installed, timeout, parse error); the caller logs a warning and proceeds without overriding
27
+ * models.json, which means the PI subprocess will fall back to direct upstream calls.
28
+ *
29
+ * Uses the user's real ~/.pi/agent/ for discovery (no PI_CODING_AGENT_DIR override) — symmetric
30
+ * with cortex init's gateway-generator.scanPIViaListModels(). ensureAuthVisible() then mirrors
31
+ * the auth file into PI_AGENT_DIR so the actual spawn can see those credentials.
32
+ */
33
+ function discoverPIProviders() {
34
+ try {
35
+ const stdout = execSync('pi --list-models 2>&1', {
36
+ timeout: 10_000,
37
+ encoding: 'utf-8',
38
+ // Intentionally do NOT set PI_CODING_AGENT_DIR — read user's real PI config.
39
+ env: { ...process.env, PI_CODING_AGENT_DIR: '' },
40
+ });
41
+ const models = parsePiListModelsOutput(stdout);
42
+ const uniq = new Set();
43
+ for (const m of models)
44
+ uniq.add(m.provider);
45
+ return Array.from(uniq);
46
+ }
47
+ catch (err) {
48
+ log.info(`pi --list-models failed at spawn: ${err.message ?? 'unknown'}`);
49
+ return [];
50
+ }
51
+ }
20
52
  const DEFAULT_PI_BINARY = 'pi';
21
53
  // DEFAULT_SESSION_DIR: sessionId.jsonl files are stored here (convention: <sessionDir>/<sessionId>.jsonl).
22
54
  // Sessions stored under logs/sessions-pi/; PI_CODING_AGENT_DIR points to data/ for models.json.
@@ -487,6 +519,7 @@ export class PIAdapter {
487
519
  sessionDir,
488
520
  sessionId: sessionIdForSpawn,
489
521
  model: config.model ?? null,
522
+ provider: config.piProvider ?? null,
490
523
  systemPrompt: config.systemPrompt ?? null,
491
524
  appendSystemPrompt: config.appendSystemPrompt ?? null,
492
525
  pluginDirs: config.pluginDirs ?? null,
@@ -494,14 +527,30 @@ export class PIAdapter {
494
527
  extensionPaths: [MCP_BRIDGE_PATH, TOOL_SHIMS_PATH, HOOK_BRIDGE_PATH],
495
528
  extraOption: config.extraOption ?? null,
496
529
  });
497
- // Write models.json before spawn so PI subprocess reads the correct baseUrl.
498
- // PI adapter is the sole writer of this file — no other code path touches it.
499
- if (config.anthropicBaseUrl) {
530
+ // Pre-spawn config sync (sole writers of PI_AGENT_DIR — no other code path touches these files):
531
+ // 1. Mirror user's ~/.pi/agent/auth.json so the PI subprocess can resolve OAuth/API key auth
532
+ // 2. Write multi-provider models.json overriding every discovered PI provider's baseUrl to
533
+ // land on the local gateway. PI uses its "Override Built-in Providers" mechanism
534
+ // (PI docs/models.md §Overriding Built-in Providers) — only baseUrl is set, auth is
535
+ // resolved from auth.json as usual.
536
+ if (config.piGatewayBaseUrl) {
500
537
  try {
501
- writeAnthropicBaseUrl(config.anthropicBaseUrl);
538
+ ensureAuthVisible();
539
+ }
540
+ catch (err) {
541
+ log.warn(`Failed to mirror PI auth.json: ${err.message}`);
542
+ }
543
+ try {
544
+ const providers = discoverPIProviders();
545
+ if (providers.length > 0) {
546
+ writeProvidersConfig(providers.map(name => ({ name })), config.piGatewayBaseUrl);
547
+ }
548
+ else {
549
+ log.warn('pi --list-models returned no providers; PI subprocess may fail to authenticate');
550
+ }
502
551
  }
503
552
  catch (err) {
504
- log.warn(`Failed to write models.json: ${err.message}`);
553
+ log.warn(`Failed to write PI models.json: ${err.message}`);
505
554
  }
506
555
  }
507
556
  const env = { ...process.env, ...(config.env ?? {}), PI_CODING_AGENT_DIR: PI_AGENT_DIR };
@@ -3,9 +3,46 @@ export declare const PI_AGENT_DIR: string;
3
3
  export declare const PI_SESSIONS_DIR: string;
4
4
  export declare const PI_MODELS_PATH: string;
5
5
  /**
6
- * Atomic-write models.json with anthropic provider config.
7
- * Called by PIAdapter.spawn() — sole writer, no other code path touches this file.
8
- * Uses a placeholder apiKey ("x") because the gateway replaces it with the real key.
6
+ * One provider entry to write into the cortex-controlled `models.json`. cortex uses PI's
7
+ * "Override Built-in Providers" mechanism (docs/models.md §Overriding Built-in Providers):
8
+ * specifying only `baseUrl` redirects all of that provider's traffic to our gateway while
9
+ * keeping PI's built-in model catalog and OAuth/API-key auth resolution from auth.json intact.
9
10
  */
10
- export declare function writeAnthropicBaseUrl(baseUrl: string): void;
11
+ export interface ProviderOverride {
12
+ /** PI provider name (e.g. "anthropic", "deepseek", "openai-codex"). */
13
+ name: string;
14
+ /**
15
+ * Path segment appended to the gateway URL. Defaults to `/${name}`.
16
+ * Set explicitly when a provider needs to land on a non-standard gateway path
17
+ * (e.g. deepseek's anthropic-compat endpoint: `/deepseek/anthropic`).
18
+ */
19
+ basePath?: string;
20
+ }
21
+ export interface WriteProvidersOpts {
22
+ /** Override target file path. Defaults to PI_MODELS_PATH. */
23
+ modelsPath?: string;
24
+ }
25
+ /**
26
+ * Atomic-write models.json with multi-provider baseUrl overrides. Each provider entry has a
27
+ * `baseUrl` pointing to `<gatewayUrl><basePath>`; no apiKey is written so PI resolves credentials
28
+ * from auth.json (or environment variables) per PI's auth resolution order.
29
+ *
30
+ * Called by PIAdapter.spawn() — sole writer of this file, no other code path touches it.
31
+ */
32
+ export declare function writeProvidersConfig(providers: ProviderOverride[], gatewayUrl: string, opts?: WriteProvidersOpts): void;
33
+ export interface EnsureAuthVisibleOpts {
34
+ /** Source: where the user's PI auth.json lives. Defaults to ~/.pi/agent/auth.json. */
35
+ userAuthPath?: string;
36
+ /** Target dir (PI_CODING_AGENT_DIR). Defaults to PI_AGENT_DIR. */
37
+ agentDir?: string;
38
+ }
39
+ /**
40
+ * Make the user's PI OAuth/API-key credentials visible to the PI subprocess running under
41
+ * cortex's PI_CODING_AGENT_DIR. Uses symlink on Linux/macOS so PI's automatic OAuth refresh
42
+ * writes back to the user's canonical location. Falls back to file copy on Windows.
43
+ *
44
+ * Idempotent: a correctly-pointed symlink is preserved; a stale file/symlink is replaced.
45
+ * Silently no-ops when the user has not logged into PI (no source auth.json).
46
+ */
47
+ export declare function ensureAuthVisible(opts?: EnsureAuthVisibleOpts): void;
11
48
  export declare function ensurePIAgentDirs(): void;
@@ -1,33 +1,118 @@
1
1
  // input: DATA_DIR
2
- // output: PI_AGENT_DIR / PI_SESSIONS_DIR / PI_MODELS_PATH constants + writeAnthropicBaseUrl + ensurePIAgentDirs
2
+ // output: PI_AGENT_DIR / PI_SESSIONS_DIR / PI_MODELS_PATH constants
3
+ // + writeProvidersConfig (multi-provider models.json override)
4
+ // + ensureAuthVisible (symlink user's ~/.pi/agent/auth.json into PI_AGENT_DIR
5
+ // so the PI subprocess can resolve OAuth/API key credentials)
6
+ // + ensurePIAgentDirs
3
7
  // pos: PI agent directory management; models.json is written exclusively by PI adapter spawn
4
- // layout: data/pi/models.json logs/sessions-pi/
5
- // PI_CODING_AGENT_DIR → DATA_DIR/data/pi (PI reads models.json from here)
8
+ // layout: data/pi/models.json data/pi/auth.json (symlink) logs/sessions-pi/
9
+ // PI_CODING_AGENT_DIR → DATA_DIR/data/pi (PI reads models.json + auth.json from here)
6
10
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
7
- import { mkdirSync, writeFileSync, renameSync } from 'fs';
11
+ import { mkdirSync, writeFileSync, renameSync, existsSync, lstatSync, readlinkSync, unlinkSync, symlinkSync, copyFileSync, } from 'fs';
8
12
  import * as path from 'path';
13
+ import * as os from 'os';
9
14
  import { DATA_DIR } from '../../core/utils.js';
15
+ import { createLogger } from '../../core/log.js';
16
+ const log = createLogger('pi-agent-dir');
10
17
  /** PI_CODING_AGENT_DIR: PI reads models.json, auth.json from this dir. */
11
18
  export const PI_AGENT_DIR = path.join(DATA_DIR, 'data', 'pi');
12
19
  export const PI_SESSIONS_DIR = path.join(DATA_DIR, 'logs', 'sessions-pi');
13
20
  export const PI_MODELS_PATH = path.join(PI_AGENT_DIR, 'models.json');
21
+ /** Default location of the user's PI OAuth/API-key credentials. */
22
+ const USER_PI_AUTH_PATH = path.join(os.homedir(), '.pi', 'agent', 'auth.json');
14
23
  /**
15
- * Atomic-write models.json with anthropic provider config.
16
- * Called by PIAdapter.spawn() — sole writer, no other code path touches this file.
17
- * Uses a placeholder apiKey ("x") because the gateway replaces it with the real key.
24
+ * Atomic-write models.json with multi-provider baseUrl overrides. Each provider entry has a
25
+ * `baseUrl` pointing to `<gatewayUrl><basePath>`; no apiKey is written so PI resolves credentials
26
+ * from auth.json (or environment variables) per PI's auth resolution order.
27
+ *
28
+ * Called by PIAdapter.spawn() — sole writer of this file, no other code path touches it.
18
29
  */
19
- export function writeAnthropicBaseUrl(baseUrl) {
20
- const data = {
21
- providers: {
22
- anthropic: { baseUrl, apiKey: 'x' },
23
- },
24
- };
30
+ export function writeProvidersConfig(providers, gatewayUrl, opts) {
31
+ const targetPath = opts?.modelsPath ?? PI_MODELS_PATH;
32
+ const providersBlock = {};
33
+ for (const p of providers) {
34
+ const basePath = p.basePath ?? `/${p.name}`;
35
+ providersBlock[p.name] = { baseUrl: `${gatewayUrl}${basePath}` };
36
+ }
37
+ const data = { providers: providersBlock };
25
38
  const content = JSON.stringify(data, null, 2) + '\n';
39
+ mkdirSync(path.dirname(targetPath), { recursive: true });
26
40
  // Atomic write: tmp + rename
27
- const tmp = `${PI_MODELS_PATH}.tmp.${process.pid}.${Date.now()}`;
28
- writeFileSync(tmp, content, 'utf8');
29
- renameSync(tmp, PI_MODELS_PATH);
41
+ const tmp = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
42
+ try {
43
+ writeFileSync(tmp, content, 'utf8');
44
+ renameSync(tmp, targetPath);
45
+ }
46
+ catch (err) {
47
+ // Best-effort cleanup of orphan tmp file (rename failure case)
48
+ try {
49
+ if (existsSync(tmp))
50
+ unlinkSync(tmp);
51
+ }
52
+ catch { /* ignore */ }
53
+ throw err;
54
+ }
30
55
  }
56
+ /**
57
+ * Make the user's PI OAuth/API-key credentials visible to the PI subprocess running under
58
+ * cortex's PI_CODING_AGENT_DIR. Uses symlink on Linux/macOS so PI's automatic OAuth refresh
59
+ * writes back to the user's canonical location. Falls back to file copy on Windows.
60
+ *
61
+ * Idempotent: a correctly-pointed symlink is preserved; a stale file/symlink is replaced.
62
+ * Silently no-ops when the user has not logged into PI (no source auth.json).
63
+ */
64
+ export function ensureAuthVisible(opts) {
65
+ const userAuth = opts?.userAuthPath ?? USER_PI_AUTH_PATH;
66
+ const agentDir = opts?.agentDir ?? PI_AGENT_DIR;
67
+ const cortexAuth = path.join(agentDir, 'auth.json');
68
+ if (!existsSync(userAuth)) {
69
+ // User hasn't logged into PI; nothing to mirror.
70
+ return;
71
+ }
72
+ mkdirSync(agentDir, { recursive: true });
73
+ // Inspect the destination — preserve correct symlink, replace anything else.
74
+ if (existsSync(cortexAuth) || isBrokenSymlink(cortexAuth)) {
75
+ try {
76
+ const stat = lstatSync(cortexAuth);
77
+ if (stat.isSymbolicLink()) {
78
+ const target = readlinkSync(cortexAuth);
79
+ if (target === userAuth && process.platform !== 'win32') {
80
+ // Already a correctly-pointing symlink, nothing to do.
81
+ return;
82
+ }
83
+ }
84
+ unlinkSync(cortexAuth);
85
+ }
86
+ catch (err) {
87
+ log.warn(`Failed to inspect/remove existing ${cortexAuth}: ${err.message}`);
88
+ return;
89
+ }
90
+ }
91
+ if (process.platform === 'win32') {
92
+ // Windows: symlink requires elevated permissions on many systems; copy instead.
93
+ // KNOWN LIMITATION: PI's OAuth refresh writes to the cortex-private copy, not the user's
94
+ // original file. Re-running ensureAuthVisible would overwrite the refreshed token. See
95
+ // /home/fangxin/.cortex/plan/generic-wibbling-pine.md §D4 for Windows-specific TODO.
96
+ copyFileSync(userAuth, cortexAuth);
97
+ }
98
+ else {
99
+ symlinkSync(userAuth, cortexAuth);
100
+ }
101
+ }
102
+ /** Returns true if `p` is a dangling symlink (exists in lstat sense but not in stat sense). */
103
+ function isBrokenSymlink(p) {
104
+ try {
105
+ const lst = lstatSync(p);
106
+ if (!lst.isSymbolicLink())
107
+ return false;
108
+ // existsSync follows links; if it returned false we already know the link is broken.
109
+ return !existsSync(p);
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ }
115
+ // ─── Directory bootstrap ──────────────────────────────────────────
31
116
  export function ensurePIAgentDirs() {
32
117
  mkdirSync(PI_AGENT_DIR, { recursive: true });
33
118
  mkdirSync(PI_SESSIONS_DIR, { recursive: true });
@@ -8,6 +8,10 @@ export interface PISpawnOptions {
8
8
  sessionPath?: string | null;
9
9
  /** Model identifier (e.g. "deepseek-v4-flash[1m]"); context-window suffix is stripped. */
10
10
  model?: string | null;
11
+ /** PI provider name (e.g. "anthropic", "deepseek", "openai-codex"). When set together with model,
12
+ * emits `--provider <name>`. When omitted, PI infers provider from model name prefix or its default.
13
+ * Sourced from the cortex profile's `mode` field at adapter-spawn time. */
14
+ provider?: string | null;
11
15
  systemPrompt?: string | null;
12
16
  /** Single string or multi-value array; pi args.js:49-51 accepts repeated --append-system-prompt flags. */
13
17
  appendSystemPrompt?: string | string[] | null;
@@ -11,9 +11,12 @@ export function buildSpawnArgs(opts) {
11
11
  if (opts.model) {
12
12
  const cleaned = stripModelSuffix(opts.model);
13
13
  args.push('--model', cleaned);
14
- // PI reads provider config from models.json (written by syncPIModelsJson);
15
- // force --provider anthropic so the gateway baseUrl is used.
16
- args.push('--provider', 'anthropic');
14
+ // Provider is decided by the active cortex profile (mode field). For non-Claude PI providers
15
+ // (deepseek / openai-codex / etc.) cortex writes a multi-provider models.json (writeProvidersConfig)
16
+ // that overrides each provider's baseUrl to the gateway, then PI selects the matching provider here.
17
+ if (opts.provider) {
18
+ args.push('--provider', opts.provider);
19
+ }
17
20
  }
18
21
  // --session accepts both a UUID (scanned from --session-dir) and a full file path.
19
22
  // Prefer sessionId (UUID) — it's robust to PI's internal file naming which may
@@ -52,6 +52,13 @@ export interface AgentSpawnConfig {
52
52
  rawTools?: string;
53
53
  /** DR-0008 Phase 3 cleanup target. Per-request ANTHROPIC_BASE_URL override (gateway-routed mode URL). */
54
54
  anthropicBaseUrl?: string;
55
+ /** PI provider name (e.g. "anthropic", "deepseek", "openai-codex"). Sourced from the active
56
+ * cortex profile's `mode` field. PI adapter passes it to the subprocess as `--provider <name>`. */
57
+ piProvider?: string;
58
+ /** Base URL of the cortex local gateway (e.g. "http://127.0.0.1:9880"). PI adapter writes a
59
+ * multi-provider models.json overriding every discovered provider's baseUrl to land on this
60
+ * gateway, so PI traffic is monitored / cost-tracked rather than going direct to upstreams. */
61
+ piGatewayBaseUrl?: string;
55
62
  /** DR-0012: Claude adapter mode. 'print' (default, -p stream-json) or 'tui' (interactive tmux + jsonl tail).
56
63
  * Ignored for non-claude backends. Sourced from the active profile's claudeBackend field. */
57
64
  claudeBackend?: 'print' | 'tui';
@@ -1,7 +1,7 @@
1
1
  export interface DiscoveredEndpoint {
2
- /** Mode key in gateway.yaml (e.g. "api", "plan", "deepseek-anthropic") */
2
+ /** Mode key in gateway.yaml + cortex profile (e.g. "plan", "deepseek", "openai-codex") */
3
3
  mode: string;
4
- /** Endpoint name (e.g. "anthropic", "openai") */
4
+ /** Endpoint group name (e.g. "anthropic", "deepseek", "openai-codex") */
5
5
  endpoint: string;
6
6
  base_url: string;
7
7
  auth_style: string;
@@ -9,28 +9,41 @@ export interface DiscoveredEndpoint {
9
9
  passthrough: boolean;
10
10
  /** Model IDs known to be available for this endpoint */
11
11
  models: string[];
12
- /** Tier-based model fallback chain for model_fallbacks */
13
- modelFallbacks: Record<string, string[]>;
12
+ /** Whether gateway.yaml should render an endpoint section for this entry. PI providers without a
13
+ * known upstream URL are surfaced as profiles but skipped in gateway.yaml. */
14
+ gatewayManaged: boolean;
14
15
  }
15
- export interface GatewayGenInput {
16
- /** Discovered endpoints from Claude Code and PI configs */
17
- endpoints: DiscoveredEndpoint[];
18
- /** Default active mode */
19
- defaultMode?: string;
16
+ export interface PiDiscoveredModel {
17
+ provider: string;
18
+ model: string;
20
19
  }
20
+ /**
21
+ * Parse the table output of `pi --list-models` into structured entries.
22
+ * Skips header row, blank lines, and the "No models available" fallback message.
23
+ *
24
+ * Example input:
25
+ * provider model context max-out thinking images
26
+ * anthropic claude-3-5-haiku-20241022 200K 8.2K no yes
27
+ * deepseek deepseek-v4-pro 1M 384K yes no
28
+ */
29
+ export declare function parsePiListModelsOutput(stdout: string): PiDiscoveredModel[];
21
30
  /**
22
31
  * Scan Claude Code and PI configurations and return discovered endpoints.
23
32
  *
24
- * Rules:
25
- * - Claude Code plan mode: always generated (OAuth bearer passthrough, no managed keys).
26
- * - Claude Code api mode: generated only if ANTHROPIC_API_KEY env var is set (referenced via $ANTHROPIC_API_KEY).
27
- * - PI providers from auth.json: use known provider defaults.
28
- * - PI providers from models.json: skip if base URL is already a gateway URL (already configured).
33
+ * - Claude Code plan mode: always generated if logged in (OAuth bearer passthrough).
34
+ * - Claude Code api mode: generated only if ANTHROPIC_API_KEY env var is set.
35
+ * - PI providers: discovered via `pi --list-models`. Each provider becomes one endpoint with
36
+ * `mode = endpoint = provider name`. `gatewayManaged` is true only if the provider has a known
37
+ * upstream URL in PI_PROVIDER_UPSTREAM (otherwise profile is generated but gateway.yaml entry
38
+ * is skipped).
29
39
  */
30
40
  export declare function discoverEndpoints(): DiscoveredEndpoint[];
31
41
  /**
32
42
  * Generate gateway.yaml content from discovered endpoints.
33
43
  * Outputs a formatted YAML string with comments explaining each mode.
44
+ *
45
+ * Endpoints with gatewayManaged=false are skipped (their profile still exists in profiles.json,
46
+ * but gateway.yaml has no entry for them — PI traffic to those providers is currently direct).
34
47
  */
35
48
  export declare function generateGatewayYaml(endpoints: DiscoveredEndpoint[], defaultMode?: string): string;
36
49
  /**