@cortex-agent/server 2026.6.18 → 2026.6.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.
- package/defaults/CORTEX.md +5 -0
- package/defaults/hooks/ask-user-question-hook.mjs +6 -1
- package/defaults/hooks/exit-plan-mode-hook.mjs +6 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +7 -0
- package/defaults/prompts/systemPrompts/coder.md +6 -1
- package/defaults/prompts/systemPrompts/direct.md +5 -0
- package/defaults/prompts/systemPrompts/web-opus-4-6.md +6 -1
- package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +6 -1
- package/defaults/prompts/systemPrompts/web.md +6 -1
- package/defaults/prompts/systemPrompts/worker.md +6 -1
- package/dist/agent-adapter/claude/adapter.d.ts +110 -1
- package/dist/agent-adapter/claude/adapter.js +117 -0
- package/dist/agent-adapter/claude/bg-task-tracker.d.ts +37 -0
- package/dist/agent-adapter/claude/bg-task-tracker.js +78 -0
- package/dist/agent-adapter/normalize/event-types.d.ts +4 -0
- package/dist/agent-adapter/pi/event-parser.d.ts +3 -1
- package/dist/agent-adapter/pi/event-parser.js +12 -2
- package/dist/agent-adapter/types.d.ts +19 -0
- package/dist/core/auth.d.ts +36 -0
- package/dist/core/auth.js +85 -0
- package/dist/core/locales/en.d.ts +6 -0
- package/dist/core/locales/slices/status.d.ts +6 -0
- package/dist/core/locales/slices/status.js +16 -0
- package/dist/core/types/agent-types.d.ts +5 -0
- package/dist/core/types/thread-types.d.ts +12 -1
- package/dist/core/version.d.ts +3 -0
- package/dist/core/version.js +4 -1
- package/dist/domain/agents/facade.js +12 -0
- package/dist/domain/costs/rate-limit-throttle.d.ts +1 -1
- package/dist/domain/costs/rate-limit-throttle.js +23 -2
- package/dist/domain/costs/resume-registry.d.ts +30 -0
- package/dist/domain/costs/resume-registry.js +68 -0
- package/dist/domain/mcp/core-server.js +5 -0
- package/dist/domain/mcp/tools/manager-qa.d.ts +2 -0
- package/dist/domain/mcp/tools/manager-qa.js +72 -0
- package/dist/domain/mcp/tools/task-ops.js +4 -2
- package/dist/domain/mcp/tools/thread-ops.js +2 -1
- package/dist/domain/mcp/tui-server.js +2 -1
- package/dist/domain/remote/client-bootstrap.js +14 -2
- package/dist/domain/remote/client-manager.d.ts +1 -1
- package/dist/domain/remote/client-manager.js +31 -5
- package/dist/domain/remote/cortex-client-config.d.ts +32 -0
- package/dist/domain/remote/cortex-client-config.js +49 -0
- package/dist/domain/remote/cortex-client.js +11 -7
- package/dist/domain/scheduling/jobs/scheduled-task.js +17 -1
- package/dist/domain/scheduling/jobs/task-dispatch.js +21 -0
- package/dist/domain/tasks/dispatcher.js +8 -0
- package/dist/domain/tasks/system/cortex-run.js +4 -2
- package/dist/domain/threads/runner.d.ts +8 -1
- package/dist/domain/threads/runner.js +81 -11
- package/dist/domain/threads/state-machine.d.ts +5 -0
- package/dist/domain/threads/state-machine.js +16 -0
- package/dist/entry/app.js +19 -4
- package/dist/entry/init.js +6 -0
- package/dist/hooks/ask-user-question-hook.mjs +6 -1
- package/dist/hooks/exit-plan-mode-hook.mjs +6 -1
- package/dist/orchestration/agent-runner.js +28 -3
- package/dist/orchestration/bg-continuation.d.ts +26 -0
- package/dist/orchestration/bg-continuation.js +34 -0
- package/dist/orchestration/conversation-runner.d.ts +3 -0
- package/dist/orchestration/conversation-runner.js +1 -1
- package/dist/orchestration/interactions/interaction-handlers.js +13 -2
- package/dist/orchestration/lifecycle.d.ts +3 -1
- package/dist/orchestration/lifecycle.js +72 -2
- package/dist/orchestration/manager-qa.d.ts +55 -0
- package/dist/orchestration/manager-qa.js +218 -0
- package/dist/orchestration/resume-dispatcher.d.ts +22 -0
- package/dist/orchestration/resume-dispatcher.js +129 -0
- package/dist/orchestration/routing/webhook.d.ts +1 -1
- package/dist/orchestration/routing/webhook.js +75 -14
- package/dist/orchestration/status-helpers.d.ts +3 -0
- package/dist/orchestration/status-helpers.js +16 -0
- package/dist/orchestration/thread-callback.d.ts +13 -1
- package/dist/orchestration/thread-callback.js +18 -1
- package/dist/orchestration/turn-notify.d.ts +26 -0
- package/dist/orchestration/turn-notify.js +66 -0
- package/dist/platform/adapters/feishu.d.ts +16 -0
- package/dist/platform/adapters/feishu.js +67 -6
- package/dist/store/schedule-repo.d.ts +6 -0
- package/dist/store/schedule-repo.js +11 -1
- package/dist/store/thread-repo.js +14 -0
- package/dist/store/version-migrations.d.ts +14 -4
- package/dist/store/version-migrations.js +67 -9
- package/package.json +1 -1
|
@@ -12,15 +12,17 @@ import { WORKSPACE_DIR } from '../../../core/utils.js';
|
|
|
12
12
|
import { cortexMDContentBlocks } from './cortex-md.js';
|
|
13
13
|
// Remote device commands proxied through app.ts webhook (separate process, no shared memory with client-manager)
|
|
14
14
|
const WEBHOOK_BASE = `http://127.0.0.1:${process.env.WEBHOOK_PORT || '3001'}`;
|
|
15
|
+
// Bearer token for the webhook auth gate. Inherited from the daemon's env (see core/auth.ts).
|
|
16
|
+
const webhookAuthHeader = () => ({ 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '' });
|
|
15
17
|
async function proxyGetOnlineDevices() {
|
|
16
|
-
const res = await fetch(`${WEBHOOK_BASE}/webhook/devices
|
|
18
|
+
const res = await fetch(`${WEBHOOK_BASE}/webhook/devices`, { headers: webhookAuthHeader() });
|
|
17
19
|
const data = await res.json();
|
|
18
20
|
return data.devices || [];
|
|
19
21
|
}
|
|
20
22
|
async function proxySendCommand(device, action, params, timeout) {
|
|
21
23
|
const res = await fetch(`${WEBHOOK_BASE}/webhook/remote-command`, {
|
|
22
24
|
method: 'POST',
|
|
23
|
-
headers: { 'Content-Type': 'application/json' },
|
|
25
|
+
headers: { 'Content-Type': 'application/json', ...webhookAuthHeader() },
|
|
24
26
|
body: JSON.stringify({ device, action, params, timeout }),
|
|
25
27
|
});
|
|
26
28
|
const data = await res.json();
|
|
@@ -14,7 +14,8 @@ const WEBHOOK_BASE = `http://127.0.0.1:${process.env.WEBHOOK_PORT || '3001'}`;
|
|
|
14
14
|
async function proxyThreadOp(action, payload) {
|
|
15
15
|
const res = await fetch(`${WEBHOOK_BASE}/webhook/thread-op`, {
|
|
16
16
|
method: 'POST',
|
|
17
|
-
|
|
17
|
+
// Bearer token for the webhook auth gate. Inherited from the daemon's env (see core/auth.ts).
|
|
18
|
+
headers: { 'Content-Type': 'application/json', 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '' },
|
|
18
19
|
body: JSON.stringify({ action, ...payload }),
|
|
19
20
|
});
|
|
20
21
|
const data = await res.json();
|
|
@@ -21,7 +21,8 @@ const webhookBaseUrl = `http://127.0.0.1:${webhookPort}`;
|
|
|
21
21
|
async function defaultHttpPost(url, body) {
|
|
22
22
|
const r = await fetch(url, {
|
|
23
23
|
method: 'POST',
|
|
24
|
-
|
|
24
|
+
// Bearer token for the webhook auth gate. Inherited from the session's env (see core/auth.ts).
|
|
25
|
+
headers: { 'Content-Type': 'application/json', 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '' },
|
|
25
26
|
body: JSON.stringify(body),
|
|
26
27
|
});
|
|
27
28
|
let parsed = null;
|
|
@@ -18,6 +18,10 @@ if (!serverHost) {
|
|
|
18
18
|
process.exit(1);
|
|
19
19
|
}
|
|
20
20
|
const serverPort = getArg('--server-port') || '3002';
|
|
21
|
+
// The WS auth token the remote client must present. Falls back to the server's own env so a
|
|
22
|
+
// bootstrap run on the server host picks it up automatically. Empty means the client cannot
|
|
23
|
+
// authenticate — we warn loudly below.
|
|
24
|
+
const clientToken = getArg('--client-token') || process.env.CORTEX_CLIENT_TOKEN || '';
|
|
21
25
|
if (!sshHost) {
|
|
22
26
|
log.error(`Usage: node --import tsx src/client-bootstrap.ts --host user@host --device-name NAME [options]
|
|
23
27
|
|
|
@@ -26,6 +30,7 @@ Options:
|
|
|
26
30
|
--device-name <name> Device name for cortex-client (required)
|
|
27
31
|
--server-host <host> Cortex server IP (required)
|
|
28
32
|
--server-port <port> Cortex server WS port (default: 3002)
|
|
33
|
+
--client-token <token> WS auth token (default: \$CORTEX_CLIENT_TOKEN from server env)
|
|
29
34
|
`);
|
|
30
35
|
process.exit(1);
|
|
31
36
|
}
|
|
@@ -99,7 +104,13 @@ async function main() {
|
|
|
99
104
|
}
|
|
100
105
|
// Step 5: Create systemd service
|
|
101
106
|
console.log('[5/5] Setting up auto-start...');
|
|
107
|
+
if (!clientToken) {
|
|
108
|
+
log.warn('No client token available (pass --client-token or set CORTEX_CLIENT_TOKEN). The');
|
|
109
|
+
log.warn('client will be REJECTED by the server WS auth gate until a token is configured.');
|
|
110
|
+
}
|
|
102
111
|
const platform = await sshExec('uname -s').catch(() => 'unknown');
|
|
112
|
+
// Token is hex (no systemd-special chars), so it is safe to embed directly.
|
|
113
|
+
const tokenEnvLine = clientToken ? `Environment=CORTEX_CLIENT_TOKEN=${clientToken}\n` : '';
|
|
103
114
|
if (platform === 'Linux') {
|
|
104
115
|
const serviceContent = `[Unit]
|
|
105
116
|
Description=Cortex Client (${deviceName})
|
|
@@ -107,7 +118,7 @@ After=network.target
|
|
|
107
118
|
|
|
108
119
|
[Service]
|
|
109
120
|
Type=simple
|
|
110
|
-
ExecStart=/usr/bin/env cortex-client
|
|
121
|
+
${tokenEnvLine}ExecStart=/usr/bin/env cortex-client
|
|
111
122
|
Restart=always
|
|
112
123
|
RestartSec=5
|
|
113
124
|
|
|
@@ -124,7 +135,8 @@ WantedBy=default.target
|
|
|
124
135
|
}
|
|
125
136
|
else {
|
|
126
137
|
// Non-Linux: just create a wrapper script
|
|
127
|
-
const
|
|
138
|
+
const tokenExport = clientToken ? `export CORTEX_CLIENT_TOKEN=${clientToken}\n` : '';
|
|
139
|
+
const startScript = `#!/bin/bash\n${tokenExport}exec cortex-client\n`;
|
|
128
140
|
await sshExec(`mkdir -p ~/.cortex/bin`);
|
|
129
141
|
await sshExec(`cat > ~/.cortex/bin/start-client.sh << 'SHEOF'\n${startScript}\nSHEOF`);
|
|
130
142
|
await sshExec(`chmod +x ~/.cortex/bin/start-client.sh`);
|
|
@@ -39,7 +39,7 @@ type SshExec = (host: string, command: string, timeout?: number) => Promise<stri
|
|
|
39
39
|
* Linux note: the shell handles PATH lookup; `nohup` detaches and `echo $!`
|
|
40
40
|
* returns the child PID on stdout.
|
|
41
41
|
*/
|
|
42
|
-
declare function buildRemoteSpawnCommand(reg: MachineEntry): string;
|
|
42
|
+
declare function buildRemoteSpawnCommand(reg: MachineEntry, clientToken?: string): string;
|
|
43
43
|
declare function startRemoteClient(device: string): Promise<void>;
|
|
44
44
|
/** Start clients on all registered devices */
|
|
45
45
|
declare function startAllRemoteClients(): Promise<void>;
|
|
@@ -10,6 +10,7 @@ import * as path from 'path';
|
|
|
10
10
|
import { execFile, spawn } from 'child_process';
|
|
11
11
|
import { getMachineRegistry } from '../tasks/dispatch-utils.js';
|
|
12
12
|
import { STORE_DIR } from '../../core/utils.js';
|
|
13
|
+
import { AUTH_HEADER, getClientToken, timingSafeEqualStr } from '../../core/auth.js';
|
|
13
14
|
import { createLogger } from '../../core/log.js';
|
|
14
15
|
import { readTasks, findTask } from '../tasks/system/task-lifecycle-edit.js';
|
|
15
16
|
import { taskMutator } from '../tasks/mutator.js';
|
|
@@ -28,7 +29,24 @@ function startClientManager(port) {
|
|
|
28
29
|
log.warn('Already running');
|
|
29
30
|
return;
|
|
30
31
|
}
|
|
31
|
-
|
|
32
|
+
// Authenticate at the HTTP upgrade (before the WS is established): the client must send a
|
|
33
|
+
// valid bearer token in the `x-cortex-token` header. Fail-closed — an unset server token or
|
|
34
|
+
// a missing/mismatched header rejects the upgrade with 401. This is the no-Cloudflare gate.
|
|
35
|
+
wss = new WebSocketServer({
|
|
36
|
+
port,
|
|
37
|
+
verifyClient: (info, cb) => {
|
|
38
|
+
const provided = info.req.headers[AUTH_HEADER];
|
|
39
|
+
const headerVal = Array.isArray(provided) ? provided[0] : provided;
|
|
40
|
+
if (timingSafeEqualStr(getClientToken(), headerVal)) {
|
|
41
|
+
cb(true);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
const from = info.req.socket?.remoteAddress || 'unknown';
|
|
45
|
+
log.warn(`WS auth rejected from ${from}: ${headerVal ? 'invalid token' : 'missing token'}`);
|
|
46
|
+
cb(false, 401, 'Unauthorized');
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
});
|
|
32
50
|
log.info(`WebSocket server started on port ${port}`);
|
|
33
51
|
wss.on('connection', (ws) => {
|
|
34
52
|
let deviceName = null;
|
|
@@ -271,11 +289,19 @@ let _getRegistryImpl = getMachineRegistry;
|
|
|
271
289
|
* Linux note: the shell handles PATH lookup; `nohup` detaches and `echo $!`
|
|
272
290
|
* returns the child PID on stdout.
|
|
273
291
|
*/
|
|
274
|
-
function buildRemoteSpawnCommand(reg) {
|
|
292
|
+
function buildRemoteSpawnCommand(reg, clientToken) {
|
|
293
|
+
const token = clientToken?.trim();
|
|
275
294
|
if (reg.win) {
|
|
276
|
-
|
|
295
|
+
// Inject the token via `cmd.exe /c set ... && cortex-client` so the WMI-spawned process
|
|
296
|
+
// sees CORTEX_CLIENT_TOKEN. Tokens are hex (no shell metacharacters), so no escaping needed.
|
|
297
|
+
const inner = token
|
|
298
|
+
? `cmd.exe /c set CORTEX_CLIENT_TOKEN=${token} && cortex-client`
|
|
299
|
+
: `cmd.exe /c cortex-client`;
|
|
300
|
+
return `powershell -Command "(Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList '${inner}').ProcessId"`;
|
|
277
301
|
}
|
|
278
|
-
|
|
302
|
+
// Single-quote the token for the remote shell (hex value has no quotes to escape).
|
|
303
|
+
const envPrefix = token ? `CORTEX_CLIENT_TOKEN='${token}' ` : '';
|
|
304
|
+
return `${envPrefix}nohup cortex-client > /dev/null 2>&1 & echo $!`;
|
|
279
305
|
}
|
|
280
306
|
async function isRemotePidAlive(device) {
|
|
281
307
|
const reg = _getRegistryImpl()[device];
|
|
@@ -340,7 +366,7 @@ async function startRemoteClient(device) {
|
|
|
340
366
|
// restart, because scheduleRestart() is otherwise only triggered by disconnect or
|
|
341
367
|
// heartbeat-timeout of an already-connected device.
|
|
342
368
|
try {
|
|
343
|
-
const pidStr = await _sshExecImpl(reg.ssh, buildRemoteSpawnCommand(reg), 30000);
|
|
369
|
+
const pidStr = await _sshExecImpl(reg.ssh, buildRemoteSpawnCommand(reg, getClientToken()), 30000);
|
|
344
370
|
const pid = parseInt(pidStr);
|
|
345
371
|
if (!isNaN(pid) && pid > 0) {
|
|
346
372
|
clientPids.set(device, pid);
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface ClientConnectEnv {
|
|
2
|
+
CORTEX_SERVER_URL?: string;
|
|
3
|
+
CORTEX_SERVER_HOST?: string;
|
|
4
|
+
CORTEX_SERVER_PORT?: string;
|
|
5
|
+
CF_ACCESS_CLIENT_ID?: string;
|
|
6
|
+
CF_ACCESS_CLIENT_SECRET?: string;
|
|
7
|
+
CORTEX_CLIENT_TOKEN?: string;
|
|
8
|
+
[key: string]: string | undefined;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Resolve the WebSocket URL the cortex-client dials.
|
|
12
|
+
*
|
|
13
|
+
* A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.fangxm.me``) takes
|
|
14
|
+
* precedence so the client can reach the agent-server through a Cloudflare
|
|
15
|
+
* Tunnel over 443/TLS. Otherwise it falls back to ``ws://<host>:<port>`` for
|
|
16
|
+
* direct/LAN reach.
|
|
17
|
+
*/
|
|
18
|
+
export declare function resolveServerUrl(env: ClientConnectEnv): string;
|
|
19
|
+
/**
|
|
20
|
+
* Cloudflare Access service-token headers, returned only when both the client
|
|
21
|
+
* id and secret are configured. These let the cortex-client pass a Cloudflare
|
|
22
|
+
* Access policy placed in front of the tunnel (the agent-server WebSocket has
|
|
23
|
+
* no auth of its own, so Access is the gate when it is exposed publicly).
|
|
24
|
+
*/
|
|
25
|
+
export declare function buildAccessHeaders(env: ClientConnectEnv): Record<string, string> | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* Connection headers the cortex-client sends on the WebSocket upgrade. Combines the
|
|
28
|
+
* optional Cloudflare Access service-token headers with the Cortex bearer token
|
|
29
|
+
* (``x-cortex-token`` from ``CORTEX_CLIENT_TOKEN``) that the agent-server's WebSocket
|
|
30
|
+
* gate requires. Returns undefined when neither is configured.
|
|
31
|
+
*/
|
|
32
|
+
export declare function buildAuthHeaders(env: ClientConnectEnv): Record<string, string> | undefined;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// input: process.env-style connection config for cortex-client
|
|
2
|
+
// output: resolved WebSocket server URL + optional Cloudflare Access headers
|
|
3
|
+
// pos: side-effect-free connection-config resolution for cortex-client
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
/**
|
|
6
|
+
* Resolve the WebSocket URL the cortex-client dials.
|
|
7
|
+
*
|
|
8
|
+
* A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.fangxm.me``) takes
|
|
9
|
+
* precedence so the client can reach the agent-server through a Cloudflare
|
|
10
|
+
* Tunnel over 443/TLS. Otherwise it falls back to ``ws://<host>:<port>`` for
|
|
11
|
+
* direct/LAN reach.
|
|
12
|
+
*/
|
|
13
|
+
export function resolveServerUrl(env) {
|
|
14
|
+
const url = env.CORTEX_SERVER_URL?.trim();
|
|
15
|
+
if (url)
|
|
16
|
+
return url;
|
|
17
|
+
const port = env.CORTEX_SERVER_PORT || '3002';
|
|
18
|
+
return `ws://${env.CORTEX_SERVER_HOST}:${port}`;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Cloudflare Access service-token headers, returned only when both the client
|
|
22
|
+
* id and secret are configured. These let the cortex-client pass a Cloudflare
|
|
23
|
+
* Access policy placed in front of the tunnel (the agent-server WebSocket has
|
|
24
|
+
* no auth of its own, so Access is the gate when it is exposed publicly).
|
|
25
|
+
*/
|
|
26
|
+
export function buildAccessHeaders(env) {
|
|
27
|
+
const id = env.CF_ACCESS_CLIENT_ID?.trim();
|
|
28
|
+
const secret = env.CF_ACCESS_CLIENT_SECRET?.trim();
|
|
29
|
+
if (id && secret) {
|
|
30
|
+
return {
|
|
31
|
+
'CF-Access-Client-Id': id,
|
|
32
|
+
'CF-Access-Client-Secret': secret,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Connection headers the cortex-client sends on the WebSocket upgrade. Combines the
|
|
39
|
+
* optional Cloudflare Access service-token headers with the Cortex bearer token
|
|
40
|
+
* (``x-cortex-token`` from ``CORTEX_CLIENT_TOKEN``) that the agent-server's WebSocket
|
|
41
|
+
* gate requires. Returns undefined when neither is configured.
|
|
42
|
+
*/
|
|
43
|
+
export function buildAuthHeaders(env) {
|
|
44
|
+
const headers = { ...(buildAccessHeaders(env) ?? {}) };
|
|
45
|
+
const token = env.CORTEX_CLIENT_TOKEN?.trim();
|
|
46
|
+
if (token)
|
|
47
|
+
headers['x-cortex-token'] = token;
|
|
48
|
+
return Object.keys(headers).length > 0 ? headers : undefined;
|
|
49
|
+
}
|
|
@@ -8,11 +8,11 @@ import * as path from 'path';
|
|
|
8
8
|
import * as os from 'os';
|
|
9
9
|
import { execFileSync, spawn } from 'child_process';
|
|
10
10
|
import { scanCortexMDChain } from '../memory/cortex-md-scanner.js';
|
|
11
|
+
import { resolveServerUrl, buildAuthHeaders } from './cortex-client-config.js';
|
|
11
12
|
import { createLogger } from '../../core/log.js';
|
|
12
13
|
const log = createLogger('cortex-client');
|
|
13
14
|
// --- Config ---
|
|
14
15
|
const SERVER_HOST = process.env.CORTEX_SERVER_HOST;
|
|
15
|
-
const SERVER_PORT = process.env.CORTEX_SERVER_PORT || '3002';
|
|
16
16
|
const DEVICE_NAME = process.env.CORTEX_DEVICE_NAME || os.hostname();
|
|
17
17
|
const PLATFORM = process.platform;
|
|
18
18
|
const HEARTBEAT_INTERVAL_MS = 5000;
|
|
@@ -20,8 +20,8 @@ const GIT_BASH_PATHS = [
|
|
|
20
20
|
'C:\\Program Files\\Git\\bin\\bash.exe',
|
|
21
21
|
'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
|
|
22
22
|
];
|
|
23
|
-
if (!SERVER_HOST) {
|
|
24
|
-
log.error('CORTEX_SERVER_HOST is required');
|
|
23
|
+
if (!SERVER_HOST && !process.env.CORTEX_SERVER_URL) {
|
|
24
|
+
log.error('Either CORTEX_SERVER_URL (full ws/wss URL) or CORTEX_SERVER_HOST is required');
|
|
25
25
|
process.exit(1);
|
|
26
26
|
}
|
|
27
27
|
// --- Output accumulator (prevents WS message size explosion) ---
|
|
@@ -598,9 +598,13 @@ let heartbeatTimer = null;
|
|
|
598
598
|
let reconnectDelay = 1000;
|
|
599
599
|
const MAX_RECONNECT_DELAY = 30000;
|
|
600
600
|
function connect() {
|
|
601
|
-
const url =
|
|
602
|
-
|
|
603
|
-
|
|
601
|
+
const url = resolveServerUrl(process.env);
|
|
602
|
+
const headers = buildAuthHeaders(process.env);
|
|
603
|
+
const hasToken = !!process.env.CORTEX_CLIENT_TOKEN?.trim();
|
|
604
|
+
const hasCf = !!(process.env.CF_ACCESS_CLIENT_ID && process.env.CF_ACCESS_CLIENT_SECRET);
|
|
605
|
+
const authTag = hasCf ? (hasToken ? ' [token+CF]' : ' [CF Access]') : (hasToken ? ' [token]' : '');
|
|
606
|
+
log.info(`Connecting to ${url} as "${DEVICE_NAME}" (${PLATFORM})${authTag}...`);
|
|
607
|
+
ws = headers ? new WebSocket(url, { headers }) : new WebSocket(url);
|
|
604
608
|
ws.on('open', () => {
|
|
605
609
|
log.info(`Connected to server`);
|
|
606
610
|
reconnectDelay = 1000;
|
|
@@ -700,5 +704,5 @@ function shutdown() {
|
|
|
700
704
|
process.on('SIGINT', shutdown);
|
|
701
705
|
process.on('SIGTERM', shutdown);
|
|
702
706
|
// --- Start ---
|
|
703
|
-
log.info(`Starting: device="${DEVICE_NAME}", platform="${PLATFORM}", server=${
|
|
707
|
+
log.info(`Starting: device="${DEVICE_NAME}", platform="${PLATFORM}", server=${resolveServerUrl(process.env)}`);
|
|
704
708
|
connect();
|
|
@@ -102,7 +102,23 @@ async function runScheduledTaskAsync({ normalizedMessage, message, projectId, sc
|
|
|
102
102
|
const threadResult = await dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effectiveProfile, statusMsg, startTime, sessionName, projectReportDest, projectId });
|
|
103
103
|
const result = threadResult.lastAgentResult;
|
|
104
104
|
await maybeNotifyCodexLowUsage({ adapter, result });
|
|
105
|
-
|
|
105
|
+
// Rate-limit pause: the runner already recorded the thread for auto-resume and left it in
|
|
106
|
+
// 'rate_limited'. Don't treat it as a failure — just reflect the paused state.
|
|
107
|
+
if (threadResult.thread?.status === 'rate_limited') {
|
|
108
|
+
const { elapsedStr } = computeElapsed(startTime);
|
|
109
|
+
if (statusMsg) {
|
|
110
|
+
const text = `${Icons.warning} ${buildSessionTag(sessionName, result?.sessionId)}Paused — rate limited, will auto-resume (${elapsedStr})`;
|
|
111
|
+
const queue = getOutboundQueue();
|
|
112
|
+
if (queue) {
|
|
113
|
+
await durableUpdate(queue, adapter, statusMsg, { text });
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
await adapter.updateMessage(statusMsg, { text });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
else if (result?.rateLimited) {
|
|
121
|
+
// Fallback: rate-limited but no active throttle, so the runner did not pause the thread.
|
|
106
122
|
const { elapsedStr } = computeElapsed(startTime);
|
|
107
123
|
if (statusMsg) {
|
|
108
124
|
const text = `${Icons.warning} ${buildSessionTag(sessionName, result?.sessionId)}Rate limited — all fallbacks exhausted (${elapsedStr})`;
|
|
@@ -226,7 +226,28 @@ async function executeDispatchTask({ selected, selectedTask, channel, scheduleTa
|
|
|
226
226
|
}
|
|
227
227
|
return { success: true, skipped: false, note: `[${selectedTask.project}] ${splitOutcome.note}` };
|
|
228
228
|
}
|
|
229
|
+
// Rate-limit pause: the runner left the thread in 'rate_limited' and recorded it for
|
|
230
|
+
// auto-resume. Keep the task CLAIMED (do not unclaim → no fresh re-dispatch that would race
|
|
231
|
+
// the thread resume), don't publish task.completed, don't finalize. resume-dispatcher re-enters
|
|
232
|
+
// the same thread when the window resets, and its rebuilt onEnd task-status-check hook closes
|
|
233
|
+
// the task loop at true termination — mirrors the DR-0014 suspended-parent branch above.
|
|
234
|
+
if (threadResult.thread?.status === 'rate_limited') {
|
|
235
|
+
if (statusMsg) {
|
|
236
|
+
// Persist the live status message so the post-resume settle can refresh it.
|
|
237
|
+
await threadStore.mutate(thread.id, (t) => { (t.metadata ??= {}).statusMsgRef = statusMsg; });
|
|
238
|
+
const text = `${Icons.warning} [${selectedTask.project}] ${selectedTask.text.substring(0, 80)} | paused — rate limited, will auto-resume`;
|
|
239
|
+
const queue = getOutboundQueue();
|
|
240
|
+
if (queue) {
|
|
241
|
+
await durableUpdate(queue, adapter, statusMsg, { text });
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
await adapter.updateMessage(statusMsg, { text }).catch(() => { });
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return { success: true, skipped: false, note: `Paused [${selectedTask.project}] — rate limited, will auto-resume` };
|
|
248
|
+
}
|
|
229
249
|
if (result?.rateLimited) {
|
|
250
|
+
// Fallback: rate-limited but no active throttle, so the runner did not pause the thread.
|
|
230
251
|
const { elapsedStr } = computeElapsed(startTime);
|
|
231
252
|
await taskMutator.unclaim(selectedTask.id);
|
|
232
253
|
if (statusMsg) {
|
|
@@ -267,6 +267,14 @@ function buildDispatchPrompt(task) {
|
|
|
267
267
|
' thread_abort(kind="too-big", diagnosis="<one-line diagnosis of what the real structure is>")',
|
|
268
268
|
'',
|
|
269
269
|
'The task will be blocked with your diagnosis and escalated: its manager (or a human) re-plans the decomposition with full context. A precise diagnosis is the most valuable thing you can produce here — it beats a half-done grind every time. (Use kind="too-big" or "mis-scoped" for structural problems, "blocked-external" for a missing external resource.) If instead you can already see the right decomposition, call `thread_split` with the subtasks.',
|
|
270
|
+
'',
|
|
271
|
+
'## If The Planning Intent Is Unclear (ask_manager)',
|
|
272
|
+
'',
|
|
273
|
+
'If during execution you hit confusion, a contradiction, or an ambiguous/under-specified intent — and you cannot settle it by reading the deliverable, code, or task spec yourself — do NOT guess and do NOT abort. Ask the manager who planned this task:',
|
|
274
|
+
'',
|
|
275
|
+
' ask_manager(question="<a specific, self-contained question about the planning intent>")',
|
|
276
|
+
'',
|
|
277
|
+
'This is lighter than thread_abort: it does not give up the task. The call blocks until the manager (or, at the top of the tree, a human) replies, then returns their answer so you can continue. Use it for genuine planning questions ("did you mean approach A or B?", "two done_when conditions conflict — which wins?"), not for things you can verify yourself.',
|
|
270
278
|
];
|
|
271
279
|
sections.push(escalation.join('\n'));
|
|
272
280
|
const completion = [
|
|
@@ -22,9 +22,11 @@ import { isMainModule } from '../../../core/utils.js';
|
|
|
22
22
|
// the daemon process, so we proxy sendCommand/isDeviceOnline through HTTP.
|
|
23
23
|
const WEBHOOK_PORT = parseInt(process.env.WEBHOOK_PORT || '3001', 10);
|
|
24
24
|
const WEBHOOK_BASE = `http://127.0.0.1:${WEBHOOK_PORT}`;
|
|
25
|
+
// Bearer token for the webhook auth gate. Inherited from the daemon/dispatcher env (see core/auth.ts).
|
|
26
|
+
const webhookAuthHeader = () => ({ 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '' });
|
|
25
27
|
async function httpIsDeviceOnline(device) {
|
|
26
28
|
try {
|
|
27
|
-
const res = await fetch(`${WEBHOOK_BASE}/webhook/devices
|
|
29
|
+
const res = await fetch(`${WEBHOOK_BASE}/webhook/devices`, { headers: webhookAuthHeader() });
|
|
28
30
|
if (!res.ok)
|
|
29
31
|
return false;
|
|
30
32
|
const data = (await res.json());
|
|
@@ -49,7 +51,7 @@ async function httpSendCommand(device, command) {
|
|
|
49
51
|
try {
|
|
50
52
|
const res = await fetch(`${WEBHOOK_BASE}/webhook/remote-command`, {
|
|
51
53
|
method: 'POST',
|
|
52
|
-
headers: { 'Content-Type': 'application/json' },
|
|
54
|
+
headers: { 'Content-Type': 'application/json', ...webhookAuthHeader() },
|
|
53
55
|
body: JSON.stringify({
|
|
54
56
|
device,
|
|
55
57
|
action: command.action,
|
|
@@ -22,6 +22,9 @@ interface ThreadContext {
|
|
|
22
22
|
stream: OutputStream;
|
|
23
23
|
lastAgentResult: any;
|
|
24
24
|
totalNumTurns: number;
|
|
25
|
+
/** Set when a step was interrupted by an API rate limit while the throttle is active.
|
|
26
|
+
* Pauses the thread (status='rate_limited') instead of completing/failing it. */
|
|
27
|
+
rateLimited?: boolean;
|
|
25
28
|
}
|
|
26
29
|
/** Per-step config built once by buildStepConfig — fully populated, no placeholders. */
|
|
27
30
|
interface StepContext {
|
|
@@ -78,6 +81,10 @@ declare function finalizeThread(threadId: string, ctx: ThreadContext): Promise<T
|
|
|
78
81
|
export declare function finalizeAbortedThread(threadId: string, meta: ThreadRecord['metadata'], reason: string | null, opts: Pick<RunThreadOptions, 'onAbort'>): Promise<void>;
|
|
79
82
|
declare function runThread(threadId: string, opts: RunThreadOptions): Promise<ThreadRunResult>;
|
|
80
83
|
declare function continueThread(threadId: string, userMessage: string, opts: RunThreadOptions): Promise<ThreadRunResult>;
|
|
84
|
+
/** Re-enter a thread paused by an API rate limit (status==='rate_limited'). Like resumeThread,
|
|
85
|
+
* the userMessage is NOT overwritten — the thread re-runs its interrupted step from the original
|
|
86
|
+
* prompt/contract. Called by resume-dispatcher when the rate-limit window resets. */
|
|
87
|
+
declare function resumeRateLimitedThread(threadId: string, opts: RunThreadOptions): Promise<ThreadRunResult>;
|
|
81
88
|
/** Re-enter a parent thread that was suspended via [WAIT_CHILDREN]. Unlike continueThread,
|
|
82
89
|
* the userMessage is NOT overwritten — the original contract stays in {{input}}; the child
|
|
83
90
|
* results arrive through metadata.pendingMessages (injected by the prompt builder). */
|
|
@@ -85,5 +92,5 @@ declare function resumeThread(threadId: string, opts: RunThreadOptions): Promise
|
|
|
85
92
|
declare function buildThreadSummary(result: ThreadRunResult): string;
|
|
86
93
|
declare function cancelActiveThread(channel: string): boolean;
|
|
87
94
|
declare function getActiveHandle(channel: string): RunningExecution | null;
|
|
88
|
-
export { runThread, continueThread, resumeThread, buildThreadSummary, cancelActiveThread, getActiveHandle, initThreadContext, resolveAndNotifyStep, buildStepConfig, setupStepCallbacks, executeAndAwaitAgent, recordStepOutcome, evaluateAndTransition, finalizeThread, };
|
|
95
|
+
export { runThread, continueThread, resumeThread, resumeRateLimitedThread, buildThreadSummary, cancelActiveThread, getActiveHandle, initThreadContext, resolveAndNotifyStep, buildStepConfig, setupStepCallbacks, executeAndAwaitAgent, recordStepOutcome, evaluateAndTransition, finalizeThread, };
|
|
89
96
|
export type { ThreadRunResult, ThreadContext, StepContext, StepCallbacks, StepInfo };
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
// input: domain/threads, mode-manager, hook-runner, handles
|
|
2
|
-
// output: runThread / continueThread / resumeThread / buildThreadSummary
|
|
2
|
+
// output: runThread / continueThread / resumeThread / resumeRateLimitedThread / buildThreadSummary
|
|
3
3
|
// pos: runtime execution engine for the Thread system
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import { threadStore } from '../../store/thread-repo.js';
|
|
6
|
-
import { resolveNextStep, buildStepPrompt, recordStepResult, evaluateTransitions, completeThread, failThread, abortThread, peekPendingControl, clearPendingControl, tryEnterWaiting, checkContractBudget, isAdHocThread, getSessionKey, getTemplate, readArtifact, resolveSystemVars, } from './index.js';
|
|
6
|
+
import { resolveNextStep, buildStepPrompt, recordStepResult, evaluateTransitions, completeThread, failThread, markThreadRateLimited, abortThread, peekPendingControl, clearPendingControl, tryEnterWaiting, checkContractBudget, isAdHocThread, getSessionKey, getTemplate, readArtifact, resolveSystemVars, } from './index.js';
|
|
7
7
|
import { runAgent, getClaudeMode, getActiveBackend, getActiveProfile } from '../agents/index.js';
|
|
8
|
+
import { isApiRateLimitError } from '../agents/config.js';
|
|
9
|
+
import { isThrottled } from '../costs/rate-limit-throttle.js';
|
|
10
|
+
import { recordResume } from '../costs/resume-registry.js';
|
|
8
11
|
import { Icons } from '../../core/icons.js';
|
|
9
12
|
import { closeSessionsByPrefix } from '../agents/index.js';
|
|
10
13
|
import * as executionRegistry from '../executions/registry.js';
|
|
@@ -219,6 +222,19 @@ async function recordStepOutcome(threadId, stepCtx, result, ctx, opts) {
|
|
|
219
222
|
// Record the step result
|
|
220
223
|
const stepEndTime = new Date().toISOString();
|
|
221
224
|
const stepDurationS = (new Date(stepEndTime).getTime() - new Date(stepStartTime).getTime()) / 1000;
|
|
225
|
+
// Rate-limit interruption (graceful path): the API window is exhausted and the throttle is
|
|
226
|
+
// active. Do NOT record the step result — leaving currentStepIndex unadvanced so resume
|
|
227
|
+
// re-runs THIS step (matches the thrown path). Tear down the execution as failed and pause the
|
|
228
|
+
// thread for auto-resume. Gate on isThrottled() so a stray rateLimited without an active
|
|
229
|
+
// throttle (no onResume will ever fire) falls through to the normal terminal path below.
|
|
230
|
+
if (result?.rateLimited && isThrottled()) {
|
|
231
|
+
executionRegistry.teardownExecution({
|
|
232
|
+
executionId: execution.id, status: 'failed', durationS: stepDurationS,
|
|
233
|
+
error: { message: 'Rate limited' },
|
|
234
|
+
});
|
|
235
|
+
await handleRateLimitInterruption(threadId, ctx, opts);
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
222
238
|
await recordStepResult(threadId, agentSlotId, {
|
|
223
239
|
sessionId: result?.sessionId || null,
|
|
224
240
|
sessionName,
|
|
@@ -258,6 +274,22 @@ async function recordStepOutcome(threadId, stepCtx, result, ctx, opts) {
|
|
|
258
274
|
});
|
|
259
275
|
}
|
|
260
276
|
}
|
|
277
|
+
/** Pause the thread for auto-resume after an API rate limit interrupted a step. Records the
|
|
278
|
+
* thread in the resume registry (drained by resume-dispatcher when the window resets) and
|
|
279
|
+
* flips it to the non-terminal 'rate_limited' status. Sets ctx.rateLimited so the loop breaks
|
|
280
|
+
* and skips completeThread / onEnd. Shared by the graceful (recordStepOutcome) and thrown
|
|
281
|
+
* (runThread catch) paths. */
|
|
282
|
+
async function handleRateLimitInterruption(threadId, ctx, opts) {
|
|
283
|
+
ctx.rateLimited = true;
|
|
284
|
+
await markThreadRateLimited(threadId);
|
|
285
|
+
recordResume({
|
|
286
|
+
kind: 'thread',
|
|
287
|
+
threadId,
|
|
288
|
+
channel: opts.channel,
|
|
289
|
+
userMessage: threadStore.get(threadId)?.userMessage ?? '',
|
|
290
|
+
recordedAt: Date.now(),
|
|
291
|
+
});
|
|
292
|
+
}
|
|
261
293
|
/** Decide whether the loop continues; run onTransition hook when transitioning.
|
|
262
294
|
* Returns false to break the loop. */
|
|
263
295
|
async function evaluateAndTransition(threadId, stepCtx, ctx, opts) {
|
|
@@ -326,6 +358,10 @@ async function runThread(threadId, opts) {
|
|
|
326
358
|
const callbacks = setupStepCallbacks(threadId, stepCtx, ctx, opts);
|
|
327
359
|
const result = await executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts);
|
|
328
360
|
await recordStepOutcome(threadId, stepCtx, result, ctx, opts);
|
|
361
|
+
// Rate-limit pause (graceful path): recordStepOutcome paused the thread. Break out so the
|
|
362
|
+
// thread is NOT completed; resume-dispatcher re-enters it when the window resets.
|
|
363
|
+
if (ctx.rateLimited)
|
|
364
|
+
break;
|
|
329
365
|
// Out-of-band control plane (DR-0015 problem 1): the agent signals abort / split / wait by
|
|
330
366
|
// calling the thread_abort / thread_split / thread_wait MCP tools, which write a typed
|
|
331
367
|
// metadata.pendingControl on this thread. Read it here at the step boundary — never scan the
|
|
@@ -394,13 +430,16 @@ async function runThread(threadId, opts) {
|
|
|
394
430
|
// Skipped on suspension: onEnd semantics are "thread truly finished" (e.g. the dispatch
|
|
395
431
|
// task-status-check hook must not nag while children are still working). The re-entry
|
|
396
432
|
// path re-runs runThread, so onEnd still fires exactly once at final termination.
|
|
397
|
-
|
|
433
|
+
// Also skipped on rate-limit pause (like suspension): the dispatch task-status-check onEnd
|
|
434
|
+
// hook must not fire and release the still-claimed task while the thread is only paused.
|
|
435
|
+
if (!enteredWaiting && !ctx.rateLimited) {
|
|
398
436
|
const threadForEnd = threadStore.get(threadId);
|
|
399
437
|
const lastStep = threadForEnd.steps[threadForEnd.steps.length - 1];
|
|
400
438
|
await executeLifecycleHook(threadId, 'end', ctx.template?.hooks?.onEnd, opts, lastStep?.agentSlotId);
|
|
401
439
|
await executeLifecycleHook(threadId, 'end', opts.extraHooks?.onEnd, opts, lastStep?.agentSlotId);
|
|
402
440
|
}
|
|
403
|
-
// Only complete if not already in a terminal state (e.g. cancelled during loop)
|
|
441
|
+
// Only complete if not already in a terminal state (e.g. cancelled during loop). A
|
|
442
|
+
// rate-limit pause leaves status='rate_limited', so this guard also skips it.
|
|
404
443
|
const threadBeforeComplete = threadStore.get(threadId);
|
|
405
444
|
if (threadBeforeComplete && threadBeforeComplete.status === 'running') {
|
|
406
445
|
await completeThread(threadId);
|
|
@@ -408,10 +447,18 @@ async function runThread(threadId, opts) {
|
|
|
408
447
|
}
|
|
409
448
|
catch (error) {
|
|
410
449
|
const t = threadStore.get(threadId);
|
|
411
|
-
|
|
412
|
-
|
|
450
|
+
// Thrown rate-limit path: the agent threw a rate-limit error while the throttle is active.
|
|
451
|
+
// Pause for auto-resume instead of failing, and do NOT rethrow — the thread is left in
|
|
452
|
+
// 'rate_limited' and finalizeThread returns normally so wrappers see thread.status, not a throw.
|
|
453
|
+
if (t && t.status === 'running' && isApiRateLimitError(error?.message) && isThrottled()) {
|
|
454
|
+
await handleRateLimitInterruption(threadId, ctx, opts);
|
|
455
|
+
}
|
|
456
|
+
else {
|
|
457
|
+
if (t && t.status === 'running') {
|
|
458
|
+
await failThread(threadId, error.message || 'Unknown error');
|
|
459
|
+
}
|
|
460
|
+
throw error;
|
|
413
461
|
}
|
|
414
|
-
throw error;
|
|
415
462
|
}
|
|
416
463
|
finally {
|
|
417
464
|
// Defensive: the per-step path finalizes each execution on success (recordStepOutcome) and on
|
|
@@ -442,13 +489,33 @@ async function continueThread(threadId, userMessage, opts) {
|
|
|
442
489
|
const thread = threadStore.get(threadId);
|
|
443
490
|
if (!thread)
|
|
444
491
|
throw new Error(`Thread not found: ${threadId}`);
|
|
445
|
-
if (thread.status !== 'running' && thread.status !== 'waiting') {
|
|
492
|
+
if (thread.status !== 'running' && thread.status !== 'waiting' && thread.status !== 'rate_limited') {
|
|
446
493
|
throw new Error(`Thread ${threadId} is ${thread.status}, cannot continue`);
|
|
447
494
|
}
|
|
448
495
|
// Update the thread's user message for the new input
|
|
449
496
|
await threadStore.mutate(threadId, (t) => {
|
|
450
497
|
t.userMessage = userMessage;
|
|
451
498
|
t.status = 'running';
|
|
499
|
+
if (t.metadata)
|
|
500
|
+
t.metadata.interruptedByRateLimit = false;
|
|
501
|
+
});
|
|
502
|
+
return runThread(threadId, opts);
|
|
503
|
+
}
|
|
504
|
+
// --- Resume a rate-limit-paused thread (auto-resume) ---
|
|
505
|
+
/** Re-enter a thread paused by an API rate limit (status==='rate_limited'). Like resumeThread,
|
|
506
|
+
* the userMessage is NOT overwritten — the thread re-runs its interrupted step from the original
|
|
507
|
+
* prompt/contract. Called by resume-dispatcher when the rate-limit window resets. */
|
|
508
|
+
async function resumeRateLimitedThread(threadId, opts) {
|
|
509
|
+
const thread = threadStore.get(threadId);
|
|
510
|
+
if (!thread)
|
|
511
|
+
throw new Error(`Thread not found: ${threadId}`);
|
|
512
|
+
if (thread.status !== 'rate_limited') {
|
|
513
|
+
throw new Error(`Thread ${threadId} is ${thread.status}, cannot resume (expected rate_limited)`);
|
|
514
|
+
}
|
|
515
|
+
await threadStore.mutate(threadId, (t) => {
|
|
516
|
+
t.status = 'running';
|
|
517
|
+
if (t.metadata)
|
|
518
|
+
t.metadata.interruptedByRateLimit = false;
|
|
452
519
|
});
|
|
453
520
|
return runThread(threadId, opts);
|
|
454
521
|
}
|
|
@@ -479,10 +546,13 @@ function buildThreadSummary(result) {
|
|
|
479
546
|
: thread.status === 'cancelled' ? Icons.blocked
|
|
480
547
|
: thread.status === 'aborted' ? Icons.stopped
|
|
481
548
|
: thread.status === 'waiting' ? Icons.processing
|
|
482
|
-
: Icons.
|
|
549
|
+
: thread.status === 'rate_limited' ? Icons.warning
|
|
550
|
+
: Icons.error;
|
|
483
551
|
const headline = thread.status === 'waiting'
|
|
484
552
|
? `${statusEmoji} Thread suspended — waiting on ${(thread.metadata?.waitingOn?.length ?? 0) + (thread.metadata?.waitingOnTasks?.length ?? 0)} child(ren) | ${steps.length} steps | $${totalCostUsd.toFixed(4)}`
|
|
485
|
-
:
|
|
553
|
+
: thread.status === 'rate_limited'
|
|
554
|
+
? `${statusEmoji} Thread paused — rate limited, will auto-resume | ${steps.length} steps | $${totalCostUsd.toFixed(4)}`
|
|
555
|
+
: `${statusEmoji} Thread complete | ${steps.length} steps | $${totalCostUsd.toFixed(4)} | ${formatDurationCompact(elapsed)}`;
|
|
486
556
|
const lines = [headline];
|
|
487
557
|
if (steps.length > 1) {
|
|
488
558
|
for (const step of steps) {
|
|
@@ -512,7 +582,7 @@ function cancelActiveThread(channel) {
|
|
|
512
582
|
function getActiveHandle(channel) {
|
|
513
583
|
return runningExecutions.getByChannel(channel)[0] ?? null;
|
|
514
584
|
}
|
|
515
|
-
export { runThread, continueThread, resumeThread, buildThreadSummary, cancelActiveThread, getActiveHandle,
|
|
585
|
+
export { runThread, continueThread, resumeThread, resumeRateLimitedThread, buildThreadSummary, cancelActiveThread, getActiveHandle,
|
|
516
586
|
// Internal helpers — exported to support focused unit tests from agent-server/tests/thread-runner.test.ts.
|
|
517
587
|
// Not part of the public API; callers outside the test harness should continue to use runThread().
|
|
518
588
|
initThreadContext, resolveAndNotifyStep, buildStepConfig, setupStepCallbacks, executeAndAwaitAgent, recordStepOutcome, evaluateAndTransition, finalizeThread, };
|
|
@@ -60,4 +60,9 @@ export interface SplitDetection {
|
|
|
60
60
|
export declare function abortThread(threadId: string, reason: string | null): Promise<boolean>;
|
|
61
61
|
export declare function completeThread(threadId: string): Promise<boolean>;
|
|
62
62
|
export declare function failThread(threadId: string, error: string): Promise<boolean>;
|
|
63
|
+
/** Pause a thread that was interrupted mid-run by an API rate limit. Non-terminal: the
|
|
64
|
+
* thread keeps its currentStepIndex/agents and is re-entered (from the interrupted step)
|
|
65
|
+
* by the resume-dispatcher when the rate-limit window resets. Does NOT set endedAt.
|
|
66
|
+
* Idempotent. */
|
|
67
|
+
export declare function markThreadRateLimited(threadId: string, note?: string): Promise<boolean>;
|
|
63
68
|
export {};
|
|
@@ -478,3 +478,19 @@ export async function failThread(threadId, error) {
|
|
|
478
478
|
log.info(`Failed thread ${threadId}: ${error}`);
|
|
479
479
|
return true;
|
|
480
480
|
}
|
|
481
|
+
/** Pause a thread that was interrupted mid-run by an API rate limit. Non-terminal: the
|
|
482
|
+
* thread keeps its currentStepIndex/agents and is re-entered (from the interrupted step)
|
|
483
|
+
* by the resume-dispatcher when the rate-limit window resets. Does NOT set endedAt.
|
|
484
|
+
* Idempotent. */
|
|
485
|
+
export async function markThreadRateLimited(threadId, note) {
|
|
486
|
+
const thread = threadStore.get(threadId);
|
|
487
|
+
if (!thread)
|
|
488
|
+
return false;
|
|
489
|
+
await threadStore.mutate(threadId, (t) => {
|
|
490
|
+
t.status = 'rate_limited';
|
|
491
|
+
t.error = note ?? 'Paused — interrupted by API rate limit';
|
|
492
|
+
(t.metadata ??= {}).interruptedByRateLimit = true;
|
|
493
|
+
});
|
|
494
|
+
log.info(`Rate-limit paused thread ${threadId}`);
|
|
495
|
+
return true;
|
|
496
|
+
}
|