@cortex-agent/server 2026.5.19-3 → 2026.5.22

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 (132) hide show
  1. package/README.md +5 -1
  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/log.js +61 -12
  7. package/dist/core/status-format.js +1 -1
  8. package/dist/core/task-parser.d.ts +1 -1
  9. package/dist/core/task-parser.js +13 -6
  10. package/dist/core/types/thread-types.d.ts +4 -2
  11. package/dist/domain/costs/codex-usage-monitor.d.ts +1 -2
  12. package/dist/domain/costs/codex-usage-monitor.js +2 -2
  13. package/dist/domain/costs/cost-tracker.d.ts +2 -0
  14. package/dist/domain/costs/cost-tracker.js +4 -20
  15. package/dist/domain/costs/rate-limit-throttle.js +1 -4
  16. package/dist/domain/mcp/tools/context.d.ts +4 -2
  17. package/dist/domain/mcp/tools/context.js +7 -5
  18. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  19. package/dist/domain/mcp/tools/schedule.js +24 -20
  20. package/dist/domain/memory/index-regen.js +8 -5
  21. package/dist/domain/monitor/disk-monitor.js +1 -6
  22. package/dist/domain/projects/index.d.ts +2 -0
  23. package/dist/domain/projects/index.js +3 -0
  24. package/dist/domain/projects/project-store.d.ts +54 -0
  25. package/dist/domain/projects/project-store.js +194 -0
  26. package/dist/domain/projects/project-types.d.ts +11 -0
  27. package/dist/domain/projects/project-types.js +5 -0
  28. package/dist/domain/remote/client-hot-reload.d.ts +1 -0
  29. package/dist/domain/remote/client-hot-reload.js +284 -53
  30. package/dist/domain/scheduling/jobs/_shared.d.ts +1 -1
  31. package/dist/domain/scheduling/jobs/_shared.js +6 -5
  32. package/dist/domain/scheduling/jobs/memory-index-regen.js +2 -2
  33. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +2 -2
  34. package/dist/domain/scheduling/jobs/scheduled-task.js +38 -36
  35. package/dist/domain/scheduling/jobs/sync-public.d.ts +1 -0
  36. package/dist/domain/scheduling/jobs/sync-public.js +34 -0
  37. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +3 -7
  38. package/dist/domain/scheduling/jobs/target-dispatch.js +7 -9
  39. package/dist/domain/scheduling/jobs/task-archive.js +2 -2
  40. package/dist/domain/scheduling/jobs/task-dispatch.js +18 -16
  41. package/dist/domain/scheduling/runner.d.ts +1 -0
  42. package/dist/domain/scheduling/runner.js +2 -0
  43. package/dist/domain/scheduling/schedule-cli.d.ts +1 -0
  44. package/dist/domain/scheduling/schedule-cli.js +14 -14
  45. package/dist/domain/scheduling/schedule-command.js +45 -36
  46. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  47. package/dist/domain/scheduling/scheduler.js +12 -11
  48. package/dist/domain/sessions/session-hooks.d.ts +10 -11
  49. package/dist/domain/sessions/session-hooks.js +26 -27
  50. package/dist/domain/sessions/session-registry.d.ts +10 -5
  51. package/dist/domain/sessions/session-registry.js +24 -9
  52. package/dist/domain/tasks/pending-tracker.js +8 -9
  53. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  54. package/dist/domain/tasks/system/task-cli.js +189 -29
  55. package/dist/domain/tasks/system/task-lifecycle-edit.js +3 -3
  56. package/dist/domain/threads/hook-runner.js +12 -7
  57. package/dist/domain/threads/runner.d.ts +3 -3
  58. package/dist/domain/threads/runner.js +30 -28
  59. package/dist/domain/threads/state-machine.d.ts +3 -0
  60. package/dist/domain/threads/state-machine.js +4 -0
  61. package/dist/entry/app.js +30 -9
  62. package/dist/entry/cli.js +19 -4
  63. package/dist/entry/daemon.js +28 -2
  64. package/dist/entry/startup-notify.js +8 -6
  65. package/dist/orchestration/agent-runner.js +19 -13
  66. package/dist/orchestration/durable-helpers.js +3 -2
  67. package/dist/orchestration/interactions/ask-user-question.d.ts +2 -3
  68. package/dist/orchestration/interactions/ask-user-question.js +5 -4
  69. package/dist/orchestration/interactions/interaction-handlers.js +8 -5
  70. package/dist/orchestration/interactions/plan-handler.js +3 -3
  71. package/dist/orchestration/lifecycle.js +43 -38
  72. package/dist/orchestration/routing/commands/cancel.js +9 -8
  73. package/dist/orchestration/routing/commands/channel.js +32 -26
  74. package/dist/orchestration/routing/commands/cost.js +5 -3
  75. package/dist/orchestration/routing/commands/device.js +2 -1
  76. package/dist/orchestration/routing/commands/dispatch.js +8 -7
  77. package/dist/orchestration/routing/commands/index.js +7 -4
  78. package/dist/orchestration/routing/commands/mode.js +24 -18
  79. package/dist/orchestration/routing/commands/nvtop.js +14 -12
  80. package/dist/orchestration/routing/commands/orient.js +2 -1
  81. package/dist/orchestration/routing/commands/schedule.js +2 -1
  82. package/dist/orchestration/routing/commands/sendfile.js +12 -9
  83. package/dist/orchestration/routing/commands/session.js +12 -10
  84. package/dist/orchestration/routing/commands/status.js +2 -2
  85. package/dist/orchestration/routing/commands/tail.js +10 -6
  86. package/dist/orchestration/routing/commands/task.js +5 -4
  87. package/dist/orchestration/routing/commands/thread-handlers.js +19 -12
  88. package/dist/orchestration/routing/hook-bridge-subscribers.js +15 -13
  89. package/dist/orchestration/status-helpers.d.ts +4 -5
  90. package/dist/orchestration/status-helpers.js +7 -8
  91. package/dist/orchestration/thread-executor.js +21 -12
  92. package/dist/platform/adapter.d.ts +13 -9
  93. package/dist/platform/adapter.js +1 -1
  94. package/dist/platform/adapters/feishu-output-stream.d.ts +27 -0
  95. package/dist/platform/adapters/feishu-output-stream.js +114 -0
  96. package/dist/platform/adapters/feishu.d.ts +16 -7
  97. package/dist/platform/adapters/feishu.js +64 -18
  98. package/dist/platform/adapters/index.d.ts +4 -1
  99. package/dist/platform/adapters/index.js +1 -1
  100. package/dist/platform/adapters/slack-output-stream.d.ts +55 -0
  101. package/dist/platform/{virtual-message.js → adapters/slack-output-stream.js} +98 -165
  102. package/dist/platform/adapters/slack-project-conduits.d.ts +9 -0
  103. package/dist/platform/adapters/slack-project-conduits.js +40 -0
  104. package/dist/platform/adapters/slack.d.ts +18 -8
  105. package/dist/platform/adapters/slack.js +82 -24
  106. package/dist/platform/index.d.ts +3 -2
  107. package/dist/platform/index.js +1 -1
  108. package/dist/platform/output-stream-chunk.d.ts +6 -0
  109. package/dist/platform/output-stream-chunk.js +45 -0
  110. package/dist/platform/output-stream-helpers.d.ts +6 -0
  111. package/dist/platform/output-stream-helpers.js +11 -0
  112. package/dist/platform/output-stream.d.ts +28 -0
  113. package/dist/platform/output-stream.js +4 -0
  114. package/dist/platform/testing.d.ts +41 -8
  115. package/dist/platform/testing.js +93 -11
  116. package/dist/platform/tool-trace.d.ts +9 -8
  117. package/dist/platform/tool-trace.js +19 -17
  118. package/dist/platform/types.d.ts +21 -1
  119. package/dist/platform/types.js +17 -1
  120. package/dist/store/channel-repo.d.ts +6 -0
  121. package/dist/store/channel-repo.js +9 -0
  122. package/dist/store/json-repository.js +12 -1
  123. package/dist/store/outbound-queue.d.ts +5 -4
  124. package/dist/store/outbound-queue.js +9 -6
  125. package/dist/store/schedule-repo.d.ts +9 -5
  126. package/dist/store/schedule-repo.js +59 -14
  127. package/dist/store/session-registry-repo.d.ts +36 -7
  128. package/dist/store/session-registry-repo.js +186 -25
  129. package/dist/store/thread-repo.d.ts +1 -0
  130. package/dist/store/thread-repo.js +8 -0
  131. package/package.json +1 -1
  132. package/dist/platform/virtual-message.d.ts +0 -68
