@cortex-agent/server 2026.6.11 → 2026.6.15
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/dist/core/gateway-generator.js +24 -3
- package/dist/core/i18n.d.ts +19 -0
- package/dist/core/i18n.js +46 -0
- package/dist/core/locales/en.d.ts +438 -0
- package/dist/core/locales/en.js +24 -0
- package/dist/core/locales/slices/commands.d.ts +214 -0
- package/dist/core/locales/slices/commands.js +462 -0
- package/dist/core/locales/slices/init.d.ts +121 -0
- package/dist/core/locales/slices/init.js +380 -0
- package/dist/core/locales/slices/interactions.d.ts +47 -0
- package/dist/core/locales/slices/interactions.js +102 -0
- package/dist/core/locales/slices/lang.d.ts +8 -0
- package/dist/core/locales/slices/lang.js +18 -0
- package/dist/core/locales/slices/scheduling.d.ts +36 -0
- package/dist/core/locales/slices/scheduling.js +74 -0
- package/dist/core/locales/slices/startup.d.ts +6 -0
- package/dist/core/locales/slices/startup.js +14 -0
- package/dist/core/locales/slices/status.d.ts +20 -0
- package/dist/core/locales/slices/status.js +48 -0
- package/dist/core/locales/zh.d.ts +5 -0
- package/dist/core/locales/zh.js +23 -0
- package/dist/core/singleton-lock.d.ts +23 -0
- package/dist/core/singleton-lock.js +53 -0
- package/dist/core/status-format.js +2 -1
- package/dist/core/utils.d.ts +9 -1
- package/dist/core/utils.js +9 -1
- package/dist/domain/agents/config.d.ts +2 -1
- package/dist/domain/agents/config.js +25 -6
- package/dist/domain/scheduling/jobs/task-dispatch.js +6 -10
- package/dist/domain/scheduling/schedule-command.js +38 -37
- package/dist/domain/system/github-release.d.ts +18 -0
- package/dist/domain/system/github-release.js +106 -0
- package/dist/domain/system/preferences.d.ts +12 -0
- package/dist/domain/system/preferences.js +36 -0
- package/dist/domain/tasks/dispatcher.d.ts +11 -2
- package/dist/domain/tasks/dispatcher.js +37 -7
- package/dist/domain/threads/prompt-builder.d.ts +6 -0
- package/dist/domain/threads/prompt-builder.js +19 -2
- package/dist/entry/app.js +36 -3
- package/dist/entry/daemon.js +12 -30
- package/dist/entry/init.d.ts +4 -3
- package/dist/entry/init.js +151 -208
- package/dist/entry/startup-notify.js +6 -3
- package/dist/orchestration/interactions/interaction-handlers.js +12 -11
- package/dist/orchestration/interactions/update-prompt-slack.js +11 -10
- package/dist/orchestration/interactions/update-prompt.js +66 -11
- package/dist/orchestration/lifecycle.js +13 -12
- package/dist/orchestration/routing/commands/cancel.js +10 -9
- package/dist/orchestration/routing/commands/channel.js +27 -26
- package/dist/orchestration/routing/commands/cost.js +10 -2
- package/dist/orchestration/routing/commands/device.js +11 -9
- package/dist/orchestration/routing/commands/dispatch.js +10 -10
- package/dist/orchestration/routing/commands/index.js +6 -2
- package/dist/orchestration/routing/commands/lang.d.ts +3 -0
- package/dist/orchestration/routing/commands/lang.js +31 -0
- package/dist/orchestration/routing/commands/mode.js +28 -27
- package/dist/orchestration/routing/commands/nvtop.js +13 -12
- package/dist/orchestration/routing/commands/orient.js +2 -1
- package/dist/orchestration/routing/commands/schedule.js +23 -22
- package/dist/orchestration/routing/commands/sendfile.js +8 -7
- package/dist/orchestration/routing/commands/session.js +11 -10
- package/dist/orchestration/routing/commands/status.js +78 -71
- package/dist/orchestration/routing/commands/tail.js +6 -5
- package/dist/orchestration/routing/commands/task.js +23 -22
- package/dist/orchestration/routing/commands/thread-handlers.js +40 -39
- package/dist/orchestration/status-helpers.js +6 -5
- package/dist/platform/interactive-builder.js +19 -18
- package/dist/store/version-migrations.d.ts +7 -0
- package/dist/store/version-migrations.js +88 -0
- package/package.json +1 -1
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// input: nothing (leaf data slice)
|
|
2
|
+
// output: schedulingEn / schedulingZh — message slice (filled by i18n extraction)
|
|
3
|
+
// pos: one locale slice; aggregated by core/locales/en.ts & zh.ts barrels
|
|
4
|
+
// >>> Keep en and zh keys in lockstep (zh typed against keyof typeof schedulingEn) <<<
|
|
5
|
+
export const schedulingEn = {
|
|
6
|
+
'schedule.help.title': '*Schedule commands:*',
|
|
7
|
+
'schedule.help.addInterval': '`!schedule add interval <duration> [--profile <name>] <message>` — repeat every duration (e.g. `30m`, `2h`, `1d`)',
|
|
8
|
+
'schedule.help.addDaily': '`!schedule add daily <HH:MM> [--profile <name>] <message>` — run every day at a fixed time (24-hour)',
|
|
9
|
+
'schedule.help.addWeekly': '`!schedule add weekly <day> <HH:MM> [--profile <name>] <message>` — run every week (day: mon,tue,wed,thu,fri,sat,sun)',
|
|
10
|
+
'schedule.help.addOnce': '`!schedule add once <duration> [--profile <name>] <message>` — run once after a delay',
|
|
11
|
+
'schedule.help.list': '`!schedule list` — show all scheduled tasks',
|
|
12
|
+
'schedule.help.pause': '`!schedule pause <id>` — pause a recurring task',
|
|
13
|
+
'schedule.help.resume': '`!schedule resume <id>` — resume a paused recurring task',
|
|
14
|
+
'schedule.help.remove': '`!schedule remove <id>` — remove a task by id',
|
|
15
|
+
'schedule.help.availableProfiles': 'Available profiles: ${profileNames}',
|
|
16
|
+
'schedule.list.empty': 'No scheduled tasks.',
|
|
17
|
+
'schedule.list.header': '*Scheduled tasks (${count}):*\n${lines}',
|
|
18
|
+
'schedule.remove.usage': 'Usage: `!schedule remove <id>`',
|
|
19
|
+
'schedule.remove.ok': 'Removed task `${id}`.',
|
|
20
|
+
'schedule.taskNotFound': 'Task not found: `${id}`',
|
|
21
|
+
'schedule.pause.usage': 'Usage: `!schedule pause <id>`',
|
|
22
|
+
'schedule.pause.ok': 'Paused task `${id}`.',
|
|
23
|
+
'schedule.resume.usage': 'Usage: `!schedule resume <id>`',
|
|
24
|
+
'schedule.resume.ok': 'Resumed task `${id}`.${nextAt}',
|
|
25
|
+
'schedule.resume.nextRun': ' Next run: ${time}.',
|
|
26
|
+
'schedule.invalidDuration': 'Invalid duration: `${duration}`. Use e.g. `30s`, `5m`, `2h`, `1d`',
|
|
27
|
+
'schedule.invalidTime': 'Invalid time: `${time}`. Use 24-hour HH:MM, e.g. `${example}`',
|
|
28
|
+
'schedule.invalidDay': 'Invalid day: `${day}`. Use: mon, tue, wed, thu, fri, sat, sun',
|
|
29
|
+
'schedule.add.intervalUsage': 'Usage: `!schedule add interval <duration> [--profile <name>] <message>`',
|
|
30
|
+
'schedule.add.dailyUsage': 'Usage: `!schedule add daily <HH:MM> [--profile <name>] <message>`',
|
|
31
|
+
'schedule.add.weeklyUsage': 'Usage: `!schedule add weekly <day> <HH:MM> [--profile <name>] <message>`',
|
|
32
|
+
'schedule.add.onceUsage': 'Usage: `!schedule add once <duration> [--profile <name>] <message>`',
|
|
33
|
+
'schedule.add.scheduledInterval': 'Scheduled every *${duration}*: "${message}"',
|
|
34
|
+
'schedule.add.scheduledDaily': 'Scheduled daily at *${time}*: "${message}"',
|
|
35
|
+
'schedule.add.scheduledWeekly': 'Scheduled weekly *${day} ${time}*: "${message}"',
|
|
36
|
+
'schedule.add.scheduledOnce': 'Scheduled once in *${duration}*: "${message}"',
|
|
37
|
+
'schedule.add.unknownType': 'Unknown type: `${type}`. Use `interval`, `daily`, `weekly`, or `once`',
|
|
38
|
+
'schedule.profileUsage': 'Usage: ${usage}',
|
|
39
|
+
};
|
|
40
|
+
export const schedulingZh = {
|
|
41
|
+
'schedule.help.title': '*定时任务命令:*',
|
|
42
|
+
'schedule.help.addInterval': '`!schedule add interval <duration> [--profile <name>] <message>` — 每隔指定时长重复(例如 `30m`、`2h`、`1d`)',
|
|
43
|
+
'schedule.help.addDaily': '`!schedule add daily <HH:MM> [--profile <name>] <message>` — 每天在固定时间运行(24 小时制)',
|
|
44
|
+
'schedule.help.addWeekly': '`!schedule add weekly <day> <HH:MM> [--profile <name>] <message>` — 每周运行(day:mon,tue,wed,thu,fri,sat,sun)',
|
|
45
|
+
'schedule.help.addOnce': '`!schedule add once <duration> [--profile <name>] <message>` — 延迟一段时间后运行一次',
|
|
46
|
+
'schedule.help.list': '`!schedule list` — 显示所有定时任务',
|
|
47
|
+
'schedule.help.pause': '`!schedule pause <id>` — 暂停一个周期任务',
|
|
48
|
+
'schedule.help.resume': '`!schedule resume <id>` — 恢复一个已暂停的周期任务',
|
|
49
|
+
'schedule.help.remove': '`!schedule remove <id>` — 按 id 删除任务',
|
|
50
|
+
'schedule.help.availableProfiles': '可用的 profile:${profileNames}',
|
|
51
|
+
'schedule.list.empty': '没有定时任务。',
|
|
52
|
+
'schedule.list.header': '*定时任务(${count}):*\n${lines}',
|
|
53
|
+
'schedule.remove.usage': '用法:`!schedule remove <id>`',
|
|
54
|
+
'schedule.remove.ok': '已删除任务 `${id}`。',
|
|
55
|
+
'schedule.taskNotFound': '未找到任务:`${id}`',
|
|
56
|
+
'schedule.pause.usage': '用法:`!schedule pause <id>`',
|
|
57
|
+
'schedule.pause.ok': '已暂停任务 `${id}`。',
|
|
58
|
+
'schedule.resume.usage': '用法:`!schedule resume <id>`',
|
|
59
|
+
'schedule.resume.ok': '已恢复任务 `${id}`。${nextAt}',
|
|
60
|
+
'schedule.resume.nextRun': ' 下次运行:${time}。',
|
|
61
|
+
'schedule.invalidDuration': '无效的时长:`${duration}`。请使用例如 `30s`、`5m`、`2h`、`1d`',
|
|
62
|
+
'schedule.invalidTime': '无效的时间:`${time}`。请使用 24 小时制 HH:MM,例如 `${example}`',
|
|
63
|
+
'schedule.invalidDay': '无效的星期:`${day}`。请使用:mon, tue, wed, thu, fri, sat, sun',
|
|
64
|
+
'schedule.add.intervalUsage': '用法:`!schedule add interval <duration> [--profile <name>] <message>`',
|
|
65
|
+
'schedule.add.dailyUsage': '用法:`!schedule add daily <HH:MM> [--profile <name>] <message>`',
|
|
66
|
+
'schedule.add.weeklyUsage': '用法:`!schedule add weekly <day> <HH:MM> [--profile <name>] <message>`',
|
|
67
|
+
'schedule.add.onceUsage': '用法:`!schedule add once <duration> [--profile <name>] <message>`',
|
|
68
|
+
'schedule.add.scheduledInterval': '已设定每 *${duration}* 运行一次:"${message}"',
|
|
69
|
+
'schedule.add.scheduledDaily': '已设定每天 *${time}* 运行:"${message}"',
|
|
70
|
+
'schedule.add.scheduledWeekly': '已设定每周 *${day} ${time}* 运行:"${message}"',
|
|
71
|
+
'schedule.add.scheduledOnce': '已设定 *${duration}* 后运行一次:"${message}"',
|
|
72
|
+
'schedule.add.unknownType': '未知的类型:`${type}`。请使用 `interval`、`daily`、`weekly` 或 `once`',
|
|
73
|
+
'schedule.profileUsage': '用法:${usage}',
|
|
74
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare const startupEn: {
|
|
2
|
+
readonly 'startup.started': "Cortex agent v${version} started on ${machine}.";
|
|
3
|
+
readonly 'startup.restarted': "Cortex agent v${version} restarted on ${machine}.";
|
|
4
|
+
readonly 'startup.reason': " Reason: ${reason}.";
|
|
5
|
+
};
|
|
6
|
+
export declare const startupZh: Record<keyof typeof startupEn, string>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// input: nothing (leaf data slice)
|
|
2
|
+
// output: startupEn / startupZh — message slice (filled by i18n extraction)
|
|
3
|
+
// pos: one locale slice; aggregated by core/locales/en.ts & zh.ts barrels
|
|
4
|
+
// >>> Keep en and zh keys in lockstep (zh typed against keyof typeof startupEn) <<<
|
|
5
|
+
export const startupEn = {
|
|
6
|
+
'startup.started': 'Cortex agent v${version} started on ${machine}.',
|
|
7
|
+
'startup.restarted': 'Cortex agent v${version} restarted on ${machine}.',
|
|
8
|
+
'startup.reason': ' Reason: ${reason}.',
|
|
9
|
+
};
|
|
10
|
+
export const startupZh = {
|
|
11
|
+
'startup.started': 'Cortex 代理 v${version} 已在 ${machine} 上启动。',
|
|
12
|
+
'startup.restarted': 'Cortex 代理 v${version} 已在 ${machine} 上重启。',
|
|
13
|
+
'startup.reason': ' 原因:${reason}。',
|
|
14
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export declare const statusEn: {
|
|
2
|
+
readonly 'status.processing': "Processing";
|
|
3
|
+
readonly 'status.done': "Done";
|
|
4
|
+
readonly 'status.waitingForUserInput': "Waiting for user input";
|
|
5
|
+
readonly 'status.cancelled': "Cancelled";
|
|
6
|
+
readonly 'status.error': "Error";
|
|
7
|
+
readonly 'status.supersededByEdit': "Superseded by edit";
|
|
8
|
+
readonly 'status.retryEdited': "edited";
|
|
9
|
+
readonly 'status.retry': "Retry";
|
|
10
|
+
readonly 'status.rateLimitedExhausted': "Rate limited — all fallbacks exhausted";
|
|
11
|
+
readonly 'status.supersededSeeNewReply': "see new reply";
|
|
12
|
+
readonly 'status.processingAskResponse': "Processing AskUserQuestion response...";
|
|
13
|
+
readonly 'status.errorBody': "Error: ${message}";
|
|
14
|
+
readonly 'status.noRunningExecutions': "No running executions.";
|
|
15
|
+
readonly 'status.runningExecutions': "Running executions: ${count}";
|
|
16
|
+
readonly 'btn.cancel': "Cancel";
|
|
17
|
+
readonly 'btn.resume': "Resume";
|
|
18
|
+
readonly 'btn.new': "New";
|
|
19
|
+
};
|
|
20
|
+
export declare const statusZh: Record<keyof typeof statusEn, string>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// input: nothing (leaf data slice)
|
|
2
|
+
// output: statusEn / statusZh — message slice (filled by i18n extraction)
|
|
3
|
+
// pos: one locale slice; aggregated by core/locales/en.ts & zh.ts barrels
|
|
4
|
+
// >>> Keep en and zh keys in lockstep (zh typed against keyof typeof statusEn) <<<
|
|
5
|
+
export const statusEn = {
|
|
6
|
+
// --- Status / lifecycle phrases ---
|
|
7
|
+
'status.processing': 'Processing',
|
|
8
|
+
'status.done': 'Done',
|
|
9
|
+
'status.waitingForUserInput': 'Waiting for user input',
|
|
10
|
+
'status.cancelled': 'Cancelled',
|
|
11
|
+
'status.error': 'Error',
|
|
12
|
+
'status.supersededByEdit': 'Superseded by edit',
|
|
13
|
+
'status.retryEdited': 'edited',
|
|
14
|
+
'status.retry': 'Retry',
|
|
15
|
+
'status.rateLimitedExhausted': 'Rate limited — all fallbacks exhausted',
|
|
16
|
+
'status.supersededSeeNewReply': 'see new reply',
|
|
17
|
+
'status.processingAskResponse': 'Processing AskUserQuestion response...',
|
|
18
|
+
'status.errorBody': 'Error: ${message}',
|
|
19
|
+
// --- Execution report ---
|
|
20
|
+
'status.noRunningExecutions': 'No running executions.',
|
|
21
|
+
'status.runningExecutions': 'Running executions: ${count}',
|
|
22
|
+
// --- Button labels ---
|
|
23
|
+
'btn.cancel': 'Cancel',
|
|
24
|
+
'btn.resume': 'Resume',
|
|
25
|
+
'btn.new': 'New',
|
|
26
|
+
};
|
|
27
|
+
export const statusZh = {
|
|
28
|
+
// --- Status / lifecycle phrases ---
|
|
29
|
+
'status.processing': '处理中',
|
|
30
|
+
'status.done': '完成',
|
|
31
|
+
'status.waitingForUserInput': '等待用户输入',
|
|
32
|
+
'status.cancelled': '已取消',
|
|
33
|
+
'status.error': '错误',
|
|
34
|
+
'status.supersededByEdit': '已被编辑取代',
|
|
35
|
+
'status.retryEdited': '已编辑',
|
|
36
|
+
'status.retry': '重试',
|
|
37
|
+
'status.rateLimitedExhausted': '触发限流 — 所有回退已用尽',
|
|
38
|
+
'status.supersededSeeNewReply': '查看新回复',
|
|
39
|
+
'status.processingAskResponse': '正在处理 AskUserQuestion 回复……',
|
|
40
|
+
'status.errorBody': '错误:${message}',
|
|
41
|
+
// --- Execution report ---
|
|
42
|
+
'status.noRunningExecutions': '没有正在运行的执行。',
|
|
43
|
+
'status.runningExecutions': '正在运行的执行:${count}',
|
|
44
|
+
// --- Button labels ---
|
|
45
|
+
'btn.cancel': '取消',
|
|
46
|
+
'btn.resume': '恢复',
|
|
47
|
+
'btn.new': '新建',
|
|
48
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { MessageKey } from './en.js';
|
|
2
|
+
/** Simplified-Chinese translations, aggregated from per-cluster slices. Must provide every
|
|
3
|
+
* MessageKey (compiler-enforced via Record<MessageKey,string>) and add none. ${param}
|
|
4
|
+
* placeholders and `code`/*bold* markdown are preserved verbatim from the en slices. */
|
|
5
|
+
export declare const zh: Record<MessageKey, string>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// input: per-cluster Simplified-Chinese slices (./slices/*) + MessageKey from en.ts
|
|
2
|
+
// output: `zh` — aggregated zh table, typed Record<MessageKey, string>
|
|
3
|
+
// pos: L0 locale barrel; the Record<MessageKey,...> type forces parity with en.ts at compile time
|
|
4
|
+
// >>> Keep slice keys in lockstep with their en counterparts <<<
|
|
5
|
+
import { langZh } from './slices/lang.js';
|
|
6
|
+
import { statusZh } from './slices/status.js';
|
|
7
|
+
import { commandsZh } from './slices/commands.js';
|
|
8
|
+
import { schedulingZh } from './slices/scheduling.js';
|
|
9
|
+
import { interactionsZh } from './slices/interactions.js';
|
|
10
|
+
import { startupZh } from './slices/startup.js';
|
|
11
|
+
import { initZh } from './slices/init.js';
|
|
12
|
+
/** Simplified-Chinese translations, aggregated from per-cluster slices. Must provide every
|
|
13
|
+
* MessageKey (compiler-enforced via Record<MessageKey,string>) and add none. ${param}
|
|
14
|
+
* placeholders and `code`/*bold* markdown are preserved verbatim from the en slices. */
|
|
15
|
+
export const zh = {
|
|
16
|
+
...langZh,
|
|
17
|
+
...statusZh,
|
|
18
|
+
...commandsZh,
|
|
19
|
+
...schedulingZh,
|
|
20
|
+
...interactionsZh,
|
|
21
|
+
...startupZh,
|
|
22
|
+
...initZh,
|
|
23
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Probe whether a PID is alive. Signal 0 performs the permission/existence check
|
|
2
|
+
* without actually delivering a signal; a throw (ESRCH/EPERM-as-dead handled by caller)
|
|
3
|
+
* means the process is not addressable as a live, signalable target. */
|
|
4
|
+
export declare function isProcessAlive(pid: number): boolean;
|
|
5
|
+
export interface AcquireResult {
|
|
6
|
+
acquired: boolean;
|
|
7
|
+
/** Set when acquired === true: whether a stale/corrupt lock was reclaimed. */
|
|
8
|
+
stale?: boolean;
|
|
9
|
+
/** Set when acquired === false: the PID currently holding the lock. */
|
|
10
|
+
holderPid?: number;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Attempt to take a PID-file singleton lock.
|
|
14
|
+
* - File missing → write own pid, { acquired: true, stale: false }
|
|
15
|
+
* - File holds a live, valid pid → { acquired: false, holderPid }
|
|
16
|
+
* - File holds a dead/corrupt pid → overwrite with own pid, { acquired: true, stale: true }
|
|
17
|
+
*
|
|
18
|
+
* This function never exits the process or logs — the caller decides how to react to a
|
|
19
|
+
* conflict (typically: log a message and process.exit(1)).
|
|
20
|
+
*/
|
|
21
|
+
export declare function tryAcquireSingletonLock(pidFile: string): AcquireResult;
|
|
22
|
+
/** Release the lock iff it is still owned by the current process. Best-effort; swallows errors. */
|
|
23
|
+
export declare function releaseSingletonLock(pidFile: string): void;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// input: a pidfile path
|
|
2
|
+
// output: tryAcquireSingletonLock / releaseSingletonLock / isProcessAlive
|
|
3
|
+
// pos: L0 zero-dependency singleton-lock primitive, shared by daemon.ts and app.ts
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { existsSync, readFileSync, writeFileSync, unlinkSync } from 'fs';
|
|
6
|
+
/** Probe whether a PID is alive. Signal 0 performs the permission/existence check
|
|
7
|
+
* without actually delivering a signal; a throw (ESRCH/EPERM-as-dead handled by caller)
|
|
8
|
+
* means the process is not addressable as a live, signalable target. */
|
|
9
|
+
export function isProcessAlive(pid) {
|
|
10
|
+
try {
|
|
11
|
+
process.kill(pid, 0);
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Attempt to take a PID-file singleton lock.
|
|
20
|
+
* - File missing → write own pid, { acquired: true, stale: false }
|
|
21
|
+
* - File holds a live, valid pid → { acquired: false, holderPid }
|
|
22
|
+
* - File holds a dead/corrupt pid → overwrite with own pid, { acquired: true, stale: true }
|
|
23
|
+
*
|
|
24
|
+
* This function never exits the process or logs — the caller decides how to react to a
|
|
25
|
+
* conflict (typically: log a message and process.exit(1)).
|
|
26
|
+
*/
|
|
27
|
+
export function tryAcquireSingletonLock(pidFile) {
|
|
28
|
+
if (existsSync(pidFile)) {
|
|
29
|
+
const raw = readFileSync(pidFile, 'utf8').trim();
|
|
30
|
+
const holderPid = Number(raw);
|
|
31
|
+
if (Number.isFinite(holderPid) && holderPid > 0 && isProcessAlive(holderPid)) {
|
|
32
|
+
return { acquired: false, holderPid };
|
|
33
|
+
}
|
|
34
|
+
// Stale (previous owner died without cleanup) or corrupt content — reclaim it.
|
|
35
|
+
writeFileSync(pidFile, String(process.pid), 'utf8');
|
|
36
|
+
return { acquired: true, stale: true };
|
|
37
|
+
}
|
|
38
|
+
writeFileSync(pidFile, String(process.pid), 'utf8');
|
|
39
|
+
return { acquired: true, stale: false };
|
|
40
|
+
}
|
|
41
|
+
/** Release the lock iff it is still owned by the current process. Best-effort; swallows errors. */
|
|
42
|
+
export function releaseSingletonLock(pidFile) {
|
|
43
|
+
try {
|
|
44
|
+
if (!existsSync(pidFile))
|
|
45
|
+
return;
|
|
46
|
+
const raw = readFileSync(pidFile, 'utf8').trim();
|
|
47
|
+
if (Number(raw) === process.pid)
|
|
48
|
+
unlinkSync(pidFile);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
/* best-effort cleanup */
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import { formatDurationCompact } from './utils.js';
|
|
6
6
|
import { Icons } from './icons.js';
|
|
7
|
+
import { t } from './i18n.js';
|
|
7
8
|
export function computeElapsed(startTime) {
|
|
8
9
|
const elapsedS = (Date.now() - startTime) / 1000;
|
|
9
10
|
return { elapsedStr: formatDurationCompact(elapsedS), elapsedS };
|
|
@@ -28,5 +29,5 @@ export function buildUserProcessingMessage({ startTime, elapsed_s = null, num_tu
|
|
|
28
29
|
const elapsed = elapsed_s ?? ((Date.now() - startTime) / 1000);
|
|
29
30
|
const sessionTag = buildSessionTag(sessionName, sessionId);
|
|
30
31
|
const turnsStr = num_turns != null ? ` | ${Icons.repeat} ${num_turns} turns` : '';
|
|
31
|
-
return `${Icons.processing}
|
|
32
|
+
return `${Icons.processing} ${t('status.processing')} | ${sessionTag}${profileName || 'default'} | ${Icons.stopwatch} ${formatDurationCompact(elapsed || 0)}${turnsStr}`;
|
|
32
33
|
}
|
package/dist/core/utils.d.ts
CHANGED
|
@@ -26,4 +26,12 @@ declare function todayISO(): string;
|
|
|
26
26
|
* `cortex-task lock-status`, `stats`, id-assignment, etc.).
|
|
27
27
|
*/
|
|
28
28
|
declare function listProjectDirs(projectsDir?: string): string[];
|
|
29
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Sentinel ANTHROPIC_API_KEY value set when the gateway is healthy but no real key exists.
|
|
31
|
+
* Its only purpose is to satisfy Claude Code's startup credential check on machines without
|
|
32
|
+
* OAuth login — upstream auth is handled by the gateway's own configured keys. Anything that
|
|
33
|
+
* treats ANTHROPIC_API_KEY as a real credential (gateway-generator discovery, saved-env
|
|
34
|
+
* snapshots) must ignore this value.
|
|
35
|
+
*/
|
|
36
|
+
declare const GATEWAY_MANAGED_KEY_PLACEHOLDER = "cortex-gateway-managed";
|
|
37
|
+
export { INSTALL_ROOT, DEFAULTS_DIR, PACKAGE_ROOT, SERVER_ROOT, REPO_ROOT, DATA_DIR, CONFIG_DIR, STORE_DIR, CONTEXT_DIR, PROJECTS_DIR, WORKSPACE_DIR, PLUGINS_DIR, PROMPTS_DIR, HOOKS_DIR, SKIP_DIRS, GATEWAY_MANAGED_KEY_PLACEHOLDER, moduleDir, isMainModule, readableTimestamp, chunkText, formatDurationCompact, todayISO, listProjectDirs };
|
package/dist/core/utils.js
CHANGED
|
@@ -95,4 +95,12 @@ function listProjectDirs(projectsDir = PROJECTS_DIR) {
|
|
|
95
95
|
return [];
|
|
96
96
|
}
|
|
97
97
|
}
|
|
98
|
-
|
|
98
|
+
/**
|
|
99
|
+
* Sentinel ANTHROPIC_API_KEY value set when the gateway is healthy but no real key exists.
|
|
100
|
+
* Its only purpose is to satisfy Claude Code's startup credential check on machines without
|
|
101
|
+
* OAuth login — upstream auth is handled by the gateway's own configured keys. Anything that
|
|
102
|
+
* treats ANTHROPIC_API_KEY as a real credential (gateway-generator discovery, saved-env
|
|
103
|
+
* snapshots) must ignore this value.
|
|
104
|
+
*/
|
|
105
|
+
const GATEWAY_MANAGED_KEY_PLACEHOLDER = 'cortex-gateway-managed';
|
|
106
|
+
export { INSTALL_ROOT, DEFAULTS_DIR, PACKAGE_ROOT, SERVER_ROOT, REPO_ROOT, DATA_DIR, CONFIG_DIR, STORE_DIR, CONTEXT_DIR, PROJECTS_DIR, WORKSPACE_DIR, PLUGINS_DIR, PROMPTS_DIR, HOOKS_DIR, SKIP_DIRS, GATEWAY_MANAGED_KEY_PLACEHOLDER, moduleDir, isMainModule, readableTimestamp, chunkText, formatDurationCompact, todayISO, listProjectDirs };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { GATEWAY_MANAGED_KEY_PLACEHOLDER } from '../../core/utils.js';
|
|
1
2
|
export interface ModeFileData {
|
|
2
3
|
mode?: string;
|
|
3
4
|
claudeMode?: string;
|
|
@@ -55,4 +56,4 @@ export declare function resolveAgentModel({ profileName, modelOverride }?: {
|
|
|
55
56
|
modelOverride?: string | null;
|
|
56
57
|
}): string;
|
|
57
58
|
export declare function detectBillingMode(): string;
|
|
58
|
-
export { GATEWAY_ANTHROPIC_URL, saveModeFile, loadModeFile, };
|
|
59
|
+
export { GATEWAY_ANTHROPIC_URL, GATEWAY_MANAGED_KEY_PLACEHOLDER, saveModeFile, loadModeFile, };
|
|
@@ -5,7 +5,7 @@ import { readFileSync, writeFileSync } from 'fs';
|
|
|
5
5
|
import { parse as parseDotenv } from 'dotenv';
|
|
6
6
|
import * as path from 'path';
|
|
7
7
|
import * as http from 'http';
|
|
8
|
-
import { STORE_DIR, CONFIG_DIR } from '../../core/utils.js';
|
|
8
|
+
import { STORE_DIR, CONFIG_DIR, GATEWAY_MANAGED_KEY_PLACEHOLDER } from '../../core/utils.js';
|
|
9
9
|
import { getProfileModel, resolveProfileConfig } from './profile-manager.js';
|
|
10
10
|
import { GATEWAY_URL, isGatewayHealthy } from '../costs/gateway-manager.js';
|
|
11
11
|
import { createLogger } from '../../core/log.js';
|
|
@@ -52,8 +52,12 @@ function readApiEnvFromDotenvFile() {
|
|
|
52
52
|
}
|
|
53
53
|
function captureApiEnvSnapshot() {
|
|
54
54
|
const fileEnv = readApiEnvFromDotenvFile();
|
|
55
|
+
// The gateway-managed placeholder is not a real credential — never let it
|
|
56
|
+
// pollute the saved env used for direct (gateway-down) connections.
|
|
57
|
+
const liveKey = normalizeEnvValue(process.env.ANTHROPIC_API_KEY);
|
|
58
|
+
const realLiveKey = liveKey === GATEWAY_MANAGED_KEY_PLACEHOLDER ? undefined : liveKey;
|
|
55
59
|
return {
|
|
56
|
-
ANTHROPIC_API_KEY:
|
|
60
|
+
ANTHROPIC_API_KEY: realLiveKey || fileEnv.ANTHROPIC_API_KEY,
|
|
57
61
|
ANTHROPIC_BASE_URL: normalizeEnvValue(process.env.ANTHROPIC_BASE_URL) || fileEnv.ANTHROPIC_BASE_URL,
|
|
58
62
|
};
|
|
59
63
|
}
|
|
@@ -234,7 +238,18 @@ export function configureEnvForMode(mode, metadata) {
|
|
|
234
238
|
if (isGatewayHealthy()) {
|
|
235
239
|
const url = gatewayModeUrl(mode, metadata);
|
|
236
240
|
process.env.ANTHROPIC_BASE_URL = url;
|
|
237
|
-
|
|
241
|
+
if (mode === 'plan') {
|
|
242
|
+
// Plan mode rides the gateway's passthrough: Claude Code must send its own OAuth
|
|
243
|
+
// bearer token, and an env API key would take precedence over OAuth — delete it.
|
|
244
|
+
delete process.env.ANTHROPIC_API_KEY;
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
// Non-plan modes: upstream auth is the gateway's job (it injects its own configured
|
|
248
|
+
// keys). Keep a key in env purely so Claude Code passes its startup credential check
|
|
249
|
+
// on machines without OAuth login (otherwise it exits with "Please run /login").
|
|
250
|
+
const saved = getSavedApiEnv();
|
|
251
|
+
process.env.ANTHROPIC_API_KEY = saved.ANTHROPIC_API_KEY || GATEWAY_MANAGED_KEY_PLACEHOLDER;
|
|
252
|
+
}
|
|
238
253
|
return url;
|
|
239
254
|
}
|
|
240
255
|
// Gateway unhealthy — fallback to direct connection
|
|
@@ -308,6 +323,10 @@ export function detectBillingMode() {
|
|
|
308
323
|
catch { }
|
|
309
324
|
return 'api';
|
|
310
325
|
}
|
|
311
|
-
//
|
|
312
|
-
|
|
313
|
-
|
|
326
|
+
// NOTE: deliberately NO configureEnvForMode() call at module scope. This module is imported
|
|
327
|
+
// transitively by CLI processes (cortex init / setup-gateway via domain/threads), where the
|
|
328
|
+
// gateway is always unhealthy — an import-time call would delete ANTHROPIC_API_KEY (plan mode)
|
|
329
|
+
// before gateway-generator discovery runs, breaking api endpoint generation. The server entry
|
|
330
|
+
// (app.ts) applies the persisted mode explicitly after dotenv loads; every agent spawn also
|
|
331
|
+
// calls configureEnvForMode() per-request (facade.runAgentOnce).
|
|
332
|
+
export { GATEWAY_ANTHROPIC_URL, GATEWAY_MANAGED_KEY_PLACEHOLDER, saveModeFile, loadModeFile, };
|
|
@@ -9,7 +9,6 @@ import * as executionRegistry from '../../executions/registry.js';
|
|
|
9
9
|
const log = createLogger('task-dispatch');
|
|
10
10
|
import * as pendingTaskTracker from '../../tasks/pending-tracker.js';
|
|
11
11
|
import { sessionStore } from '../../../store/session-registry-repo.js';
|
|
12
|
-
import { allConfigsRateLimited } from '../../agents/facade.js';
|
|
13
12
|
import { selectAndClaimTask, computeNextInterval, updateScheduleInterval } from '../../tasks/dispatcher.js';
|
|
14
13
|
import { taskMutator } from '../../tasks/mutator.js';
|
|
15
14
|
import { createThread, detectSplitMarker } from '../../threads/index.js';
|
|
@@ -69,19 +68,16 @@ async function runDispatchAsync({ channel, scheduleTaskId, profileName }) {
|
|
|
69
68
|
let selectedTask = null;
|
|
70
69
|
let outcome = { success: false, skipped: false, note: '' };
|
|
71
70
|
try {
|
|
72
|
-
// Step 1: Dry run — check there is a dispatchable task without claiming
|
|
73
|
-
|
|
71
|
+
// Step 1: Dry run — check there is a dispatchable task without claiming.
|
|
72
|
+
// Rate-limit eligibility is decided per-task inside selection, against each task's
|
|
73
|
+
// TEMPLATE profiles (profileName only resolves __active__ slots) — see dispatcher.ts.
|
|
74
|
+
const preview = await selectAndClaimTask({ scheduleTaskId, dryRun: true, profileName });
|
|
74
75
|
if (!preview) {
|
|
75
76
|
outcome = { success: false, skipped: true, note: 'No dispatchable tasks available' };
|
|
76
77
|
return;
|
|
77
78
|
}
|
|
78
|
-
// Step 2:
|
|
79
|
-
|
|
80
|
-
outcome = { success: false, skipped: true, note: `All configs rate-limited for ${profileName}` };
|
|
81
|
-
return;
|
|
82
|
-
}
|
|
83
|
-
// Step 3: Real claim + execute
|
|
84
|
-
const selected = await selectAndClaimTask({ scheduleTaskId });
|
|
79
|
+
// Step 2: Real claim + execute
|
|
80
|
+
const selected = await selectAndClaimTask({ scheduleTaskId, profileName });
|
|
85
81
|
if (!selected) {
|
|
86
82
|
outcome = { success: false, skipped: true, note: 'No dispatchable tasks available' };
|
|
87
83
|
return;
|