@cortex-agent/server 2026.5.24-1 → 2026.5.25-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.
@@ -1,23 +1,17 @@
1
- // input: fs, path, os, Claude credentials.json, `pi --list-models` output
1
+ // input: fs, path, os, `pi --list-models` output
2
2
  // output: discoverEndpoints / generateGatewayYaml / writeGatewayYaml / parsePiListModelsOutput
3
- // — scans Claude OAuth + spawns pi --list-models, produces gateway.yaml content
3
+ // — spawns pi --list-models, produces gateway.yaml content
4
4
  // pos: init-time gateway config auto-generation. PI model metadata is owned by the PI agent
5
5
  // (we shell out to `pi --list-models` rather than maintain provider/model whitelists).
6
- import { readFileSync, writeFileSync, copyFileSync, mkdirSync, existsSync } from 'fs';
6
+ // Claude plan mode is always assumed (user must have claude login), no credential scanning.
7
+ import { writeFileSync, copyFileSync, mkdirSync, existsSync } from 'fs';
7
8
  import { execSync } from 'child_process';
8
9
  import * as path from 'path';
9
10
  import * as os from 'os';
10
11
  import { createLogger } from './log.js';
11
12
  const log = createLogger('gateway-generator');
12
- // ─── Paths ─────────────────────────────────────────────────────────
13
- const CLAUDE_CREDENTIALS = path.join(os.homedir(), '.claude', '.credentials.json');
14
- // ─── Anthropic Claude Code tier table (only used for Claude OAuth path) ─────
15
- /** Model names used in gateway model_fallbacks (API-level model IDs). */
16
- const ANTHROPIC_MODEL_TIERS = {
17
- max: ['claude-opus-4-7', 'claude-sonnet-4-6', 'claude-haiku-4-5'],
18
- pro: ['claude-opus-4-7', 'claude-sonnet-4-6', 'claude-haiku-4-5'],
19
- free: ['claude-haiku-4-5'],
20
- };
13
+ // ─── Anthropic models (default tier) ─────────────────────────────
14
+ const ANTHROPIC_MODELS = ['claude-opus-4-7', 'claude-sonnet-4-6', 'claude-haiku-4-5'];
21
15
  // ─── PI provider → upstream URL lookup (manually maintained) ────────────────
22
16
  /**
23
17
  * Map a PI built-in provider name to its real upstream URL. Used by `generateGatewayYaml` so PI
@@ -60,50 +54,6 @@ const PI_PROVIDER_UPSTREAM = {
60
54
  // env-driven URLs (region / account ID / resource name) — not safely templated here.
61
55
  // Users wanting these through the gateway must edit gateway.yaml manually.
62
56
  };
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
75
- }
76
- }
77
- /** Read and parse Claude Code credentials. Returns null if not logged in. */
78
- function scanClaudeCode() {
79
- try {
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'));
91
- }
92
- const oauth = raw?.claudeAiOauth;
93
- if (!oauth?.accessToken) {
94
- log.info('Claude Code credentials exist but no OAuth token found');
95
- return null;
96
- }
97
- return {
98
- subscriptionType: oauth.subscriptionType || 'free',
99
- accessToken: oauth.accessToken,
100
- };
101
- }
102
- catch (e) {
103
- log.warn(`Failed to read Claude Code credentials: ${e.message}`);
104
- return null;
105
- }
106
- }
107
57
  /**
108
58
  * Parse the table output of `pi --list-models` into structured entries.
109
59
  * Skips header row, blank lines, and the "No models available" fallback message.
@@ -174,34 +124,29 @@ function scanPIViaListModels() {
174
124
  */