@@ -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 });
@@ -8,9 +8,9 @@ register('memory-index-regen', async (payload) => {
8
8
  const { channel } = payload;
9
9
  try {
10
10
  const projects = runMemoryIndexRegen();
11
- await ctx.adapter.postMessage(channel, { text: `:brain: Memory index regen: ${projects.length} projects updated` });
11
+ await ctx.adapter.postMessage({ type: 'interactive-reply', conduit: channel }, { text: `:brain: Memory index regen: ${projects.length} projects updated` });
12
12
  }
13
13
  catch (err) {
14
- await ctx.adapter.postMessage(channel, { text: `:warning: Memory index regen error: ${err}` });
14
+ await ctx.adapter.postMessage({ type: 'interactive-reply', conduit: channel }, { text: `:warning: Memory index regen error: ${err}` });
15
15
  }
16
16
  });
@@ -1,11 +1,11 @@
1
1
  import type { ScheduleTarget, ScheduleTask } from '../../../store/schedule-repo.js';
2
2
  interface RunScheduledTaskInput {
3
3
  message: string;
4
- channel: string;
4
+ projectId: string;
5
5
  scheduleTaskId: string;
6
6
  profileName: string;
7
7
  target?: ScheduleTarget;
8
8
  fallback?: ScheduleTask['fallback'];
9
9
  }
