@cortex-agent/server 2026.9.21 → 2026.9.25

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 (139) hide show
  1. package/defaults/config/thread-templates/agents/creative.json +17 -0
  2. package/defaults/prompts/systemPrompts/creative.md +13 -0
  3. package/defaults/prompts/systemPrompts/direct.md +1 -1
  4. package/dist/agent-adapter/claude/adapter.d.ts +12 -0
  5. package/dist/agent-adapter/claude/adapter.js +19 -1
  6. package/dist/agent-adapter/claude/spawn-args.d.ts +7 -0
  7. package/dist/agent-adapter/claude/spawn-args.js +10 -0
  8. package/dist/agent-adapter/pi/child-runner.d.ts +4 -2
  9. package/dist/agent-adapter/pi/child-runner.js +5 -1
  10. package/dist/agent-adapter/pi/event-parser.d.ts +3 -2
  11. package/dist/agent-adapter/pi/event-parser.js +46 -2
  12. package/dist/agent-adapter/pi/extensions.d.ts +7 -1
  13. package/dist/agent-adapter/pi/extensions.js +10 -3
  14. package/dist/agent-adapter/pi/mcp-bridge.js +8 -8
  15. package/dist/agent-adapter/pi/pi-session.js +5 -0
  16. package/dist/agent-adapter/pi/runtime.js +3 -0
  17. package/dist/agent-adapter/pi/session-options.js +5 -1
  18. package/dist/agent-adapter/pi/subagent.d.ts +15 -3
  19. package/dist/agent-adapter/pi/subagent.js +18 -0
  20. package/dist/agent-adapter/pi/tool-shims.d.ts +6 -1
  21. package/dist/agent-adapter/pi/tool-shims.js +34 -1
  22. package/dist/agent-adapter/types.d.ts +5 -0
  23. package/dist/core/agents/subagent/types.d.ts +3 -0
  24. package/dist/core/config-generator.js +17 -2
  25. package/dist/core/debug-mode.d.ts +11 -10
  26. package/dist/core/debug-mode.js +12 -18
  27. package/dist/core/exec-async.d.ts +26 -0
  28. package/dist/core/exec-async.js +47 -0
  29. package/dist/core/locales/en.d.ts +14 -1
  30. package/dist/core/locales/slices/commands.d.ts +12 -1
  31. package/dist/core/locales/slices/commands.js +24 -2
  32. package/dist/core/locales/slices/startup.d.ts +2 -0
  33. package/dist/core/locales/slices/startup.js +4 -0
  34. package/dist/core/rebuild-progress.d.ts +58 -0
  35. package/dist/core/rebuild-progress.js +103 -0
  36. package/dist/core/resilient-watch.js +5 -3
  37. package/dist/core/run-registry.d.ts +7 -0
  38. package/dist/core/run-registry.js +6 -0
  39. package/dist/core/types/thread-types.d.ts +23 -4
  40. package/dist/domain/agents/agent-state.d.ts +7 -0
  41. package/dist/domain/agents/agent-state.js +9 -1
  42. package/dist/domain/agents/agent-switch.d.ts +38 -0
  43. package/dist/domain/agents/agent-switch.js +106 -0
  44. package/dist/domain/agents/config.d.ts +20 -2
  45. package/dist/domain/agents/config.js +58 -4
  46. package/dist/domain/agents/index.d.ts +1 -0
  47. package/dist/domain/agents/index.js +1 -0
  48. package/dist/domain/agents/profile-manager.d.ts +6 -0
  49. package/dist/domain/agents/profile-manager.js +14 -1
  50. package/dist/domain/executions/registry.d.ts +2 -0
  51. package/dist/domain/executions/registry.js +84 -7
  52. package/dist/domain/plugins/runtime.js +1 -1
  53. package/dist/domain/plugins/skill-projection.d.ts +8 -2
  54. package/dist/domain/plugins/skill-projection.js +76 -19
  55. package/dist/domain/remote/client-bootstrap.js +1 -1
  56. package/dist/domain/remote/client-hot-reload.d.ts +1 -1
  57. package/dist/domain/remote/client-hot-reload.js +27 -23
  58. package/dist/domain/runs/engine-spec.js +4 -0
  59. package/dist/domain/runs/request.d.ts +6 -0
  60. package/dist/domain/runs/run.js +1 -0
  61. package/dist/domain/runs/spec-loader.d.ts +4 -3
  62. package/dist/domain/runs/spec-loader.js +4 -3
  63. package/dist/domain/scheduling/jobs/sync-public.js +6 -6
  64. package/dist/domain/scheduling/scheduler.js +14 -12
  65. package/dist/domain/sessions/session-lifecycle.d.ts +5 -0
  66. package/dist/domain/sessions/session-lifecycle.js +13 -1
  67. package/dist/domain/system/rebuild-hold.d.ts +44 -0
  68. package/dist/domain/system/rebuild-hold.js +91 -0
  69. package/dist/domain/system/server-update-check.d.ts +2 -1
  70. package/dist/domain/system/server-update-check.js +15 -13
  71. package/dist/domain/tasks/archiver.js +21 -13
  72. package/dist/domain/tasks/mutator.js +60 -59
  73. package/dist/domain/tasks/system/task-completion.d.ts +7 -2
  74. package/dist/domain/tasks/system/task-completion.js +69 -6
  75. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -1
  76. package/dist/domain/tasks/system/task-lifecycle-edit.js +21 -2
  77. package/dist/domain/tasks/system/task-lock.d.ts +23 -0
  78. package/dist/domain/tasks/system/task-lock.js +29 -1
  79. package/dist/domain/tasks/system/task-mutations.d.ts +14 -1
  80. package/dist/domain/tasks/system/task-mutations.js +25 -2
  81. package/dist/domain/tasks/system/task-state.d.ts +12 -1
  82. package/dist/domain/tasks/system/task-state.js +19 -2
  83. package/dist/domain/threads/prompt-builder.d.ts +9 -6
  84. package/dist/domain/threads/prompt-builder.js +28 -10
  85. package/dist/domain/threads/runner.js +7 -3
  86. package/dist/domain/threads/state-machine.js +15 -11
  87. package/dist/domain/threads/template-loader.js +6 -4
  88. package/dist/domain/threads/template-validate.d.ts +43 -6
  89. package/dist/domain/threads/template-validate.js +12 -0
  90. package/dist/domain/ui-service/app-router.d.ts +10 -0
  91. package/dist/domain/ui-service/app-router.js +2 -1
  92. package/dist/domain/ui-service/input-schemas.d.ts +11 -0
  93. package/dist/domain/ui-service/input-schemas.js +11 -0
  94. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  95. package/dist/domain/ui-service/mutate/sessions.js +40 -0
  96. package/dist/domain/ui-service/mutate/tasks.js +4 -3
  97. package/dist/domain/ui-service/query/config.js +19 -1
  98. package/dist/domain/ui-service/query/memory.js +28 -34
  99. package/dist/domain/ui-service/query/sessions.js +89 -12
  100. package/dist/domain/ui-service/query/system.js +19 -0
  101. package/dist/domain/ui-service/query-input-schemas.d.ts +1 -0
  102. package/dist/domain/ui-service/query-input-schemas.js +2 -0
  103. package/dist/domain/ui-service/types.d.ts +97 -3
  104. package/dist/domain/ui-service/ui-service.js +2 -1
  105. package/dist/entry/app.js +23 -4
  106. package/dist/entry/daemon-notice.d.ts +10 -1
  107. package/dist/entry/daemon-notice.js +16 -1
  108. package/dist/entry/daemon.d.ts +43 -2
  109. package/dist/entry/daemon.js +163 -9
  110. package/dist/orchestration/agent-runner.js +16 -0
  111. package/dist/orchestration/conversation-request.d.ts +33 -0
  112. package/dist/orchestration/conversation-request.js +78 -16
  113. package/dist/orchestration/mid-turn-inject.d.ts +3 -0
  114. package/dist/orchestration/mid-turn-inject.js +9 -4
  115. package/dist/orchestration/resume-dispatcher.js +4 -2
  116. package/dist/orchestration/routing/commands/mode.js +114 -63
  117. package/dist/orchestration/thread-executor.js +13 -0
  118. package/dist/orchestration/turn/turn.js +1 -0
  119. package/dist/store/conversation-display-projection.d.ts +9 -1
  120. package/dist/store/conversation-display-projection.js +13 -6
  121. package/dist/store/conversation-history-reader.d.ts +19 -0
  122. package/dist/store/conversation-history-reader.js +163 -44
  123. package/dist/store/conversation-history-repo.d.ts +37 -10
  124. package/dist/store/conversation-history-repo.js +161 -139
  125. package/dist/store/session-registry-journal.d.ts +4 -0
  126. package/dist/store/session-registry-journal.js +4 -0
  127. package/dist/store/session-registry-repo.d.ts +2 -1
  128. package/dist/store/session-registry-repo.js +2 -0
  129. package/dist/store/task-repo.d.ts +6 -3
  130. package/dist/store/task-repo.js +26 -10
  131. package/package.json +2 -1
  132. package/web/dist/AGENTS.md +10 -0
  133. package/web/dist/assets/index-B1dBi8Za.css +1 -0
  134. package/web/dist/assets/{index-DZTuqUO4.js → index-BAeLybF0.js} +1 -1
  135. package/web/dist/assets/index-BcQI8Fh5.js +445 -0
  136. package/web/dist/index.html +12 -4
  137. package/web/dist/theme.css +211 -40
  138. package/web/dist/assets/index-CwwQNMpP.css +0 -1
  139. package/web/dist/assets/index-DLSfgq3o.js +0 -444
