@cortex-agent/server 2026.6.18 → 2026.6.24
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/config/thread-templates.json +12 -6
- package/defaults/context/user/CORTEX.md +2 -2
- package/defaults/hooks/ask-user-question-hook.mjs +7 -1
- package/defaults/hooks/exit-plan-mode-hook.mjs +7 -1
- package/defaults/hooks/memory-ref-tracker.mjs +1 -0
- package/defaults/hooks/new-session-hook.mjs +1 -0
- package/defaults/hooks/post-task-hook.mjs +1 -0
- package/defaults/hooks/rules-loader.mjs +1 -0
- package/defaults/hooks/sensitive-file-edit.mjs +1 -0
- package/defaults/hooks/session-activity-tracker.mjs +1 -0
- package/defaults/hooks/task-status-check.mjs +1 -0
- package/defaults/hooks/tasks-yaml-guard.mjs +1 -0
- package/defaults/plugins/cortex-feishu/.claude-plugin/plugin.json +5 -0
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +163 -0
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/scripts/ensure-lark-cli.sh +53 -0
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +7 -0
- package/defaults/prompts/directives/coder-reviewer.md +6 -6
- package/defaults/prompts/directives/coder.md +14 -15
- 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-tui.d.ts +12 -0
- package/dist/agent-adapter/claude/adapter-tui.js +15 -0
- package/dist/agent-adapter/claude/adapter.d.ts +110 -1
- package/dist/agent-adapter/claude/adapter.js +123 -2
- package/dist/agent-adapter/claude/bg-task-tracker.d.ts +45 -0
- package/dist/agent-adapter/claude/bg-task-tracker.js +91 -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/gateway-generator.js +10 -1
- package/dist/core/locales/en.d.ts +12 -0
- package/dist/core/locales/slices/interactions.d.ts +6 -0
- package/dist/core/locales/slices/interactions.js +14 -0
- package/dist/core/locales/slices/status.d.ts +6 -0
- package/dist/core/locales/slices/status.js +16 -0
- package/dist/core/status-format.d.ts +14 -0
- package/dist/core/status-format.js +23 -1
- package/dist/core/types/agent-types.d.ts +5 -0
- package/dist/core/types/thread-types.d.ts +15 -1
- package/dist/core/version.d.ts +3 -0
- package/dist/core/version.js +4 -1
- package/dist/domain/agents/facade.d.ts +13 -0
- package/dist/domain/agents/facade.js +36 -1
- 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/feishu/index.js +5 -51
- package/dist/domain/mcp/feishu-server.js +3 -2
- 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/memory/user-context.d.ts +6 -5
- package/dist/domain/memory/user-context.js +12 -7
- package/dist/domain/remote/client-bootstrap.js +14 -2
- package/dist/domain/remote/client-hot-reload.d.ts +9 -2
- package/dist/domain/remote/client-hot-reload.js +77 -6
- 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 +22 -0
- package/dist/domain/sessions/session-hooks.d.ts +31 -1
- package/dist/domain/sessions/session-hooks.js +69 -17
- package/dist/domain/system/doctor.d.ts +63 -0
- package/dist/domain/system/doctor.js +362 -0
- package/dist/domain/tasks/dispatcher.js +8 -0
- package/dist/domain/tasks/system/cortex-run.js +4 -2
- package/dist/domain/tasks/system/task-cli.js +7 -4
- package/dist/domain/tasks/system/task-state.d.ts +10 -1
- package/dist/domain/tasks/system/task-state.js +31 -1
- package/dist/domain/threads/prompt-builder.d.ts +7 -4
- package/dist/domain/threads/prompt-builder.js +9 -8
- package/dist/domain/threads/runner.d.ts +8 -1
- package/dist/domain/threads/runner.js +111 -18
- package/dist/domain/threads/state-machine.d.ts +5 -0
- package/dist/domain/threads/state-machine.js +16 -0
- package/dist/entry/app.js +44 -5
- package/dist/entry/cli.js +10 -0
- package/dist/entry/doctor-cli.d.ts +12 -0
- package/dist/entry/doctor-cli.js +76 -0
- package/dist/entry/init.js +6 -0
- package/dist/hooks/ask-user-question-hook.mjs +7 -1
- package/dist/hooks/exit-plan-mode-hook.mjs +7 -1
- package/dist/hooks/memory-ref-tracker.mjs +1 -0
- package/dist/hooks/new-session-hook.mjs +1 -0
- package/dist/hooks/post-task-hook.mjs +1 -0
- package/dist/hooks/rules-loader.mjs +1 -0
- package/dist/hooks/sensitive-file-edit.mjs +1 -0
- package/dist/hooks/session-activity-tracker.mjs +1 -0
- package/dist/hooks/task-status-check.mjs +1 -0
- package/dist/hooks/tasks-yaml-guard.mjs +1 -0
- package/dist/orchestration/agent-runner.js +30 -4
- 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 +5 -2
- package/dist/orchestration/interactions/interaction-handlers.js +13 -2
- package/dist/orchestration/lifecycle.d.ts +5 -2
- package/dist/orchestration/lifecycle.js +87 -3
- package/dist/orchestration/manager-qa.d.ts +56 -0
- package/dist/orchestration/manager-qa.js +223 -0
- package/dist/orchestration/resume-dispatcher.d.ts +27 -0
- package/dist/orchestration/resume-dispatcher.js +145 -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 +17 -1
- package/dist/orchestration/thread-callback.js +57 -36
- 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/plugin-sync.d.ts +21 -0
- package/dist/store/plugin-sync.js +119 -0
- 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 +23 -4
- package/dist/store/version-migrations.js +167 -9
- package/dist/tui/App.js +11 -7
- package/dist/tui/components/Dashboard.js +26 -11
- package/dist/tui/components/InputBox.js +43 -4
- package/dist/tui/components/SidePanel.js +1 -1
- package/package.json +1 -1
- package/dist/domain/mcp/feishu/bitable.d.ts +0 -3
- package/dist/domain/mcp/feishu/bitable.js +0 -168
- package/dist/domain/mcp/feishu/blocks-to-text.d.ts +0 -19
- package/dist/domain/mcp/feishu/blocks-to-text.js +0 -43
- package/dist/domain/mcp/feishu/docx.d.ts +0 -3
- package/dist/domain/mcp/feishu/docx.js +0 -163
- package/dist/domain/mcp/feishu/drive.d.ts +0 -23
- package/dist/domain/mcp/feishu/drive.js +0 -66
- package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +0 -40
- package/dist/domain/mcp/feishu/markdown-to-blocks.js +0 -191
- package/dist/domain/mcp/feishu/sheets.d.ts +0 -3
- package/dist/domain/mcp/feishu/sheets.js +0 -119
- package/dist/domain/mcp/feishu/wiki.d.ts +0 -3
- package/dist/domain/mcp/feishu/wiki.js +0 -77
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Header name carrying the bearer token on both the WS upgrade and webhook requests. */
|
|
2
|
+
export declare const AUTH_HEADER = "x-cortex-token";
|
|
3
|
+
/** Env var holding the cortex-client ↔ server WebSocket token. */
|
|
4
|
+
export declare const CLIENT_TOKEN_ENV = "CORTEX_CLIENT_TOKEN";
|
|
5
|
+
/** Env var holding the webhook HTTP bearer token. */
|
|
6
|
+
export declare const WEBHOOK_TOKEN_ENV = "CORTEX_WEBHOOK_TOKEN";
|
|
7
|
+
/**
|
|
8
|
+
* Constant-time string comparison. Returns false (fail-closed) when either side is
|
|
9
|
+
* empty/undefined or the lengths differ — an unset configured token never matches.
|
|
10
|
+
*/
|
|
11
|
+
export declare function timingSafeEqualStr(a: string | undefined, b: string | undefined): boolean;
|
|
12
|
+
/** Read the configured client (WebSocket) token at call time (after dotenv loads). */
|
|
13
|
+
export declare function getClientToken(): string;
|
|
14
|
+
/** Read the configured webhook token at call time (after dotenv loads). */
|
|
15
|
+
export declare function getWebhookToken(): string;
|
|
16
|
+
export interface EnsureAuthTokensOptions {
|
|
17
|
+
/** Path to the .env file to persist generated tokens into. Defaults to CONFIG_DIR/.env. */
|
|
18
|
+
envPath?: string;
|
|
19
|
+
/** Env object to read/mutate. Defaults to process.env (injectable for tests). */
|
|
20
|
+
env?: Record<string, string | undefined>;
|
|
21
|
+
}
|
|
22
|
+
export interface EnsureAuthTokensResult {
|
|
23
|
+
clientToken: string;
|
|
24
|
+
webhookToken: string;
|
|
25
|
+
/** Names of tokens that were freshly generated this call (empty when all pre-existed). */
|
|
26
|
+
generated: string[];
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Ensure both auth tokens exist. For each missing/blank token: generate a 32-byte hex
|
|
30
|
+
* secret, set it on `env`, and (if anything was generated) append the new keys to the
|
|
31
|
+
* .env file so they survive restarts. Idempotent — pre-existing tokens are left untouched.
|
|
32
|
+
*
|
|
33
|
+
* Called once at server startup BEFORE the WebSocket and webhook servers start, so both
|
|
34
|
+
* surfaces enforce a real token (fail-closed).
|
|
35
|
+
*/
|
|
36
|
+
export declare function ensureAuthTokens(opts?: EnsureAuthTokensOptions): EnsureAuthTokensResult;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// input: process.env / CONFIG_DIR/.env, request headers
|
|
2
|
+
// output: ensureAuthTokens + getClientToken/getWebhookToken + timingSafeEqualStr + AUTH_HEADER
|
|
3
|
+
// pos: Shared-secret auth for the cortex-client WebSocket and the webhook HTTP server.
|
|
4
|
+
// No Cloudflare dependency — two independent bearer tokens carried in the
|
|
5
|
+
// `x-cortex-token` header, generated on first start and persisted to .env (fail-closed).
|
|
6
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
7
|
+
import * as crypto from 'crypto';
|
|
8
|
+
import { readFileSync, appendFileSync, mkdirSync } from 'fs';
|
|
9
|
+
import * as path from 'path';
|
|
10
|
+
import { CONFIG_DIR } from './utils.js';
|
|
11
|
+
import { createLogger } from './log.js';
|
|
12
|
+
const log = createLogger('auth');
|
|
13
|
+
/** Header name carrying the bearer token on both the WS upgrade and webhook requests. */
|
|
14
|
+
export const AUTH_HEADER = 'x-cortex-token';
|
|
15
|
+
/** Env var holding the cortex-client ↔ server WebSocket token. */
|
|
16
|
+
export const CLIENT_TOKEN_ENV = 'CORTEX_CLIENT_TOKEN';
|
|
17
|
+
/** Env var holding the webhook HTTP bearer token. */
|
|
18
|
+
export const WEBHOOK_TOKEN_ENV = 'CORTEX_WEBHOOK_TOKEN';
|
|
19
|
+
/**
|
|
20
|
+
* Constant-time string comparison. Returns false (fail-closed) when either side is
|
|
21
|
+
* empty/undefined or the lengths differ — an unset configured token never matches.
|
|
22
|
+
*/
|
|
23
|
+
export function timingSafeEqualStr(a, b) {
|
|
24
|
+
const aBuf = Buffer.from(a || '');
|
|
25
|
+
const bBuf = Buffer.from(b || '');
|
|
26
|
+
if (aBuf.length === 0 || bBuf.length !== aBuf.length)
|
|
27
|
+
return false;
|
|
28
|
+
return crypto.timingSafeEqual(aBuf, bBuf);
|
|
29
|
+
}
|
|
30
|
+
/** Read the configured client (WebSocket) token at call time (after dotenv loads). */
|
|
31
|
+
export function getClientToken() {
|
|
32
|
+
return (process.env[CLIENT_TOKEN_ENV] || '').trim();
|
|
33
|
+
}
|
|
34
|
+
/** Read the configured webhook token at call time (after dotenv loads). */
|
|
35
|
+
export function getWebhookToken() {
|
|
36
|
+
return (process.env[WEBHOOK_TOKEN_ENV] || '').trim();
|
|
37
|
+
}
|
|
38
|
+
function genToken() {
|
|
39
|
+
return crypto.randomBytes(32).toString('hex');
|
|
40
|
+
}
|
|
41
|
+
function appendTokensToEnvFile(envPath, names, env) {
|
|
42
|
+
let existing = '';
|
|
43
|
+
try {
|
|
44
|
+
existing = readFileSync(envPath, 'utf-8');
|
|
45
|
+
}
|
|
46
|
+
catch { /* no file yet */ }
|
|
47
|
+
const lines = ['', '# Auth tokens (auto-generated) — WS client + webhook bearer'];
|
|
48
|
+
for (const name of names)
|
|
49
|
+
lines.push(`${name}=${env[name]}`);
|
|
50
|
+
lines.push('');
|
|
51
|
+
// Guard against gluing the first key onto a file that lacks a trailing newline.
|
|
52
|
+
const needsLeadingNl = existing.length > 0 && !existing.endsWith('\n');
|
|
53
|
+
const block = (needsLeadingNl ? '\n' : '') + lines.join('\n');
|
|
54
|
+
mkdirSync(path.dirname(envPath), { recursive: true });
|
|
55
|
+
appendFileSync(envPath, block);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Ensure both auth tokens exist. For each missing/blank token: generate a 32-byte hex
|
|
59
|
+
* secret, set it on `env`, and (if anything was generated) append the new keys to the
|
|
60
|
+
* .env file so they survive restarts. Idempotent — pre-existing tokens are left untouched.
|
|
61
|
+
*
|
|
62
|
+
* Called once at server startup BEFORE the WebSocket and webhook servers start, so both
|
|
63
|
+
* surfaces enforce a real token (fail-closed).
|
|
64
|
+
*/
|
|
65
|
+
export function ensureAuthTokens(opts = {}) {
|
|
66
|
+
const env = opts.env ?? process.env;
|
|
67
|
+
const envPath = opts.envPath ?? path.join(CONFIG_DIR, '.env');
|
|
68
|
+
const generated = [];
|
|
69
|
+
const ensureOne = (name) => {
|
|
70
|
+
const existing = env[name]?.trim();
|
|
71
|
+
if (existing)
|
|
72
|
+
return existing;
|
|
73
|
+
const value = genToken();
|
|
74
|
+
env[name] = value;
|
|
75
|
+
generated.push(name);
|
|
76
|
+
return value;
|
|
77
|
+
};
|
|
78
|
+
const clientToken = ensureOne(CLIENT_TOKEN_ENV);
|
|
79
|
+
const webhookToken = ensureOne(WEBHOOK_TOKEN_ENV);
|
|
80
|
+
if (generated.length > 0) {
|
|
81
|
+
appendTokensToEnvFile(envPath, generated, env);
|
|
82
|
+
log.info(`Generated auth token(s): ${generated.join(', ')} → ${envPath}`);
|
|
83
|
+
}
|
|
84
|
+
return { clientToken, webhookToken, generated };
|
|
85
|
+
}
|
|
@@ -41,7 +41,16 @@ const FLAT_ENDPOINT_KEYS = ['keys', 'base_url', 'auth_style', 'passthrough', 'fa
|
|
|
41
41
|
/** Synthetic mode name used to hold a flat endpoint config (aistatus assigns these to mode "default"). */
|
|
42
42
|
const FLAT_MODE = 'default';
|
|
43
43
|
// ─── Anthropic models (default tier) ─────────────────────────────
|
|
44
|
-
|
|
44
|
+
// Each 1M-capable model also exposes a "[1m]" variant — Claude Code's context-window suffix that
|
|
45
|
+
// opts the session into the 1M-token window. Haiku 4.5 is 200K-only, so it has no [1m] variant.
|
|
46
|
+
const ANTHROPIC_MODELS = [
|
|
47
|
+
'claude-fable-5', 'claude-fable-5[1m]',
|
|
48
|
+
'claude-opus-4-8', 'claude-opus-4-8[1m]',
|
|
49
|
+
'claude-opus-4-7', 'claude-opus-4-7[1m]',
|
|
50
|
+
'claude-opus-4-6', 'claude-opus-4-6[1m]',
|
|
51
|
+
'claude-sonnet-4-6', 'claude-sonnet-4-6[1m]',
|
|
52
|
+
'claude-haiku-4-5',
|
|
53
|
+
];
|
|
45
54
|
// ─── PI provider → upstream URL lookup (manually maintained) ────────────────
|
|
46
55
|
/**
|
|
47
56
|
* Map a PI built-in provider name to its real upstream URL. Used by `generateGatewayYaml` so PI
|
|
@@ -167,6 +167,12 @@ export declare const en: {
|
|
|
167
167
|
'modal.planFeedbackTitle': "Plan Feedback";
|
|
168
168
|
'modal.feedbackLabel': "Your feedback (Cortex will revise the plan)";
|
|
169
169
|
'modal.feedbackPlaceholder': "What should be changed?";
|
|
170
|
+
'subtask.fromTask': "Subtask #${taskId}";
|
|
171
|
+
'subtask.fromUnknown': "a subtask";
|
|
172
|
+
'subtask.escalateHeader': "[Subtask question — escalated to you] ${from} hit something unclear/contradictory while executing and has no manager above it, so it is checking with you:";
|
|
173
|
+
'subtask.questionLabel': "Question: ${question}";
|
|
174
|
+
'subtask.escalateReply': "Just reply in this channel — your next message will be returned to that subtask as the answer.";
|
|
175
|
+
'subtask.replyDelivered': "Your reply has been delivered to the subtask that asked.";
|
|
170
176
|
'schedule.help.title': "*Schedule commands:*";
|
|
171
177
|
'schedule.help.addInterval': "`!schedule add interval <duration> [--profile <name>] <message>` — repeat every duration (e.g. `30m`, `2h`, `1d`)";
|
|
172
178
|
'schedule.help.addDaily': "`!schedule add daily <HH:MM> [--profile <name>] <message>` — run every day at a fixed time (24-hour)";
|
|
@@ -414,6 +420,7 @@ export declare const en: {
|
|
|
414
420
|
'status.processing': "Processing";
|
|
415
421
|
'status.done': "Done";
|
|
416
422
|
'status.waitingForUserInput': "Waiting for user input";
|
|
423
|
+
'status.backgroundRunning': "Background task running";
|
|
417
424
|
'status.cancelled': "Cancelled";
|
|
418
425
|
'status.error': "Error";
|
|
419
426
|
'status.supersededByEdit': "Superseded by edit";
|
|
@@ -423,11 +430,16 @@ export declare const en: {
|
|
|
423
430
|
'status.supersededSeeNewReply': "see new reply";
|
|
424
431
|
'status.processingAskResponse': "Processing AskUserQuestion response...";
|
|
425
432
|
'status.errorBody': "Error: ${message}";
|
|
433
|
+
'notify.turnComplete': "Turn complete";
|
|
434
|
+
'notify.turnFailed': "Turn failed";
|
|
435
|
+
'notify.contextCompacted': "Context auto-compacted (${trigger}${tokens}). Earlier conversation history has been summarized; please restate key information if needed.";
|
|
436
|
+
'notify.contextCompactedTokens': ", ~${preTokens} tokens before compaction";
|
|
426
437
|
'status.noRunningExecutions': "No running executions.";
|
|
427
438
|
'status.runningExecutions': "Running executions: ${count}";
|
|
428
439
|
'btn.cancel': "Cancel";
|
|
429
440
|
'btn.resume': "Resume";
|
|
430
441
|
'btn.new': "New";
|
|
442
|
+
'btn.newq': "New (quiet)";
|
|
431
443
|
'lang.current': "Current language: *${lang}*";
|
|
432
444
|
'lang.switched': "Language switched to *${lang}*.";
|
|
433
445
|
'lang.usage': "Usage: `!lang <en|zh>`";
|
|
@@ -43,5 +43,11 @@ export declare const interactionsEn: {
|
|
|
43
43
|
readonly 'modal.planFeedbackTitle': "Plan Feedback";
|
|
44
44
|
readonly 'modal.feedbackLabel': "Your feedback (Cortex will revise the plan)";
|
|
45
45
|
readonly 'modal.feedbackPlaceholder': "What should be changed?";
|
|
46
|
+
readonly 'subtask.fromTask': "Subtask #${taskId}";
|
|
47
|
+
readonly 'subtask.fromUnknown': "a subtask";
|
|
48
|
+
readonly 'subtask.escalateHeader': "[Subtask question — escalated to you] ${from} hit something unclear/contradictory while executing and has no manager above it, so it is checking with you:";
|
|
49
|
+
readonly 'subtask.questionLabel': "Question: ${question}";
|
|
50
|
+
readonly 'subtask.escalateReply': "Just reply in this channel — your next message will be returned to that subtask as the answer.";
|
|
51
|
+
readonly 'subtask.replyDelivered': "Your reply has been delivered to the subtask that asked.";
|
|
46
52
|
};
|
|
47
53
|
export declare const interactionsZh: Record<keyof typeof interactionsEn, string>;
|
|
@@ -50,6 +50,13 @@ export const interactionsEn = {
|
|
|
50
50
|
'modal.planFeedbackTitle': 'Plan Feedback',
|
|
51
51
|
'modal.feedbackLabel': 'Your feedback (Cortex will revise the plan)',
|
|
52
52
|
'modal.feedbackPlaceholder': 'What should be changed?',
|
|
53
|
+
// --- manager-qa.ts (subtask escalated to a human at the top of the tree) ---
|
|
54
|
+
'subtask.fromTask': 'Subtask #${taskId}',
|
|
55
|
+
'subtask.fromUnknown': 'a subtask',
|
|
56
|
+
'subtask.escalateHeader': '[Subtask question — escalated to you] ${from} hit something unclear/contradictory while executing and has no manager above it, so it is checking with you:',
|
|
57
|
+
'subtask.questionLabel': 'Question: ${question}',
|
|
58
|
+
'subtask.escalateReply': 'Just reply in this channel — your next message will be returned to that subtask as the answer.',
|
|
59
|
+
'subtask.replyDelivered': 'Your reply has been delivered to the subtask that asked.',
|
|
53
60
|
};
|
|
54
61
|
export const interactionsZh = {
|
|
55
62
|
// --- interaction-handlers.ts ---
|
|
@@ -99,4 +106,11 @@ export const interactionsZh = {
|
|
|
99
106
|
'modal.planFeedbackTitle': '计划反馈',
|
|
100
107
|
'modal.feedbackLabel': '你的反馈(Cortex 将修订计划)',
|
|
101
108
|
'modal.feedbackPlaceholder': '应该修改什么?',
|
|
109
|
+
// --- manager-qa.ts (subtask escalated to a human at the top of the tree) ---
|
|
110
|
+
'subtask.fromTask': '子任务 #${taskId}',
|
|
111
|
+
'subtask.fromUnknown': '一个子任务',
|
|
112
|
+
'subtask.escalateHeader': '[子任务提问 — 已升级到你] ${from} 在执行中遇到不清楚/矛盾之处,没有上级 manager,转而向你确认:',
|
|
113
|
+
'subtask.questionLabel': '问题: ${question}',
|
|
114
|
+
'subtask.escalateReply': '直接在本频道回复即可——你的下一条消息会作为答复返回给该子任务。',
|
|
115
|
+
'subtask.replyDelivered': '已把你的回复作为答复返回给提问的子任务。',
|
|
102
116
|
};
|
|
@@ -2,6 +2,7 @@ export declare const statusEn: {
|
|
|
2
2
|
readonly 'status.processing': "Processing";
|
|
3
3
|
readonly 'status.done': "Done";
|
|
4
4
|
readonly 'status.waitingForUserInput': "Waiting for user input";
|
|
5
|
+
readonly 'status.backgroundRunning': "Background task running";
|
|
5
6
|
readonly 'status.cancelled': "Cancelled";
|
|
6
7
|
readonly 'status.error': "Error";
|
|
7
8
|
readonly 'status.supersededByEdit': "Superseded by edit";
|
|
@@ -11,10 +12,15 @@ export declare const statusEn: {
|
|
|
11
12
|
readonly 'status.supersededSeeNewReply': "see new reply";
|
|
12
13
|
readonly 'status.processingAskResponse': "Processing AskUserQuestion response...";
|
|
13
14
|
readonly 'status.errorBody': "Error: ${message}";
|
|
15
|
+
readonly 'notify.turnComplete': "Turn complete";
|
|
16
|
+
readonly 'notify.turnFailed': "Turn failed";
|
|
17
|
+
readonly 'notify.contextCompacted': "Context auto-compacted (${trigger}${tokens}). Earlier conversation history has been summarized; please restate key information if needed.";
|
|
18
|
+
readonly 'notify.contextCompactedTokens': ", ~${preTokens} tokens before compaction";
|
|
14
19
|
readonly 'status.noRunningExecutions': "No running executions.";
|
|
15
20
|
readonly 'status.runningExecutions': "Running executions: ${count}";
|
|
16
21
|
readonly 'btn.cancel': "Cancel";
|
|
17
22
|
readonly 'btn.resume': "Resume";
|
|
18
23
|
readonly 'btn.new': "New";
|
|
24
|
+
readonly 'btn.newq': "New (quiet)";
|
|
19
25
|
};
|
|
20
26
|
export declare const statusZh: Record<keyof typeof statusEn, string>;
|
|
@@ -7,6 +7,7 @@ export const statusEn = {
|
|
|
7
7
|
'status.processing': 'Processing',
|
|
8
8
|
'status.done': 'Done',
|
|
9
9
|
'status.waitingForUserInput': 'Waiting for user input',
|
|
10
|
+
'status.backgroundRunning': 'Background task running',
|
|
10
11
|
'status.cancelled': 'Cancelled',
|
|
11
12
|
'status.error': 'Error',
|
|
12
13
|
'status.supersededByEdit': 'Superseded by edit',
|
|
@@ -16,6 +17,12 @@ export const statusEn = {
|
|
|
16
17
|
'status.supersededSeeNewReply': 'see new reply',
|
|
17
18
|
'status.processingAskResponse': 'Processing AskUserQuestion response...',
|
|
18
19
|
'status.errorBody': 'Error: ${message}',
|
|
20
|
+
// --- Turn-completion notification ---
|
|
21
|
+
'notify.turnComplete': 'Turn complete',
|
|
22
|
+
'notify.turnFailed': 'Turn failed',
|
|
23
|
+
// --- Context compaction notification ---
|
|
24
|
+
'notify.contextCompacted': 'Context auto-compacted (${trigger}${tokens}). Earlier conversation history has been summarized; please restate key information if needed.',
|
|
25
|
+
'notify.contextCompactedTokens': ', ~${preTokens} tokens before compaction',
|
|
19
26
|
// --- Execution report ---
|
|
20
27
|
'status.noRunningExecutions': 'No running executions.',
|
|
21
28
|
'status.runningExecutions': 'Running executions: ${count}',
|
|
@@ -23,12 +30,14 @@ export const statusEn = {
|
|
|
23
30
|
'btn.cancel': 'Cancel',
|
|
24
31
|
'btn.resume': 'Resume',
|
|
25
32
|
'btn.new': 'New',
|
|
33
|
+
'btn.newq': 'New (quiet)',
|
|
26
34
|
};
|
|
27
35
|
export const statusZh = {
|
|
28
36
|
// --- Status / lifecycle phrases ---
|
|
29
37
|
'status.processing': '处理中',
|
|
30
38
|
'status.done': '完成',
|
|
31
39
|
'status.waitingForUserInput': '等待用户输入',
|
|
40
|
+
'status.backgroundRunning': '后台任务运行中',
|
|
32
41
|
'status.cancelled': '已取消',
|
|
33
42
|
'status.error': '错误',
|
|
34
43
|
'status.supersededByEdit': '已被编辑取代',
|
|
@@ -38,6 +47,12 @@ export const statusZh = {
|
|
|
38
47
|
'status.supersededSeeNewReply': '查看新回复',
|
|
39
48
|
'status.processingAskResponse': '正在处理 AskUserQuestion 回复……',
|
|
40
49
|
'status.errorBody': '错误:${message}',
|
|
50
|
+
// --- Turn-completion notification ---
|
|
51
|
+
'notify.turnComplete': '回合完成',
|
|
52
|
+
'notify.turnFailed': '回合失败',
|
|
53
|
+
// --- Context compaction notification ---
|
|
54
|
+
'notify.contextCompacted': '上下文已自动压缩(${trigger}${tokens})。早期对话历史已被摘要,如有需要请重述关键信息。',
|
|
55
|
+
'notify.contextCompactedTokens': ',压缩前 ~${preTokens} tokens',
|
|
41
56
|
// --- Execution report ---
|
|
42
57
|
'status.noRunningExecutions': '没有正在运行的执行。',
|
|
43
58
|
'status.runningExecutions': '正在运行的执行:${count}',
|
|
@@ -45,4 +60,5 @@ export const statusZh = {
|
|
|
45
60
|
'btn.cancel': '取消',
|
|
46
61
|
'btn.resume': '恢复',
|
|
47
62
|
'btn.new': '新建',
|
|
63
|
+
'btn.newq': '新建(静默)',
|
|
48
64
|
};
|
|
@@ -16,3 +16,17 @@ export declare function buildUserProcessingMessage({ startTime, elapsed_s, num_t
|
|
|
16
16
|
sessionName?: string | null;
|
|
17
17
|
sessionId?: string | null;
|
|
18
18
|
}): string;
|
|
19
|
+
/** Build the multi-agent thread step status line. When task info is present (task-dispatch
|
|
20
|
+
* threads carry taskProject/taskId/taskText in metadata) the line leads with the task identity
|
|
21
|
+
* — "[proj] <text…> · `id`" — so a glance tells you what is running; the short thread id is kept
|
|
22
|
+
* at the tail for thread-op debugging. Without task info it falls back to the thread-only form. */
|
|
23
|
+
export declare function buildThreadStatusMessage({ threadId, stepNumber, label, elapsedS, numTurns, taskProject, taskId, taskText }: {
|
|
24
|
+
threadId: string;
|
|
25
|
+
stepNumber: number;
|
|
26
|
+
label: string;
|
|
27
|
+
elapsedS: number;
|
|
28
|
+
numTurns?: number | null;
|
|
29
|
+
taskProject?: string | null;
|
|
30
|
+
taskId?: string | null;
|
|
31
|
+
taskText?: string | null;
|
|
32
|
+
}): string;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// input: formatDurationCompact (core/utils)
|
|
2
|
-
// output:
|
|
2
|
+
// output: 5 pure formatting functions: computeElapsed / formatMetricsSuffix / buildSessionTag / buildUserProcessingMessage / buildThreadStatusMessage
|
|
3
3
|
// pos: zero-dependency pure functions in the core layer; the subset imported by domain-layer status-helpers
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import { formatDurationCompact } from './utils.js';
|
|
@@ -31,3 +31,25 @@ export function buildUserProcessingMessage({ startTime, elapsed_s = null, num_tu
|
|
|
31
31
|
const turnsStr = num_turns != null ? ` | ${Icons.repeat} ${num_turns} turns` : '';
|
|
32
32
|
return `${Icons.processing} ${t('status.processing')} | ${sessionTag}${profileName || 'default'} | ${Icons.stopwatch} ${formatDurationCompact(elapsed || 0)}${turnsStr}`;
|
|
33
33
|
}
|
|
34
|
+
const THREAD_STATUS_TASK_TEXT_MAX = 60;
|
|
35
|
+
const THREAD_STATUS_THREAD_ID_LEN = 12;
|
|
36
|
+
/** Build the multi-agent thread step status line. When task info is present (task-dispatch
|
|
37
|
+
* threads carry taskProject/taskId/taskText in metadata) the line leads with the task identity
|
|
38
|
+
* — "[proj] <text…> · `id`" — so a glance tells you what is running; the short thread id is kept
|
|
39
|
+
* at the tail for thread-op debugging. Without task info it falls back to the thread-only form. */
|
|
40
|
+
export function buildThreadStatusMessage({ threadId, stepNumber, label, elapsedS, numTurns = null, taskProject = null, taskId = null, taskText = null }) {
|
|
41
|
+
const shortId = threadId.substring(0, THREAD_STATUS_THREAD_ID_LEN);
|
|
42
|
+
const turnsPart = numTurns != null ? ` (${numTurns} turns)` : '';
|
|
43
|
+
const stepPart = `Step ${stepNumber}: *${label}*${turnsPart}`;
|
|
44
|
+
const timePart = `${Icons.stopwatch} ${formatDurationCompact(elapsedS)}`;
|
|
45
|
+
if (taskId) {
|
|
46
|
+
const projPart = taskProject ? `[${taskProject}] ` : '';
|
|
47
|
+
const raw = (taskText ?? '').trim();
|
|
48
|
+
const text = raw.length > THREAD_STATUS_TASK_TEXT_MAX
|
|
49
|
+
? raw.slice(0, THREAD_STATUS_TASK_TEXT_MAX).trimEnd() + '…'
|
|
50
|
+
: raw;
|
|
51
|
+
const textPart = text ? `${text} ` : '';
|
|
52
|
+
return `${Icons.processing} ${projPart}${textPart}· \`${taskId}\` | ${stepPart} | ${shortId} | ${timePart}`;
|
|
53
|
+
}
|
|
54
|
+
return `${Icons.processing} Thread ${shortId} | ${stepPart} | ${timePart}`;
|
|
55
|
+
}
|
|
@@ -16,6 +16,11 @@ export interface AgentResult {
|
|
|
16
16
|
finalOutput: string | null;
|
|
17
17
|
codexRateLimits?: Record<string, unknown>;
|
|
18
18
|
codexRawLogPath?: string | null;
|
|
19
|
+
/** Number of background tasks (run_in_background) still running when this turn's
|
|
20
|
+
* result fired. >0 means the CC backend will spontaneously emit a continuation turn
|
|
21
|
+
* once they finish; orchestration holds the status in a "waiting" state instead of
|
|
22
|
+
* sealing it as complete. Absent/0 for backends without background-task support. */
|
|
23
|
+
pendingBackgroundTasks?: number;
|
|
19
24
|
}
|
|
20
25
|
export interface AgentHandle {
|
|
21
26
|
promise: Promise<AgentResult>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export type ThreadId = string;
|
|
2
2
|
export type AgentSlotId = string;
|
|
3
|
-
export type ThreadStatus = 'running' | 'waiting' | 'completed' | 'failed' | 'cancelled' | 'aborted';
|
|
3
|
+
export type ThreadStatus = 'running' | 'waiting' | 'rate_limited' | 'completed' | 'failed' | 'cancelled' | 'aborted';
|
|
4
4
|
/** A named stage of an agent. When an agent declares `stages`, each transition target
|
|
5
5
|
* may select one stage (syntax `"agent:stage"`). Stages that set `continuesSession: true`
|
|
6
6
|
* send only an incremental prompt when the persistent session is being resumed — the
|
|
@@ -248,6 +248,14 @@ export interface ThreadMetadata {
|
|
|
248
248
|
/** Children whose results were already queued into pendingMessages — persistent
|
|
249
249
|
* idempotency for completion callbacks (survives restarts, unlike the in-memory fired set). */
|
|
250
250
|
deliveredChildResults?: string[];
|
|
251
|
+
/** Open questions a subtask asked this manager via ask_manager (DR-0016), for visibility /
|
|
252
|
+
* debugging. The authoritative pending-question state lives in orchestration/manager-qa's
|
|
253
|
+
* in-memory store; this is the manager-side mirror, cleared by answer_subtask. */
|
|
254
|
+
pendingQuestions?: Array<{
|
|
255
|
+
questionId: string;
|
|
256
|
+
fromTaskId: string | null;
|
|
257
|
+
question: string;
|
|
258
|
+
}>;
|
|
251
259
|
/** Delegation contract this thread was spawned with (child side). */
|
|
252
260
|
contract?: ThreadContract | null;
|
|
253
261
|
/** Ancestor goal chain, root-first — injected into the child prompt to prevent drift. */
|
|
@@ -256,6 +264,12 @@ export interface ThreadMetadata {
|
|
|
256
264
|
* onEnd task-status-check hook on re-entry (extraHooks are not persisted). */
|
|
257
265
|
taskId?: string | null;
|
|
258
266
|
taskProject?: string | null;
|
|
267
|
+
/** Task text (TASKS.yaml `text`) at dispatch time, for the thread step status line so a glance
|
|
268
|
+
* shows what is running. Persisted because status updates outlive the in-memory selected task. */
|
|
269
|
+
taskText?: string | null;
|
|
270
|
+
/** Set when the thread was paused (status==='rate_limited') by an API rate limit, so the
|
|
271
|
+
* resume path and startup recovery can tell a rate-limit pause apart from a real failure. */
|
|
272
|
+
interruptedByRateLimit?: boolean;
|
|
259
273
|
/** Destination kind decided at spawn time, so re-entry can rebuild RunThreadOptions. */
|
|
260
274
|
resumeDest?: 'interactive-reply' | 'project-report' | null;
|
|
261
275
|
/** Live status message persisted at suspension so the post-resume settle can refresh it
|
package/dist/core/version.d.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
1
|
/** Cortex version — reads from package.json at module load time.
|
|
2
2
|
* Format: CalVer `YYYY.M.D` (no zero-padding), e.g. `2026.5.19`. */
|
|
3
3
|
export declare const CORTEX_VERSION: string;
|
|
4
|
+
/** Canonical Cortex usage documentation site. Single source of truth for the
|
|
5
|
+
* docs URL injected into system prompts (see store/version-migrations.ts docs block). */
|
|
6
|
+
export declare const CORTEX_DOCS_URL = "https://fangxm233.github.io/cortex-agent/";
|
package/dist/core/version.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// input: package.json (read at module load)
|
|
2
|
-
// output: CORTEX_VERSION string (CalVer: YYYY.M.D, no zero-padding)
|
|
2
|
+
// output: CORTEX_VERSION string (CalVer: YYYY.M.D, no zero-padding); CORTEX_DOCS_URL (docs site)
|
|
3
3
|
// pos: single source of truth for Cortex version — imported by MCP servers and anywhere else
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import { readFileSync } from 'node:fs';
|
|
@@ -10,3 +10,6 @@ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
|
|
|
10
10
|
/** Cortex version — reads from package.json at module load time.
|
|
11
11
|
* Format: CalVer `YYYY.M.D` (no zero-padding), e.g. `2026.5.19`. */
|
|
12
12
|
export const CORTEX_VERSION = pkg.version;
|
|
13
|
+
/** Canonical Cortex usage documentation site. Single source of truth for the
|
|
14
|
+
* docs URL injected into system prompts (see store/version-migrations.ts docs block). */
|
|
15
|
+
export const CORTEX_DOCS_URL = 'https://fangxm233.github.io/cortex-agent/';
|
|
@@ -58,6 +58,18 @@ export interface RunAgentOptions {
|
|
|
58
58
|
* `mode` name; no gateway path string leaks into profiles.json.
|
|
59
59
|
*/
|
|
60
60
|
export declare function buildPiGatewaySubPath(mode: string | null, provider: string): string | undefined;
|
|
61
|
+
/** Plugins that load only for sessions originating from a specific platform channel.
|
|
62
|
+
* Mirrors the channel-gated MCP loading (loadFeishuMcp = channel.startsWith('feishu:')):
|
|
63
|
+
* the cortex-feishu skill bundle is only relevant when the user is working inside Feishu,
|
|
64
|
+
* so it is stripped from non-Feishu sessions even when listed in an agent's pluginDirs. */
|
|
65
|
+
export declare const CHANNEL_SCOPED_PLUGINS: ReadonlyArray<{
|
|
66
|
+
plugin: string;
|
|
67
|
+
channelPrefix: string;
|
|
68
|
+
}>;
|
|
69
|
+
/** Drop channel-scoped plugin dirs whose channel prefix the current session does not match.
|
|
70
|
+
* Non-scoped plugins always pass through. Matched by the plugin dir's final path segment
|
|
71
|
+
* (basename) so substrings like `cortex-feishu-x` are not affected. */
|
|
72
|
+
export declare function filterChannelScopedPlugins(dirs: string[] | undefined, channel: string | undefined): string[] | undefined;
|
|
61
73
|
declare function buildSpawnConfig(options: RunAgentOptions, config: AgentConfig, anthropicBaseUrl: string | undefined): AgentSpawnConfig;
|
|
62
74
|
export declare function runWithAdapter(adapter: AgentAdapter, message: string, options: RunAgentOptions, config: AgentConfig, anthropicBaseUrl: string | undefined): AgentHandle;
|
|
63
75
|
export declare function runAgentOnce(message: string, options: RunAgentOptions, config: AgentConfig): AgentHandle;
|
|
@@ -68,6 +80,7 @@ export declare function allConfigsRateLimited(profileName: string | null): boole
|
|
|
68
80
|
export declare const _test: {
|
|
69
81
|
runWithAdapter: typeof runWithAdapter;
|
|
70
82
|
buildSpawnConfig: typeof buildSpawnConfig;
|
|
83
|
+
filterChannelScopedPlugins: typeof filterChannelScopedPlugins;
|
|
71
84
|
};
|
|
72
85
|
export { closeSession, closeSessionsByPrefix, closeAllSessions, _test as claudeTest, } from '../../agent-adapter/claude/adapter.js';
|
|
73
86
|
export { shutdownCodex, buildMcpBlock } from '../../agent-adapter/codex/adapter.js';
|
|
@@ -9,6 +9,7 @@ import { isModeRateLimited, isThrottled } from '../costs/rate-limit-throttle.js'
|
|
|
9
9
|
import { GATEWAY_URL } from '../costs/gateway-manager.js';
|
|
10
10
|
import { createLogger } from '../../core/log.js';
|
|
11
11
|
import { loadCortexRules } from '../memory/rules-loader.js';
|
|
12
|
+
import { t } from '../../core/i18n.js';
|
|
12
13
|
const log = createLogger('facade');
|
|
13
14
|
// --- PI gateway routing ---
|
|
14
15
|
/**
|
|
@@ -28,6 +29,28 @@ export function buildPiGatewaySubPath(mode, provider) {
|
|
|
28
29
|
return undefined;
|
|
29
30
|
return `/m/${mode}/${provider}`;
|
|
30
31
|
}
|
|
32
|
+
// --- Channel-scoped plugin gating ---
|
|
33
|
+
/** Plugins that load only for sessions originating from a specific platform channel.
|
|
34
|
+
* Mirrors the channel-gated MCP loading (loadFeishuMcp = channel.startsWith('feishu:')):
|
|
35
|
+
* the cortex-feishu skill bundle is only relevant when the user is working inside Feishu,
|
|
36
|
+
* so it is stripped from non-Feishu sessions even when listed in an agent's pluginDirs. */
|
|
37
|
+
export const CHANNEL_SCOPED_PLUGINS = [
|
|
38
|
+
{ plugin: 'cortex-feishu', channelPrefix: 'feishu:' },
|
|
39
|
+
];
|
|
40
|
+
/** Drop channel-scoped plugin dirs whose channel prefix the current session does not match.
|
|
41
|
+
* Non-scoped plugins always pass through. Matched by the plugin dir's final path segment
|
|
42
|
+
* (basename) so substrings like `cortex-feishu-x` are not affected. */
|
|
43
|
+
export function filterChannelScopedPlugins(dirs, channel) {
|
|
44
|
+
if (!dirs)
|
|
45
|
+
return dirs;
|
|
46
|
+
return dirs.filter((dir) => {
|
|
47
|
+
const base = dir.split('/').filter(Boolean).pop();
|
|
48
|
+
const rule = CHANNEL_SCOPED_PLUGINS.find((r) => r.plugin === base);
|
|
49
|
+
if (!rule)
|
|
50
|
+
return true;
|
|
51
|
+
return !!channel && channel.startsWith(rule.channelPrefix);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
31
54
|
// --- Adapter execution ---
|
|
32
55
|
function buildSpawnConfig(options, config, anthropicBaseUrl) {
|
|
33
56
|
// Pack the Cortex execution context only if at least one field is set, so adapters can
|
|
@@ -57,7 +80,7 @@ function buildSpawnConfig(options, config, anthropicBaseUrl) {
|
|
|
57
80
|
model: config.model,
|
|
58
81
|
systemPrompt: typeof options.systemPrompt === 'string' ? options.systemPrompt : undefined,
|
|
59
82
|
outputStyle: typeof options.outputStyle === 'string' ? options.outputStyle : undefined,
|
|
60
|
-
pluginDirs: Array.isArray(options.pluginDirs) ? options.pluginDirs : undefined,
|
|
83
|
+
pluginDirs: filterChannelScopedPlugins(Array.isArray(options.pluginDirs) ? options.pluginDirs : undefined, options.channel),
|
|
61
84
|
env: config.extraEnv && Object.keys(config.extraEnv).length > 0 ? config.extraEnv : undefined,
|
|
62
85
|
extraOption: config.extraOption && Object.keys(config.extraOption).length > 0 ? config.extraOption : undefined,
|
|
63
86
|
claudeBackend: config.claudeBackend,
|
|
@@ -130,6 +153,17 @@ export function runWithAdapter(adapter, message, options, config, anthropicBaseU
|
|
|
130
153
|
model: event.model || undefined,
|
|
131
154
|
}).catch(err => log.warn('recordCost failed:', err?.message ?? err));
|
|
132
155
|
break;
|
|
156
|
+
case 'context_compacted':
|
|
157
|
+
// Notify the user that the context was compacted. Off by default; opt in via
|
|
158
|
+
// CORTEX_NOTIFY_COMPACTION=1. Reuses onAssistantMessage so the notice reaches the
|
|
159
|
+
// user through the same channel as normal assistant output.
|
|
160
|
+
if (process.env.CORTEX_NOTIFY_COMPACTION === '1') {
|
|
161
|
+
const tokens = event.preTokens
|
|
162
|
+
? t('notify.contextCompactedTokens', { preTokens: event.preTokens })
|
|
163
|
+
: '';
|
|
164
|
+
options.onAssistantMessage?.(`🗜️ ${t('notify.contextCompacted', { trigger: event.trigger, tokens })}`);
|
|
165
|
+
}
|
|
166
|
+
break;
|
|
133
167
|
case 'plan_written':
|
|
134
168
|
options.onPlanWritten?.({ path: event.path, content: event.content, toolUseId: event.toolUseId });
|
|
135
169
|
break;
|
|
@@ -288,6 +322,7 @@ export function allConfigsRateLimited(profileName) {
|
|
|
288
322
|
export const _test = {
|
|
289
323
|
runWithAdapter,
|
|
290
324
|
buildSpawnConfig,
|
|
325
|
+
filterChannelScopedPlugins,
|
|
291
326
|
};
|
|
292
327
|
// --- Bridge helper re-exports (replacing claude-bridge.ts / codex-bridge.ts) ---
|
|
293
328
|
export { closeSession, closeSessionsByPrefix, closeAllSessions, _test as claudeTest, } from '../../agent-adapter/claude/adapter.js';
|
|
@@ -11,7 +11,7 @@ export interface ThrottlePersistence {
|
|
|
11
11
|
modes?: string[];
|
|
12
12
|
} | null>;
|
|
13
13
|
}
|
|
14
|
-
declare function initRateLimitThrottle(adapter: PlatformAdapter, persistence: ThrottlePersistence): Promise<void>;
|
|
14
|
+
declare function initRateLimitThrottle(adapter: PlatformAdapter, persistence: ThrottlePersistence, onResume?: () => void): Promise<void>;
|
|
15
15
|
interface RateLimitInfo {
|
|
16
16
|
status?: string;
|
|
17
17
|
resetsAt?: number;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
// input: rate_limit_event + persistence + slack client
|
|
1
|
+
// input: rate_limit_event + persistence + slack client + optional onResume hook
|
|
2
2
|
// output: init/handleRateLimitEvent/isThrottled/isModeRateLimited/getThrottleState
|
|
3
3
|
// pos: Pure state tracker — no scheduler coupling. Mode-level rate limit tracking.
|
|
4
|
+
// onResume (injected) fires when the window clears (timer path + expired-on-restart),
|
|
5
|
+
// decoupling the resume dispatch (orchestration) from this domain module.
|
|
4
6
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
7
|
import { createLogger } from '../../core/log.js';
|
|
6
8
|
import { Icons } from '../../core/icons.js';
|
|
@@ -10,6 +12,7 @@ const RESUME_BUFFER_MS = 5_000;
|
|
|
10
12
|
// --- Module state ---
|
|
11
13
|
let _adapter = null;
|
|
12
14
|
let _persistence = null;
|
|
15
|
+
let _onResume = null;
|
|
13
16
|
let _isThrottled = false;
|
|
14
17
|
let _resetsAt = null; // Unix seconds
|
|
15
18
|
let _resumeTimer = null;
|
|
@@ -48,6 +51,19 @@ function clearThrottle() {
|
|
|
48
51
|
_persistence?.save(null).catch(e => {
|
|
49
52
|
log.error(`Failed to persist cleared throttle: ${e.message}`);
|
|
50
53
|
});
|
|
54
|
+
fireResume();
|
|
55
|
+
}
|
|
56
|
+
/** Notify the (optional) resume hook that the rate-limit window has ended. Errors are
|
|
57
|
+
* swallowed so a faulty resume path can never break the throttle state machine. */
|
|
58
|
+
function fireResume() {
|
|
59
|
+
if (!_onResume)
|
|
60
|
+
return;
|
|
61
|
+
try {
|
|
62
|
+
_onResume();
|
|
63
|
+
}
|
|
64
|
+
catch (e) {
|
|
65
|
+
log.error(`onResume hook failed: ${e.message}`);
|
|
66
|
+
}
|
|
51
67
|
}
|
|
52
68
|
function scheduleResumeTimer() {
|
|
53
69
|
if (_resumeTimer)
|
|
@@ -59,9 +75,10 @@ function scheduleResumeTimer() {
|
|
|
59
75
|
}, delayMs);
|
|
60
76
|
}
|
|
61
77
|
// --- Public API ---
|
|
62
|
-
async function initRateLimitThrottle(adapter, persistence) {
|
|
78
|
+
async function initRateLimitThrottle(adapter, persistence, onResume) {
|
|
63
79
|
_adapter = adapter;
|
|
64
80
|
_persistence = persistence;
|
|
81
|
+
_onResume = onResume ?? null;
|
|
65
82
|
// Recover throttle state from disk (survives restart)
|
|
66
83
|
const persisted = await persistence.load();
|
|
67
84
|
if (persisted) {
|
|
@@ -79,6 +96,9 @@ async function initRateLimitThrottle(adapter, persistence) {
|
|
|
79
96
|
else {
|
|
80
97
|
log.info(`Throttle expired during downtime (resetsAt was ${new Date(persisted.resetsAt * 1000).toISOString()}). Clearing.`);
|
|
81
98
|
await persistence.save(null);
|
|
99
|
+
// The window already reset while the process was down — resume anything that was
|
|
100
|
+
// recorded before the restart.
|
|
101
|
+
fireResume();
|
|
82
102
|
}
|
|
83
103
|
}
|
|
84
104
|
log.info('Initialized');
|
|
@@ -134,5 +154,6 @@ function _testReset() {
|
|
|
134
154
|
_rateLimitedModes.clear();
|
|
135
155
|
_adapter = null;
|
|
136
156
|
_persistence = null;
|
|
157
|
+
_onResume = null;
|
|
137
158
|
}
|
|
138
159
|
export { initRateLimitThrottle, handleRateLimitEvent, isThrottled, isModeRateLimited, getThrottleState, _testReset };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** One unit of work that was interrupted by a rate limit and should be resumed
|
|
2
|
+
* once the limit window resets. `direct` = an interactive conversation (resumed by
|
|
3
|
+
* re-routing a message into the channel's pooled session); `thread` = a thread
|
|
4
|
+
* pipeline (resumed via continueThread). */
|
|
5
|
+
export type ResumeEntry = {
|
|
6
|
+
kind: 'direct';
|
|
7
|
+
channel: string;
|
|
8
|
+
userMessage: string;
|
|
9
|
+
recordedAt: number;
|
|
10
|
+
} | {
|
|
11
|
+
kind: 'thread';
|
|
12
|
+
threadId: string;
|
|
13
|
+
channel: string;
|
|
14
|
+
userMessage: string;
|
|
15
|
+
recordedAt: number;
|
|
16
|
+
};
|
|
17
|
+
export interface ResumePersistence {
|
|
18
|
+
save: (entries: ResumeEntry[]) => Promise<void>;
|
|
19
|
+
load: () => Promise<ResumeEntry[]>;
|
|
20
|
+
}
|
|
21
|
+
declare function initResumeRegistry(persistence: ResumePersistence): Promise<void>;
|
|
22
|
+
/** Record an interrupted session/thread for later resume. Idempotent per key
|
|
23
|
+
* (direct→channel, thread→threadId): a newer record overwrites the older one. */
|
|
24
|
+
declare function recordResume(entry: ResumeEntry): void;
|
|
25
|
+
/** Drain the registry: return all pending entries and clear (persists the empty list).
|
|
26
|
+
* "take + clear" is atomic so each entry is dispatched at most once. */
|
|
27
|
+
declare function takeAllResumes(): ResumeEntry[];
|
|
28
|
+
declare function getResumeCount(): number;
|
|
29
|
+
declare function _testReset(): void;
|
|
30
|
+
export { initResumeRegistry, recordResume, takeAllResumes, getResumeCount, _testReset };
|