@cortex-agent/server 2026.5.19 → 2026.5.22-2

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 (134) hide show
  1. package/README.md +188 -0
  2. package/defaults/config/thread-templates.json +65 -39
  3. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +4 -4
  4. package/defaults/prompts/directives/coder-reviewer.md +9 -4
  5. package/defaults/prompts/directives/coder.md +10 -2
  6. package/dist/core/gateway-generator.js +26 -4
  7. package/dist/core/log.js +61 -12
  8. package/dist/core/profile-generator.js +4 -3
  9. package/dist/core/status-format.js +1 -1
  10. package/dist/core/task-parser.d.ts +1 -1
  11. package/dist/core/task-parser.js +13 -6
  12. package/dist/core/types/thread-types.d.ts +4 -2
  13. package/dist/domain/costs/codex-usage-monitor.d.ts +1 -2
  14. package/dist/domain/costs/codex-usage-monitor.js +2 -2
  15. package/dist/domain/costs/cost-tracker.d.ts +2 -0
  16. package/dist/domain/costs/cost-tracker.js +4 -20
  17. package/dist/domain/costs/rate-limit-throttle.js +1 -4
  18. package/dist/domain/mcp/tools/context.d.ts +4 -2
  19. package/dist/domain/mcp/tools/context.js +7 -5
  20. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  21. package/dist/domain/mcp/tools/schedule.js +24 -20
  22. package/dist/domain/memory/index-regen.js +8 -5
  23. package/dist/domain/monitor/disk-monitor.js +1 -6
  24. package/dist/domain/projects/index.d.ts +2 -0
  25. package/dist/domain/projects/index.js +3 -0
  26. package/dist/domain/projects/project-store.d.ts +54 -0
  27. package/dist/domain/projects/project-store.js +194 -0
  28. package/dist/domain/projects/project-types.d.ts +11 -0
  29. package/dist/domain/projects/project-types.js +5 -0
  30. package/dist/domain/remote/client-hot-reload.d.ts +1 -0
  31. package/dist/domain/remote/client-hot-reload.js +284 -53
  32. package/dist/domain/scheduling/jobs/_shared.d.ts +1 -1
  33. package/dist/domain/scheduling/jobs/_shared.js +6 -5
  34. package/dist/domain/scheduling/jobs/memory-index-regen.js +2 -2
  35. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +2 -2
  36. package/dist/domain/scheduling/jobs/scheduled-task.js +38 -36
  37. package/dist/domain/scheduling/jobs/sync-public.d.ts +1 -0
  38. package/dist/domain/scheduling/jobs/sync-public.js +34 -0
  39. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +3 -7
  40. package/dist/domain/scheduling/jobs/target-dispatch.js +7 -9
  41. package/dist/domain/scheduling/jobs/task-archive.js +2 -2
  42. package/dist/domain/scheduling/jobs/task-dispatch.js +18 -16
  43. package/dist/domain/scheduling/runner.d.ts +1 -0
  44. package/dist/domain/scheduling/runner.js +2 -0
  45. package/dist/domain/scheduling/schedule-cli.d.ts +1 -0
  46. package/dist/domain/scheduling/schedule-cli.js +14 -14
  47. package/dist/domain/scheduling/schedule-command.js +45 -36
  48. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  49. package/dist/domain/scheduling/scheduler.js +12 -11
  50. package/dist/domain/sessions/session-hooks.d.ts +10 -11
  51. package/dist/domain/sessions/session-hooks.js +26 -27
  52. package/dist/domain/sessions/session-registry.d.ts +10 -5
  53. package/dist/domain/sessions/session-registry.js +24 -9
  54. package/dist/domain/tasks/pending-tracker.js +8 -9
  55. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  56. package/dist/domain/tasks/system/task-cli.js +189 -29
  57. package/dist/domain/tasks/system/task-lifecycle-edit.js +3 -3
  58. package/dist/domain/threads/hook-runner.js +12 -7
  59. package/dist/domain/threads/runner.d.ts +3 -3
  60. package/dist/domain/threads/runner.js +30 -28
  61. package/dist/domain/threads/state-machine.d.ts +3 -0
  62. package/dist/domain/threads/state-machine.js +4 -0
  63. package/dist/entry/app.js +30 -9
  64. package/dist/entry/cli.js +19 -4
  65. package/dist/entry/daemon.js +28 -2
  66. package/dist/entry/startup-notify.js +8 -6
  67. package/dist/orchestration/agent-runner.js +19 -13
  68. package/dist/orchestration/durable-helpers.js +3 -2
  69. package/dist/orchestration/interactions/ask-user-question.d.ts +2 -3
  70. package/dist/orchestration/interactions/ask-user-question.js +5 -4
  71. package/dist/orchestration/interactions/interaction-handlers.js +8 -5
  72. package/dist/orchestration/interactions/plan-handler.js +3 -3
  73. package/dist/orchestration/lifecycle.js +43 -38
  74. package/dist/orchestration/routing/commands/cancel.js +9 -8
  75. package/dist/orchestration/routing/commands/channel.js +32 -26
  76. package/dist/orchestration/routing/commands/cost.js +5 -3
  77. package/dist/orchestration/routing/commands/device.js +2 -1
  78. package/dist/orchestration/routing/commands/dispatch.js +8 -7
  79. package/dist/orchestration/routing/commands/index.js +7 -4
  80. package/dist/orchestration/routing/commands/mode.js +24 -18
  81. package/dist/orchestration/routing/commands/nvtop.js +14 -12
  82. package/dist/orchestration/routing/commands/orient.js +2 -1
  83. package/dist/orchestration/routing/commands/schedule.js +2 -1
  84. package/dist/orchestration/routing/commands/sendfile.js +12 -9
  85. package/dist/orchestration/routing/commands/session.js +12 -10
  86. package/dist/orchestration/routing/commands/status.js +2 -2
  87. package/dist/orchestration/routing/commands/tail.js +10 -6
  88. package/dist/orchestration/routing/commands/task.js +5 -4
  89. package/dist/orchestration/routing/commands/thread-handlers.js +19 -12
  90. package/dist/orchestration/routing/hook-bridge-subscribers.js +15 -13
  91. package/dist/orchestration/status-helpers.d.ts +4 -5
  92. package/dist/orchestration/status-helpers.js +7 -8
  93. package/dist/orchestration/thread-executor.js +21 -12
  94. package/dist/platform/adapter.d.ts +13 -9
  95. package/dist/platform/adapter.js +1 -1
  96. package/dist/platform/adapters/feishu-output-stream.d.ts +27 -0
  97. package/dist/platform/adapters/feishu-output-stream.js +114 -0
  98. package/dist/platform/adapters/feishu.d.ts +16 -7
  99. package/dist/platform/adapters/feishu.js +64 -18
  100. package/dist/platform/adapters/index.d.ts +4 -1
  101. package/dist/platform/adapters/index.js +1 -1
  102. package/dist/platform/adapters/slack-output-stream.d.ts +55 -0
  103. package/dist/platform/{virtual-message.js → adapters/slack-output-stream.js} +98 -165
  104. package/dist/platform/adapters/slack-project-conduits.d.ts +9 -0
  105. package/dist/platform/adapters/slack-project-conduits.js +40 -0
  106. package/dist/platform/adapters/slack.d.ts +18 -8
  107. package/dist/platform/adapters/slack.js +82 -24
  108. package/dist/platform/index.d.ts +3 -2
  109. package/dist/platform/index.js +1 -1
  110. package/dist/platform/output-stream-chunk.d.ts +6 -0
  111. package/dist/platform/output-stream-chunk.js +45 -0
  112. package/dist/platform/output-stream-helpers.d.ts +6 -0
  113. package/dist/platform/output-stream-helpers.js +11 -0
  114. package/dist/platform/output-stream.d.ts +28 -0
  115. package/dist/platform/output-stream.js +4 -0
  116. package/dist/platform/testing.d.ts +41 -8
  117. package/dist/platform/testing.js +93 -11
  118. package/dist/platform/tool-trace.d.ts +9 -8
  119. package/dist/platform/tool-trace.js +19 -17
  120. package/dist/platform/types.d.ts +21 -1
  121. package/dist/platform/types.js +17 -1
  122. package/dist/store/channel-repo.d.ts +6 -0
  123. package/dist/store/channel-repo.js +9 -0
  124. package/dist/store/json-repository.js +12 -1
  125. package/dist/store/outbound-queue.d.ts +5 -4
  126. package/dist/store/outbound-queue.js +9 -6
  127. package/dist/store/schedule-repo.d.ts +9 -5
  128. package/dist/store/schedule-repo.js +59 -14
  129. package/dist/store/session-registry-repo.d.ts +36 -7
  130. package/dist/store/session-registry-repo.js +186 -25
  131. package/dist/store/thread-repo.d.ts +1 -0
  132. package/dist/store/thread-repo.js +8 -0
  133. package/package.json +15 -8
  134. package/dist/platform/virtual-message.d.ts +0 -68