10
- export declare function runScheduledTask({ message, channel, scheduleTaskId, profileName, target, fallback }: RunScheduledTaskInput): void;
10
+ export declare function runScheduledTask({ message, projectId, scheduleTaskId, profileName, target, fallback }: RunScheduledTaskInput): void;
11
11
  export {};
@@ -7,11 +7,10 @@ import { createLogger } from '../../../core/log.js';
7
7
  import * as executionRegistry from '../../executions/registry.js';
8
8
  const log = createLogger('scheduled-task');
9
9
  import * as pendingTaskTracker from '../../tasks/pending-tracker.js';
10
- import { sessionRegistryRepo } from '../../../store/session-registry-repo.js';
11
- import { sessionRepo } from '../../../store/session-repo.js';
10
+ import { sessionStore } from '../../../store/session-registry-repo.js';
12
11
  import { threadStore } from '../../../store/thread-repo.js';
13
- import { getActiveProfile, getActiveBackend, getDefaultAgent } from '../../agents/index.js';
14
- import { detectProject } from '../../costs/cost-tracker.js';
12
+ import { getActiveProfile, getDefaultAgent } from '../../agents/index.js';
13
+ import { projectStore } from '../../projects/index.js';
15
14
  import { normalizeSkillCommandPrefix } from '../../memory/skill-scanner.js';
16
15
  import { isValidDispatchPrompt, hasRunningExecutionForSchedule } from '../../tasks/dispatcher.js';
17
16
  import { allConfigsRateLimited } from '../../agents/facade.js';
@@ -38,8 +37,8 @@ function passScheduledGuards(schedKey, scheduleTaskId) {
38
37
  }
39
38
  return true;
40
39
  }