175
125
  export function discoverEndpoints() {
176
126
  const endpoints = [];
177
- // ── Claude Code → Anthropic plan mode ──
178
- const claude = scanClaudeCode();
179
- if (claude) {
180
- const models = ANTHROPIC_MODEL_TIERS[claude.subscriptionType || 'free'] || ANTHROPIC_MODEL_TIERS.free;
181
- // plan mode — OAuth bearer passthrough
127
+ // ── Claude Code → Anthropic plan mode (always on) ──
128
+ endpoints.push({
129
+ mode: 'plan',
130
+ endpoint: 'anthropic',
131
+ base_url: 'https://api.anthropic.com',
132
+ auth_style: 'bearer',
133
+ keys: [],
134
+ passthrough: true,
135
+ models: ANTHROPIC_MODELS,
136
+ gatewayManaged: true,
137
+ });
138
+ // api mode — only if ANTHROPIC_API_KEY is set
139
+ if (process.env.ANTHROPIC_API_KEY) {
182
140
  endpoints.push({
183
- mode: 'plan',
141
+ mode: 'api',
184
142
  endpoint: 'anthropic',
185
143
  base_url: 'https://api.anthropic.com',
186
- auth_style: 'bearer',
187
- keys: [],
144
+ auth_style: 'anthropic',
145
+ keys: ['$ANTHROPIC_API_KEY'],
188
146
  passthrough: true,
189
- models,
147
+ models: ANTHROPIC_MODELS,
190
148
  gatewayManaged: true,
191
149
  });
192
- // api mode — only if ANTHROPIC_API_KEY is set
193
- if (process.env.ANTHROPIC_API_KEY) {
194
- endpoints.push({
195
- mode: 'api',
196
- endpoint: 'anthropic',
197
- base_url: 'https://api.anthropic.com',
198
- auth_style: 'anthropic',
199
- keys: ['$ANTHROPIC_API_KEY'],
200
- passthrough: true,
201
- models,
202
- gatewayManaged: true,
203
- });
204
- }
205
150
  }
206
151
  // ── PI → per-provider endpoints (one mode per provider) ──
207
152
  const piModels = scanPIViaListModels();
@@ -238,7 +238,7 @@ export function configureEnvForMode(mode, metadata) {
238
238
  return url;
239
239
  }
240
240
  // Gateway unhealthy — fallback to direct connection
241
- log.info(`Gateway unhealthy — using direct Anthropic connection (mode=${mode})`);
241
+ log.debug(`Gateway unhealthy — using direct Anthropic connection (mode=${mode})`);
242
242
  if (mode === 'plan') {
243
243
  // Plan mode direct: delete everything, let Claude Code use OAuth
244
244
  delete process.env.ANTHROPIC_API_KEY;
@@ -70,8 +70,8 @@ function defaultNow() {
70
70
  }
71
71
  // ── Main check-and-prompt flow ──────────────────────────────────
72
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') {
73
+ // 1. Disable toggle: auto-update is on by default, opt-out via env var
74
+ if (process.env.CORTEX_SERVER_UPDATE_DISABLE === '1') {
75
75
  return { action: null, latestVersion: null };
76
76
  }
77
77
  // 2. Dev mode: skip entirely
package/dist/entry/cli.js CHANGED
@@ -5,6 +5,12 @@
5
5
  // init [--home <path>] — interactive init (async, runInit)
6
6
  // start — fork app.js
7
7
  // daemon — fork daemon.js
8
+ // daemon stop — stop running daemon gracefully (SIGTERM)
9
+ // daemon status — check daemon + child status (PID, uptime)
10
+ // daemon restart — graceful: signal daemon to drain and respawn app.js
11
+ // daemon restart --hard — hard: send SIGTERM directly to app.js (daemon recovers)
12
+ // daemon restart --force— force: send SIGKILL immediately to app.js
13
+ // daemon restart-self — stop daemon, then re-fork daemon.js
8
14
  // task <subcommand> — delegate to task-cli
9
15
  // config — show resolved paths
10
16
  // Packaged as dist/entry/cli.js, registered in package.json bin.
@@ -12,7 +18,7 @@
12
18
  import { fork } from 'child_process';
13
19
  import * as path from 'path';
14
20
  import { fileURLToPath } from 'url';
15
- import { existsSync, readdirSync, mkdirSync, writeFileSync, utimesSync } from 'fs';
21
+ import { existsSync, readdirSync, mkdirSync, writeFileSync, utimesSync, readFileSync, unlinkSync } from 'fs';
16
22
  import { INSTALL_ROOT, DATA_DIR, STORE_DIR, isMainModule } from '../core/utils.js';
17
23
  import { formatHelp } from '../core/cli-utils.js';
18
24
  import { createLogger } from '../core/log.js';
@@ -20,6 +26,7 @@ import { runCli as taskRunCli } from '../domain/tasks/system/task-cli.js';
20
26
  import { getResolvedPaths, formatConfigOutput, runInit, } from './init.js';
21
27
  import { discoverEndpoints, generateGatewayYaml, writeGatewayYaml, dryRunGatewayYaml } from '../core/gateway-generator.js';
22
28
  import { generateProfiles, writeProfilesJson } from '../core/profile-generator.js';
29
+ import { CORTEX_VERSION } from '../core/version.js';
23
30
  // ─── Paths ──────────────────────────────────────────────────────
24
31
  const log = createLogger('cli');
25
32
  const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
@@ -68,8 +75,14 @@ export function getCliHelp() {
68
75
  commands: [
69
76
  { name: 'init', description: 'Initialize CORTEX_HOME directory with configs and API keys' },
70
77
  { name: 'start', description: 'Start the Cortex server (node dist/entry/app.js)' },
71
- { name: 'daemon', description: 'Daemon mode with file watching and auto-restart' },
72
- { name: 'restart', description: 'Signal a running daemon to drain and respawn app.js (touches $STORE_DIR/.restart)' },
78
+ { name: 'daemon', description: 'Start daemon mode with file watching and auto-restart' },
79
+ { name: 'daemon stop', description: 'Stop the running daemon gracefully (SIGTERM)' },
80
+ { name: 'daemon status', description: 'Check daemon + child status (PID, uptime)' },
81
+ { name: 'daemon restart', description: 'Graceful restart — signal daemon to drain and respawn app.js' },
82
+ { name: 'daemon restart --hard', description: 'Hard restart — send SIGTERM directly to app.js (daemon auto-recovers)' },
83
+ { name: 'daemon restart --force', description: 'Force restart — send SIGKILL immediately to app.js' },
84
+ { name: 'daemon restart-self', description: 'Stop and restart the daemon process itself' },
85
+ { name: 'restart', description: 'Legacy alias for daemon restart (touches $STORE_DIR/.restart)' },
73
86
  { name: 'task', description: 'Task system CLI (delegate to cortex-task)' },
74
87
  { name: 'config', description: 'Show resolved paths and initialization status' },
75
88
  { name: 'setup-gateway', description: 'Auto-detect Claude/PI configs and generate gateway.yaml + profiles.json' },
@@ -83,9 +96,330 @@ export function getCliHelp() {
83
96
  { description: 'Show resolved paths', command: 'cortex config' },
84
97
  { description: 'Re-generate gateway config', command: 'cortex setup-gateway' },
85
98
  { description: 'Start the server', command: 'cortex start' },
99
+ { description: 'Stop the daemon', command: 'cortex daemon stop' },
100
+ { description: 'Check daemon status', command: 'cortex daemon status' },
101
+ { description: 'Graceful restart', command: 'cortex daemon restart' },
102
+ { description: 'Hard restart app.js', command: 'cortex daemon restart --hard' },
103
+ { description: 'Restart daemon itself', command: 'cortex daemon restart-self' },
86
104
  ],
87
105
  });
88
106
  }
107
+ // ─── Daemon stop ──────────────────────────────────────────────────
108
+ async function stopDaemonInternal() {
109
+ const pidFile = path.join(STORE_DIR, 'daemon.pid');
110
+ // Case 1: No PID file
111
+ if (!existsSync(pidFile)) {
112
+ return { exitCode: 0, stdout: 'Cortex daemon is not running.\n', stderr: '' };
113
+ }
114
+ // Read PID
115
+ let pid;
116
+ try {
117
+ const raw = readFileSync(pidFile, 'utf8').trim();
118
+ pid = Number(raw);
119
+ if (!Number.isFinite(pid) || pid <= 0) {
120
+ try {
121
+ unlinkSync(pidFile);
122
+ }
123
+ catch { }
124
+ return { exitCode: 0, stdout: 'Cortex daemon is not running (removed corrupted PID file).\n', stderr: '' };
125
+ }
126
+ }
127
+ catch (err) {
128
+ return { exitCode: 1, stdout: '', stderr: `Failed to read PID file: ${err.message}\n` };
129
+ }
130
+ // Case 2: PID file exists but process is dead (stale)
131
+ let alive = false;
132
+ try {
133
+ process.kill(pid, 0);
134
+ alive = true;
135
+ }
136
+ catch {
137
+ alive = false;
138
+ }
139
+ if (!alive) {
140
+ try {
141
+ unlinkSync(pidFile);
142
+ }
143
+ catch { }
144
+ return { exitCode: 0, stdout: `Cortex daemon is not running (removed stale PID file for PID ${pid}).\n`, stderr: '' };
145
+ }
146
+ // Case 3: Process is alive — send SIGTERM
147
+ try {
148
+ process.kill(pid, 'SIGTERM');
149
+ }
150
+ catch (err) {
151
+ return { exitCode: 1, stdout: '', stderr: `Failed to send signal to daemon (PID ${pid}): ${err.message}\n` };
152
+ }
153
+ // Poll until the process exits (up to 10 seconds, 200ms intervals)
154
+ const maxWaitMs = 10_000;
155
+ const pollIntervalMs = 200;
156
+ const deadline = Date.now() + maxWaitMs;
157
+ while (Date.now() < deadline) {
158
+ await new Promise(r => setTimeout(r, pollIntervalMs));
159
+ try {
160
+ process.kill(pid, 0);
161
+ }
162
+ catch {
163
+ break;
164
+ }
165
+ }
166
+ // Recheck liveness
167
+ try {
168
+ process.kill(pid, 0);
169
+ // Still alive after timeout — force kill
170
+ try {
171
+ process.kill(pid, 'SIGKILL');
172
+ }
173
+ catch { }
174
+ return {
175
+ exitCode: 1,
176
+ stdout: '',
177
+ stderr: `Daemon (PID ${pid}) did not stop within ${maxWaitMs / 1000}s. Forcibly killed (SIGKILL).\n`,
178
+ };
179
+ }
180
+ catch {
181
+ // Process is dead — success
182
+ }
183
+ // Clean up PID file in case daemon's exit handler didn't run
184
+ try {
185
+ if (existsSync(pidFile)) {
186
+ const raw = readFileSync(pidFile, 'utf8').trim();
187
+ if (Number(raw) === pid)
188
+ unlinkSync(pidFile);
189
+ }
190
+ }
191
+ catch { }
192
+ return { exitCode: 0, stdout: `Cortex daemon stopped (PID ${pid}).\n`, stderr: '' };
193
+ }
194
+ // ─── Daemon status ────────────────────────────────────────────────
195
+ /** Format a duration in milliseconds as a human-readable string. */
196
+ function formatDuration(ms) {
197
+ const seconds = Math.floor(ms / 1000);
198
+ const hours = Math.floor(seconds / 3600);
199
+ const minutes = Math.floor((seconds % 3600) / 60);
200
+ const secs = seconds % 60;
201
+ if (hours > 0)
202
+ return `${hours}h ${minutes}m ${secs}s`;
203
+ if (minutes > 0)
204
+ return `${minutes}m ${secs}s`;
205
+ return `${secs}s`;
206
+ }
207
+ /** Get the uptime of a process from /proc/<pid>/stat. Returns 'unknown' on non-Linux or failure. */
208
+ function getProcessUptime(pid) {
209
+ try {
210
+ const statPath = `/proc/${pid}/stat`;
211
+ if (!existsSync(statPath))
212
+ return 'unknown';
213
+ const stat = readFileSync(statPath, 'utf8');
214
+ // Format: pid (comm) state ppid ... starttime ...
215
+ // starttime is field 22 (1-indexed), which is index 19 in the fields after comm
216
+ const commEnd = stat.lastIndexOf(')');
217
+ const afterComm = stat.substring(commEnd + 2).split(' ');
218
+ const starttimeTicks = parseInt(afterComm[19], 10);
219
+ if (!Number.isFinite(starttimeTicks))
220
+ return 'unknown';
221
+ const uptimeRaw = readFileSync('/proc/uptime', 'utf8');
222
+ const systemUptimeSec = parseFloat(uptimeRaw.split(' ')[0]);
223
+ const clkTck = 100; // Linux CONFIG_HZ default
224
+ const bootTimeMs = Date.now() - systemUptimeSec * 1000;
225
+ const processStartMs = bootTimeMs + (starttimeTicks / clkTck) * 1000;
226
+ const elapsedMs = Date.now() - processStartMs;
227
+ if (elapsedMs < 0)
228
+ return 'unknown';
229
+ return formatDuration(elapsedMs);
230
+ }
231
+ catch {
232
+ return 'unknown';
233
+ }
234
+ }
235
+ function getDaemonStatusInternal() {
236
+ const pidFile = path.join(STORE_DIR, 'daemon.pid');
237
+ // Case 1: No PID file
238
+ if (!existsSync(pidFile)) {
239
+ return { exitCode: 0, stdout: 'Cortex daemon is not running.\n', stderr: '' };
240
+ }
241
+ // Read PID
242
+ let pid;
243
+ try {
244
+ const raw = readFileSync(pidFile, 'utf8').trim();
245
+ pid = Number(raw);
246
+ if (!Number.isFinite(pid) || pid <= 0) {
247
+ try {
248
+ unlinkSync(pidFile);
249
+ }
250
+ catch { }
251
+ return { exitCode: 0, stdout: 'Cortex daemon is not running (removed corrupted PID file).\n', stderr: '' };
252
+ }
253
+ }
254
+ catch (err) {
255
+ return { exitCode: 1, stdout: '', stderr: `Failed to read PID file: ${err.message}\n` };
256
+ }
257
+ // Case 2: PID file exists but process is dead (stale)
258
+ let alive = false;
259
+ try {
260
+ process.kill(pid, 0);
261
+ alive = true;
262
+ }
263
+ catch {
264
+ alive = false;
265
+ }
266
+ if (!alive) {
267
+ try {
268
+ unlinkSync(pidFile);
269
+ }
270
+ catch { }
271
+ return { exitCode: 0, stdout: `Cortex daemon is not running (removed stale PID file for PID ${pid}).\n`, stderr: '' };
272
+ }
273
+ // Case 3: Process is alive — report status
274
+ const uptime = getProcessUptime(pid);
275
+ const lines = [
276
+ 'Cortex daemon is running.',
277
+ ` PID: ${pid}`,
278
+ ` Uptime: ${uptime}`,
279
+ ];
280
+ // Check child (app.js) status via daemon-child.pid
281
+ const childPidFile = path.join(STORE_DIR, 'daemon-child.pid');
282
+ if (existsSync(childPidFile)) {
283
+ try {
284
+ const raw = readFileSync(childPidFile, 'utf8').trim();
285
+ const childPid = Number(raw);
286
+ if (Number.isFinite(childPid) && childPid > 0) {
287
+ let childAlive = false;
288
+ try {
289
+ process.kill(childPid, 0);
290
+ childAlive = true;
291
+ }
292
+ catch { }
293
+ if (childAlive) {
294
+ const childUptime = getProcessUptime(childPid);
295
+ lines.push(` Child: app.js (PID ${childPid}, uptime ${childUptime})`);
296
+ }
297
+ else {
298
+ lines.push(` Child: none (stale PID ${childPid} — daemon will restart)`);
299
+ }
300
+ }
301
+ }
302
+ catch { }
303
+ }
304
+ if (!lines.some(l => l.startsWith(' Child:'))) {
305
+ lines.push(' Child: starting...');
306
+ }
307
+ return { exitCode: 0, stdout: lines.join('\n') + '\n', stderr: '' };
308
+ }
309
+ // ─── Daemon restart ────────────────────────────────────────────────
310
+ function daemonRestartInternal() {
311
+ const pidFile = path.join(STORE_DIR, 'daemon.pid');
312
+ if (!existsSync(pidFile)) {
313
+ return { exitCode: 1, stdout: '', stderr: 'Cortex daemon is not running. Nothing to restart.\n' };
314
+ }
315
+ let pid;
316
+ try {
317
+ const raw = readFileSync(pidFile, 'utf8').trim();
318
+ pid = Number(raw);
319
+ if (!Number.isFinite(pid) || pid <= 0) {
320
+ return { exitCode: 1, stdout: '', stderr: 'Daemon PID file is corrupted. Is the daemon running?\n' };
321
+ }
322
+ }
323
+ catch (err) {
324
+ return { exitCode: 1, stdout: '', stderr: `Failed to read PID file: ${err.message}\n` };
325
+ }
326
+ let alive = false;
327
+ try {
328
+ process.kill(pid, 0);
329
+ alive = true;
330
+ }
331
+ catch {
332
+ alive = false;
333
+ }
334
+ if (!alive) {
335
+ try {
336
+ unlinkSync(pidFile);
337
+ }
338
+ catch { }
339
+ return { exitCode: 1, stdout: '', stderr: 'Cortex daemon is not running. Nothing to restart.\n' };
340
+ }
341
+ // Touch .restart trigger file for the daemon to pick up
342
+ const trigger = path.join(STORE_DIR, '.restart');
343
+ try {
344
+ mkdirSync(STORE_DIR, { recursive: true });
345
+ if (existsSync(trigger)) {
346
+ const now = new Date();
347
+ utimesSync(trigger, now, now);
348
+ }
349
+ else {
350
+ writeFileSync(trigger, '');
351
+ }
352
+ return { exitCode: 0, stdout: `Restart signal sent to daemon (PID ${pid}).\n`, stderr: '' };
353
+ }
354
+ catch (err) {
355
+ return { exitCode: 1, stdout: '', stderr: `Failed to signal daemon restart: ${err.message || String(err)}\n` };
356
+ }
357
+ }
358
+ // ─── Daemon hard restart (SIGTERM/SIGKILL directly to app.js) ─────
359
+ function daemonRestartHardInternal(force) {
360
+ const pidFile = path.join(STORE_DIR, 'daemon.pid');
361
+ // Verify daemon is running first
362
+ if (!existsSync(pidFile)) {
363
+ return { exitCode: 1, stdout: '', stderr: 'Cortex daemon is not running. Nothing to restart.\n' };
364
+ }
365
+ let daemonPid;
366
+ try {
367
+ const raw = readFileSync(pidFile, 'utf8').trim();
368
+ daemonPid = Number(raw);
369
+ if (!Number.isFinite(daemonPid) || daemonPid <= 0) {
370
+ return { exitCode: 1, stdout: '', stderr: 'Daemon PID file is corrupted.\n' };
371
+ }
372
+ }
373
+ catch (err) {
374
+ return { exitCode: 1, stdout: '', stderr: `Failed to read daemon PID file: ${err.message}\n` };
375
+ }
376
+ let daemonAlive = false;
377
+ try {
378
+ process.kill(daemonPid, 0);
379
+ daemonAlive = true;
380
+ }
381
+ catch { }
382
+ if (!daemonAlive) {
383
+ try {
384
+ unlinkSync(pidFile);
385
+ }
386
+ catch { }
387
+ return { exitCode: 1, stdout: '', stderr: 'Cortex daemon is not running.\n' };
388
+ }
389
+ // Read child PID
390
+ const childPidFile = path.join(STORE_DIR, 'daemon-child.pid');
391
+ if (!existsSync(childPidFile)) {
392
+ return { exitCode: 1, stdout: '', stderr: 'No child PID file found. Is app.js running?\n' };
393
+ }
394
+ let childPid;
395
+ try {
396
+ const raw = readFileSync(childPidFile, 'utf8').trim();
397
+ childPid = Number(raw);
398
+ if (!Number.isFinite(childPid) || childPid <= 0) {
399
+ return { exitCode: 1, stdout: '', stderr: 'Child PID file is corrupted.\n' };
400
+ }
401
+ }
402
+ catch (err) {
403
+ return { exitCode: 1, stdout: '', stderr: `Failed to read child PID file: ${err.message}\n` };
404
+ }
405
+ let childAlive = false;
406
+ try {
407
+ process.kill(childPid, 0);
408
+ childAlive = true;
409
+ }
410
+ catch { }
411
+ if (!childAlive) {
412
+ return { exitCode: 1, stdout: '', stderr: `Child process (PID ${childPid}) is not running.\n` };
413
+ }
414
+ const signal = force ? 'SIGKILL' : 'SIGTERM';
415
+ try {
416
+ process.kill(childPid, signal);
417
+ }
418
+ catch (err) {
419
+ return { exitCode: 1, stdout: '', stderr: `Failed to send ${signal} to app.js (PID ${childPid}): ${err.message}\n` };
420
+ }
421
+ return { exitCode: 0, stdout: `Sent ${signal} to app.js (PID ${childPid}). Daemon will restart it automatically.\n`, stderr: '' };
422
+ }
89
423
  // ─── Config output ──────────────────────────────────────────────
90
424
  export function getConfigOutput() {
91
425
  const paths = {
@@ -194,8 +528,29 @@ export async function runCli(argv) {
194
528
  return result;
195
529
  }
196
530
  case 'start':
197
- case 'daemon':
198
- return { exitCode: 0, stdout: '', stderr: `'${cmd}' must be run from the main entry point, not imported.\nUse: node dist/entry/cli.js ${cmd}` };
531
+ return { exitCode: 0, stdout: '', stderr: `'start' must be run from the main entry point, not imported.\nUse: node dist/entry/cli.js start` };
532
+ case 'daemon': {
533
+ if (rest[0] === 'stop') {
534
+ return stopDaemonInternal();
535
+ }
536
+ if (rest[0] === 'status') {
537
+ return getDaemonStatusInternal();
538
+ }
539
+ if (rest[0] === 'restart') {
540
+ if (rest[1] === '--hard')
541
+ return daemonRestartHardInternal(false);
542
+ if (rest[1] === '--force')
543
+ return daemonRestartHardInternal(true);
544
+ return daemonRestartInternal();
545
+ }
546
+ if (rest.includes('--help') || rest.includes('-h')) {
547
+ return { exitCode: 0, stdout: getCliHelp(), stderr: '' };
548
+ }
549
+ if (rest.includes('--version') || rest.includes('-V')) {
550
+ return { exitCode: 0, stdout: `${CORTEX_VERSION}\n`, stderr: '' };
551
+ }
552
+ return { exitCode: 0, stdout: '', stderr: `'daemon' must be run from the main entry point, not imported.\nUse: node dist/entry/cli.js daemon` };
553
+ }
199
554
  default:
200
555
  return { exitCode: 1, stdout: '', stderr: `Unknown command: '${cmd}'. Use --help to see available commands.` };
201
556
  }
@@ -221,6 +576,13 @@ function main() {
221
576
  }
222
577
  // Other subcommands (init, task, config, setup-gateway) handle --help internally via runCli()
223
578
  }
579
+ // Handle --version / -V for subcommands
580
+ if (rest.includes('--version') || rest.includes('-V')) {
581
+ if (cmd === 'daemon') {
582
+ console.log(CORTEX_VERSION);
583
+ process.exit(0);
584
+ }
585
+ }
224
586
  // ── Subcommands that replace the process (fork + wait) ──
225
587
  if (cmd === 'start') {
226
588
  if (!existsSync(APP_JS)) {
@@ -237,6 +599,40 @@ function main() {
237
599
  return; // let the event loop keep the process alive
238
600
  }
239
601
  if (cmd === 'daemon') {
602
+ // restart-self: stop the running daemon, wait, then re-fork
603
+ if (rest[0] === 'restart-self') {
604
+ runCli(['daemon', 'stop']).then(async (stopResult) => {
605
+ if (stopResult.stdout)
606
+ console.log(stopResult.stdout);
607
+ if (stopResult.stderr)
608
+ console.error(stopResult.stderr);
609
+ if (!existsSync(DAEMON_JS)) {
610
+ log.error(`Entry not found: ${DAEMON_JS}`);
611
+ log.error('Run `npm run build` first.');
612
+ process.exit(1);
613
+ }
614
+ console.log('Starting daemon...');
615
+ fork(DAEMON_JS, [], {
616
+ cwd: DATA_DIR,
617
+ detached: true,
618
+ stdio: 'ignore',
619
+ env: { ...process.env },
620
+ });
621
+ process.exit(0);
622
+ });
623
+ return;
624
+ }
625
+ // Subcommands that don't fork: stop, status, restart — delegate to runCli
626
+ if (rest[0] === 'stop' || rest[0] === 'status' || rest[0] === 'restart') {
627
+ runCli(args).then((result) => {
628
+ if (result.stdout)
629
+ console.log(result.stdout);
630
+ if (result.stderr)
631
+ console.error(result.stderr);
632
+ process.exit(result.exitCode);
633
+ });
634
+ return;
635
+ }
240
636
  if (!existsSync(DAEMON_JS)) {
241
637
  log.error(`Entry not found: ${DAEMON_JS}`);
242
638
  log.error('Run `npm run build` first.');
@@ -49,6 +49,7 @@ const log = createLogger('daemon');
49
49
  // --- Paths ---
50
50
  const MODULE_DIR = moduleDir(import.meta.url);
51
51
  const PID_FILE = path.join(STORE_DIR, 'daemon.pid');
52
+ const CHILD_PID_FILE = path.join(STORE_DIR, 'daemon-child.pid');
52
53
  // --- Config ---
53
54
  const APP_ENTRY = path.join(MODULE_DIR, 'app.js');
54
55
  const RESTART_TRIGGER = path.join(STORE_DIR, '.restart');
@@ -127,6 +128,11 @@ function startChild() {
127
128
  child = fork(APP_ENTRY, [], buildChildProcessConfig(reasonForChild));
128
129
  // Daemon only logs its own messages; app.ts handles its own output independently.
129
130
  log.info(`app.ts started — PID ${child.pid}`);
131
+ // Persist child PID so CLI (daemon status / daemon restart --hard) can find it
132
+ try {
133
+ writeFileSync(CHILD_PID_FILE, String(child.pid), 'utf8');
134
+ }
135
+ catch { }
130
136
  // IPC: app.ts tells us when it's busy/idle
131
137
  child.on('message', (msg) => {
132
138
  if (msg?.type === 'busy') {
@@ -156,6 +162,12 @@ function startChild() {
156
162
  child.on('exit', (code, signal) => {
157
163
  child = null;
158
164
  childBusy = false;
165
+ // Clean up child PID file
166
+ try {
167
+ if (existsSync(CHILD_PID_FILE))
168
+ unlinkSync(CHILD_PID_FILE);
169
+ }
170
+ catch { }
159
171
  if (shuttingDown) {
160
172
  log.info('app.ts exited (shutdown).');
161
173
  return;
@@ -500,6 +512,11 @@ function releaseSingletonLock() {
500
512
  unlinkSync(PID_FILE);
501
513
  }
502
514
  catch { }
515
+ try {
516
+ if (existsSync(CHILD_PID_FILE))
517
+ unlinkSync(CHILD_PID_FILE);
518
+ }
519
+ catch { }
503
520
  }
504
521
  function main() {
505
522
  // Recursion guard: if log.error() itself throws (e.g. EPIPE on a broken stderr),
@@ -2,10 +2,11 @@
2
2
  // output: buildStartupMessage + sendStartupDmIfConfigured
3
3
  // pos: send DM notification to admin channel during startup
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { CORTEX_VERSION } from '../core/version.js';
5
6
  function buildStartupMessage({ machine, restartReason }) {
6
7
  const machineLabel = machine || 'unknown-machine';
7
8
  const verb = restartReason ? 'restarted' : 'started';
8
- const base = `Cortex agent ${verb} on ${machineLabel}.`;
9
+ const base = `Cortex agent v${CORTEX_VERSION} ${verb} on ${machineLabel}.`;
9
10
  return restartReason ? `${base} Reason: ${restartReason}.` : base;
10
11
  }
11
12
  async function sendStartupDmIfConfigured(adapter, { machine, restartReason } = {}) {
@@ -22,6 +22,7 @@ import { createLogger } from '../../core/log.js';
22
22
  let _adapter = null;
23
23
  let _bus = null;
24
24
  const log = createLogger('cancel-button');
25
+ const askLog = createLogger('ask-user-question-modal');
25
26
  /** Called once from app.ts during startup, after EventBus is constructed. */
26
27
  export function initInteractionHandlers(bus) {
27
28
  _bus = bus;
@@ -52,24 +53,44 @@ async function handleOpenModal(ctx) {
52
53
  await _adapter.openModal(ctx.triggerId, askUserQuestion.buildQuestionModalDefinition(group));
53
54
  }
54
55
  async function handleModalSubmit(ctx) {
55
- if (!_adapter)
56
+ if (!_adapter) {
57
+ askLog.error('handleModalSubmit: _adapter is null');
56
58
  return;
57
- const { groupId } = JSON.parse(ctx.privateMetadata);
59
+ }
60
+ let groupId;
61
+ try {
62
+ const meta = JSON.parse(ctx.privateMetadata || '{}');
63
+ groupId = meta.groupId;
64
+ }
65
+ catch {
66
+ askLog.error('handleModalSubmit: failed to parse privateMetadata', { privateMetadata: ctx.privateMetadata });
67
+ await ctx.ack();
68
+ return;
69
+ }
70
+ if (!groupId) {
71
+ askLog.error('handleModalSubmit: privateMetadata missing groupId', { privateMetadata: ctx.privateMetadata });
72
+ await ctx.ack();
73
+ return;
74
+ }
58
75
  const group = askUserQuestion.getGroup(groupId);
59
76
  if (!group) {
77
+ askLog.warn('handleModalSubmit: group not found (may have expired)', { groupId });
60
78
  await ctx.ack();
61
79
  return;
62
80
  }
63
81
  const answers = collectModalAnswers(group, ctx.values);
64
82
  if (answers.errors) {
83
+ askLog.info('handleModalSubmit: validation errors', { groupId, errors: answers.errors });
65
84
  await ctx.ack({ errors: answers.errors });
66
85
  return;
67
86
  }
68
87
  await ctx.ack();
88
+ askLog.info('handleModalSubmit: answers collected', { groupId, totalQuestions: group.questions.length });
69
89
  for (const [pendingId, answer] of answers.collected)
70
90
  group.answers.set(pendingId, answer);
71
91
  await updateQuestionMessage(group);
72
92
  if (group.answers.size === group.questions.length) {
93
+ askLog.info('handleModalSubmit: all questions answered, resolving', { groupId });
73
94
  const g = group;
74
95
  _bus?.publish({ type: 'ask-user.answered', channel: g.channel, requestId: g.hookRequestId, sessionId: g.sessionId, answer: askUserQuestion.formatGroupResponse(group) });
75
96
  const resolved = askUserQuestion.tryResolveHook(group);
@@ -69,12 +69,17 @@ export function createSlackUpdatePrompt(adapter, router, opts) {
69
69
  }
70
70
  // Stamp version onto buttons
71
71
  const versionedButtons = buttonTemplates.map(b => ({ ...b, value: spec.latestVersion }));
72
- // Post interactive message to admin DM
72
+ // Post interactive message to admin DM.
73
+ // Convention: richBlocks contains content-only sections; buttons go in the
74
+ // top-level `actions` field. The Slack adapter's postInteractive
75
+ // (adapters/slack.ts:434-440) appends an actions block from content.actions,
76
+ // so embedding another actions block inside richBlocks would duplicate the
77
+ // button row. Pattern follows buildPlanApprovalContent
78
+ // (platform/interactive-builder.ts:117-127).
73
79
  const messageRef = await adapter.postInteractive({ type: 'system-notice' }, {
74
80
  text: `Cortex Server v${spec.latestVersion} is available. Update now?`,
75
81
  richBlocks: [
76
82
  { type: 'section', text: `Cortex Server v${spec.latestVersion} is available.` },
77
- { type: 'actions', elements: versionedButtons },
78
83
  ],
79
84
  actions: versionedButtons,
80
85
  });
@@ -182,23 +182,28 @@ export class SlackAdapter {
182
182
  onModalSubmit(callbackId, handler) {
183
183
  this.app.view(callbackId, async ({ ack, body, view }) => {
184
184
  let ackCalled = false;
185
- await handler({
186
- callbackId,
187
- privateMetadata: view.private_metadata || '',
188
- values: this.normalizeModalValues(view.state?.values || {}),
189
- userId: body.user?.id || '',
190
- async ack(response) {
191
- if (ackCalled)
192
- return;
193
- ackCalled = true;
194
- if (response?.errors) {
195
- await ack({ response_action: 'errors', errors: response.errors });
196
- }
197
- else {
198
- await ack();
199
- }
200
- },
201
- });
185
+ try {
186
+ await handler({
187
+ callbackId,
188
+ privateMetadata: view.private_metadata || '',
189
+ values: this.normalizeModalValues(view.state?.values || {}),
190
+ userId: body.user?.id || '',
191
+ async ack(response) {
192
+ if (ackCalled)
193
+ return;
194
+ ackCalled = true;
195
+ if (response?.errors) {
196
+ await ack({ response_action: 'errors', errors: response.errors });
197
+ }
198
+ else {
199
+ await ack();
200
+ }
201
+ },
202
+ });
203
+ }
204
+ catch (err) {
205
+ log.error(`Modal submit handler crashed for callbackId=${callbackId}: ${err?.message || err}`, err?.stack);
206
+ }
202
207
  if (!ackCalled)
203
208
  await ack();
204
209
  });
@@ -16,9 +16,14 @@ const log = createLogger('version-migrations');
16
16
  // String comparison fails on cross-digit boundaries (2026.5.9 vs 2026.5.23)
17
17
  // so we parse into numeric components and compare element-wise.
18
18
  // Returns negative if a < b, positive if a > b, 0 if equal.
19
+ /** Strip -N suffix from CalVer strings so that "2026.5.24-1" → "2026.5.24". */
20
+ function stripSuffix(v) {
21
+ const dash = v.indexOf('-');
22
+ return dash === -1 ? v : v.slice(0, dash);
23
+ }
19
24
  export function compareCalVer(a, b) {
20
- const [aYear, aMonth, aDay] = a.split('.').map(Number);
21
- const [bYear, bMonth, bDay] = b.split('.').map(Number);
25
+ const [aYear, aMonth, aDay] = stripSuffix(a).split('.').map(Number);
26
+ const [bYear, bMonth, bDay] = stripSuffix(b).split('.').map(Number);
22
27
  if (aYear !== bYear)
23
28
  return aYear - bYear;
24
29
  if (aMonth !== bMonth)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortex-agent/server",
3
- "version": "2026.5.24-1",
3
+ "version": "2026.5.25-1",
4
4
  "type": "module",
5
5
  "description": "Autonomous agent system for long-running projects — mission-driven, multi-agent pipelines, self-evolving skills.",
6
6
  "engines": {