@@ -1,3 +1,13 @@
1
+ // input: validated portable skill directories
2
+ // output: snapshots, copies, and exact validators
3
+ // pos: Recursive portable skill projection helpers
4
+ //
5
+ // Change detection is stat-based on purpose: every projected file used to be read and sha256'd
6
+ // three times per spawn (build, copy, validate). The source-side guarantees — symlink containment,
7
+ // torn reads, "changed after validation" — hold on the identity of the inode (dev/ino) plus its
8
+ // stat signature (size, mtime, ctime, mode), which any content write or replacement moves. A
9
+ // materialized copy has its own inode and timestamps, so it is compared on path + byte length +
10
+ // mode + directory set. File bytes are never hashed.
1
11
  import { createHash } from 'node:crypto';
2
12
  import fs from 'node:fs';
3
13
  import path from 'node:path';
@@ -20,25 +30,44 @@ function assertSameFile(expected, actual, filePath) {
20
30
  throw new Error(`Skill file changed while being read: ${filePath}`);
21
31
  }
22
32
  }
23
- function readStableFile(root, filePath) {
33
+ /** Stable identity of a file without reading its bytes: any content write moves mtime/ctime,
34
+ * and any replacement moves the inode. */
35
+ function statSignature(stat) {
36
+ return `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.ino}:${stat.mode & 0o777}`;
37
+ }
38
+ const OPEN_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0);
39
+ /** Open a file through its realpath with O_NOFOLLOW and assert the inode did not change under us.
40
+ * Returns the open fd plus the validated stat — callers either stat it or read from it. */
41
+ function openStableFile(root, filePath) {
24
42
  const resolved = safeRealpath(root, filePath);
25
- const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0);
26
- const fd = fs.openSync(resolved, flags);
43
+ const fd = fs.openSync(resolved, OPEN_FLAGS);
27
44
  try {
28
45
  const opened = fs.fstatSync(fd);
29
46
  assertRegularFile(opened, resolved);
30
- assertSameFile(opened, fs.statSync(safeRealpath(root, filePath)), filePath);
31
- const bytes = fs.readFileSync(fd);
32
- assertSameFile(opened, fs.fstatSync(fd), filePath);
33
- return { bytes, mode: opened.mode & 0o777 };
47
+ // A symlink swapped in between realpath() and open() must be caught. lstat avoids a second
48
+ // realpath walk (the most expensive syscall here): for the regular file we expect, lstat and
49
+ // stat agree; a swapped-in symlink reports its own inode and mismatches.
50
+ assertSameFile(opened, fs.lstatSync(filePath), filePath);
51
+ return { fd, stat: fs.fstatSync(fd) };
34
52
  }