@@ -0,0 +1,194 @@
1
+ // input: PROJECTS_DIR (from @core/paths.js or constructor arg)
2
+ // output: ProjectStore — list / get / exists / getDefault / resolveFromMessage / refresh
3
+ // + auto-scaffold of general/ project on first initialize()
4
+ // pos: Read-only project registry with fs.watch cache invalidation
5
+ // "general" is always synthesized; never persisted.
6
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
7
+ import * as fs from 'node:fs';
8
+ import * as path from 'node:path';
9
+ import { PROJECTS_DIR } from '../../core/paths.js';
10
+ import { createLogger } from '../../core/log.js';
11
+ const log = createLogger('project-store');
12
+ const DEBOUNCE_MS = 1000;
13
+ const GENERAL_SCAFFOLD_STATUS = `# general
14
+
15
+ Status: active
16
+
17
+ `;
18
+ const GENERAL_SCAFFOLD_CORTEX = `# general
19
+
20
+ Synthetic umbrella project — always present. Created automatically by the system.
21
+ `;
22
+ export class ProjectStore {
23
+ projectsDir;
24
+ watchEnabled;
25
+ projects = [];
26
+ initialized = false;
27
+ watcher = null;
28
+ debounceTimer = null;
29
+ constructor(opts = {}) {
30
+ this.projectsDir = opts.projectsDir ?? PROJECTS_DIR;
31
+ this.watchEnabled = opts.watchEnabled ?? true;
32
+ }
33
+ /**
34
+ * Scan PROJECTS_DIR, scaffold general if absent, build cache, start watcher.
35
+ * Idempotent — safe to call multiple times.
36
+ */
37
+ async initialize() {
38
+ if (this.initialized)
39
+ return;
40
+ this.scaffoldGeneral();
41
+ this.scan();
42
+ this.initialized = true;
43
+ if (this.watchEnabled) {
44
+ this.startWatcher();
45
+ }
46
+ log.info(`ProjectStore initialized: ${this.projects.length} projects (${this.projectsDir})`);
47
+ }
48
+ /** Return all known projects. Always includes "general". */
49
+ list() {
50
+ return [...this.projects];
51
+ }
52
+ /** Look up a project by id. Returns undefined for unknown ids. */
53
+ get(id) {
54
+ return this.projects.find((p) => p.id === id);
55
+ }
56
+ /** True if a project with the given id exists. */
57
+ exists(id) {
58
+ return this.projects.some((p) => p.id === id);
59
+ }
60
+ /** Return the "general" umbrella project. Always present. */
61
+ getDefault() {
62
+ // Guaranteed to exist after initialize()
63
+ return this.projects.find((p) => p.kind === 'general');
64
+ }
65
+ /**
66
+ * Resolve a project from a message string using heuristic patterns.
67
+ *
68
+ * Priority:
69
+ * 1. [project:xxx] explicit tag — always wins
70
+ * 2. Case-insensitive substring match against scanned project ids
71
+ * (longest match wins when multiple project names appear in the message)
72
+ * 3. 'general' fallback
73
+ *
74
+ * Returns the matching Project or the default general project.
75
+ */
76
+ resolveFromMessage(msg) {
77
+ if (!msg)
78
+ return this.getDefault();
79
+ // 1. [project:xxx] tag — always wins
80
+ const tagMatch = msg.match(/\[project:([^\]]+)\]/);
81
+ if (tagMatch)
82
+ return this.get(tagMatch[1]) ?? this.getDefault();
83
+ // 2. Case-insensitive substring match (longest project id wins)
84
+ const lower = msg.toLowerCase();
85
+ let bestMatch = null;
86
+ let bestLen = 0;
87
+ for (const project of this.projects) {
88
+ if (project.kind === 'general')
89
+ continue;
90
+ const lowerName = project.id.toLowerCase();
91
+ if (lower.includes(lowerName) && project.id.length > bestLen) {
92
+ bestMatch = project;
93
+ bestLen = project.id.length;
94
+ }
95
+ }
96
+ // 3. Fallback
97
+ return bestMatch ?? this.getDefault();
98
+ }
99
+ /** Force a rescan of PROJECTS_DIR (e.g. after watcher event or manual trigger). */
100
+ refresh() {
101
+ this.scan();
102
+ }
103
+ /** Stop the fs.watch watcher and release resources. */
104
+ destroy() {
105
+ if (this.debounceTimer) {
106
+ clearTimeout(this.debounceTimer);
107
+ this.debounceTimer = null;
108
+ }
109
+ if (this.watcher) {
110
+ this.watcher.close();
111
+ this.watcher = null;
112
+ }
113
+ this.initialized = false;
114
+ }
115
+ // ── Private ──────────────────────────────────────────────────
116
+ /** Create general/ scaffold if the directory does not exist. */
117
+ scaffoldGeneral() {
118
+ const generalDir = path.join(this.projectsDir, 'general');
119
+ if (fs.existsSync(generalDir))
120
+ return;
121
+ fs.mkdirSync(generalDir, { recursive: true });
122
+ fs.writeFileSync(path.join(generalDir, 'STATUS.md'), GENERAL_SCAFFOLD_STATUS, 'utf8');
123
+ fs.writeFileSync(path.join(generalDir, 'CORTEX.md'), GENERAL_SCAFFOLD_CORTEX, 'utf8');
124
+ log.info(`Scaffolded general project at ${generalDir}`);
125
+ }
126
+ /** Read PROJECTS_DIR and rebuild the in-memory cache. */
127
+ scan() {
128
+ const result = [];
129
+ // Always synthesize "general"
130
+ result.push(this.makeGeneralProject());
131
+ // Enumerate real project directories
132
+ try {
133
+ const entries = fs.readdirSync(this.projectsDir, { withFileTypes: true });
134
+ for (const entry of entries) {
135
+ if (!entry.isDirectory())
136
+ continue;
137
+ if (entry.name.startsWith('.'))
138
+ continue;
139
+ if (entry.name === 'general')
140
+ continue; // already added
141
+ result.push({
142
+ id: entry.name,
143
+ name: entry.name,
144
+ kind: 'user',
145
+ contextDir: path.join(this.projectsDir, entry.name),
146
+ });
147
+ }
148
+ }
149
+ catch {
150
+ // PROJECTS_DIR missing or unreadable — only "general" will be present
151
+ }
152
+ this.projects = result;
153
+ }
154
+ makeGeneralProject() {
155
+ return {
156
+ id: 'general',
157
+ name: 'general',
158
+ kind: 'general',
159
+ contextDir: path.join(this.projectsDir, 'general'),
160
+ };
161
+ }
162
+ /** Watch PROJECTS_DIR for add/remove of subdirectories. */
163
+ startWatcher() {
164
+ try {
165
+ this.watcher = fs.watch(this.projectsDir, (eventType, filename) => {
166
+ // On Linux 'rename' fires for create/delete; filter to directory-relevant events
167
+ if (!filename)
168
+ return;
169
+ // Ignore events for dotfiles and non-directory files (we can't easily check
170
+ // what type the changed entry is from the event alone, so we just debounce-scan)
171
+ if (filename.startsWith('.'))
172
+ return;
173
+ this.debouncedRescan();
174
+ });
175
+ this.watcher.on('error', (err) => {
176
+ log.error(`Watcher error for ${this.projectsDir}:`, err.message);
177
+ });
178
+ }
179
+ catch (err) {
180
+ log.error(`Failed to start watcher for ${this.projectsDir}:`, err);
181
+ }
182
+ }
183
+ debouncedRescan() {
184
+ if (this.debounceTimer)
185
+ clearTimeout(this.debounceTimer);
186
+ this.debounceTimer = setTimeout(() => {
187
+ this.debounceTimer = null;
188
+ this.scan();
189
+ log.debug(`Rescanned projects after directory change`);
190
+ }, DEBOUNCE_MS);
191
+ }
192
+ }
193
+ // --- Singleton ---
194
+ export const projectStore = new ProjectStore();
@@ -0,0 +1,11 @@
1
+ export interface Project {
2
+ /** Directory name under PROJECTS_DIR, e.g. "cortex-self". Also the canonical identifier. */
3
+ id: string;
4
+ /** Human-readable name. Same as `id` by default; may be refined later. */
5
+ name: string;
6
+ /** 'general' = synthetic umbrella project (always present, never persisted on disk).
7
+ * 'user' = real project directory under PROJECTS_DIR. */
8
+ kind: 'general' | 'user';
9
+ /** Absolute path to the project's directory under PROJECTS_DIR. */
10
+ contextDir: string;
11
+ }
@@ -0,0 +1,5 @@
1
+ // input: nothing (leaf module)
2
+ // output: Project — id, name, kind, contextDir
3
+ // pos: pure type definitions for the Project domain entity
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ export {};
@@ -7,6 +7,7 @@ interface DeviceResult {
7
7
  error?: string;
8
8
  }