41
- export function runScheduledTask({ message, channel, scheduleTaskId, profileName, target, fallback }) {
42
- const schedKey = `sched:${scheduleTaskId || channel}`;
40
+ export function runScheduledTask({ message, projectId, scheduleTaskId, profileName, target, fallback }) {
41
+ const schedKey = `sched:${scheduleTaskId || projectId}`;
43
42
  if (!passScheduledGuards(schedKey, scheduleTaskId))
44
43
  return;
45
44
  const normalizedMessage = normalizeSkillCommandPrefix(message);
@@ -47,7 +46,7 @@ export function runScheduledTask({ message, channel, scheduleTaskId, profileName
47
46
  log.info('Auto-prefixed skill command:', normalizedMessage.substring(0, 80));
48
47
  }
49
48
  if (!isValidDispatchPrompt(normalizedMessage)) {
50
- log.warn(`Guard dropped null/empty prompt for schedule ${scheduleTaskId} (channel=${channel}, profile=${profileName}): "${message?.substring(0, 60) || String(message)}"`);
49
+ log.warn(`Guard dropped null/empty prompt for schedule ${scheduleTaskId} (project=${projectId}, profile=${profileName}): "${message?.substring(0, 60) || String(message)}"`);
51
50
  return;
52
51
  }
53
52
  if (allConfigsRateLimited(profileName)) {
@@ -56,57 +55,57 @@ export function runScheduledTask({ message, channel, scheduleTaskId, profileName
56
55
  }
57
56
  scheduledTaskActive.set(schedKey, true);
58
57
  ctx.bus.publish({ type: 'llm.active-count-delta', delta: 1 });
59
- runScheduledTaskAsync({ normalizedMessage, message, channel, scheduleTaskId, profileName, target, fallback }).finally(() => {
58
+ runScheduledTaskAsync({ normalizedMessage, message, projectId, scheduleTaskId, profileName, target, fallback }).finally(() => {
60
59
  scheduledTaskActive.delete(schedKey);
61
60
  ctx.bus.publish({ type: 'llm.active-count-delta', delta: -1 });
62
61
  });
63
62
  }
64
63
  // --- Plan resolution ---
65
- async function resolveDispatchPlan(channel, target, fallback) {
66
- const backend = getActiveBackend();
67
- return planScheduledDispatch({
64
+ async function resolveDispatchPlan(projectId, target, fallback) {
65
+ const plan = await planScheduledDispatch({
68
66
  target,
69
67
  fallback,
70
- fallbackChannel: channel,
68
+ fallbackChannel: projectId,
71
69
  lookups: {
72
- findActiveThread: (ch) => threadStore.findActive(ch),
73
- getChannelSession: (ch) => sessionRepo.getSessionAsync(ch, backend),
74
- lookupSession: (name) => sessionRegistryRepo.lookupSession(name),
70
+ lookupSession: (name) => sessionStore.lookupSession(name),
75
71
  getThread: (id) => threadStore.get(id),
76
72
  },
77
73
  });
74
+ return plan;
78
75
  }
79
76
  // --- Async implementation ---
80
- async function runScheduledTaskAsync({ normalizedMessage, message, channel, scheduleTaskId, profileName, target, fallback }) {
77
+ async function runScheduledTaskAsync({ normalizedMessage, message, projectId, scheduleTaskId, profileName, target, fallback }) {
81
78
  const startTime = Date.now();
82
- const effectiveProfile = profileName || getActiveProfile(channel) || 'default';
83
- const sessionName = await sessionRegistryRepo.generateSessionName();
79
+ const plan = await resolveDispatchPlan(projectId, target, fallback);
80
+ // Build the project-report destination for all outbound messages from this scheduled run.
81
+ const projectReportDest = { type: 'project-report', projectId, trigger: 'scheduled', sessionId: '' };
82
+ const effectiveProfile = profileName || getActiveProfile(projectId) || 'default';
83
+ const sessionName = await sessionStore.generateSessionName();
84
84
  const adapter = ctx.adapter;
85
- const plan = await resolveDispatchPlan(channel, target, fallback);
86
85
  // Skip plans short-circuit before posting the processing status, so they don't pollute Slack.
87
86
  if (plan.kind === 'skip') {
88
87
  log.info(`Skipping schedule ${scheduleTaskId}: ${plan.reason}`);
89
88
  try {
90
- await adapter.postMessage(channel, { text: `:fast_forward: Scheduled task skipped — ${plan.reason}` });
89
+ await adapter.postMessage(projectReportDest, { text: `:fast_forward: Scheduled task skipped — ${plan.reason}` });
91
90
  }
92
91
  catch { }
93
92
  return;
94
93
  }
95
94
  let statusMsg = null;
96
95
  try {
97
- statusMsg = await adapter.postMessage(plan.channel, { text: buildUserProcessingMessage({ startTime, profileName: effectiveProfile, sessionName }) });
96
+ statusMsg = await adapter.postMessage(projectReportDest, { text: buildUserProcessingMessage({ startTime, profileName: effectiveProfile, sessionName }) });
98
97
  }
99
98
  catch (e) {
100
99
  log.error('Failed to post status message:', e.message);
101
100
  }
102
101
  try {
103
- const threadResult = await dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effectiveProfile, statusMsg, startTime, sessionName });
102
+ const threadResult = await dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effectiveProfile, statusMsg, startTime, sessionName, projectReportDest, projectId });
104
103
  const result = threadResult.lastAgentResult;
105
- await maybeNotifyCodexLowUsage({ adapter, channel: plan.channel, result });
104
+ await maybeNotifyCodexLowUsage({ adapter, result });
106
105
  if (result?.rateLimited) {
107
106
  const { elapsedStr } = computeElapsed(startTime);
108
107
  if (statusMsg) {
109
- const text = `:warning: ${buildSessionTag(sessionName, result?.sessionId)}Rate limited — all fallbacks exhausted (${elapsedStr}s)`;
108
+ const text = `:warning: ${buildSessionTag(sessionName, result?.sessionId)}Rate limited — all fallbacks exhausted (${elapsedStr})`;
110
109
  const queue = getOutboundQueue();
111
110
  if (queue) {
112
111
  await durableUpdate(queue, adapter, statusMsg, { text });
@@ -117,8 +116,8 @@ async function runScheduledTaskAsync({ normalizedMessage, message, channel, sche
117
116
  }
118
117
  }
119
118
  else {
120
- await finalizeThreadSuccess(adapter, plan.channel, statusMsg, {
121
- startTime, sessionName, result, threadResult, project: detectProject(message), trigger: 'scheduled',
119
+ await finalizeThreadSuccess(adapter, projectId, statusMsg, {
120
+ startTime, sessionName, result, threadResult, project: projectId, trigger: 'scheduled',
122
121
  label: message?.substring(0, 60) || null, sessionKind: 'scheduled', statusPrefix: 'Done',
123
122
  });
124
123
  }
@@ -127,7 +126,7 @@ async function runScheduledTaskAsync({ normalizedMessage, message, channel, sche
127
126
  const { elapsedStr } = computeElapsed(startTime);
128
127
  const queue = getOutboundQueue();
129
128
  if (statusMsg) {
130
- const text = `:x: ${buildSessionTag(sessionName, null)}Error (${elapsedStr}s)`;
129
+ const text = `:x: ${buildSessionTag(sessionName, null)}Error (${elapsedStr})`;
131
130
  if (queue) {
132
131
  await durableUpdate(queue, adapter, statusMsg, { text });
133
132
  }
@@ -137,21 +136,22 @@ async function runScheduledTaskAsync({ normalizedMessage, message, channel, sche
137
136
  }
138
137
  try {
139
138
  if (queue) {
140
- await durablePost(queue, adapter, plan.channel, { text: `Scheduled task error: ${error.message}` });
139
+ await durablePost(queue, adapter, projectReportDest, { text: `Scheduled task error: ${error.message}` });
141
140
  }
142
141
  else {
143
- await adapter.postMessage(plan.channel, { text: `Scheduled task error: ${error.message}` });
142
+ await adapter.postMessage(projectReportDest, { text: `Scheduled task error: ${error.message}` });
144
143
  }
145
144
  }
146
145
  catch { }
147
146
  }
148
147
  }
149
- function dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effectiveProfile, statusMsg, startTime, sessionName }) {
150
- const project = detectProject(message);
151
- const onProgress = statusMsg ? buildProgressUpdater(ctx.adapter, plan.channel, statusMsg, startTime, effectiveProfile, sessionName) : undefined;
152
- const icb = ctx.buildInteractiveCallbacks?.(plan.channel, null);
148
+ function dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effectiveProfile, statusMsg, startTime, sessionName, projectReportDest, projectId }) {
149
+ const project = projectStore.resolveFromMessage(message)?.id ?? 'general';
150
+ const onProgress = statusMsg ? buildProgressUpdater(ctx.adapter, statusMsg, startTime, effectiveProfile, sessionName) : undefined;
151
+ const icb = ctx.buildInteractiveCallbacks?.(projectId, null);
153
152
  const baseRunOpts = {
154
- adapter: ctx.adapter, channel: plan.channel, threadTs: statusMsg?.messageId || null, statusMsg, startTime, onProgress,
153
+ adapter: ctx.adapter, channel: projectId, threadTs: statusMsg?.messageId || null, statusMsg, startTime, onProgress,
154
+ destination: projectReportDest,
155
155
  onToolUse: icb?.onToolUse ?? null, onPlanWritten: icb?.onPlanWritten ?? null, onAskUserQuestion: icb?.onAskUserQuestion ?? null,
156
156
  };
157
157
  if (plan.kind === 'continue-thread') {
@@ -164,10 +164,11 @@ function dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effe
164
164
  userMessage: normalizedMessage,
165
165
  userMessageTs: `sched_${Date.now()}`,
166
166
  platformThreadId: statusMsg?.messageId || null,
167
+ projectId: project,
167
168
  });
168
169
  // Default-thread metadata is unused by createDefaultThread today, so attach trigger / scheduleTaskId
169
170
  // post-creation so executionRegistry rows still carry the schedule association.
170
- threadStore.set({ ...thread, metadata: { scheduleTaskId, trigger: 'scheduled', project, profileOverride: effectiveProfile } });
171
+ threadStore.set({ ...thread, metadata: { scheduleTaskId, trigger: 'scheduled', profileOverride: effectiveProfile } });
171
172
  return runThreadExec(thread.id, { ...baseRunOpts, existingSessionId: plan.existingSessionId });
172
173
  }
173
174
  // plan.kind === 'fresh' — original scheduled-task semantics: scheduler template, fresh session.
@@ -175,7 +176,8 @@ function dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effe
175
176
  templateName: 'scheduler',
176
177
  userMessage: normalizedMessage,
177
178
  userMessageTs: `sched_${Date.now()}`,
178
- metadata: { scheduleTaskId, trigger: 'scheduled', project, profileOverride: effectiveProfile },
179
+ projectId: project,
180
+ metadata: { scheduleTaskId, trigger: 'scheduled', profileOverride: effectiveProfile },
179
181
  });
180
182
  return runThreadExec(thread.id, { ...baseRunOpts, existingSessionId: null });
181
183
  }