@dofy/namo 0.7.0 → 0.7.1
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/README.md +8 -4
- package/README.zh-CN.md +8 -4
- package/dist/src/agent-registry.js +46 -9
- package/dist/src/agent-registry.js.map +1 -1
- package/dist/src/agents.js +60 -8
- package/dist/src/agents.js.map +1 -1
- package/dist/src/auto-memory.js +1 -1
- package/dist/src/cards.js +1 -1
- package/dist/src/cards.js.map +1 -1
- package/dist/src/claude-runtime.js +331 -0
- package/dist/src/claude-runtime.js.map +1 -0
- package/dist/src/cli.js +5 -4
- package/dist/src/cli.js.map +1 -1
- package/dist/src/daily-turns.js +56 -0
- package/dist/src/daily-turns.js.map +1 -0
- package/dist/src/doctor.js +3 -3
- package/dist/src/doctor.js.map +1 -1
- package/dist/src/engine.js +164 -75
- package/dist/src/engine.js.map +1 -1
- package/dist/src/external-wait-bridge.js +1 -3
- package/dist/src/external-wait-bridge.js.map +1 -1
- package/dist/src/external-waits.js +13 -12
- package/dist/src/external-waits.js.map +1 -1
- package/dist/src/feedback.js +27 -11
- package/dist/src/feedback.js.map +1 -1
- package/dist/src/image-inputs.js +1 -0
- package/dist/src/image-inputs.js.map +1 -1
- package/dist/src/live-upgrade.js +1 -1
- package/dist/src/live-upgrade.js.map +1 -1
- package/dist/src/locales/en.js +59 -18
- package/dist/src/locales/en.js.map +1 -1
- package/dist/src/locales/zh-CN.js +59 -18
- package/dist/src/locales/zh-CN.js.map +1 -1
- package/dist/src/management.js +84 -16
- package/dist/src/management.js.map +1 -1
- package/dist/src/memory-extractor.js +2 -2
- package/dist/src/memory-extractor.js.map +1 -1
- package/dist/src/onboarding.js +28 -10
- package/dist/src/onboarding.js.map +1 -1
- package/dist/src/prompts.js +1 -1
- package/dist/src/prompts.js.map +1 -1
- package/dist/src/runner-worker.js +5 -6
- package/dist/src/runner-worker.js.map +1 -1
- package/dist/src/runner.js +11 -1
- package/dist/src/runner.js.map +1 -1
- package/dist/src/runtime-config.js +5 -1
- package/dist/src/runtime-config.js.map +1 -1
- package/dist/src/tasks.js +35 -3
- package/dist/src/tasks.js.map +1 -1
- package/dist/src/ui.js +1 -1
- package/dist/src/ui.js.map +1 -1
- package/dist/ui/assets/index-CcbYEcXS.js +133 -0
- package/dist/ui/assets/{index-CJAhDqDy.css → index-Cks2QULV.css} +1 -1
- package/dist/ui/index.html +2 -2
- package/docs/architecture.md +10 -9
- package/docs/operations.md +14 -2
- package/docs/release-notes.md +11 -0
- package/docs/technical-guide-zh-cn.md +6 -6
- package/docs/technical-guide.md +6 -6
- package/docs-site/content.js +5 -5
- package/package.json +2 -2
- package/dist/ui/assets/index-DkhjblIL.js +0 -131
package/dist/src/engine.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { sessionList } from './session-list.js';
|
|
2
2
|
import { decideMcpApproval, mcpApprovalCommand, revokeBrowserGrant } from './mcp-write-approval.js';
|
|
3
3
|
import { memoryDirectories } from './memory-access.js';
|
|
4
|
-
import { AgentRegistryError, selectAgent, selectedPolicyHash } from './agent-registry.js';
|
|
4
|
+
import { AgentRegistryError, agentCodexConfig, getAgentRegistry, resolveAgent, selectAgent, selectedPolicyHash } from './agent-registry.js';
|
|
5
|
+
import { agentLabel } from './agents.js';
|
|
5
6
|
import { mkdirSync, realpathSync, readFileSync } from 'node:fs';
|
|
6
7
|
import { pathsOverlap } from './path-policy.js';
|
|
7
8
|
export { pathsOverlap } from './path-policy.js';
|
|
@@ -23,7 +24,6 @@ import { formatControlDisplay } from './control-display.js';
|
|
|
23
24
|
import { resolveCodexBinary } from './codex-installation.js';
|
|
24
25
|
import { RuntimeVersions } from './runtime-version.js';
|
|
25
26
|
import { NAMO_VERSION } from './version.js';
|
|
26
|
-
import { agentCodexConfig } from './agent-registry.js';
|
|
27
27
|
import { EvidenceRecorder, readEvidence } from './evidence.js';
|
|
28
28
|
import { runnerJob } from './runner-store.js';
|
|
29
29
|
import { evidenceBrief, taskStateLabel, taskStatus } from './presentation.js';
|
|
@@ -47,6 +47,7 @@ import { Schedules } from './schedules.js';
|
|
|
47
47
|
import { conversationControl } from './conversation-control.js';
|
|
48
48
|
import { applyDirectoryRequests, decideDirectory, getDirectoryRequest } from './directory-approval.js';
|
|
49
49
|
import { redactExpiredInbox } from './inbox-retention.js';
|
|
50
|
+
import { DailyTurns } from './daily-turns.js';
|
|
50
51
|
export class SendError extends Error {
|
|
51
52
|
unknown;
|
|
52
53
|
code;
|
|
@@ -69,7 +70,33 @@ export class Engine {
|
|
|
69
70
|
const m = this.store.get(task.inboxKey);
|
|
70
71
|
return m?.envelope?.chatType === 'group' ? JSON.stringify(['group', task.chatKey, task.scopeKey, task.ownerId]) : task.chatKey;
|
|
71
72
|
}
|
|
73
|
+
detachedReservations() {
|
|
74
|
+
const activeRuns = new Set(Array.from(this.active.values(), slot => slot.run));
|
|
75
|
+
return (this.runtime.reservations?.() ?? []).filter(reservation => !activeRuns.has(reservation.runId));
|
|
76
|
+
}
|
|
77
|
+
nextRunnableTask(reservations) {
|
|
78
|
+
const candidates = this.tasks.candidates();
|
|
79
|
+
if (!candidates.length)
|
|
80
|
+
return;
|
|
81
|
+
const occupied = new Set(this.active.keys());
|
|
82
|
+
const blockedPaths = Array.from(this.active.values(), slot => this.tasks.directories(slot.task)).flat();
|
|
83
|
+
for (const reservation of reservations) {
|
|
84
|
+
occupied.add(reservation.slotKey ?? reservation.chatKey);
|
|
85
|
+
blockedPaths.push(...(reservation.paths?.length ? reservation.paths : [reservation.cwd]));
|
|
86
|
+
}
|
|
87
|
+
return candidates.find(task => {
|
|
88
|
+
if (occupied.has(this.slotKey(task)))
|
|
89
|
+
return false;
|
|
90
|
+
if (!blockedPaths.length)
|
|
91
|
+
return true;
|
|
92
|
+
return this.tasks.directories(task).every(path => !blockedPaths.some(root => pathsOverlap(root, path)));
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
get dailyTurnLimit() {
|
|
96
|
+
return this.config.codex?.dailyTurnLimit ?? (this.config.feishu?.access ? 100 : 0);
|
|
97
|
+
}
|
|
72
98
|
tasks;
|
|
99
|
+
dailyTurns;
|
|
73
100
|
outputBusy = false;
|
|
74
101
|
stopped = false;
|
|
75
102
|
started = false;
|
|
@@ -102,6 +129,7 @@ export class Engine {
|
|
|
102
129
|
this.log = log;
|
|
103
130
|
this.onFatal = onFatal;
|
|
104
131
|
this.tasks = new Tasks(store);
|
|
132
|
+
this.dailyTurns = new DailyTurns(store);
|
|
105
133
|
this.feedback = new Feedback(store, sender, task => this.taskAccessible(task), this.redact);
|
|
106
134
|
this.artifacts = new ArtifactDelivery(store, sender, config.codex?.denyPaths, config.codex?.explicitDenyPaths ? { dataDir: config.dataDir, explicitDenyPaths: config.codex.explicitDenyPaths } : undefined, id => { const task = this.tasks.get(id); return !!task && this.taskAccessible(task); });
|
|
107
135
|
if (config.file) {
|
|
@@ -323,7 +351,7 @@ export class Engine {
|
|
|
323
351
|
return true;
|
|
324
352
|
}
|
|
325
353
|
const command = m.text.trim().split(/\s/)[0];
|
|
326
|
-
if (['/deliver', '/profile', '/model', '/issues', '/issue', '/resolve', '/status', '/version', '/whoami', '/cancel', '/reset', '/new', '/refresh', '/directories', '/session', '/tasks', '/task', '/help', '/unsupported', '/too-long'].includes(command)) {
|
|
354
|
+
if (['/deliver', '/profile', '/model', '/agent', '/issues', '/issue', '/resolve', '/status', '/version', '/whoami', '/cancel', '/reset', '/new', '/refresh', '/directories', '/session', '/tasks', '/task', '/help', '/unsupported', '/too-long'].includes(command)) {
|
|
327
355
|
if (!this.store.claim(m.key))
|
|
328
356
|
return true;
|
|
329
357
|
let reply;
|
|
@@ -347,6 +375,8 @@ export class Engine {
|
|
|
347
375
|
reply = this.profileCommand(m);
|
|
348
376
|
else if (command === '/model')
|
|
349
377
|
reply = this.modelCommand(m);
|
|
378
|
+
else if (command === '/agent')
|
|
379
|
+
reply = this.agentCommand(m);
|
|
350
380
|
else if (['/issues', '/issue', '/resolve'].includes(command)) {
|
|
351
381
|
const recovery = new Recovery(this.store), actor = { id: m.senderId, chatKey: m.chatKey };
|
|
352
382
|
const parts = m.text.trim().split(/\s+/);
|
|
@@ -414,6 +444,7 @@ export class Engine {
|
|
|
414
444
|
'**直接说出你的要求**',
|
|
415
445
|
'可以让我执行工作、查看或停止任务、补充要求、交付文件、管理会话,以及创建或管理定时任务。',
|
|
416
446
|
'个人档案、模型偏好和记忆可在私聊中管理;需要确认目标时,我会询问。',
|
|
447
|
+
'私聊发送 `/agent` 查看或切换执行器。',
|
|
417
448
|
'收到等待问题后可以引用问题回复或选择选项;发送结果不明时请先核对聊天记录。',
|
|
418
449
|
'本机运行 namo ui 可管理配置与任务。'
|
|
419
450
|
].join('\n\n');
|
|
@@ -439,12 +470,55 @@ export class Engine {
|
|
|
439
470
|
}
|
|
440
471
|
return false;
|
|
441
472
|
}
|
|
473
|
+
agentCommand(m) {
|
|
474
|
+
const f = this.config.feishu, codex = this.config.codex, e = m.envelope;
|
|
475
|
+
if (e?.chatType !== 'p2p' || e.kind !== 'instruction' || e.type !== 'text'
|
|
476
|
+
|| e.parentId || e.rootId || e.materials.length || e.limitations.length)
|
|
477
|
+
return '请在机器人私聊中单独发送 /agent 文字命令。';
|
|
478
|
+
if (!codex || !f || !admitted(this.contextConfig().feishu, m.senderId, m.chatId, e.tenantKey))
|
|
479
|
+
return '当前身份未获准切换执行器。';
|
|
480
|
+
const config = { ...this.config, codex };
|
|
481
|
+
const registry = getAgentRegistry(config);
|
|
482
|
+
const options = registry.profiles.filter(p => p.enabled).map(p => `${agentLabel(p)} · \`/agent ${p.id}\``);
|
|
483
|
+
const parts = m.text.trim().split(/\s+/);
|
|
484
|
+
if (parts.length > 2)
|
|
485
|
+
return '发送 `/agent` 查看执行器和切换命令。';
|
|
486
|
+
if (parts.length === 2) {
|
|
487
|
+
const useDefault = parts[1] === 'default';
|
|
488
|
+
const target = registry.profiles.find(p => p.enabled && p.id === (useDefault ? registry.defaultProfile : parts[1]));
|
|
489
|
+
if (!target)
|
|
490
|
+
return '执行器未启用。请在本机工作台配置后重试。\n\n' + options.join('\n');
|
|
491
|
+
if (this.store.hasPending(m.chatKey, m.key, m.senderId, scopeOf(m)))
|
|
492
|
+
return '当前会话仍有未完成的任务,请完成或停止后再切换。';
|
|
493
|
+
if (this.configurationDraining)
|
|
494
|
+
return '服务正在应用配置,请稍后再切换执行器。';
|
|
495
|
+
this.tasks.switchAgent(m, target.id, useDefault);
|
|
496
|
+
return `已切换到 ${agentLabel(target)}。下一条任务会续接该执行器自己的工作线。`;
|
|
497
|
+
}
|
|
498
|
+
let current;
|
|
499
|
+
try {
|
|
500
|
+
current = agentLabel(resolveAgent(config, this.selectedAgent(m)));
|
|
501
|
+
}
|
|
502
|
+
catch {
|
|
503
|
+
current = '当前执行器不可用';
|
|
504
|
+
}
|
|
505
|
+
return [`**当前执行器:${current}**`, ...options, '`/agent default` 使用服务默认'].join('\n');
|
|
506
|
+
}
|
|
442
507
|
modelCommand(m) {
|
|
443
508
|
const f = this.config.feishu;
|
|
444
509
|
if (m.envelope?.chatType !== 'p2p' || m.envelope.type !== 'text' || m.envelope.parentId || m.envelope.rootId || m.envelope.materials.length)
|
|
445
510
|
return '请在机器人私聊中单独发送 /model 文字命令。';
|
|
446
511
|
if (!f?.appId || !f.domain || !(f.access ? admitted(f, m.senderId, m.chatId, m.envelope.tenantKey) : f.allowedUserIds?.includes(m.senderId)))
|
|
447
512
|
return '当前身份未获准设置模型。';
|
|
513
|
+
try {
|
|
514
|
+
if (this.selectedAgent(m)?.adapter === 'claude')
|
|
515
|
+
return '当前使用 Claude Code。Claude 模型由本机工作台配置。';
|
|
516
|
+
}
|
|
517
|
+
catch (error) {
|
|
518
|
+
if (error instanceof AgentRegistryError)
|
|
519
|
+
return '当前执行器不可用。请发送 /agent 查看可用执行器。';
|
|
520
|
+
throw error;
|
|
521
|
+
}
|
|
448
522
|
const identity = { channel: f.domain, appId: f.appId, userId: m.senderId };
|
|
449
523
|
const parts = m.text.trim().split(/\s+/);
|
|
450
524
|
if (parts.length > 2)
|
|
@@ -507,16 +581,38 @@ export class Engine {
|
|
|
507
581
|
if (!this.config.codex)
|
|
508
582
|
return;
|
|
509
583
|
const c = { ...this.config, codex: this.config.codex };
|
|
584
|
+
if (!reference) {
|
|
585
|
+
const scheduleId = /^schedule:(S-[A-F0-9]{12}):\d+$/.exec(m.key)?.[1];
|
|
586
|
+
if (scheduleId) {
|
|
587
|
+
const row = this.store.db.prepare('SELECT binding FROM schedules WHERE id=? AND ownerId=? AND chatKey=? AND scopeKey=?')
|
|
588
|
+
.get(scheduleId, m.senderId, m.chatKey, scopeOf(m));
|
|
589
|
+
if (row?.binding) {
|
|
590
|
+
const pinned = JSON.parse(String(row.binding)).agentSelection;
|
|
591
|
+
const current = selectAgent(c, pinned?.profileId ?? 'codex');
|
|
592
|
+
if (pinned && pinned.adapter !== current.adapter)
|
|
593
|
+
throw new AgentRegistryError('agent_configuration_changed');
|
|
594
|
+
return current;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
}
|
|
510
598
|
const bound = reference ?? this.tasks.binding(m);
|
|
511
599
|
const selected = bound ? this.tasks.selection(bound.id) : undefined;
|
|
512
|
-
|
|
600
|
+
if (reference && selected && selected.profileId !== 'codex')
|
|
601
|
+
return selected;
|
|
602
|
+
return selectAgent(c, bound ? selected?.profileId ?? 'codex' : this.tasks.agentPreference(m));
|
|
513
603
|
}
|
|
514
604
|
versionLines(m) {
|
|
515
605
|
let version = null;
|
|
516
606
|
try {
|
|
517
607
|
const c = this.config.codex;
|
|
518
|
-
if (c)
|
|
519
|
-
|
|
608
|
+
if (c) {
|
|
609
|
+
const selection = this.selectedAgent(m);
|
|
610
|
+
if (selection?.adapter === 'claude') {
|
|
611
|
+
const profile = resolveAgent({ ...this.config, codex: c }, selection);
|
|
612
|
+
return `Namo:\`${NAMO_VERSION}\`\n执行器:${agentLabel(profile)}`;
|
|
613
|
+
}
|
|
614
|
+
version = this.versions.get(agentCodexConfig({ ...this.config, codex: c }, selection));
|
|
615
|
+
}
|
|
520
616
|
}
|
|
521
617
|
catch { /* Invalid or missing runtime is reported without leaking paths or errors. */ }
|
|
522
618
|
return `Namo:\`${NAMO_VERSION}\`\nCodex CLI:${version ? `\`${version}\`` : '暂不可用,检测中或未安装'}`;
|
|
@@ -561,7 +657,8 @@ export class Engine {
|
|
|
561
657
|
this.paused = paused;
|
|
562
658
|
if (this.config.codex) {
|
|
563
659
|
try {
|
|
564
|
-
|
|
660
|
+
const c = { ...this.config, codex: this.config.codex };
|
|
661
|
+
this.versions.get(agentCodexConfig(c, selectAgent(c, 'codex')));
|
|
565
662
|
}
|
|
566
663
|
catch { /* A missing runtime remains visible as unavailable. */ }
|
|
567
664
|
}
|
|
@@ -569,6 +666,7 @@ export class Engine {
|
|
|
569
666
|
this.approvals?.start();
|
|
570
667
|
this.log('recovered', this.store.recover(this.runtime.persistent));
|
|
571
668
|
this.tasks.recover(this.runtime.persistent);
|
|
669
|
+
this.dailyTurns.pruneFinishedReservations();
|
|
572
670
|
this.feedback.recover();
|
|
573
671
|
this.store.db.prepare("UPDATE settings SET value=? WHERE key LIKE 'title-summary:%' AND json_valid(value) AND json_extract(value,'$.state')='running'").run(JSON.stringify({ state: 'failed' }));
|
|
574
672
|
this.artifacts.recover();
|
|
@@ -604,8 +702,7 @@ export class Engine {
|
|
|
604
702
|
const models = this.modelCatalog.models;
|
|
605
703
|
if (!models.length)
|
|
606
704
|
return;
|
|
607
|
-
const
|
|
608
|
-
const reservations = (this.runtime.reservations?.() ?? []).filter(r => !active.has(r.runId));
|
|
705
|
+
const reservations = this.detachedReservations();
|
|
609
706
|
if (this.active.size + reservations.length + (this.memoryRunning ? 1 : 0) + (this.controlRunning ? 1 : 0) >= this.config.concurrency)
|
|
610
707
|
return;
|
|
611
708
|
const row = this.store.db.prepare(`SELECT s.key FROM settings s JOIN tasks t ON s.key='title-summary:'||t.id||':task' OR s.key='title-summary:'||t.id||':result'
|
|
@@ -648,13 +745,9 @@ export class Engine {
|
|
|
648
745
|
return;
|
|
649
746
|
}
|
|
650
747
|
const allowed = this.store.transaction(() => {
|
|
651
|
-
const
|
|
652
|
-
if (
|
|
653
|
-
|
|
654
|
-
if (!Number.isSafeInteger(used) || used < 0 || used >= limit)
|
|
655
|
-
return false;
|
|
656
|
-
this.store.db.prepare('INSERT INTO settings(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(quota, String(used + 1));
|
|
657
|
-
}
|
|
748
|
+
const charge = this.dailyTurns.charge(this.dailyTurnLimit);
|
|
749
|
+
if (charge.state === 'invalid' || charge.state === 'exhausted')
|
|
750
|
+
return false;
|
|
658
751
|
this.store.db.prepare('UPDATE settings SET value=? WHERE key=?').run(JSON.stringify({ state: 'running', model }), key);
|
|
659
752
|
return true;
|
|
660
753
|
});
|
|
@@ -685,8 +778,7 @@ export class Engine {
|
|
|
685
778
|
WHERE i.state='queued' AND i.taskId IS NULL ORDER BY i.seq LIMIT 1`).get();
|
|
686
779
|
if (!row)
|
|
687
780
|
return;
|
|
688
|
-
const
|
|
689
|
-
const reserved = (this.runtime.reservations?.() ?? []).filter(r => !activeRuns.has(r.runId));
|
|
781
|
+
const reserved = this.detachedReservations();
|
|
690
782
|
if (this.active.size + reserved.length + (this.memoryRunning ? 1 : 0) + (this.titleRunning ? 1 : 0) >= this.config.concurrency) {
|
|
691
783
|
this.memoryAbort?.abort('foreground_control');
|
|
692
784
|
this.titleAbort?.abort('foreground_control');
|
|
@@ -694,20 +786,21 @@ export class Engine {
|
|
|
694
786
|
}
|
|
695
787
|
const message = this.store.get(String(row.key));
|
|
696
788
|
const pending = this.tasks.pending(message).filter(t => t.scopeKey === scopeOf(message) && ['queued', 'running', 'waiting'].includes(t.state));
|
|
697
|
-
|
|
789
|
+
const input = {
|
|
790
|
+
text: message.text,
|
|
791
|
+
now: new Date().toISOString(),
|
|
792
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
793
|
+
pending: pending.map(task => {
|
|
794
|
+
const wait = task.state === 'waiting' ? new Waits(this.store).current(task.id) : undefined;
|
|
795
|
+
return { id: task.id, state: task.state, ...(wait ? { question: wait.question, waitId: wait.id } : {}) };
|
|
796
|
+
}),
|
|
797
|
+
};
|
|
798
|
+
const limit = this.dailyTurnLimit;
|
|
799
|
+
const charge = pending.length && limit ? this.store.transaction(() => this.dailyTurns.charge(limit)) : undefined;
|
|
800
|
+
if (!pending.length || charge?.state === 'invalid' || charge?.state === 'exhausted') {
|
|
698
801
|
this.store.transaction(() => { this.store.db.prepare('DELETE FROM settings WHERE key=?').run(`control-classify:${message.key}`); this.route(this.store.get(message.key), true); });
|
|
699
802
|
return;
|
|
700
803
|
}
|
|
701
|
-
const input = { text: message.text, now: new Date().toISOString(), timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, pending: pending.map(t => { const w = t.state === 'waiting' ? new Waits(this.store).current(t.id) : undefined; return { id: t.id, state: t.state, ...(w ? { question: w.question, waitId: w.id } : {}) }; }) };
|
|
702
|
-
const limit = this.config.codex?.dailyTurnLimit ?? (this.config.feishu?.access ? 100 : 0), quota = `daily-turns:${new Date().toISOString().slice(0, 10)}`;
|
|
703
|
-
if (limit > 0) {
|
|
704
|
-
const saved = this.store.db.prepare('SELECT value FROM settings WHERE key=?').get(quota), used = saved ? Number(saved.value) : 0;
|
|
705
|
-
if (!Number.isSafeInteger(used) || used >= limit) {
|
|
706
|
-
this.store.transaction(() => { this.store.db.prepare('DELETE FROM settings WHERE key=?').run(`control-classify:${message.key}`); this.route(this.store.get(message.key), true); });
|
|
707
|
-
return;
|
|
708
|
-
}
|
|
709
|
-
this.store.db.prepare('INSERT INTO settings(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(quota, String(used + 1));
|
|
710
|
-
}
|
|
711
804
|
this.controlAbort = new AbortController();
|
|
712
805
|
this.controlRunning = this.runtime.classifyControl(input, this.controlAbort.signal).then(result => {
|
|
713
806
|
if (this.stopped)
|
|
@@ -911,6 +1004,17 @@ export class Engine {
|
|
|
911
1004
|
return;
|
|
912
1005
|
}
|
|
913
1006
|
const m = { ...source, key: `schedule:${schedule.id}:${schedule.nextAt}`, text: schedule.content, createdAt: now };
|
|
1007
|
+
if (schedule.kind === 'task') {
|
|
1008
|
+
try {
|
|
1009
|
+
this.selectedAgent(m);
|
|
1010
|
+
}
|
|
1011
|
+
catch (error) {
|
|
1012
|
+
if (!(error instanceof AgentRegistryError))
|
|
1013
|
+
throw error;
|
|
1014
|
+
pause('绑定的执行器暂不可用', true);
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
914
1018
|
if (!this.store.enqueue(m))
|
|
915
1019
|
return;
|
|
916
1020
|
if (schedule.kind === 'reminder') {
|
|
@@ -938,45 +1042,37 @@ export class Engine {
|
|
|
938
1042
|
void this.feedback.tick({ waitCards: !!this.config.feishu?.cards, progress: this.config.feishu?.progressUpdates, cadenceMs: this.config.feishu?.progressIntervalMs, heartbeatMs: this.config.feishu?.progressHeartbeatMs }).catch(() => this.fatal('feedback_storage_error'));
|
|
939
1043
|
// Extraction is background work: yield its slot when a user task arrives.
|
|
940
1044
|
if (this.memoryRunning) {
|
|
941
|
-
const
|
|
942
|
-
|
|
943
|
-
const blocked = [...this.active.values(), ...reservations];
|
|
944
|
-
const ready = this.tasks.candidates().some(t => !this.active.has(this.slotKey(t)) && !blocked.some(a => ('task' in a ? this.slotKey(a.task) : a.slotKey ?? a.chatKey) === this.slotKey(t) || ('task' in a ? this.tasks.directories(a.task) : a.paths?.length ? a.paths : [a.cwd]).some(root => this.tasks.directories(t).some(path => pathsOverlap(root, path)))));
|
|
945
|
-
if (ready && this.active.size + reservations.length + 1 >= this.config.concurrency)
|
|
1045
|
+
const reservations = this.detachedReservations();
|
|
1046
|
+
if (this.active.size + reservations.length + 1 >= this.config.concurrency && this.nextRunnableTask(reservations))
|
|
946
1047
|
this.memoryAbort?.abort('foreground_task');
|
|
947
1048
|
}
|
|
948
1049
|
if (this.titleRunning) {
|
|
949
|
-
const
|
|
950
|
-
const reservations = (this.runtime.reservations?.() ?? []).filter(r => !activeIds.has(r.runId));
|
|
1050
|
+
const reservations = this.detachedReservations();
|
|
951
1051
|
if (this.tasks.candidates().length && this.active.size + reservations.length + (this.memoryRunning ? 1 : 0) + (this.controlRunning ? 1 : 0) + 1 >= this.config.concurrency)
|
|
952
1052
|
this.titleAbort?.abort('foreground_task');
|
|
953
1053
|
}
|
|
954
1054
|
this.startControlClassification();
|
|
955
1055
|
for (;;) {
|
|
956
|
-
const
|
|
957
|
-
const reservations = (this.runtime.reservations?.() ?? []).filter(r => !activeRuns.has(r.runId));
|
|
1056
|
+
const reservations = this.detachedReservations();
|
|
958
1057
|
if (this.active.size + reservations.length + (this.memoryRunning ? 1 : 0) + (this.titleRunning ? 1 : 0) + (this.controlRunning || this.runtime.classifyControl && this.config.concurrency > 1 ? 1 : 0) >= this.config.concurrency)
|
|
959
1058
|
break;
|
|
960
1059
|
const claimed = this.store.transaction(() => {
|
|
961
1060
|
if (this.store.db.prepare("SELECT 1 FROM settings WHERE key='maintenance'").get())
|
|
962
1061
|
return;
|
|
963
|
-
const next = this.
|
|
1062
|
+
const next = this.nextRunnableTask(reservations);
|
|
964
1063
|
if (!next)
|
|
965
1064
|
return;
|
|
966
|
-
const limit = this.
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
return;
|
|
974
|
-
}
|
|
975
|
-
this.store.db.prepare('INSERT INTO settings(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key, String(used + 1));
|
|
1065
|
+
const limit = this.dailyTurnLimit;
|
|
1066
|
+
const charge = this.dailyTurns.charge(limit);
|
|
1067
|
+
if (charge.state === 'invalid')
|
|
1068
|
+
throw new Error('daily_turn_count_invalid');
|
|
1069
|
+
if (charge.state === 'exhausted') {
|
|
1070
|
+
this.store.addOutput(next.inboxKey, `quota:${charge.day}`, `今日模型执行次数已达到服务上限(${limit} 次,按 UTC 日期统计)。任务已保留排队,将在下一 UTC 日自动继续;也可取消。`);
|
|
1071
|
+
return;
|
|
976
1072
|
}
|
|
977
1073
|
const run = this.tasks.start(next);
|
|
978
|
-
if (
|
|
979
|
-
this.
|
|
1074
|
+
if (charge.state === 'charged')
|
|
1075
|
+
this.dailyTurns.reserve(run, charge.day);
|
|
980
1076
|
return { next, run };
|
|
981
1077
|
});
|
|
982
1078
|
if (!claimed)
|
|
@@ -984,22 +1080,14 @@ export class Engine {
|
|
|
984
1080
|
const { next, run } = claimed;
|
|
985
1081
|
this.track(next, run);
|
|
986
1082
|
}
|
|
987
|
-
const reserved = this.runtime.reservations?.() ?? [];
|
|
988
|
-
const runs = new Set([...this.active.values()].map(a => a.run));
|
|
989
1083
|
if (!this.configurationDraining && !this.memoryRunning && this.autoMemories?.pending()
|
|
990
|
-
&& this.active.size +
|
|
1084
|
+
&& this.active.size + this.detachedReservations().length + (this.controlRunning ? 1 : 0) + (this.titleRunning ? 1 : 0) < this.config.concurrency
|
|
991
1085
|
&& !this.store.db.prepare("SELECT 1 FROM settings WHERE key='maintenance'").get()) {
|
|
992
1086
|
const allowed = this.store.transaction(() => {
|
|
993
|
-
const
|
|
994
|
-
if (
|
|
995
|
-
return true;
|
|
996
|
-
const key = `daily-turns:${new Date().toISOString().slice(0, 10)}`, row = this.store.db.prepare('SELECT value FROM settings WHERE key=?').get(key), used = row ? Number(row.value) : 0;
|
|
997
|
-
if (!Number.isSafeInteger(used) || used < 0)
|
|
1087
|
+
const charge = this.dailyTurns.charge(this.dailyTurnLimit);
|
|
1088
|
+
if (charge.state === 'invalid')
|
|
998
1089
|
throw new Error('daily_turn_count_invalid');
|
|
999
|
-
|
|
1000
|
-
return false;
|
|
1001
|
-
this.store.db.prepare('INSERT INTO settings(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key, String(used + 1));
|
|
1002
|
-
return true;
|
|
1090
|
+
return charge.state !== 'exhausted';
|
|
1003
1091
|
});
|
|
1004
1092
|
if (allowed) {
|
|
1005
1093
|
this.memoryAbort = new AbortController();
|
|
@@ -1029,7 +1117,7 @@ export class Engine {
|
|
|
1029
1117
|
const promise = Promise.resolve().then(() => this.execute(task, run, abort.signal))
|
|
1030
1118
|
.catch(() => this.fatal('execution_storage_error'))
|
|
1031
1119
|
.finally(() => { this.active.delete(slotKey); void this.pump(); });
|
|
1032
|
-
this.active.set(slotKey, { key: task.inboxKey, task, run,
|
|
1120
|
+
this.active.set(slotKey, { key: task.inboxKey, task, run, abort, promise });
|
|
1033
1121
|
}
|
|
1034
1122
|
async execute(task, run, signal) {
|
|
1035
1123
|
const m = this.store.get(task.inboxKey);
|
|
@@ -1088,7 +1176,7 @@ export class Engine {
|
|
|
1088
1176
|
onSchedule: (args, callId) => new Schedules(this.store).tool(m, args, callId, () => this.workspace(m, task)),
|
|
1089
1177
|
onActivity: phase => recordActivity(this.store, run, phase),
|
|
1090
1178
|
onProgress: event => recordProgress(this.store, run, event, this.redact),
|
|
1091
|
-
onThread: threadId => { if (!new Waits(this.store).resume(task))
|
|
1179
|
+
onThread: threadId => { if (this.tasks.selection(task.id)?.adapter !== 'claude' && !new Waits(this.store).resume(task))
|
|
1092
1180
|
this.store.db.prepare('INSERT OR IGNORE INTO settings(key,value) VALUES(?,?)').run(`control-tools-v4-thread:${threadId}`, '1'); this.store.saveThread(this.tasks.sessionKey(task), threadId); this.store.saveRun(m.key, threadId); this.tasks.saveRun(run, threadId); },
|
|
1093
1181
|
onTurn: turnId => { const threadId = this.store.thread(this.tasks.sessionKey(task)); if (threadId) {
|
|
1094
1182
|
this.store.saveRun(m.key, threadId, turnId);
|
|
@@ -1121,6 +1209,7 @@ export class Engine {
|
|
|
1121
1209
|
if (this.runtime.summarizeTitle && this.config.feishu?.cards && this.tasks.get(task.id)?.state === 'succeeded')
|
|
1122
1210
|
enqueueTitle(this.store, task.id, 'result');
|
|
1123
1211
|
}
|
|
1212
|
+
this.dailyTurns.clearReservation(run);
|
|
1124
1213
|
const finished = this.tasks.get(task.id);
|
|
1125
1214
|
for (const image of result.generatedImages ?? []) {
|
|
1126
1215
|
try {
|
|
@@ -1145,13 +1234,7 @@ export class Engine {
|
|
|
1145
1234
|
this.store.transaction(() => {
|
|
1146
1235
|
const inbox = this.store.get(task.inboxKey);
|
|
1147
1236
|
if (!runnerJob(this.store, run) && inbox?.state === 'running' && !inbox.cancelRequested) {
|
|
1148
|
-
|
|
1149
|
-
if (reservation && /^\d{4}-\d{2}-\d{2}$/.test(String(reservation.value))) {
|
|
1150
|
-
const counter = `daily-turns:${String(reservation.value)}`, row = this.store.db.prepare('SELECT value FROM settings WHERE key=?').get(counter), used = Number(row?.value);
|
|
1151
|
-
if (Number.isSafeInteger(used) && used > 0)
|
|
1152
|
-
this.store.db.prepare('UPDATE settings SET value=? WHERE key=?').run(String(used - 1), counter);
|
|
1153
|
-
this.store.db.prepare('DELETE FROM settings WHERE key=?').run(`daily-turn-run:${run}`);
|
|
1154
|
-
}
|
|
1237
|
+
this.dailyTurns.refundUndispatched(run);
|
|
1155
1238
|
this.store.db.prepare("UPDATE task_runs SET state='not_started',error='receiver_detached_before_dispatch',finishedAt=? WHERE id=? AND state='running'").run(Date.now(), run);
|
|
1156
1239
|
this.store.db.prepare("UPDATE tasks SET state='queued',startedAt=NULL,error=NULL WHERE id=? AND state='running'").run(task.id);
|
|
1157
1240
|
this.store.db.prepare("UPDATE inbox SET state='queued',error=NULL WHERE key=? AND state='running'").run(task.inboxKey);
|
|
@@ -1162,15 +1245,17 @@ export class Engine {
|
|
|
1162
1245
|
if (this.runtime.persistent && e instanceof RuntimeError && ['runner_observer_error', 'runner_record_missing'].includes(e.code))
|
|
1163
1246
|
throw e;
|
|
1164
1247
|
const code = signal.aborted && !this.runtime.persistent ? 'cancelled' : e instanceof RuntimeError ? e.code : 'runtime_error';
|
|
1248
|
+
const agent = this.tasks.selection(task.id)?.adapter === 'claude' ? 'Claude Code' : 'Codex';
|
|
1165
1249
|
const text = code === 'cancelled' ? '这条请求已停止。已发生的操作不会自动撤销。'
|
|
1166
1250
|
: code === 'runner_lost' ? '独立执行进程失联,结果未确认,没有自动重跑。可能仍有子进程或外部操作;并发名额与目录占位保留。请在本机核对进程和操作后,通过异常核对入口解除占位。'
|
|
1167
1251
|
: code === 'turn_timeout' ? '这条请求超时,执行器已停止。执行结果未确认,没有自动重跑。'
|
|
1168
|
-
: `这条请求未完成(${code}
|
|
1252
|
+
: `这条请求未完成(${code})。请在本机工作台检查 ${agent} 连接与任务状态。没有自动重跑。`;
|
|
1169
1253
|
await this.active.get(this.slotKey(task))?.steering;
|
|
1170
1254
|
this.store.transaction(() => {
|
|
1171
1255
|
evidence?.finish(false);
|
|
1172
1256
|
const report = evidence?.report ?? readEvidence(this.store, task.id).find(r => r.runId === run);
|
|
1173
1257
|
this.tasks.finish(task, run, text + (report ? evidenceBrief(report) : ''), code);
|
|
1258
|
+
this.dailyTurns.clearReservation(run);
|
|
1174
1259
|
});
|
|
1175
1260
|
this.log('turn_failed', { messageId: m.messageId, code });
|
|
1176
1261
|
}
|
|
@@ -1242,9 +1327,9 @@ export class Engine {
|
|
|
1242
1327
|
this.store.transaction(() => {
|
|
1243
1328
|
const selection = this.selectedAgent(m, ref), f = this.config.feishu;
|
|
1244
1329
|
let preference = f?.appId && f.domain ? userModel(this.store, { channel: f.domain, appId: f.appId, userId: m.senderId }) : '';
|
|
1245
|
-
if (m.envelope?.chatType === 'group' || f?.access && !(this.config.codex?.allowedModels ?? []).includes(preference))
|
|
1330
|
+
if (selection?.adapter === 'claude' || m.envelope?.chatType === 'group' || f?.access && !(this.config.codex?.allowedModels ?? []).includes(preference))
|
|
1246
1331
|
preference = '';
|
|
1247
|
-
const configured = this.config.codex && selection ?
|
|
1332
|
+
const configured = this.config.codex && selection ? resolveAgent({ ...this.config, codex: this.config.codex }, selection).model : this.config.codex?.model;
|
|
1248
1333
|
const task = this.tasks.create(m, workspace, ref, selection, preference || configured || null);
|
|
1249
1334
|
if (this.runtime.summarizeTitle && this.config.feishu?.cards)
|
|
1250
1335
|
enqueueTitle(this.store, task.id, 'task');
|
|
@@ -1265,6 +1350,10 @@ export class Engine {
|
|
|
1265
1350
|
this.reply(m, e.message);
|
|
1266
1351
|
return;
|
|
1267
1352
|
}
|
|
1353
|
+
if (e instanceof AgentRegistryError || e instanceof RuntimeError && e.code.startsWith('agent_')) {
|
|
1354
|
+
this.reply(m, '当前执行器不可用。请发送 /agent 切换,或在本机工作台检查配置。');
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1268
1357
|
if (!(e instanceof RuntimeError))
|
|
1269
1358
|
throw e;
|
|
1270
1359
|
this.reply(m, `工作目录不可用(${e.code}),尚未执行。请检查目录配置。`);
|