35
- finally {
53
+ catch (error) {
36
54
  fs.closeSync(fd);
55
+ throw error;
37
56
  }
38
57
  }
39
58
  function pushFile(packageRoot, files, filePath, relativePath) {
40
- const source = readStableFile(packageRoot, filePath);
41
- files.push({ path: relativePath, sha256: sha256(source.bytes), mode: source.mode });
59
+ const { fd, stat } = openStableFile(packageRoot, filePath);
60
+ try {
61
+ files.push({
62
+ path: relativePath,
63
+ signature: statSignature(stat),
64
+ size: stat.size,
65
+ mode: stat.mode & 0o777,
66
+ });
67
+ }
68
+ finally {
69
+ fs.closeSync(fd);
70
+ }
42
71
  }
43
72
  function scanDirectory(packageRoot, logicalPath, relativePath, stack, dirs, files) {
44
73
  const real = safeRealpath(packageRoot, logicalPath);
@@ -86,21 +115,40 @@ function ensureDir(directory) {
86
115
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
87
116
  fs.chmodSync(directory, 0o700);
88
117
  }
89
- function copyFile(packageRoot, source, target, expected) {
90
- const file = readStableFile(packageRoot, source);
91
- if (sha256(file.bytes) !== expected.sha256 || file.mode !== expected.mode) {
92
- throw new Error(`Skill file changed after validation: ${source}`);
118
+ function copyFile(packageRoot, source, target, expected, requireSourceSignature) {
119
+ const { fd, stat } = openStableFile(packageRoot, source);
120
+ try {
121
+ if (requireSourceSignature && statSignature(stat) !== expected.signature) {
122
+ throw new Error(`Skill file changed after validation: ${source}`);
123
+ }
124
+ // Byte length + mode are the descriptor-level contract for every copy; a same-length in-place
125
+ // rewrite is only distinguishable through the full signature, which the plugin-source copy
126
+ // enforces above. Copies taken from an already validated snapshot carry that snapshot's own
127
+ // timestamps, so they compare on shape.
128
+ if (stat.size !== expected.size || (stat.mode & 0o777) !== expected.mode) {
129
+ throw new Error(`Skill file changed after validation: ${source}`);
130
+ }
131
+ const bytes = fs.readFileSync(fd);
132
+ // No second read: the inode must be the one we opened, unchanged by the read itself.
133
+ const after = fs.fstatSync(fd);
134
+ assertSameFile(stat, after, source);
135
+ if (after.size !== expected.size || statSignature(after) !== statSignature(stat)) {
136
+ throw new Error(`Skill file changed while being read: ${source}`);
137
+ }
138
+ fs.writeFileSync(target, bytes, { mode: expected.mode });
139
+ fs.chmodSync(target, expected.mode);
140
+ }
141
+ finally {
142
+ fs.closeSync(fd);
93
143
  }
94
- fs.writeFileSync(target, file.bytes, { mode: expected.mode });
95
- fs.chmodSync(target, expected.mode);
96
144
  }
97
- export function copyProjectedSkillTree(packageRoot, skillRoot, tree, targetRoot) {
145
+ export function copyProjectedSkillTree(packageRoot, skillRoot, tree, targetRoot, opts = {}) {
98
146
  ensureDir(targetRoot);
99
147
  for (const dir of tree.dirs)
100
148
  ensureDir(path.join(targetRoot, dir));
101
149
  for (const file of tree.files) {
102
150
  ensureDir(path.dirname(path.join(targetRoot, file.path)));
103
- copyFile(packageRoot, path.join(skillRoot, file.path), path.join(targetRoot, file.path), file);
151
+ copyFile(packageRoot, path.join(skillRoot, file.path), path.join(targetRoot, file.path), file, opts.requireSourceSignature === true);
104
152
  }
105
153
  }
106
154
  function scanMaterializedDirectory(root, current, relativePath, dirs, files) {
@@ -128,12 +176,21 @@ function actualTree(root) {
128
176
  files.sort((a, b) => a.path.localeCompare(b.path));
129
177
  return { dirs, files, sha256: treeSha256(dirs, files) };
130
178
  }
179
+ /** The parts of a tree a materialized copy can be compared on: the source's mtime/ctime/inode
180
+ * belong to the source, while a copy has its own. Path, byte length, mode and the directory set
181
+ * still catch a truncated, extra, missing or wrongly-permissioned projection. */
182
+ function materializedShape(tree) {
183
+ return JSON.stringify({
184
+ dirs: tree.dirs,
185
+ files: tree.files.map(({ path, size, mode }) => ({ path, size, mode })),
186
+ });
187
+ }
131
188
  export function validateProjectedSkillTree(targetRoot, expected) {
132
189
  const stat = fs.lstatSync(targetRoot);
133
190
  if (!stat.isDirectory() || stat.isSymbolicLink())
134
191
  throw new Error(`Portable projection target is invalid: ${targetRoot}`);
135
192
  const actual = actualTree(targetRoot);
136
- if (JSON.stringify(actual) !== JSON.stringify(expected)) {
193
+ if (materializedShape(actual) !== materializedShape(expected)) {
137
194
  throw new Error(`Portable projection skill tree mismatch: ${targetRoot}`);
138
195
  }
139
196
  }
@@ -85,7 +85,7 @@ async function main() {
85
85
  }
86
86
  // Step 3: Ship the managed bundle to ~/.cortex/client/current/
87
87
  console.log('[3/4] Deploying client bundle...');
88
- const bundle = resolveBundle();
88
+ const bundle = await resolveBundle();
89
89
  if (!bundle) {
90
90
  log.error('No client bundle available (dev: client repo build failed; release: npm registry unreachable).');
91
91
  process.exit(1);
@@ -13,7 +13,7 @@ interface PushAttempt {
13
13
  ok: boolean | null;
14
14
  }
15
15
  declare function loadBundleFromDir(dir: string, version: string): ClientBundle | null;
16
- declare function resolveBundle(): ClientBundle | null;
16
+ declare function resolveBundle(): Promise<ClientBundle | null>;
17
17
  /** Pure decision: push when the device diverges, unless the same bundle is in
18
18
  * flight or recently failed on that device. */
19
19
  declare function shouldPush(reported: string | null, bundleHash: string, last: PushAttempt | undefined, now: number): boolean;
@@ -2,7 +2,7 @@ import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import * as os from 'os';
4
4
  import * as crypto from 'crypto';
5
- import { execSync } from 'child_process';
5
+ import { runFile, runShell } from '../../core/exec-async.js';
6
6
  import { setClientUpdateHooks, getOnlineDevices, sendControlMessage, } from './client-manager.js';
7
7
  import { STORE_DIR } from '../../core/utils.js';
8
8
  import { createLogger } from '../../core/log.js';
@@ -68,22 +68,23 @@ function loadBundleFromDir(dir, version) {
68
68
  }
69
69
  return { version, hash: h.digest('hex'), files };
70
70
  }
71
- /** Dev mode: bundle straight from the client repo (esbuild, sub-second). */
72
- function buildDevBundle() {
71
+ /** Dev mode: bundle straight from the client repo (esbuild, sub-second).
72
+ * Async: the build can take a while and this runs inside the server process. */
73
+ async function buildDevBundle() {
73
74
  const repo = resolveClientRepo();
74
75
  if (!repo) {
75
76
  log.warn('Dev mode: client repo not found — client hot-reload idle');
76
77
  return null;
77
78
  }
78
- try {
79
+ {
79
80
  const start = Date.now();
80
- execSync('npm run bundle', { cwd: repo, encoding: 'utf8', timeout: 120000, stdio: 'pipe' });
81
+ const built = await runShell('npm run bundle', { cwd: repo, timeoutMs: 120000 });
82
+ if (!built.ok) {
83
+ log.error(`Client bundle build failed: ${(built.stderr || built.error || '').trim()}`);
84
+ return null;
85
+ }
81
86
  log.info(`Client bundle built in ${Date.now() - start}ms`);
82
87
  }
83
- catch (err) {
84
- log.error(`Client bundle build failed: ${err.message}`);
85
- return null;
86
- }
87
88
  let version = 'dev';
88
89
  try {
89
90
  version = `${JSON.parse(fs.readFileSync(path.join(repo, 'package.json'), 'utf8')).version}-dev`;
@@ -92,16 +93,15 @@ function buildDevBundle() {
92
93
  return loadBundleFromDir(path.join(repo, 'dist'), version);
93
94
  }
94
95
  /** Release mode: latest published client package, bundle files cached per version. */
95
- function fetchReleaseBundle() {
96
+ async function fetchReleaseBundle() {
96
97
  let version = '';
97
- try {
98
- version = execSync('npm view @cortex-agent/client version', {
99
- encoding: 'utf8', timeout: 30000, stdio: 'pipe',
100
- }).trim();
101
- }
102
- catch (err) {
103
- log.warn(`Release mode: npm registry unreachable — client hot-reload idle (${err.message})`);
104
- return null;
98
+ {
99
+ const probed = await runFile('npm', ['view', '@cortex-agent/client', 'version'], { timeoutMs: 30000 });
100
+ if (!probed.ok) {
101
+ log.warn(`Release mode: npm registry unreachable — client hot-reload idle (${(probed.stderr || probed.error || '').trim()})`);
102
+ return null;
103
+ }
104
+ version = probed.stdout.trim();
105
105
  }
106
106
  if (!version)
107
107
  return null;
@@ -112,11 +112,15 @@ function fetchReleaseBundle() {
112
112
  let tmp = null;
113
113
  try {
114
114
  tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cortex-client-bundle-'));
115
- execSync(`npm pack @cortex-agent/client@${version}`, { cwd: tmp, encoding: 'utf8', timeout: 60000, stdio: 'pipe' });
115
+ const packed = await runFile('npm', ['pack', `@cortex-agent/client@${version}`], { cwd: tmp, timeoutMs: 60000 });
116
+ if (!packed.ok)
117
+ throw new Error(`npm pack failed: ${(packed.stderr || packed.error || '').trim()}`);
116
118
  const tgz = fs.readdirSync(tmp).find((f) => f.endsWith('.tgz'));
117
119
  if (!tgz)
118
120
  throw new Error('npm pack produced no tgz');
119
- execSync(`tar -xzf ${JSON.stringify(tgz)}`, { cwd: tmp, encoding: 'utf8', timeout: 30000, stdio: 'pipe' });
121
+ const untarred = await runFile('tar', ['-xzf', tgz], { cwd: tmp, timeoutMs: 30000 });
122
+ if (!untarred.ok)
123
+ throw new Error(`tar failed: ${(untarred.stderr || untarred.error || '').trim()}`);
120
124
  fs.mkdirSync(cacheDir, { recursive: true });
121
125
  for (const name of BUNDLE_FILES) {
122
126
  fs.copyFileSync(path.join(tmp, 'package', 'dist', name), path.join(cacheDir, name));
@@ -132,7 +136,7 @@ function fetchReleaseBundle() {
132
136
  }
133
137
  return loadBundleFromDir(cacheDir, version);
134
138
  }
135
- function resolveBundle() {
139
+ async function resolveBundle() {
136
140
  return isDevMode() ? buildDevBundle() : fetchReleaseBundle();
137
141
  }
138
142
  // --- Push decision ---
@@ -212,8 +216,8 @@ function onUpdateResult(device, result) {
212
216
  function initClientHotReload(notify) {
213
217
  _notify = notify;
214
218
  setClientUpdateHooks({ onHello, onUpdateResult });
215
- setImmediate(() => {
216
- const bundle = resolveBundle();
219
+ setImmediate(async () => {
220
+ const bundle = await resolveBundle();
217
221
  if (!bundle)
218
222
  return;
219
223
  _bundle = bundle;
@@ -107,6 +107,10 @@ function spawnPolicy(request) {
107
107
  // and `disableHooks` are the same fact with opposite polarity, and `undefined` must survive
108
108
  // as `undefined` so an unset policy keeps the adapter's own default.
109
109
  disableHooks: request.policy.hooks === undefined ? undefined : !request.policy.hooks,
110
+ // Same polarity rule for skills, and the same reason to keep `undefined` alive: only an
111
+ // agent that opted out states anything here.
112
+ disableSkills: request.policy.skills === false ? true : undefined,
113
+ settingSources: request.policy.settingSources,
110
114
  streamDeltas: request.policy.streamDeltas,
111
115
  captureTranscripts: request.policy.captureTranscripts,
112
116
  preserveUnreportedAccounting: request.benchmark?.preserveUnreportedAccounting,
@@ -55,6 +55,12 @@ export interface RunRequest {
55
55
  hooks: boolean;
56
56
  streamDeltas?: boolean;
57
57
  loadRules: boolean;
58
+ /** Whether the backend loads its skill layer. Absent keeps the backend's own default (every
59
+ * skill it can see); false is how an agent runs with none. */
60
+ skills?: boolean;
61
+ /** Which setting files the backend may load beyond what Cortex passes. Absent keeps its
62
+ * default; `[]` loads none. */
63
+ settingSources?: string[];
58
64
  mcpComposition: McpComposition;
59
65
  /** Legacy thread-surface selector: only consulted when `mcpComposition` is undefined (the
60
66
  * thread path always resolves an explicit value). */
@@ -332,6 +332,7 @@ export class AgentRunImpl {
332
332
  run: this,
333
333
  trackSessionId: this.request.session.sessionId,
334
334
  backendSessionId: attempt.backendSessionId ?? this.request.session.backendSessionId,
335
+ subagent: this.request.context.trigger === 'subagent',
335
336
  });
336
337
  // The engine's spawn-time backend id is authoritative even when it never emits a
337
338
  // `session_started` event (an interrupted first turn). Surfaces that persist the resume target
@@ -56,9 +56,10 @@ export declare function bareSpec(): AgentSpec;
56
56
  * `fromAgentDefinition`): `AgentDefinition` merged with any per-template ref overrides, which
57
57
  * `threads/template-loader.resolveAgentSlotConfig` already produced and both callers hold.
58
58
  *
59
- * `mcpComposition` is the caller's, not the slot's: a thread step gets the thread-control surface
60
- * and a plain conversation gets the direct one, and that is a property of the surface the run is
61
- * opened on rather than of the agent.
59
+ * `mcpComposition` is the surface's default, which the agent may override: the caller passes what
60
+ * the surface would otherwise run on (thread-control for a thread step, direct for a plain
61
+ * conversation) and resolves `config.mcpComposition` over it before calling, so an agent that
62
+ * declares a narrower surface keeps it on every path.
62
63
  */
63
64
  export declare function fromAgentSlot(config: AgentSlotConfig, opts: {
64
65
  mcpComposition: McpComposition;
@@ -17,9 +17,10 @@ export function bareSpec() {
17
17
  * `fromAgentDefinition`): `AgentDefinition` merged with any per-template ref overrides, which
18
18
  * `threads/template-loader.resolveAgentSlotConfig` already produced and both callers hold.
19
19
  *
20
- * `mcpComposition` is the caller's, not the slot's: a thread step gets the thread-control surface
21
- * and a plain conversation gets the direct one, and that is a property of the surface the run is
22
- * opened on rather than of the agent.
20
+ * `mcpComposition` is the surface's default, which the agent may override: the caller passes what
21
+ * the surface would otherwise run on (thread-control for a thread step, direct for a plain
22
+ * conversation) and resolves `config.mcpComposition` over it before calling, so an agent that
23
+ * declares a narrower surface keeps it on every path.
23
24
  */
24
25
  export function fromAgentSlot(config, opts) {
25
26
  return {
@@ -1,4 +1,4 @@
1
- import { execFileSync } from 'child_process';
1
+ import { runFile } from '../../../core/exec-async.js';
2
2
  import * as path from 'path';
3
3
  import { register, ctx } from '../job-registry.js';
4
4
  import { Icons } from '../../../core/icons.js';
@@ -16,11 +16,11 @@ register('sync-public', async (payload) => {
16
16
  const syncScript = resolveSyncPublicScript();
17
17
  if (!syncScript)
18
18
  throw new Error('CORTEX_REPO is unset; public sync requires a source checkout');
19
- const output = execFileSync('bash', [syncScript], {
20
- timeout: 30_000,
21
- encoding: 'utf-8',
22
- stdio: ['pipe', 'pipe', 'pipe'],
23
- });
19
+ // Async: this is a scheduled job inside the long-lived server process.
20
+ const synced = await runFile('bash', [syncScript], { timeoutMs: 30_000 });
21
+ if (!synced.ok)
22
+ throw new Error((synced.stderr || synced.error || 'sync script failed').trim());
23
+ const output = synced.stdout;
24
24
  const lines = output.trim().split('\n');
25
25
  const lastLine = lines[lines.length - 1] || '';
26
26
  if (lastLine.includes('0 failed') || lastLine.includes('everything in sync') || lastLine.includes('OK:') || lastLine.includes('SKIP:')) {
@@ -1,6 +1,6 @@
1
1
  import { watch } from 'fs';
2
- import { execSync } from 'child_process';
3
2
  import { randomBytes } from 'crypto';
3
+ import { runShell } from '../../core/exec-async.js';
4
4
  import { Icons } from '../../core/icons.js';
5
5
  import { DATA_DIR } from '../../core/utils.js';
6
6
  import { createLogger } from '../../core/log.js';
@@ -453,17 +453,19 @@ class Scheduler {
453
453
  if (task.preCheck) {
454
454
  const freshTask = await this._repo.findTask(task.id);
455
455
  if (freshTask?.preCheck) {
456
- try {
457
- execSync(freshTask.preCheck, {
458
- timeout: 15000,
459
- env: { ...process.env, PRECHECK_LAST_RUN: String(freshTask.lastRun || 0) },
460
- stdio: 'pipe',
461
- cwd: DATA_DIR,
462
- });
463
- }
464
- catch (e) {
465
- const output = (e.stdout || e.stderr || '').toString().trim();
466
- log.info(`Pre-check skip for ${task.id}: ${output || 'exit ' + e.status}`);
456
+ // Async: a preCheck is arbitrary user shell, so it must never block the event loop
457
+ // (execSync here stalled every session, socket and timer for up to the timeout).
458
+ const precheck = await runShell(freshTask.preCheck, {
459
+ timeoutMs: 15000,
460
+ env: { ...process.env, PRECHECK_LAST_RUN: String(freshTask.lastRun || 0) },
461
+ cwd: DATA_DIR,
462
+ });
463
+ if (!precheck.ok) {
464
+ const output = (precheck.stdout || precheck.stderr || '').trim();
465
+ const outcome = precheck.timedOut
466
+ ? 'timeout'
467
+ : `exit ${precheck.code ?? precheck.signal ?? 'unknown'}`;
468
+ log.info(`Pre-check skip for ${task.id}: ${output || outcome}`);
467
469
  await this._withWriteGuard(() => this._repo.updateTask(task.id, (t) => {
468
470
  const nextDelayMs = getNextDelay(t);
469
471
  t.nextRun = Date.now() + nextDelayMs;
@@ -12,6 +12,7 @@ export interface SessionRegistryWriter {
12
12
  projectId: string;
13
13
  label?: string | null;
14
14
  profileName?: string | null;
15
+ agentName?: string | null;
15
16
  browser?: SessionBrowserOption | null;
16
17
  commissionId?: string | null;
17
18
  commissionDraft?: string | null;
@@ -28,6 +29,9 @@ export interface RegisterNamedSessionOpts {
28
29
  origin?: SessionOrigin;
29
30
  label?: string | null;
30
31
  profileName?: string | null;
32
+ /** The agent template the session runs as; null/absent means it follows the channel's selection
33
+ * and, beneath that, the global default. */
34
+ agentName?: string | null;
31
35
  /** Opt-in browser access for this session; null/absent means no browser tools at all. */
32
36
  browser?: SessionBrowserOption | null;
33
37
  /** Commission membership, fixed at creation (DR-0037 v2). */
@@ -71,6 +75,7 @@ export declare function createDirectSession(deps: CreateDirectSessionDeps, opts:
71
75
  projectId: string;
72
76
  sessionId?: string;
73
77
  profileName?: string | null;
78
+ agentName?: string | null;
74
79
  selection?: {
75
80
  model?: string;
76
81
  provider?: string;
@@ -1,7 +1,7 @@
1
1
  import * as crypto from 'node:crypto';
2
2
  import { setSessionAsync, deleteSessionAsync } from './session.js';
3
3
  import { conversationLedger } from '../../store/conversation-ledger-repo.js';
4
- import { applyChannelSelection, setActiveProfile } from '../agents/index.js';
4
+ import { applyChannelSelection, setActiveProfile, setDefaultAgent, setSelectionDefaultAgent, } from '../agents/index.js';
5
5
  import { resolveProfileConfig } from '../agents/profile-manager.js';
6
6
  import * as sessionBackup from './session-backup.js';
7
7
  import { resolveCommissionCreate } from '../commissions/commission-draft.js';
@@ -23,6 +23,7 @@ export async function registerNamedSession(store, opts) {
23
23
  projectId: opts.projectId,
24
24
  label: opts.label ?? null,
25
25
  profileName: opts.profileName ?? null,
26
+ agentName: opts.agentName ?? null,
26
27
  browser: opts.browser ?? null,
27
28
  commissionId: commission?.commissionId ?? opts.commissionId ?? null,
28
29
  commissionDraft: commission?.commissionDraft ?? opts.commissionDraft ?? null,
@@ -71,6 +72,16 @@ export async function createDirectSession(deps, opts) {
71
72
  mode: opts.selection.mode ?? null,
72
73
  });
73
74
  }
75
+ // The environment the session opens in, written to the channel BEFORE the first turn is routed
76
+ // (the run path resolves the agent per turn from the session record, then this map). No switch
77
+ // rule is needed: a channel minted here has no history, so the cross-backend guard the rule
78
+ // exists for has nothing to refuse.
79
+ if (opts.agentName)
80
+ setDefaultAgent(opts.agentName, channel);
81
+ // Seeded on the same condition as the selection above: `selection` present is what marks a
82
+ // composer behind this call, and a composer that named no agent stated the default.
83
+ if (opts.selection)
84
+ setSelectionDefaultAgent(opts.agentName ?? null);
74
85
  // settings.commissionEnabled is the feature's kill switch (on by default since DR-0037 v4).
75
86
  // Refuse here rather than downgrade: a caller that asked for a commission and silently got an
76
87
  // ordinary session would only discover it much later. This is the server-side backstop for every
@@ -85,6 +96,7 @@ export async function createDirectSession(deps, opts) {
85
96
  projectId: opts.projectId,
86
97
  origin: 'direct',
87
98
  profileName: opts.profileName ?? null,
99
+ agentName: opts.agentName ?? null,
88
100
  browser: opts.browser ?? null,
89
101
  commissionFor: opts.commission
90
102
  ? (name) => resolveCommissionCreate(opts.projectId, name, opts.commission)
@@ -0,0 +1,44 @@
1
+ import type { PlatformAdapter } from '../../platform/index.js';
2
+ export interface RebuildHold {
3
+ /** The pipeline step in flight ('web', 'install', 'restart'), when the supervisor named one. */
4
+ phase: string | null;
5
+ /** What triggered the rebuild, verbatim ('src change: core/foo.ts'). */
6
+ reason: string | null;
7
+ /** When this process first started holding, in epoch ms. */
8
+ since: number;
9
+ }
10
+ /** Apply a supervisor hold message. Renews the lease and keeps the original `since`, so the UI and
11
+ * the refusal text can say how long the app has been closed for business. */
12
+ export declare function holdNewTurns(p: {
13
+ phase?: string | null;
14
+ reason?: string | null;
15
+ now?: number;
16
+ }): void;
17
+ /** Lift the hold (pipeline aborted, or finished without replacing this process). */
18
+ export declare function releaseNewTurnHold(): void;
19
+ /** The active hold, or null. Reading it is what expires a stale lease. */
20
+ export declare function rebuildHold(now?: number): RebuildHold | null;
21
+ /** True while new turns must be refused. */
22
+ export declare function isRebuildHeld(now?: number): boolean;
23
+ /**
24
+ * Tell whoever sent this message that it was not processed. Never throws — a refusal that fails to
25
+ * be delivered must still leave the turn un-started.
26
+ *
27
+ * Two audiences, two channels. A person who just typed gets the answer where they typed it, and
28
+ * nothing else: they are looking at that conversation. A callback (a finished background agent, a
29
+ * woken thread, a resume) has no reader, so it becomes a warning-level system notice instead — that
30
+ * is the difference between "the restart ate my subagent's report" and knowing which message to
31
+ * re-drive. Either way the work itself is NOT re-queued: nothing here survives the restart.
32
+ */
33
+ export declare function refuseTurnForRebuild(p: {
34
+ adapter: PlatformAdapter;
35
+ channel: string;
36
+ /** The refused message's text, for the notice. */
37
+ text: string;
38
+ /** True when a human is waiting on this message in `channel`. */
39
+ interactive: boolean;
40
+ }): Promise<void>;
41
+ /** Test hook: drop the hold between cases. */
42
+ export declare const _test: {
43
+ reset(): void;
44
+ };
@@ -0,0 +1,91 @@
1
+ // input: entry/daemon-notice.ts (the supervisor's 'rebuild-hold' IPC message)
2
+ // output: isRebuildHeld() / rebuildHold() — the admission answer every turn starter asks —
3
+ // plus refuseTurnForRebuild(), the one wording for a turn that was not admitted
4
+ // pos: the one piece of supervisor-pushed state this process keeps. The daemon knows it is about
5
+ // to rebuild and replace us; nothing inside the app can work that out on its own.
6
+ //
7
+ // Why a turn must not start under a hold: the app spawns the backend CLI as its own child and owns
8
+ // its stdout. When the supervisor SIGTERMs the app, that CLI keeps running (it is past the point of
9
+ // caring) and writes its answer into a pipe with no reader — a turn that is never delivered, never
10
+ // completes, and leaves the session showing "processing" forever. Refusing the turn up front turns
11
+ // a silent orphan into a message the person can resend.
12
+ //
13
+ // The hold EXPIRES. A daemon that dies mid-pipeline must not leave this process refusing work for
14
+ // the rest of its life, so every phase change renews a short lease and the absence of news
15
+ // eventually means "carry on".
16
+ import { Icons } from '../../core/icons.js';
17
+ import { t } from '../../core/i18n.js';
18
+ import { emitSystemNotice } from './system-notice.js';
19
+ /** How long a single 'hold' message is trusted. The supervisor re-sends on every phase change, and
20
+ * the longest single phase (web build, or `npm install -g` rewriting the vendored closure) runs
21
+ * well inside this. Fails open by design. */
22
+ const HOLD_LEASE_MS = 5 * 60_000;
23
+ let held = null;
24
+ /** Apply a supervisor hold message. Renews the lease and keeps the original `since`, so the UI and
25
+ * the refusal text can say how long the app has been closed for business. */
26
+ export function holdNewTurns(p) {
27
+ const now = p.now ?? Date.now();
28
+ held = {
29
+ phase: p.phase ?? null,
30
+ reason: p.reason ?? null,
31
+ since: held?.since ?? now,
32
+ expiresAt: now + HOLD_LEASE_MS,
33
+ };
34
+ }
35
+ /** Lift the hold (pipeline aborted, or finished without replacing this process). */
36
+ export function releaseNewTurnHold() {
37
+ held = null;
38
+ }
39
+ /** The active hold, or null. Reading it is what expires a stale lease. */
40
+ export function rebuildHold(now = Date.now()) {
41
+ if (!held)
42
+ return null;
43
+ if (now >= held.expiresAt) {
44
+ held = null;
45
+ return null;
46
+ }
47
+ const { phase, reason, since } = held;
48
+ return { phase, reason, since };
49
+ }
50
+ /** True while new turns must be refused. */
51
+ export function isRebuildHeld(now = Date.now()) {
52
+ return rebuildHold(now) !== null;
53
+ }
54
+ /** Longest message excerpt carried into the dropped-message notice. Enough to recognise which
55
+ * message it was, short enough for a toast. */
56
+ const PREVIEW_CHARS = 160;
57
+ function preview(text) {
58
+ const flat = text.replace(/\s+/g, ' ').trim();
59
+ if (!flat)
60
+ return '(no text)';
61
+ return flat.length > PREVIEW_CHARS ? `${flat.slice(0, PREVIEW_CHARS)}…` : flat;
62
+ }
63
+ /**
64
+ * Tell whoever sent this message that it was not processed. Never throws — a refusal that fails to
65
+ * be delivered must still leave the turn un-started.
66
+ *
67
+ * Two audiences, two channels. A person who just typed gets the answer where they typed it, and
68
+ * nothing else: they are looking at that conversation. A callback (a finished background agent, a
69
+ * woken thread, a resume) has no reader, so it becomes a warning-level system notice instead — that
70
+ * is the difference between "the restart ate my subagent's report" and knowing which message to
71
+ * re-drive. Either way the work itself is NOT re-queued: nothing here survives the restart.
72
+ */
73
+ export async function refuseTurnForRebuild(p) {
74
+ const phase = rebuildHold()?.phase ?? 'restart';
75
+ if (p.interactive) {
76
+ const destination = { type: 'interactive-reply', conduit: p.channel, sessionId: '' };
77
+ await p.adapter
78
+ .postMessage(destination, { text: `${Icons.warning} ${t('startup.rebuildHold', { phase })}` })
79
+ .catch(() => { });
80
+ return;
81
+ }
82
+ await emitSystemNotice(p.adapter, {
83
+ level: 'warning',
84
+ title: 'Rebuild',
85
+ text: t('startup.rebuildHoldDropped', { phase, channel: p.channel, preview: preview(p.text) }),
86
+ }).catch(() => { });
87
+ }
88
+ /** Test hook: drop the hold between cases. */
89
+ export const _test = {
90
+ reset() { held = null; },
91
+ };
@@ -5,7 +5,8 @@ export { compareCalVer };
5
5
  export declare function isUpdateDevMode(): boolean;
6
6
  export interface CheckServerUpdateDeps {
7
7
  prompt: UpdatePrompt;
8
- getLatest?: () => string | null;
8
+ /** May be async: the default implementation shells out to `npm view` without blocking. */
9
+ getLatest?: () => string | null | Promise<string | null>;
9
10
  spawnInstall?: () => void;
10
11
  loadState?: () => UpdateState | null;
11
12
  saveState?: (s: UpdateState) => void;