@cortex-agent/server 2026.8.3 → 2026.8.6
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.
- package/defaults/config/thread-templates/agents/benchmark-coder.json +2 -2
- package/defaults/config/thread-templates/agents/benchmark-fixer.json +17 -0
- package/defaults/config/thread-templates/agents/benchmark-reviewer.json +5 -5
- package/defaults/config/thread-templates/templates/benchmark-coder-review-fix.json +21 -0
- package/defaults/plugins/cortex-system/skills/thread/SKILL.md +1 -0
- package/defaults/prompts/directives/benchmark-coder.md +1 -0
- package/defaults/prompts/directives/benchmark-fixer.md +1 -0
- package/defaults/prompts/directives/benchmark-reviewer.md +1 -0
- package/defaults/prompts/systemPrompts/benchmark-coder.md +1 -0
- package/defaults/prompts/systemPrompts/benchmark-fixer.md +1 -0
- package/defaults/prompts/systemPrompts/benchmark-reviewer.md +1 -0
- package/dist/agent-adapter/capabilities.d.ts +32 -1
- package/dist/agent-adapter/capabilities.js +39 -1
- package/dist/agent-adapter/claude/adapter.d.ts +15 -0
- package/dist/agent-adapter/claude/adapter.js +29 -7
- package/dist/agent-adapter/claude/spawn-args.d.ts +5 -2
- package/dist/agent-adapter/claude/spawn-args.js +29 -6
- package/dist/agent-adapter/index.js +11 -1
- package/dist/agent-adapter/normalize/tool-names.d.ts +4 -0
- package/dist/agent-adapter/normalize/tool-names.js +10 -0
- package/dist/agent-adapter/pi/adapter.d.ts +20 -8
- package/dist/agent-adapter/pi/adapter.js +130 -35
- package/dist/agent-adapter/pi/agent-dir.d.ts +20 -53
- package/dist/agent-adapter/pi/agent-dir.js +48 -89
- package/dist/agent-adapter/pi/custom-catalog.d.ts +10 -0
- package/dist/agent-adapter/pi/custom-catalog.js +42 -0
- package/dist/agent-adapter/pi/defaults.d.ts +9 -0
- package/dist/agent-adapter/pi/defaults.js +14 -4
- package/dist/agent-adapter/pi/discovery.d.ts +1 -3
- package/dist/agent-adapter/pi/discovery.js +3 -15
- package/dist/agent-adapter/pi/event-parser.js +8 -0
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +13 -0
- package/dist/agent-adapter/pi/mcp-bridge.js +31 -6
- package/dist/agent-adapter/pi/mcp-duration.d.ts +28 -0
- package/dist/agent-adapter/pi/mcp-duration.js +48 -0
- package/dist/agent-adapter/pi/policy-guard.d.ts +40 -0
- package/dist/agent-adapter/pi/policy-guard.js +111 -0
- package/dist/agent-adapter/pi/providers-config.d.ts +62 -0
- package/dist/agent-adapter/pi/providers-config.js +101 -0
- package/dist/agent-adapter/pi/quota-probe.d.ts +11 -0
- package/dist/agent-adapter/pi/quota-probe.js +36 -0
- package/dist/agent-adapter/pi/quota-sink.d.ts +25 -0
- package/dist/agent-adapter/pi/quota-sink.js +31 -0
- package/dist/agent-adapter/pi/session-files.d.ts +2 -0
- package/dist/agent-adapter/pi/session-files.js +19 -0
- package/dist/agent-adapter/pi/session-support.d.ts +14 -3
- package/dist/agent-adapter/pi/session-support.js +8 -0
- package/dist/agent-adapter/pi/spawn-args.d.ts +11 -1
- package/dist/agent-adapter/pi/spawn-args.js +13 -0
- package/dist/agent-adapter/pi/tool-shims.d.ts +2 -2
- package/dist/agent-adapter/pi/tool-shims.js +32 -21
- package/dist/agent-adapter/pi/web-search.js +36 -8
- package/dist/agent-adapter/types.d.ts +14 -0
- package/dist/core/locales/en.d.ts +54 -1
- package/dist/core/locales/en.js +2 -0
- package/dist/core/locales/slices/commands.d.ts +12 -1
- package/dist/core/locales/slices/commands.js +24 -2
- package/dist/core/locales/slices/providers.d.ts +45 -0
- package/dist/core/locales/slices/providers.js +95 -0
- package/dist/core/locales/zh.js +2 -0
- package/dist/core/resilient-watch.d.ts +28 -0
- package/dist/core/resilient-watch.js +110 -0
- package/dist/core/settings.js +15 -20
- package/dist/core/types/agent-types.d.ts +6 -0
- package/dist/core/types/thread-types.d.ts +21 -3
- package/dist/core/utils.d.ts +21 -1
- package/dist/core/utils.js +37 -1
- package/dist/domain/agent-run/agent-run-cli.js +3 -1
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +31 -0
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +231 -24
- package/dist/domain/agent-run/benchmark-thread-identity.d.ts +15 -2
- package/dist/domain/agent-run/benchmark-thread-identity.js +123 -34
- package/dist/domain/agent-run/identity.d.ts +5 -0
- package/dist/domain/agent-run/identity.js +4 -1
- package/dist/domain/agent-run/journal.d.ts +3 -2
- package/dist/domain/agent-run/manifest.js +11 -4
- package/dist/domain/agent-run/pinned-node-process.d.ts +4 -0
- package/dist/domain/agent-run/pinned-node-process.js +9 -0
- package/dist/domain/agent-run/role-surface.d.ts +2 -2
- package/dist/domain/agent-run/role-surface.js +7 -3
- package/dist/domain/agent-run/run-config.d.ts +10 -1
- package/dist/domain/agent-run/run-config.js +57 -6
- package/dist/domain/agent-run/runner.js +149 -31
- package/dist/domain/agents/facade.d.ts +37 -122
- package/dist/domain/agents/facade.js +47 -115
- package/dist/domain/agents/spawn-config.d.ts +135 -0
- package/dist/domain/agents/spawn-config.js +121 -0
- package/dist/domain/benchmark/accounting-reconciliation.d.ts +98 -0
- package/dist/domain/benchmark/accounting-reconciliation.js +218 -0
- package/dist/domain/benchmark/arm-schema.d.ts +43 -0
- package/dist/domain/benchmark/arm-schema.js +243 -0
- package/dist/domain/benchmark/capabilities.d.ts +4 -0
- package/dist/domain/benchmark/capabilities.js +54 -0
- package/dist/domain/benchmark/decimal-text.d.ts +27 -0
- package/dist/domain/benchmark/decimal-text.js +67 -0
- package/dist/domain/benchmark/lease-echo.d.ts +43 -0
- package/dist/domain/benchmark/lease-echo.js +56 -0
- package/dist/domain/benchmark/policy-backed-runtime-deps.d.ts +14 -0
- package/dist/domain/benchmark/policy-backed-runtime-deps.js +47 -0
- package/dist/domain/benchmark/policy-compiler.d.ts +68 -0
- package/dist/domain/benchmark/policy-compiler.js +680 -0
- package/dist/domain/benchmark/resolved-policy.d.ts +110 -0
- package/dist/domain/benchmark/resolved-policy.js +195 -0
- package/dist/domain/benchmark/trial-adapter-factory.d.ts +38 -0
- package/dist/domain/benchmark/trial-adapter-factory.js +165 -0
- package/dist/domain/benchmark/trial-thread-adapter.d.ts +25 -0
- package/dist/domain/benchmark/trial-thread-adapter.js +106 -0
- package/dist/domain/benchmark/variant-proposal.d.ts +45 -0
- package/dist/domain/benchmark/variant-proposal.js +42 -0
- package/dist/domain/benchmark/workspace-lease.d.ts +99 -0
- package/dist/domain/benchmark/workspace-lease.js +272 -0
- package/dist/domain/costs/codex-quota.d.ts +29 -0
- package/dist/domain/costs/codex-quota.js +102 -0
- package/dist/domain/costs/cost-tracker.d.ts +48 -9
- package/dist/domain/costs/cost-tracker.js +74 -18
- package/dist/domain/costs/rate-limit-throttle.d.ts +23 -1
- package/dist/domain/costs/rate-limit-throttle.js +61 -6
- package/dist/domain/costs/resume-registry.d.ts +3 -1
- package/dist/domain/costs/resume-registry.js +10 -1
- package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +26 -2
- package/dist/domain/mcp/tools/benchmark-thread-run.js +63 -20
- package/dist/domain/mcp/tools/cost.js +15 -6
- package/dist/domain/pi-providers/custom-provider-model.d.ts +53 -0
- package/dist/domain/pi-providers/custom-provider-model.js +122 -0
- package/dist/domain/pi-providers/custom-provider-service.d.ts +59 -0
- package/dist/domain/pi-providers/custom-provider-service.js +143 -0
- package/dist/domain/pi-providers/gateway-route-store.d.ts +23 -0
- package/dist/domain/pi-providers/gateway-route-store.js +78 -0
- package/dist/domain/pi-providers/index.d.ts +4 -0
- package/dist/domain/pi-providers/index.js +8 -0
- package/dist/domain/pi-providers/models-json-store.d.ts +6 -0
- package/dist/domain/pi-providers/models-json-store.js +77 -0
- package/dist/domain/remote/client-hot-reload.d.ts +9 -1
- package/dist/domain/remote/client-hot-reload.js +60 -12
- package/dist/domain/scheduling/jobs/_shared.d.ts +4 -1
- package/dist/domain/scheduling/jobs/_shared.js +11 -2
- package/dist/domain/scheduling/jobs/scheduled-task.js +1 -0
- package/dist/domain/scheduling/jobs/task-dispatch.js +49 -54
- package/dist/domain/sessions/session-lifecycle.d.ts +22 -0
- package/dist/domain/sessions/session-lifecycle.js +20 -1
- package/dist/domain/system/install-cli.js +8 -3
- package/dist/domain/system/system-notice.d.ts +4 -1
- package/dist/domain/system/system-notice.js +6 -2
- package/dist/domain/tasks/dispatch-utils.d.ts +0 -4
- package/dist/domain/tasks/dispatch-utils.js +24 -37
- package/dist/domain/threads/runner.d.ts +16 -1
- package/dist/domain/threads/runner.js +62 -8
- package/dist/domain/threads/template-loader.d.ts +5 -0
- package/dist/domain/threads/template-loader.js +120 -36
- package/dist/domain/threads/template-validate.d.ts +244 -0
- package/dist/domain/threads/template-validate.js +574 -0
- package/dist/domain/threads/template-validate.parity.d.ts +1 -0
- package/dist/domain/threads/template-validate.parity.js +47 -0
- package/dist/domain/threads/template-writer.d.ts +55 -0
- package/dist/domain/threads/template-writer.js +131 -0
- package/dist/domain/ui-service/app-router.d.ts +143 -1
- package/dist/domain/ui-service/app-router.js +29 -3
- package/dist/domain/ui-service/input-schemas.d.ts +228 -4
- package/dist/domain/ui-service/input-schemas.js +132 -1
- package/dist/domain/ui-service/mutate/config.d.ts +10 -1
- package/dist/domain/ui-service/mutate/config.js +45 -5
- package/dist/domain/ui-service/mutate/custom-providers.d.ts +8 -0
- package/dist/domain/ui-service/mutate/custom-providers.js +37 -0
- package/dist/domain/ui-service/mutate/profiles.d.ts +21 -0
- package/dist/domain/ui-service/mutate/profiles.js +156 -0
- package/dist/domain/ui-service/mutate/schedules.d.ts +2 -1
- package/dist/domain/ui-service/mutate/schedules.js +53 -3
- package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
- package/dist/domain/ui-service/mutate/sessions.js +25 -1
- package/dist/domain/ui-service/mutate/system.d.ts +2 -1
- package/dist/domain/ui-service/mutate/system.js +17 -3
- package/dist/domain/ui-service/mutate/thread-templates.d.ts +4 -0
- package/dist/domain/ui-service/mutate/thread-templates.js +71 -0
- package/dist/domain/ui-service/query/config.js +30 -0
- package/dist/domain/ui-service/query/custom-providers.d.ts +8 -0
- package/dist/domain/ui-service/query/custom-providers.js +13 -0
- package/dist/domain/ui-service/query/machine-detail.d.ts +2 -0
- package/dist/domain/ui-service/query/machine-detail.js +56 -0
- package/dist/domain/ui-service/query/machine-probe.d.ts +18 -0
- package/dist/domain/ui-service/query/machine-probe.js +136 -0
- package/dist/domain/ui-service/query/schedules.js +5 -0
- package/dist/domain/ui-service/query/sessions.js +8 -2
- package/dist/domain/ui-service/query/thread-template-detail.d.ts +8 -0
- package/dist/domain/ui-service/query/thread-template-detail.js +94 -0
- package/dist/domain/ui-service/query/thread-templates.d.ts +5 -3
- package/dist/domain/ui-service/query/thread-templates.js +44 -7
- package/dist/domain/ui-service/types.d.ts +298 -7
- package/dist/domain/ui-service/ui-service.js +27 -3
- package/dist/entry/app.js +24 -3
- package/dist/entry/auth-cli.d.ts +4 -1
- package/dist/entry/auth-cli.js +10 -2
- package/dist/entry/cli-help.js +6 -2
- package/dist/entry/cli.js +2 -1
- package/dist/entry/daemon.d.ts +0 -11
- package/dist/entry/daemon.js +5 -49
- package/dist/entry/provider-cli.d.ts +16 -0
- package/dist/entry/provider-cli.js +203 -0
- package/dist/events/event-types.d.ts +2 -1
- package/dist/orchestration/agent-runner.js +3 -2
- package/dist/orchestration/routing/commands/cost.d.ts +8 -0
- package/dist/orchestration/routing/commands/cost.js +93 -21
- package/dist/orchestration/routing/commands/login-custom.d.ts +26 -0
- package/dist/orchestration/routing/commands/login-custom.js +89 -0
- package/dist/orchestration/routing/commands/login.d.ts +3 -0
- package/dist/orchestration/routing/commands/login.js +7 -0
- package/dist/orchestration/routing/message-router.js +48 -33
- package/dist/orchestration/routing/webhook.js +1 -1
- package/dist/orchestration/session-events.d.ts +2 -1
- package/dist/orchestration/session-events.js +1 -0
- package/dist/orchestration/thread-callback.js +1 -1
- package/dist/store/conversation-history-repo.d.ts +5 -1
- package/dist/store/conversation-history-repo.js +2 -1
- package/dist/store/cost-repo.d.ts +17 -0
- package/dist/store/cost-repo.js +47 -5
- package/dist/store/profile-repo.d.ts +0 -10
- package/dist/store/profile-repo.js +34 -56
- package/dist/store/session-registry-repo.d.ts +12 -0
- package/dist/store/session-registry-repo.js +16 -0
- package/package.json +1 -1
- package/web/dist/assets/index-DYMfaAi4.css +1 -0
- package/web/dist/assets/index-uOoZjGKa.js +141 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-DrNx9R6c.js +0 -139
- package/web/dist/assets/index-zpf3OSKC.css +0 -1
|
@@ -7,10 +7,10 @@
|
|
|
7
7
|
// (local npm + process.kill + detached respawn).
|
|
8
8
|
import * as fs from 'fs';
|
|
9
9
|
import * as path from 'path';
|
|
10
|
-
import { execSync, execFile, spawn } from 'child_process';
|
|
10
|
+
import { execSync, execFile, execFileSync, spawn } from 'child_process';
|
|
11
11
|
import { getMachineRegistry } from '../tasks/dispatch-utils.js';
|
|
12
12
|
import { sshExec, clientPids, buildRemoteSpawnCommand, buildRemoteInstallCommand } from './client-manager.js';
|
|
13
|
-
import { STORE_DIR } from '../../core/utils.js';
|
|
13
|
+
import { STORE_DIR, withNpmPrefix } from '../../core/utils.js';
|
|
14
14
|
import { createLogger } from '../../core/log.js';
|
|
15
15
|
import { Icons } from '../../core/icons.js';
|
|
16
16
|
const log = createLogger('client-hot-reload');
|
|
@@ -128,6 +128,32 @@ function scpToRemote(host, localPath, remotePath, timeout = 60000) {
|
|
|
128
128
|
});
|
|
129
129
|
});
|
|
130
130
|
}
|
|
131
|
+
// --- Release mode: npm global prefix resolution ---
|
|
132
|
+
const CLIENT_PKG = '@cortex-agent/client';
|
|
133
|
+
/**
|
|
134
|
+
* The client is installed as the `cortex-client` binary — resolve the npm global
|
|
135
|
+
* prefix from it (see resolveNpmGlobalPrefix), so the version probe and the update
|
|
136
|
+
* both act on the root the client actually lives in rather than npm's default.
|
|
137
|
+
*/
|
|
138
|
+
function clientNpmArgs(args) {
|
|
139
|
+
return withNpmPrefix(args, 'cortex-client');
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Remote counterpart of resolveNpmGlobalPrefix: same derivation, done in the
|
|
143
|
+
* remote shell (the prefix is a property of the remote host, not of this one).
|
|
144
|
+
* Windows hosts keep the plain command — npm there installs into the roaming
|
|
145
|
+
* prefix owned by the user, so EACCES is not a failure mode.
|
|
146
|
+
*/
|
|
147
|
+
function buildRemoteNpmUpdateCommand(reg) {
|
|
148
|
+
const plain = `npm update -g ${CLIENT_PKG} 2>&1`;
|
|
149
|
+
if (reg.win)
|
|
150
|
+
return plain;
|
|
151
|
+
return [
|
|
152
|
+
'b="$(command -v cortex-client 2>/dev/null)"; p=""',
|
|
153
|
+
'[ -n "$b" ] && p="$(dirname "$(dirname "$b")")"',
|
|
154
|
+
`if [ -n "$p" ] && [ -d "$p/lib/node_modules" ]; then npm update -g --prefix "$p" ${CLIENT_PKG} 2>&1; else ${plain}; fi`,
|
|
155
|
+
].join('; ');
|
|
156
|
+
}
|
|
131
157
|
// --- Release mode: npm registry helpers ---
|
|
132
158
|
function getNpmRegistryVersion() {
|
|
133
159
|
try {
|
|
@@ -143,14 +169,22 @@ function getNpmRegistryVersion() {
|
|
|
143
169
|
}
|
|
144
170
|
}
|
|
145
171
|
function getLocalInstalledVersion() {
|
|
172
|
+
// Must use the same prefix as the update below, or the probe reads a different
|
|
173
|
+
// (empty) global root and reports the client as missing on every check.
|
|
174
|
+
let out = '';
|
|
146
175
|
try {
|
|
147
|
-
|
|
176
|
+
out = execFileSync('npm', clientNpmArgs(['ls', '-g', CLIENT_PKG, '--json']), {
|
|
148
177
|
encoding: 'utf8',
|
|
149
178
|
timeout: 15000,
|
|
150
179
|
stdio: 'pipe',
|
|
151
180
|
}).trim();
|
|
152
|
-
|
|
153
|
-
|
|
181
|
+
}
|
|
182
|
+
catch (err) {
|
|
183
|
+
// `npm ls` exits non-zero when the package is absent, but still prints JSON.
|
|
184
|
+
out = String(err?.stdout ?? '').trim();
|
|
185
|
+
}
|
|
186
|
+
try {
|
|
187
|
+
return JSON.parse(out)?.dependencies?.[CLIENT_PKG]?.version || null;
|
|
154
188
|
}
|
|
155
189
|
catch {
|
|
156
190
|
return null;
|
|
@@ -158,7 +192,7 @@ function getLocalInstalledVersion() {
|
|
|
158
192
|
}
|
|
159
193
|
function npmUpdateLocal() {
|
|
160
194
|
return new Promise((resolve, reject) => {
|
|
161
|
-
execFile('npm', ['update', '-g',
|
|
195
|
+
execFile('npm', clientNpmArgs(['update', '-g', CLIENT_PKG]), { timeout: 120000 }, (err, stdout, stderr) => {
|
|
162
196
|
if (err)
|
|
163
197
|
reject(new Error(`npm update error: ${err.message}\n${stderr}`));
|
|
164
198
|
else
|
|
@@ -166,9 +200,17 @@ function npmUpdateLocal() {
|
|
|
166
200
|
});
|
|
167
201
|
});
|
|
168
202
|
}
|
|
169
|
-
async function getRemoteInstalledVersion(
|
|
203
|
+
async function getRemoteInstalledVersion(reg) {
|
|
204
|
+
const host = reg.ssh;
|
|
170
205
|
try {
|
|
171
|
-
|
|
206
|
+
// Same prefix caveat as the local probe: read the root the client is installed in.
|
|
207
|
+
const cmd = reg.win
|
|
208
|
+
? `npm ls -g ${CLIENT_PKG} --json 2>/dev/null || true`
|
|
209
|
+
: [
|
|
210
|
+
'b="$(command -v cortex-client 2>/dev/null)"; p=""',
|
|
211
|
+
'[ -n "$b" ] && p="$(dirname "$(dirname "$b")")"',
|
|
212
|
+
`if [ -n "$p" ] && [ -d "$p/lib/node_modules" ]; then npm ls -g --prefix "$p" ${CLIENT_PKG} --json 2>/dev/null || true; else npm ls -g ${CLIENT_PKG} --json 2>/dev/null || true; fi`,
|
|
213
|
+
].join('; ');
|
|
172
214
|
const result = await sshExec(host, cmd, 15000);
|
|
173
215
|
try {
|
|
174
216
|
const parsed = JSON.parse(result);
|
|
@@ -294,6 +336,12 @@ async function updateClientReleaseLocal(device, latestVersion, deps) {
|
|
|
294
336
|
catch (err) {
|
|
295
337
|
res.error = err.message;
|
|
296
338
|
log.warn(` ${device}: local release update failed — ${res.error}`);
|
|
339
|
+
// The client was already killed. A failed update must not leave the device
|
|
340
|
+
// offline — bring it back up on the old binary.
|
|
341
|
+
try {
|
|
342
|
+
res.restarted = await deps.restart();
|
|
343
|
+
}
|
|
344
|
+
catch { }
|
|
297
345
|
}
|
|
298
346
|
return res;
|
|
299
347
|
}
|
|
@@ -311,7 +359,7 @@ async function updateClientRelease(device, reg, latestVersion) {
|
|
|
311
359
|
}
|
|
312
360
|
try {
|
|
313
361
|
// 1. Check remote installed version
|
|
314
|
-
const remoteVer = await getRemoteInstalledVersion(reg
|
|
362
|
+
const remoteVer = await getRemoteInstalledVersion(reg);
|
|
315
363
|
res.oldVersion = remoteVer || '?';
|
|
316
364
|
if (remoteVer === latestVersion) {
|
|
317
365
|
log.info(` ${device}: already at latest (${latestVersion})`);
|
|
@@ -319,8 +367,8 @@ async function updateClientRelease(device, reg, latestVersion) {
|
|
|
319
367
|
}
|
|
320
368
|
// 2. Kill existing client
|
|
321
369
|
await killClientOnDevice(device, reg);
|
|
322
|
-
// 3. npm update
|
|
323
|
-
const updateOutput = await sshExec(reg.ssh,
|
|
370
|
+
// 3. npm update (prefix resolved in the remote shell — see buildRemoteNpmUpdateCommand)
|
|
371
|
+
const updateOutput = await sshExec(reg.ssh, buildRemoteNpmUpdateCommand(reg), 60000);
|
|
324
372
|
res.updated = true;
|
|
325
373
|
log.info(` ${device}: npm update output: ${updateOutput.slice(0, 200)}`);
|
|
326
374
|
// 4. Restart client
|
|
@@ -443,4 +491,4 @@ function formatUpdateSlackMessage(result) {
|
|
|
443
491
|
}
|
|
444
492
|
return lines.join('\n');
|
|
445
493
|
}
|
|
446
|
-
export { checkAndUpdateClients, formatUpdateSlackMessage, updateClientReleaseLocal };
|
|
494
|
+
export { checkAndUpdateClients, formatUpdateSlackMessage, updateClientReleaseLocal, buildRemoteNpmUpdateCommand, };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { PlatformAdapter, MessageRef } from '../../../platform/index.js';
|
|
2
2
|
import type { AgentResult } from '../../../core/types/agent-types.js';
|
|
3
3
|
export declare function buildProgressUpdater(adapter: PlatformAdapter, statusMsg: MessageRef, startTime: number, effectiveProfile: string, sessionName: string): (progress: Record<string, any> | null) => void;
|
|
4
|
-
export declare function finalizeThreadSuccess(adapter: PlatformAdapter, channel: string, statusMsg: MessageRef | null, { startTime, sessionName, result, threadResult, project, trigger, label, sessionKind, sessionOrigin, statusPrefix }: {
|
|
4
|
+
export declare function finalizeThreadSuccess(adapter: PlatformAdapter, channel: string, statusMsg: MessageRef | null, { startTime, sessionName, result, threadResult, project, trigger, label, sessionKind, sessionOrigin, statusPrefix, scheduleId }: {
|
|
5
5
|
startTime: number;
|
|
6
6
|
sessionName: string;
|
|
7
7
|
result: AgentResult | null;
|
|
@@ -15,4 +15,7 @@ export declare function finalizeThreadSuccess(adapter: PlatformAdapter, channel:
|
|
|
15
15
|
* a dispatch thread (origin 'thread') from a direct session. */
|
|
16
16
|
sessionOrigin: 'scheduled' | 'thread';
|
|
17
17
|
statusPrefix: string;
|
|
18
|
+
/** ScheduleTask.id whose fire produced this run (scheduled-task job). Persisted on the session
|
|
19
|
+
* record so the UI can group runs by schedule and render the trigger card. */
|
|
20
|
+
scheduleId?: string | null;
|
|
18
21
|
}): Promise<void>;
|
|
@@ -22,16 +22,25 @@ export function buildProgressUpdater(adapter, statusMsg, startTime, effectivePro
|
|
|
22
22
|
});
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
|
-
export async function finalizeThreadSuccess(adapter, channel, statusMsg, { startTime, sessionName, result, threadResult, project, trigger, label, sessionKind, sessionOrigin, statusPrefix }) {
|
|
25
|
+
export async function finalizeThreadSuccess(adapter, channel, statusMsg, { startTime, sessionName, result, threadResult, project, trigger, label, sessionKind, sessionOrigin, statusPrefix, scheduleId }) {
|
|
26
26
|
const { elapsedStr, elapsedS } = computeElapsed(startTime);
|
|
27
27
|
if (result?.sessionId) {
|
|
28
|
+
// Register under the thread's last-step TRACK id: the conversation transcript and the
|
|
29
|
+
// session.message stream are keyed by it (threads/runner.ts step recorder), so registering
|
|
30
|
+
// the backend id instead yields a session with no transcript. The step registration for the
|
|
31
|
+
// same track id (origin 'thread') is intentionally overwritten — one record per run. The
|
|
32
|
+
// backend id is kept as backendSessionId, the resume target if the user replies to the run.
|
|
33
|
+
const steps = threadResult.thread?.steps ?? [];
|
|
34
|
+
const trackSessionId = steps.length > 0 ? steps[steps.length - 1]?.sessionId : null;
|
|
28
35
|
await sessionStore.registerSession(sessionName, {
|
|
29
|
-
sessionId: result.sessionId, channel,
|
|
36
|
+
sessionId: trackSessionId || result.sessionId, channel,
|
|
30
37
|
backend: getActiveBackend(), kind: sessionKind,
|
|
31
38
|
origin: sessionOrigin,
|
|
32
39
|
label,
|
|
33
40
|
profileName: getActiveProfile(channel),
|
|
34
41
|
projectId: project,
|
|
42
|
+
backendSessionId: result.sessionId,
|
|
43
|
+
scheduleId: scheduleId ?? null,
|
|
35
44
|
});
|
|
36
45
|
}
|
|
37
46
|
const metrics = formatMetricsSuffix({ costUsd: threadResult.totalCostUsd, numTurns: threadResult.totalNumTurns });
|
|
@@ -133,6 +133,7 @@ async function runScheduledTaskAsync({ normalizedMessage, message, projectId, sc
|
|
|
133
133
|
await finalizeThreadSuccess(adapter, projectId, statusMsg, {
|
|
134
134
|
startTime, sessionName, result, threadResult, project: projectId, trigger: 'scheduled',
|
|
135
135
|
label: message?.substring(0, 60) || null, sessionKind: 'scheduled', sessionOrigin: 'scheduled', statusPrefix: 'Done',
|
|
136
|
+
scheduleId: scheduleTaskId || null,
|
|
136
137
|
});
|
|
137
138
|
}
|
|
138
139
|
}
|
|
@@ -271,70 +271,65 @@ async function executeDispatchTask({ selected, selectedTask, channel, scheduleTa
|
|
|
271
271
|
}
|
|
272
272
|
return { success: true, skipped: false, note: `Completed [${selectedTask.project}] ${selectedTask.text.substring(0, 60)}` };
|
|
273
273
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
274
|
+
/** Counts this failure and, at the threshold, blocks the task. Runs BEFORE the claim is
|
|
275
|
+
* released: block() clears claimed_by itself, and its ownership check only passes while
|
|
276
|
+
* this dispatch's generation is still the task's own — unclaim() nulls that generation,
|
|
277
|
+
* so quarantining afterwards is refused as stale and the task loops forever. */
|
|
278
|
+
async function quarantineAfterFailure(taskId, ownership, error) {
|
|
279
|
+
const prev = dispatchFailureCounts.get(taskId) || { count: 0, lastError: '' };
|
|
280
|
+
const next = { count: prev.count + 1, lastError: error.message };
|
|
281
|
+
dispatchFailureCounts.set(taskId, next);
|
|
282
|
+
if (next.count < DISPATCH_FAILURE_QUARANTINE_THRESHOLD)
|
|
283
|
+
return false;
|
|
284
|
+
const blockReason = sanitizeBlockReason(`dispatch-failed-${next.count}x: ${error.message}`);
|
|
285
|
+
try {
|
|
286
|
+
const blockResult = await taskMutator.block(taskId, blockReason, { ownership });
|
|
287
|
+
if (blockResult.success) {
|
|
288
|
+
dispatchFailureCounts.delete(taskId);
|
|
289
|
+
return true;
|
|
284
290
|
}
|
|
291
|
+
log.error(`Failed to auto-block task ${taskId}: ${blockResult.message}`);
|
|
285
292
|
}
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
let blockReason = null;
|
|
289
|
-
if (selectedTask?.id) {
|
|
290
|
-
const taskId = selectedTask.id;
|
|
291
|
-
const prev = dispatchFailureCounts.get(taskId) || { count: 0, lastError: '' };
|
|
292
|
-
const next = { count: prev.count + 1, lastError: error.message };
|
|
293
|
-
dispatchFailureCounts.set(taskId, next);
|
|
294
|
-
if (next.count >= DISPATCH_FAILURE_QUARANTINE_THRESHOLD) {
|
|
295
|
-
blockReason = sanitizeBlockReason(`dispatch-failed-${next.count}x: ${error.message}`);
|
|
296
|
-
try {
|
|
297
|
-
const ownership = { generation: selectedTask.dispatch_generation ?? null };
|
|
298
|
-
const blockResult = await taskMutator.block(taskId, blockReason, { ownership });
|
|
299
|
-
if (blockResult.success) {
|
|
300
|
-
blocked = true;
|
|
301
|
-
dispatchFailureCounts.delete(taskId);
|
|
302
|
-
}
|
|
303
|
-
else {
|
|
304
|
-
log.error(`Failed to auto-block task ${taskId}: ${blockResult.message}`);
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
catch (e) {
|
|
308
|
-
log.error(`Failed to auto-block task ${taskId}: ${e.message}`);
|
|
309
|
-
}
|
|
310
|
-
}
|
|
293
|
+
catch (e) {
|
|
294
|
+
log.error(`Failed to auto-block task ${taskId}: ${e.message}`);
|
|
311
295
|
}
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
async function postDispatchErrorNotice(selectedTask, channel, error, blocked) {
|
|
299
|
+
const adapter = ctx.adapter;
|
|
300
|
+
const text = blocked && selectedTask
|
|
301
|
+
? `${Icons.blocked} Auto-blocked after ${DISPATCH_FAILURE_QUARANTINE_THRESHOLD} consecutive dispatch failures. Reason recorded in TASKS.yaml. Task: [${selectedTask.project}] ${String(selectedTask.text).substring(0, 80)}. Last error: ${error.message}. Unblock with \`cortex-task unblock --task-id ${selectedTask.id}\`.`
|
|
302
|
+
: `${Icons.error} Task dispatch error: ${error.message}`;
|
|
303
|
+
const projDest = { type: 'project-report', projectId: selectedTask?.project || channel, trigger: 'task-dispatch', sessionId: '' };
|
|
312
304
|
try {
|
|
313
305
|
const queue = getOutboundQueue();
|
|
314
|
-
if (
|
|
315
|
-
|
|
316
|
-
const projDest = { type: 'project-report', projectId: selectedTask.project || errChannel, trigger: 'task-dispatch', sessionId: '' };
|
|
317
|
-
if (queue) {
|
|
318
|
-
await durablePost(queue, adapter, projDest, { text });
|
|
319
|
-
}
|
|
320
|
-
else {
|
|
321
|
-
await adapter.postMessage(projDest, { text });
|
|
322
|
-
}
|
|
306
|
+
if (queue) {
|
|
307
|
+
await durablePost(queue, adapter, projDest, { text });
|
|
323
308
|
}
|
|
324
309
|
else {
|
|
325
|
-
|
|
326
|
-
const projDest = { type: 'project-report', projectId: selectedTask?.project || errChannel, trigger: 'task-dispatch', sessionId: '' };
|
|
327
|
-
if (queue) {
|
|
328
|
-
await durablePost(queue, adapter, projDest, { text });
|
|
329
|
-
}
|
|
330
|
-
else {
|
|
331
|
-
await adapter.postMessage(projDest, { text });
|
|
332
|
-
}
|
|
310
|
+
await adapter.postMessage(projDest, { text });
|
|
333
311
|
}
|
|
334
312
|
}
|
|
335
313
|
catch { }
|
|
336
|
-
|
|
337
|
-
|
|
314
|
+
}
|
|
315
|
+
async function handleDispatchError(error, selectedTask, channel) {
|
|
316
|
+
log.error(`Error: ${error.message}`);
|
|
317
|
+
const ownership = { generation: selectedTask?.dispatch_generation ?? null };
|
|
318
|
+
const blocked = selectedTask?.id
|
|
319
|
+
? await quarantineAfterFailure(selectedTask.id, ownership, error)
|
|
320
|
+
: false;
|
|
321
|
+
// A blocked task is already released by block(); only a task going back to the queue
|
|
322
|
+
// needs its claim dropped.
|
|
323
|
+
if (selectedTask && !blocked) {
|
|
324
|
+
try {
|
|
325
|
+
await taskMutator.unclaim(selectedTask.id, { ownership });
|
|
326
|
+
}
|
|
327
|
+
catch (e) {
|
|
328
|
+
log.error(`Failed to unclaim task: ${e.message}`);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
await postDispatchErrorNotice(selectedTask, channel, error, blocked);
|
|
332
|
+
return { success: false, skipped: false, note: `Error: ${error.message}${blocked ? ' (blocked)' : ''}` };
|
|
338
333
|
}
|
|
339
334
|
// --- Cancel dispatched task ---
|
|
340
335
|
export async function cancelDispatchedTask({ taskId, channel }) {
|
|
@@ -70,6 +70,28 @@ export interface AttachExistingSessionOpts {
|
|
|
70
70
|
/** Attach a channel to an existing session: restore its profile (if any), point sessions.json at it,
|
|
71
71
|
* and switch the conversation ledger. Mirrors the !resume switch sequence. */
|
|
72
72
|
export declare function attachExistingSession(channel: string, opts: AttachExistingSessionOpts): Promise<void>;
|
|
73
|
+
export interface AdoptScheduledSessionStore {
|
|
74
|
+
getById(sessionId: string): Promise<{
|
|
75
|
+
name: string;
|
|
76
|
+
channel: string;
|
|
77
|
+
backend: string;
|
|
78
|
+
origin: SessionOrigin;
|
|
79
|
+
profileName: string | null;
|
|
80
|
+
} | null>;
|
|
81
|
+
/** Re-point the registry record: channel → the adopted channel, kind → local, origin → direct. */
|
|
82
|
+
convertToDirect(sessionId: string, opts: {
|
|
83
|
+
channel: string;
|
|
84
|
+
}): Promise<unknown | null>;
|
|
85
|
+
}
|
|
86
|
+
/** Convert a scheduled run's session into a normal direct web session (design 27b: replying adopts
|
|
87
|
+
* the run). Attaches a dedicated `web:<sessionId>` conduit to the existing session — the same
|
|
88
|
+
* switch sequence as !resume, so a later send resumes the run's transcript — then re-points the
|
|
89
|
+
* registry record. `scheduleId` is intentionally KEPT on the record (provenance for the trigger
|
|
90
|
+
* card / schedule grouping). Idempotent: a non-scheduled record just returns its current channel;
|
|
91
|
+
* an unknown id returns null. */
|
|
92
|
+
export declare function adoptScheduledSession(store: AdoptScheduledSessionStore, sessionId: string): Promise<{
|
|
93
|
+
channel: string;
|
|
94
|
+
} | null>;
|
|
73
95
|
/** Clear a channel's session state: drop sessions.json keys for every backend, clean session
|
|
74
96
|
* backups, and clear the conversation ledger. Mirrors the store-level half of !new. */
|
|
75
97
|
export declare function resetChannelSession(channel: string): Promise<void>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// input: Session stores, conversation ledger, profile state
|
|
2
|
-
// output: Session register
|
|
2
|
+
// output: Session register/attach/create/adopt/reset primitives
|
|
3
3
|
// pos: Central session lifecycle shared by chat and TUI
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import * as crypto from 'node:crypto';
|
|
@@ -69,6 +69,25 @@ export async function attachExistingSession(channel, opts) {
|
|
|
69
69
|
sessionId: opts.sessionId, sessionName: opts.sessionName, backend: opts.backend, profileName: opts.profileName,
|
|
70
70
|
});
|
|
71
71
|
}
|
|
72
|
+
/** Convert a scheduled run's session into a normal direct web session (design 27b: replying adopts
|
|
73
|
+
* the run). Attaches a dedicated `web:<sessionId>` conduit to the existing session — the same
|
|
74
|
+
* switch sequence as !resume, so a later send resumes the run's transcript — then re-points the
|
|
75
|
+
* registry record. `scheduleId` is intentionally KEPT on the record (provenance for the trigger
|
|
76
|
+
* card / schedule grouping). Idempotent: a non-scheduled record just returns its current channel;
|
|
77
|
+
* an unknown id returns null. */
|
|
78
|
+
export async function adoptScheduledSession(store, sessionId) {
|
|
79
|
+
const record = await store.getById(sessionId);
|
|
80
|
+
if (!record)
|
|
81
|
+
return null;
|
|
82
|
+
if (record.origin !== 'scheduled')
|
|
83
|
+
return { channel: record.channel };
|
|
84
|
+
const channel = `web:${sessionId}`;
|
|
85
|
+
await attachExistingSession(channel, {
|
|
86
|
+
sessionId, sessionName: record.name, backend: record.backend, profileName: record.profileName,
|
|
87
|
+
});
|
|
88
|
+
await store.convertToDirect(sessionId, { channel });
|
|
89
|
+
return { channel };
|
|
90
|
+
}
|
|
72
91
|
/** Clear a channel's session state: drop sessions.json keys for every backend, clean session
|
|
73
92
|
* backups, and clear the conversation ledger. Mirrors the store-level half of !new. */
|
|
74
93
|
export async function resetChannelSession(channel) {
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
// input: CORTEX_VERSION, child_process (execSync, spawn), compareCalVer from server-update-check
|
|
1
|
+
// input: CORTEX_VERSION, child_process (execSync, spawn), compareCalVer from server-update-check, withNpmPrefix
|
|
2
2
|
// output: cortex install latest CLI
|
|
3
3
|
// pos: CLI module for cortex install — install latest Cortex version from npm
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import { execSync, spawn } from 'node:child_process';
|
|
6
6
|
import { CORTEX_VERSION } from '../../core/version.js';
|
|
7
|
+
import { withNpmPrefix } from '../../core/utils.js';
|
|
7
8
|
import { compareCalVer } from './server-update-check.js';
|
|
8
9
|
// ─── Help ─────────────────────────────────────────────────────────
|
|
9
10
|
export function getInstallHelp() {
|
|
@@ -56,9 +57,13 @@ async function installLatest() {
|
|
|
56
57
|
process.stdout.write(`Current version: ${CORTEX_VERSION}\n`);
|
|
57
58
|
process.stdout.write(`Latest version: ${latest}\n`);
|
|
58
59
|
process.stdout.write(`Installing @cortex-agent/server@${latest}...\n\n`);
|
|
59
|
-
// 4. Run npm install -g (stdio: 'inherit' so user sees npm progress)
|
|
60
|
+
// 4. Run npm install -g (stdio: 'inherit' so user sees npm progress).
|
|
61
|
+
// The prefix is pinned to the root the running `cortex` binary lives in — without it
|
|
62
|
+
// npm falls back to its configured/system prefix (root-owned → EACCES) on machines
|
|
63
|
+
// that were installed with `--prefix ~/.npm-global` but no .npmrc entry.
|
|
60
64
|
return new Promise((resolve) => {
|
|
61
|
-
const
|
|
65
|
+
const args = withNpmPrefix(['install', '-g', `@cortex-agent/server@${latest}`], 'cortex');
|
|
66
|
+
const child = spawn('npm', args, {
|
|
62
67
|
stdio: 'inherit',
|
|
63
68
|
cwd: '/tmp',
|
|
64
69
|
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PlatformAdapter, RichBlock } from '../../platform/index.js';
|
|
1
|
+
import type { PlatformAdapter, RichBlock, ActionElement } from '../../platform/index.js';
|
|
2
2
|
export type SystemNoticeLevel = 'info' | 'warning' | 'error';
|
|
3
3
|
export interface SystemNoticeInput {
|
|
4
4
|
/** The notice body (same text that goes to the admin channel). */
|
|
@@ -9,6 +9,9 @@ export interface SystemNoticeInput {
|
|
|
9
9
|
title?: string;
|
|
10
10
|
/** Optional platform-native content; Web notices continue to use the secret-free text fields. */
|
|
11
11
|
richBlocks?: RichBlock[];
|
|
12
|
+
/** Optional action buttons attached to the platform post (Slack/Feishu interactive).
|
|
13
|
+
* When present the notice is delivered via postInteractive; absent keeps postMessage. */
|
|
14
|
+
actions?: ActionElement[];
|
|
12
15
|
}
|
|
13
16
|
/** Publish a `system.notice` event on the shared EventBus (the Web notification-toast source).
|
|
14
17
|
* No-op when no bus is wired (matches publishSessionMessage). */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// input: PlatformAdapter, notice payload, shared job context
|
|
2
|
-
// output: Web publication and rich best-effort admin delivery
|
|
2
|
+
// output: Web publication and rich/actionable best-effort admin delivery
|
|
3
3
|
// pos: Domain seam for admin and system broadcasts
|
|
4
4
|
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
5
|
import { ctx as jobCtx } from '../scheduling/job-registry.js';
|
|
@@ -20,7 +20,11 @@ export function publishSystemNotice(p) {
|
|
|
20
20
|
export async function emitSystemNotice(adapter, p) {
|
|
21
21
|
publishSystemNotice(p);
|
|
22
22
|
try {
|
|
23
|
-
const
|
|
23
|
+
const destination = { type: 'system-notice' };
|
|
24
|
+
const content = { text: p.text, ...(p.richBlocks ? { richBlocks: p.richBlocks } : {}) };
|
|
25
|
+
const ref = p.actions?.length
|
|
26
|
+
? await adapter.postInteractive(destination, { ...content, actions: p.actions })
|
|
27
|
+
: await adapter.postMessage(destination, content);
|
|
24
28
|
return ref.conduit.length > 0;
|
|
25
29
|
}
|
|
26
30
|
catch {
|
|
@@ -41,10 +41,6 @@ declare function getMachineRegistry(): MachineRegistry;
|
|
|
41
41
|
* Falls back to 'local' if no machines are registered.
|
|
42
42
|
*/
|
|
43
43
|
declare function getLocalMachine(): string;
|
|
44
|
-
/**
|
|
45
|
-
* Start watching machines.json for changes. Reloads on file edit.
|
|
46
|
-
* Handles atomic file replacement (rename event) by re-creating the watcher.
|
|
47
|
-
*/
|
|
48
44
|
declare function startMachineRegistryWatcher(): void;
|
|
49
45
|
/**
|
|
50
46
|
* Stop watching machines.json (for tests / graceful shutdown).
|
|
@@ -1,18 +1,19 @@
|
|
|
1
|
-
// input: machine config, task
|
|
1
|
+
// input: machine config, resilient watch, task ownership
|
|
2
2
|
// output: device registry, task IDs, dispatch outcome helpers
|
|
3
3
|
// pos: Shared task dispatch utilities
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import * as crypto from 'crypto';
|
|
6
|
-
import { readFileSync,
|
|
6
|
+
import { readFileSync, existsSync } from 'fs';
|
|
7
7
|
import * as path from 'path';
|
|
8
8
|
import { CONFIG_DIR } from '../../core/utils.js';
|
|
9
9
|
import { createLogger } from '../../core/log.js';
|
|
10
|
+
import { createFileWatchMonitor } from '../../core/resilient-watch.js';
|
|
10
11
|
import { Icons } from '../../core/icons.js';
|
|
11
12
|
const log = createLogger('machine-registry');
|
|
12
13
|
const MACHINES_FILE = path.join(CONFIG_DIR, 'machines.json');
|
|
13
14
|
let _registry = {};
|
|
14
15
|
let _loaded = false;
|
|
15
|
-
let
|
|
16
|
+
let _watchMonitor = null;
|
|
16
17
|
let _reloadTimer = null;
|
|
17
18
|
// --- Admin notification (hot-reload → Slack) ---
|
|
18
19
|
let _adminNotifier = null;
|
|
@@ -75,48 +76,34 @@ function getLocalMachine() {
|
|
|
75
76
|
}
|
|
76
77
|
/**
|
|
77
78
|
* Start watching machines.json for changes. Reloads on file edit.
|
|
78
|
-
*
|
|
79
|
+
* Watches the parent directory so atomic file replacement keeps monitoring active.
|
|
79
80
|
*/
|
|
81
|
+
function scheduleMachineReload() {
|
|
82
|
+
if (_reloadTimer)
|
|
83
|
+
clearTimeout(_reloadTimer);
|
|
84
|
+
_reloadTimer = setTimeout(() => {
|
|
85
|
+
_reloadTimer = null;
|
|
86
|
+
loadMachinesFromFile(false);
|
|
87
|
+
}, 300);
|
|
88
|
+
}
|
|
80
89
|
function startMachineRegistryWatcher() {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if (eventType === 'rename') {
|
|
89
|
-
// File was atomically replaced — inode changed, watcher is dead.
|
|
90
|
-
// Re-create after a short delay to let the new file settle.
|
|
91
|
-
setTimeout(() => setup(), 100);
|
|
92
|
-
return; // setup() will handle the reload after the new watcher fires
|
|
93
|
-
}
|
|
94
|
-
if (_reloadTimer)
|
|
95
|
-
clearTimeout(_reloadTimer);
|
|
96
|
-
_reloadTimer = setTimeout(() => {
|
|
97
|
-
_reloadTimer = null;
|
|
98
|
-
loadMachinesFromFile(false); // hot-reload: don't crash on error
|
|
99
|
-
}, 300);
|
|
100
|
-
});
|
|
101
|
-
}
|
|
102
|
-
catch (e) {
|
|
103
|
-
log.error(`Failed to watch machines.json: ${e.message}`);
|
|
104
|
-
}
|
|
105
|
-
};
|
|
106
|
-
setup();
|
|
90
|
+
_watchMonitor?.close();
|
|
91
|
+
_watchMonitor = createFileWatchMonitor({
|
|
92
|
+
label: 'machines.json',
|
|
93
|
+
filePath: MACHINES_FILE,
|
|
94
|
+
onChange: scheduleMachineReload,
|
|
95
|
+
warn: (message) => log.error(message),
|
|
96
|
+
});
|
|
107
97
|
}
|
|
108
98
|
/**
|
|
109
99
|
* Stop watching machines.json (for tests / graceful shutdown).
|
|
110
100
|
*/
|
|
111
101
|
function stopMachineRegistryWatcher() {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
116
|
-
if (_reloadTimer) {
|
|
102
|
+
_watchMonitor?.close();
|
|
103
|
+
_watchMonitor = null;
|
|
104
|
+
if (_reloadTimer)
|
|
117
105
|
clearTimeout(_reloadTimer);
|
|
118
|
-
|
|
119
|
-
}
|
|
106
|
+
_reloadTimer = null;
|
|
120
107
|
}
|
|
121
108
|
// --- Auto-load at import time (equivalent to the old hardcoded constant) ---
|
|
122
109
|
// This ensures getMachineRegistry() works immediately for all consumers.
|
|
@@ -2,7 +2,10 @@ import { type PendingControl } from './index.js';
|
|
|
2
2
|
import type { OutputStream } from '../../platform/output-stream.js';
|
|
3
3
|
import type { RunningExecution } from '../../core/running-executions.js';
|
|
4
4
|
import { type StepTranscriptRecorder } from './thread-transcript.js';
|
|
5
|
-
import type { ThreadRecord, AgentSlotId, AgentSlotConfig, ThreadTemplate, RunThreadOptions } from '../../core/types/thread-types.js';
|
|
5
|
+
import type { ThreadRecord, AgentSlotId, AgentSlotConfig, ThreadTemplate, RunThreadOptions, TransitionResult } from '../../core/types/thread-types.js';
|
|
6
|
+
/** Why the step loop stopped scheduling, in the transition engine's own terms. `transition` is
|
|
7
|
+
* excluded because it is the one verdict that does not stop the loop. */
|
|
8
|
+
export type ThreadStopReason = Exclude<TransitionResult['reason'], 'transition'>;
|
|
6
9
|
export declare class BenchmarkRateLimitError extends Error {
|
|
7
10
|
readonly provider: string | null;
|
|
8
11
|
readonly code = "BENCHMARK_RATE_LIMITED";
|
|
@@ -20,6 +23,9 @@ interface ThreadRunResult {
|
|
|
20
23
|
lastAgentResult: any;
|
|
21
24
|
/** The execution ID from the last completed step — used by handleAgentSuccess in the wrapper. */
|
|
22
25
|
executionId: string | null;
|
|
26
|
+
/** Why the transition engine stopped scheduling steps, in its own typed terms. Null when the
|
|
27
|
+
* loop left for a reason the engine never judged. */
|
|
28
|
+
stopReason: ThreadStopReason | null;
|
|
23
29
|
}
|
|
24
30
|
/** Outer-scope state shared across the whole runThread() lifecycle. */
|
|
25
31
|
interface ThreadContext {
|
|
@@ -32,6 +38,9 @@ interface ThreadContext {
|
|
|
32
38
|
/** Set when a step was interrupted by a provider throttle.
|
|
33
39
|
* Pauses the thread (status='rate_limited') instead of completing/failing it. */
|
|
34
40
|
rateLimited?: boolean;
|
|
41
|
+
/** Why the transition engine stopped scheduling steps. Null when the loop left for a reason the
|
|
42
|
+
* engine never judged — an abort, a wait or a throttle. */
|
|
43
|
+
stopReason: ThreadStopReason | null;
|
|
35
44
|
}
|
|
36
45
|
/** Per-step config built once by buildStepConfig — fully populated, no placeholders. */
|
|
37
46
|
interface StepContext {
|
|
@@ -41,6 +50,9 @@ interface StepContext {
|
|
|
41
50
|
multiAgent: boolean;
|
|
42
51
|
/** Stage this step runs. Null for single-stage agents (no `stages` map declared). */
|
|
43
52
|
stage: string | null;
|
|
53
|
+
/** Index this step occupies in the thread's step list, captured before the step runs (the
|
|
54
|
+
* record advances it once the step's result is recorded). */
|
|
55
|
+
stepIndex: number;
|
|
44
56
|
prompt: string;
|
|
45
57
|
/** True when this step re-enters an interrupted attempt's backend session: the prompt is the
|
|
46
58
|
* continuation reminder, and first-step files are not re-attached. */
|
|
@@ -48,6 +60,9 @@ interface StepContext {
|
|
|
48
60
|
/** Flipped by the step callbacks on the first streamed assistant/tool event. Gates capturing
|
|
49
61
|
* the interrupted backend session — an attempt with no activity has nothing worth resuming. */
|
|
50
62
|
sawActivity: boolean;
|
|
63
|
+
/** The last non-empty assistant message this step emitted, captured off the normalized event
|
|
64
|
+
* channel every backend populates. Stays null when the step emitted none. */
|
|
65
|
+
terminalAssistantText: string | null;
|
|
51
66
|
/** Backend `--resume` target (slot.backendSessionId via beginStepSession); null → fresh. */
|
|
52
67
|
resumeSessionId: string | null;
|
|
53
68
|
/** Stable Cortex track id (slot.sessionId, minted at step start) — the conversation-history /
|