9
9
  interface ClientUpdateResult {
10
+ mode: 'dev' | 'release';
10
11
  oldVersion: string | null;
11
12
  newVersion: string;
12
13
  devices: DeviceResult[];
@@ -1,32 +1,53 @@
1
- // Client hot-reload via npm update — replaces the old SCP-based approach.
2
- // On startup, checks all registered remote devices for outdated cortex-client
3
- // and runs `npm update -g cortex-client` + restart when needed.
1
+ // Client hot-reload — two modes:
2
+ // Dev mode (CORTEX_REPO set): build client from source, check tgz mtime,
3
+ // SCP to remotes + npm install -g + restart.
4
+ // Release mode (CORTEX_REPO unset): check npm registry vs remote installed
5
+ // version, npm update -g + restart.
4
6
  import * as fs from 'fs';
5
7
  import * as path from 'path';
6
- import { execSync } from 'child_process';
8
+ import { execSync, execFile } from 'child_process';
7
9
  import { getMachineRegistry } from '../tasks/dispatch-utils.js';
8
- import { sshExec, clientPids } from './client-manager.js';
10
+ import { sshExec, clientPids, buildRemoteSpawnCommand } from './client-manager.js';
9
11
  import { STORE_DIR } from '../../core/utils.js';
10
12
  import { createLogger } from '../../core/log.js';
11
13
  const log = createLogger('client-hot-reload');
12
14
  const VERSION_FILE = path.join(STORE_DIR, 'client-version.json');
13
- // --- Version helpers ---
14
- function getLocalClientVersion() {
15
+ // --- Mode detection ---
16
+ function isDevMode() {
17
+ const repo = process.env.CORTEX_REPO;
18
+ if (!repo)
19
+ return false;
15
20
  try {
16
- const result = execSync('npm ls -g cortex-client --json 2>/dev/null || true', { encoding: 'utf8', timeout: 10000 });
21
+ return fs.existsSync(repo) && fs.statSync(repo).isDirectory();
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ function resolveClientRepo() {
28
+ // Explicit override
29
+ if (process.env.CORTEX_CLIENT_REPO) {
30
+ const p = process.env.CORTEX_CLIENT_REPO;
17
31
  try {
18
- const parsed = JSON.parse(result);
19
- return parsed?.dependencies?.['cortex-client']?.version || null;
20
- }
21
- catch {
22
- return null;
32
+ if (fs.existsSync(p) && fs.statSync(p).isDirectory())
33
+ return p;
23
34
  }
35
+ catch { }
24
36
  }
25
- catch {
37
+ // Derive from CORTEX_REPO (sibling directory)
38
+ const repo = process.env.CORTEX_REPO;
39
+ if (!repo)
26
40
  return null;
41
+ const clientPath = path.resolve(repo, '..', 'client');
42
+ try {
43
+ if (fs.existsSync(clientPath) && fs.statSync(clientPath).isDirectory())
44
+ return clientPath;
27
45
  }
46
+ catch { }
47
+ return null;
28
48
  }
29
- function loadStoredVersion() {
49
+ // --- Version state persistence ---
50
+ function loadStoredState() {
30
51
  try {
31
52
  return JSON.parse(fs.readFileSync(VERSION_FILE, 'utf8'));
32
53
  }
@@ -34,9 +55,105 @@ function loadStoredVersion() {
34
55
  return null;
35
56
  }
36
57
  }
37
- function saveVersion(ver) {
58
+ function saveDevState(mtime, tgzPath) {
38
59
  fs.mkdirSync(STORE_DIR, { recursive: true });
39
- fs.writeFileSync(VERSION_FILE, JSON.stringify({ version: ver, updatedAt: new Date().toISOString() }, null, 2));
60
+ fs.writeFileSync(VERSION_FILE, JSON.stringify({
61
+ mode: 'dev',
62
+ dev: { mtime, tgzPath },
63
+ updatedAt: new Date().toISOString(),
64
+ }, null, 2));
65
+ }
66
+ function saveReleaseState(version) {
67
+ fs.mkdirSync(STORE_DIR, { recursive: true });
68
+ fs.writeFileSync(VERSION_FILE, JSON.stringify({
69
+ mode: 'release',
70
+ release: { version },
71
+ updatedAt: new Date().toISOString(),
72
+ }, null, 2));
73
+ }
74
+ // --- Dev mode: client build ---
75
+ function buildClient(repoPath) {
76
+ try {
77
+ log.info(`Building client in ${repoPath}...`);
78
+ // Step 1: build
79
+ const buildStart = Date.now();
80
+ execSync('npm run build', { cwd: repoPath, encoding: 'utf8', timeout: 120000, stdio: 'pipe' });
81
+ log.info(` build: ${Date.now() - buildStart}ms`);
82
+ // Step 2: clean old tgz
83
+ try {
84
+ const oldTgzs = fs.readdirSync(repoPath).filter(f => f.startsWith('cortex-agent-client-') && f.endsWith('.tgz'));
85
+ for (const f of oldTgzs) {
86
+ fs.unlinkSync(path.join(repoPath, f));
87
+ }
88
+ }
89
+ catch { }
90
+ // Step 3: pack
91
+ const packStart = Date.now();
92
+ execSync('npm pack', { cwd: repoPath, encoding: 'utf8', timeout: 60000, stdio: 'pipe' });
93
+ log.info(` pack: ${Date.now() - packStart}ms`);
94
+ // Step 4: find the produced tgz
95
+ const candidates = fs.readdirSync(repoPath)
96
+ .filter(f => f.startsWith('cortex-agent-client-') && f.endsWith('.tgz'))
97
+ .map(f => ({ f, mtime: fs.statSync(path.join(repoPath, f)).mtimeMs }))
98
+ .sort((a, b) => b.mtime - a.mtime);
99
+ if (candidates.length === 0) {
100
+ log.error('Build succeeded but no cortex-agent-client-*.tgz found');
101
+ return null;
102
+ }
103
+ const tgzPath = path.join(repoPath, candidates[0].f);
104
+ log.info(`Client built: ${candidates[0].f} (mtime=${candidates[0].mtime})`);
105
+ return { tgzPath, mtime: candidates[0].mtime };
106
+ }
107
+ catch (err) {
108
+ log.error(`Client build failed: ${err.message}`);
109
+ return null;
110
+ }
111
+ }
112
+ // --- Dev mode: SCP to remote ---
113
+ function scpToRemote(host, localPath, remotePath, timeout = 60000) {
114
+ return new Promise((resolve, reject) => {
115
+ execFile('scp', [
116
+ '-o', 'ConnectTimeout=10',
117
+ '-o', 'StrictHostKeyChecking=no',
118
+ localPath,
119
+ `${host}:${remotePath}`,
120
+ ], { timeout }, (err, stdout, stderr) => {
121
+ if (err)
122
+ reject(new Error(`SCP error: ${err.message}\n${stderr}`));
123
+ else
124
+ resolve(stdout.trim());
125
+ });
126
+ });
127
+ }
128
+ // --- Release mode: npm registry helpers ---
129
+ function getNpmRegistryVersion() {
130
+ try {
131
+ const result = execSync('npm view @cortex-agent/client version 2>/dev/null || true', {
132
+ encoding: 'utf8',
133
+ timeout: 15000,
134
+ stdio: 'pipe',
135
+ }).trim();
136
+ return result || null;
137
+ }
138
+ catch {
139
+ return null;
140
+ }
141
+ }
142
+ async function getRemoteInstalledVersion(host) {
143
+ try {
144
+ const cmd = 'npm ls -g @cortex-agent/client --json 2>/dev/null || true';
145
+ const result = await sshExec(host, cmd, 15000);
146
+ try {
147
+ const parsed = JSON.parse(result);
148
+ return parsed?.dependencies?.['@cortex-agent/client']?.version || null;
149
+ }
150
+ catch {
151
+ return null;
152
+ }
153
+ }
154
+ catch {
155
+ return null;
156
+ }
40
157
  }
41
158
  // --- Per-device operations ---
42
159
  async function killClientOnDevice(device, reg) {
@@ -63,75 +180,189 @@ async function killClientOnDevice(device, reg) {
63
180
  return false;
64
181
  }
65
182
  }
66
- async function updateClientOnDevice(device, reg) {
183
+ async function restartClientOnDevice(device, reg) {
184
+ try {
185
+ if (reg.win) {
186
+ const wmiArg = 'cmd.exe /c cortex-client';
187
+ await sshExec(reg.ssh, `powershell -Command "(Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList '${wmiArg}').ProcessId"`, 30000);
188
+ }
189
+ else {
190
+ await sshExec(reg.ssh, buildRemoteSpawnCommand(reg), 30000);
191
+ }
192
+ return true;
193
+ }
194
+ catch (err) {
195
+ log.warn(`Failed to restart client on ${device}: ${err.message}`);
196
+ return false;
197
+ }
198
+ }
199
+ // --- Dev mode: full per-device update ---
200
+ async function updateClientDev(device, reg, tgzPath, tgzName) {
67
201
  const res = { device, updated: false, restarted: false };
202
+ if (!reg.ssh) {
203
+ res.error = 'Local client dev-update not supported (use npm install -g with tgz manually)';
204
+ return res;
205
+ }
68
206
  try {
69
- if (!reg.ssh) {
70
- // Local device: npm update + restart handled externally
71
- res.error = 'Local client update not yet supported (use npm update -g cortex-client manually)';
207
+ // 1. Kill existing client
208
+ await killClientOnDevice(device, reg);
209
+ // 2. SCP tgz to remote
210
+ const remoteTmpPath = `/tmp/${tgzName}`;
211
+ log.info(` ${device}: SCP ${tgzName} → ${reg.ssh}:/tmp/`);
212
+ await scpToRemote(reg.ssh, tgzPath, remoteTmpPath, 60000);
213
+ // 3. Install from tgz
214
+ const installCmd = `npm install -g ${remoteTmpPath} 2>&1`;
215
+ const installOutput = await sshExec(reg.ssh, installCmd, 60000);
216
+ log.info(` ${device}: npm install -g output: ${installOutput.slice(0, 200)}`);
217
+ res.updated = true;
218
+ // 4. Clean up remote tgz
219
+ try {
220
+ await sshExec(reg.ssh, `rm -f ${remoteTmpPath}`, 10000);
221
+ }
222
+ catch { }
223
+ // 5. Restart client
224
+ res.restarted = await restartClientOnDevice(device, reg);
225
+ }
226
+ catch (err) {
227
+ res.error = err.message;
228
+ log.warn(` ${device}: dev update failed — ${res.error}`);
229
+ }
230
+ return res;
231
+ }
232
+ // --- Release mode: full per-device update ---
233
+ async function updateClientRelease(device, reg, latestVersion) {
234
+ const res = { device, updated: false, restarted: false, oldVersion: '?', newVersion: latestVersion };
235
+ if (!reg.ssh) {
236
+ res.error = 'Local client update not yet supported (use npm update -g @cortex-agent/client manually)';
237
+ return res;
238
+ }
239
+ try {
240
+ // 1. Check remote installed version
241
+ const remoteVer = await getRemoteInstalledVersion(reg.ssh);
242
+ res.oldVersion = remoteVer || '?';
243
+ if (remoteVer === latestVersion) {
244
+ log.info(` ${device}: already at latest (${latestVersion})`);
72
245
  return res;
73
246
  }
74
- // Kill existing client
247
+ // 2. Kill existing client
75
248
  await killClientOnDevice(device, reg);
76
- // npm update
77
- const updateCmd = 'npm update -g cortex-client 2>&1';
78
- const updateOutput = await sshExec(reg.ssh, updateCmd, 60000);
249
+ // 3. npm update
250
+ const updateOutput = await sshExec(reg.ssh, 'npm update -g @cortex-agent/client 2>&1', 60000);
79
251
  res.updated = true;
80
252
  log.info(` ${device}: npm update output: ${updateOutput.slice(0, 200)}`);
81
- // Restart (config file is managed by LLM, not rewritten here)
82
- if (reg.win) {
83
- const wmiArg = 'cortex-client';
84
- await sshExec(reg.ssh, `powershell -Command "(Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList '${wmiArg}').ProcessId"`, 30000);
85
- }
86
- else {
87
- await sshExec(reg.ssh, `nohup cortex-client > /dev/null 2>&1 & echo $!`, 30000);
88
- }
89
- res.restarted = true;
253
+ // 4. Restart client
254
+ res.restarted = await restartClientOnDevice(device, reg);
90
255
  }
91
256
  catch (err) {
92
257
  res.error = err.message;
93
- log.warn(` ${device}: update failed — ${res.error}`);
258
+ log.warn(` ${device}: release update failed — ${res.error}`);
94
259
  }
95
260
  return res;
96
261
  }
97
262
  // --- Main check-and-update ---
98
263
  async function checkAndUpdateClients() {
99
- const localVersion = getLocalClientVersion();
100
- const stored = loadStoredVersion();
101
- // First run: save version, skip update
102
- if (!stored) {
103
- const ver = localVersion || 'unknown';
104
- log.info(`First run — saving client version ${ver}, skipping update`);
105
- saveVersion(ver);
264
+ const dev = isDevMode();
265
+ const stored = loadStoredState();
266
+ const start = Date.now();
267
+ if (dev) {
268
+ return checkAndUpdateDev(stored, start);
269
+ }
270
+ else {
271
+ return checkAndUpdateRelease(stored, start);
272
+ }
273
+ }
274
+ async function checkAndUpdateDev(stored, start) {
275
+ const clientRepo = resolveClientRepo();
276
+ if (!clientRepo) {
277
+ log.warn('Dev mode: CORTEX_REPO is set but client repo not found — skipping update');
106
278
  return null;
107
279
  }
108
- // No local version info (cortex-client not installed locally)
109
- if (!localVersion) {
110
- log.info('cortex-client not found in local npm — skipping hot-reload');
280
+ // Build client from source
281
+ const built = buildClient(clientRepo);
282
+ if (!built) {
283
+ log.error('Dev mode: client build failed — skipping update');
111
284
  return null;
112
285
  }
113
- // No change
114
- if (stored.version === localVersion) {
286
+ const tgzName = path.basename(built.tgzPath);
287
+ // First run or mode change: save state, skip update
288
+ if (!stored || stored.mode !== 'dev') {
289
+ const label = !stored ? 'First run' : 'Mode changed to dev';
290
+ log.info(`Dev mode — ${label}: saving client mtime=${built.mtime}, skipping update`);
291
+ saveDevState(built.mtime, built.tgzPath);
115
292
  return null;
116
293
  }
117
- log.info(`cortex-client updated: ${stored.version} → ${localVersion}`);
118
- const start = Date.now();
294
+ // Compare mtime
295
+ const oldMtime = stored.dev?.mtime ?? 0;
296
+ if (built.mtime === oldMtime) {
297
+ log.info(`Dev mode: client tgz mtime unchanged (${built.mtime}) — skipping update`);
298
+ return null;
299
+ }
300
+ log.info(`Dev mode: client tgz changed — mtime ${oldMtime} → ${built.mtime}`);
301
+ const registry = getMachineRegistry();
302
+ const devices = await Promise.all(Object.entries(registry).map(async ([device, reg]) => {
303
+ return updateClientDev(device, reg, built.tgzPath, tgzName);
304
+ }));
305
+ const duration = Date.now() - start;
306
+ saveDevState(built.mtime, built.tgzPath);
307
+ for (const d of devices) {
308
+ const status = d.updated && d.restarted ? 'OK' : (d.error ? 'FAIL' : 'SKIP');
309
+ log.info(` ${d.device}: ${status}${d.error ? ` (${d.error})` : ''}`);
310
+ }
311
+ return {
312
+ mode: 'dev',
313
+ oldVersion: String(oldMtime),
314
+ newVersion: String(built.mtime),
315
+ devices,
316
+ duration,
317
+ };
318
+ }
319
+ async function checkAndUpdateRelease(stored, start) {
320
+ // Get latest version from npm registry
321
+ const latestVersion = getNpmRegistryVersion();
322
+ if (!latestVersion) {
323
+ log.warn('Release mode: could not fetch latest version from npm registry — skipping update');
324
+ return null;
325
+ }
326
+ // First run or mode change: save state, skip update
327
+ if (!stored || stored.mode !== 'release') {
328
+ const label = !stored ? 'First run' : 'Mode changed to release';
329
+ log.info(`Release mode — ${label}: saving version ${latestVersion}, skipping update`);
330
+ saveReleaseState(latestVersion);
331
+ return null;
332
+ }
333
+ // Compare versions
334
+ const oldVersion = stored.release?.version ?? '?';
335
+ if (oldVersion === latestVersion) {
336
+ log.info(`Release mode: version unchanged (${latestVersion}) — skipping update`);
337
+ return null;
338
+ }
339
+ log.info(`Release mode: new version available — ${oldVersion} → ${latestVersion}`);
119
340
  const registry = getMachineRegistry();
120
341
  const devices = await Promise.all(Object.entries(registry).map(async ([device, reg]) => {
121
- return updateClientOnDevice(device, reg);
342
+ return updateClientRelease(device, reg, latestVersion);
122
343
  }));
123
344
  const duration = Date.now() - start;
124
- saveVersion(localVersion);
345
+ saveReleaseState(latestVersion);
125
346
  for (const d of devices) {
126
347
  const status = d.updated && d.restarted ? 'OK' : (d.error ? 'FAIL' : 'SKIP');
127
348
  log.info(` ${d.device}: ${status}${d.error ? ` (${d.error})` : ''}`);
128
349
  }
129
- return { oldVersion: stored.version, newVersion: localVersion, devices, duration };
350
+ return {
351
+ mode: 'release',
352
+ oldVersion,
353
+ newVersion: latestVersion,
354
+ devices,
355
+ duration,
356
+ };
130
357
  }
131
358
  // --- Slack message formatting ---
132
359
  function formatUpdateSlackMessage(result) {
360
+ const modeLabel = result.mode === 'dev' ? '[dev]' : '[release]';
361
+ const versionLabel = result.mode === 'dev'
362
+ ? `mtime \`${result.oldVersion}\` → \`${result.newVersion}\``
363
+ : `\`${result.oldVersion}\` → \`${result.newVersion}\``;
133
364
  const lines = [
134
- `:arrows_counterclockwise: *Client hot-reload* \`${result.oldVersion}\` → \`${result.newVersion}\` (${(result.duration / 1000).toFixed(1)}s)`,
365
+ `:arrows_counterclockwise: *Client hot-reload ${modeLabel}* ${versionLabel} (${(result.duration / 1000).toFixed(1)}s)`,
135
366
  ];
136
367
  for (const d of result.devices) {
137
368
  const icon = d.updated && d.restarted ? ':white_check_mark:' : ':x:';
@@ -1,6 +1,6 @@
1
1
  import type { PlatformAdapter, MessageRef } from '../../../platform/index.js';
2
2
  import type { AgentResult } from '../../../core/types/agent-types.js';
3
- export declare function buildProgressUpdater(adapter: PlatformAdapter, channel: string, statusMsg: MessageRef, startTime: number, effectiveProfile: string, sessionName: string): (progress: Record<string, any> | null) => void;
3
+ export declare function buildProgressUpdater(adapter: PlatformAdapter, statusMsg: MessageRef, startTime: number, effectiveProfile: string, sessionName: string): (progress: Record<string, any> | null) => void;
4
4
  export declare function finalizeThreadSuccess(adapter: PlatformAdapter, channel: string, statusMsg: MessageRef | null, { startTime, sessionName, result, threadResult, project, trigger, label, sessionKind, statusPrefix }: {
5
5
  startTime: number;
6
6
  sessionName: string;
@@ -1,13 +1,13 @@
1
- // input: PlatformAdapter + sessionRegistryRepo + status-helpers
1
+ // input: PlatformAdapter + sessionStore + status-helpers
2
2
  // output: finalizeThreadSuccess + buildProgressUpdater
3
3
  // pos: shared helper functions used by both the scheduled-task and task-dispatch jobs
4
4
  import { buildSessionTag, buildUserProcessingMessage, computeElapsed, formatMetricsSuffix } from '../../../core/status-format.js';
5
5
  import { createLogger } from '../../../core/log.js';
6
- import { sessionRegistryRepo } from '../../../store/session-registry-repo.js';
6
+ import { sessionStore } from '../../../store/session-registry-repo.js';
7
7
  import { getOutboundQueue, durableUpdate } from '../../../store/outbound-queue.js';
8
8
  import { getActiveBackend, getActiveProfile } from '../../agents/index.js';
9
9
  const log = createLogger('scheduler');
10
- export function buildProgressUpdater(adapter, channel, statusMsg, startTime, effectiveProfile, sessionName) {
10
+ export function buildProgressUpdater(adapter, statusMsg, startTime, effectiveProfile, sessionName) {
11
11
  return (progress) => {
12
12
  adapter.updateMessage(statusMsg, {
13
13
  text: buildUserProcessingMessage({
@@ -24,16 +24,17 @@ export function buildProgressUpdater(adapter, channel, statusMsg, startTime, eff
24
24
  export async function finalizeThreadSuccess(adapter, channel, statusMsg, { startTime, sessionName, result, threadResult, project, trigger, label, sessionKind, statusPrefix }) {
25
25
  const { elapsedStr, elapsedS } = computeElapsed(startTime);
26
26
  if (result?.sessionId) {
27
- await sessionRegistryRepo.registerSession(sessionName, {
27
+ await sessionStore.registerSession(sessionName, {
28
28
  sessionId: result.sessionId, channel,
29
29
  backend: getActiveBackend(), kind: sessionKind,
30
30
  label,
31
31
  profileName: getActiveProfile(channel),
32
+ projectId: project,
32
33
  });
33
34
  }
34
35
  const metrics = formatMetricsSuffix({ costUsd: threadResult.totalCostUsd, numTurns: threadResult.totalNumTurns });
35
36
  if (statusMsg) {
36
- const text = `:white_check_mark: ${statusPrefix} | ${buildSessionTag(sessionName, result?.sessionId)}(${elapsedStr}s${metrics})`;
37
+ const text = `:white_check_mark: ${statusPrefix} | ${buildSessionTag(sessionName, result?.sessionId)}(${elapsedStr}${metrics})`;
37
38
  const queue = getOutboundQueue();
38
39
  if (queue) {
39
40
  await durableUpdate(queue, adapter, statusMsg, { text });