@dofy/namo 0.6.2 → 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.
Files changed (67) hide show
  1. package/README.md +8 -4
  2. package/README.zh-CN.md +8 -4
  3. package/dist/scripts/smoke-skills.js +2 -4
  4. package/dist/scripts/smoke-skills.js.map +1 -1
  5. package/dist/src/agent-registry.js +46 -9
  6. package/dist/src/agent-registry.js.map +1 -1
  7. package/dist/src/agents.js +60 -8
  8. package/dist/src/agents.js.map +1 -1
  9. package/dist/src/auto-memory.js +1 -1
  10. package/dist/src/cards.js +1 -1
  11. package/dist/src/cards.js.map +1 -1
  12. package/dist/src/claude-runtime.js +331 -0
  13. package/dist/src/claude-runtime.js.map +1 -0
  14. package/dist/src/cli.js +5 -4
  15. package/dist/src/cli.js.map +1 -1
  16. package/dist/src/codex-connection.js +10 -1
  17. package/dist/src/codex-connection.js.map +1 -1
  18. package/dist/src/daily-turns.js +56 -0
  19. package/dist/src/daily-turns.js.map +1 -0
  20. package/dist/src/doctor.js +3 -3
  21. package/dist/src/doctor.js.map +1 -1
  22. package/dist/src/engine.js +164 -75
  23. package/dist/src/engine.js.map +1 -1
  24. package/dist/src/external-wait-bridge.js +1 -3
  25. package/dist/src/external-wait-bridge.js.map +1 -1
  26. package/dist/src/external-waits.js +13 -12
  27. package/dist/src/external-waits.js.map +1 -1
  28. package/dist/src/feedback.js +27 -11
  29. package/dist/src/feedback.js.map +1 -1
  30. package/dist/src/image-inputs.js +1 -0
  31. package/dist/src/image-inputs.js.map +1 -1
  32. package/dist/src/live-upgrade.js +1 -1
  33. package/dist/src/live-upgrade.js.map +1 -1
  34. package/dist/src/locales/en.js +61 -20
  35. package/dist/src/locales/en.js.map +1 -1
  36. package/dist/src/locales/zh-CN.js +61 -20
  37. package/dist/src/locales/zh-CN.js.map +1 -1
  38. package/dist/src/management.js +84 -16
  39. package/dist/src/management.js.map +1 -1
  40. package/dist/src/memory-extractor.js +2 -2
  41. package/dist/src/memory-extractor.js.map +1 -1
  42. package/dist/src/onboarding.js +28 -10
  43. package/dist/src/onboarding.js.map +1 -1
  44. package/dist/src/prompts.js +1 -1
  45. package/dist/src/prompts.js.map +1 -1
  46. package/dist/src/runner-worker.js +5 -6
  47. package/dist/src/runner-worker.js.map +1 -1
  48. package/dist/src/runner.js +11 -1
  49. package/dist/src/runner.js.map +1 -1
  50. package/dist/src/runtime-config.js +5 -1
  51. package/dist/src/runtime-config.js.map +1 -1
  52. package/dist/src/runtime.js +1 -1
  53. package/dist/src/tasks.js +35 -3
  54. package/dist/src/tasks.js.map +1 -1
  55. package/dist/src/ui.js +1 -1
  56. package/dist/src/ui.js.map +1 -1
  57. package/dist/ui/assets/index-CcbYEcXS.js +133 -0
  58. package/dist/ui/assets/{index-CJAhDqDy.css → index-Cks2QULV.css} +1 -1
  59. package/dist/ui/index.html +2 -2
  60. package/docs/architecture.md +12 -11
  61. package/docs/operations.md +15 -3
  62. package/docs/release-notes.md +20 -0
  63. package/docs/technical-guide-zh-cn.md +7 -7
  64. package/docs/technical-guide.md +7 -7
  65. package/docs-site/content.js +6 -6
  66. package/package.json +2 -2
  67. package/dist/ui/assets/index-if-v2JVj.js +0 -131
@@ -0,0 +1,56 @@
1
+ const reservationPrefix = 'daily-turn-run:';
2
+ export function dailyTurnDay() {
3
+ return new Date().toISOString().slice(0, 10);
4
+ }
5
+ export class DailyTurns {
6
+ store;
7
+ constructor(store) {
8
+ this.store = store;
9
+ }
10
+ used(day) {
11
+ const row = this.store.db.prepare('SELECT value FROM settings WHERE key=?').get(`daily-turns:${day}`);
12
+ return row ? Number(row.value) : 0;
13
+ }
14
+ /** The caller wraps this in the transaction that admits the model turn. */
15
+ charge(limit) {
16
+ if (!limit)
17
+ return { state: 'unlimited' };
18
+ const day = dailyTurnDay();
19
+ const used = this.used(day);
20
+ if (!Number.isSafeInteger(used) || used < 0)
21
+ return { state: 'invalid', day };
22
+ if (used >= limit)
23
+ return { state: 'exhausted', day };
24
+ this.setUsed(day, used + 1);
25
+ return { state: 'charged', day };
26
+ }
27
+ setUsed(day, used) {
28
+ this.store.db.prepare('INSERT INTO settings(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value')
29
+ .run(`daily-turns:${day}`, String(used));
30
+ }
31
+ reserve(run, day) {
32
+ this.store.db.prepare('INSERT INTO settings(key,value) VALUES(?,?)').run(reservationPrefix + run, day);
33
+ }
34
+ clearReservation(run) {
35
+ this.store.db.prepare('DELETE FROM settings WHERE key=?').run(reservationPrefix + run);
36
+ }
37
+ /** After task recovery, only a running task can still need its original charge. */
38
+ pruneFinishedReservations() {
39
+ this.store.db.prepare(`DELETE FROM settings WHERE key GLOB ? AND NOT EXISTS (
40
+ SELECT 1 FROM task_runs WHERE id=substr(settings.key, ?) AND state='running'
41
+ )`).run(`${reservationPrefix}*`, reservationPrefix.length + 1);
42
+ }
43
+ /** Only the caller that proves the run never reached the model may refund it. */
44
+ refundUndispatched(run) {
45
+ const key = reservationPrefix + run;
46
+ const row = this.store.db.prepare('SELECT value FROM settings WHERE key=?').get(key);
47
+ const day = row?.value;
48
+ if (typeof day !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(day))
49
+ return;
50
+ const used = this.used(day);
51
+ if (Number.isSafeInteger(used) && used > 0)
52
+ this.setUsed(day, used - 1);
53
+ this.clearReservation(run);
54
+ }
55
+ }
56
+ //# sourceMappingURL=daily-turns.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"daily-turns.js","sourceRoot":"","sources":["../../src/daily-turns.ts"],"names":[],"mappings":"AAEA,MAAM,iBAAiB,GAAG,iBAAiB,CAAC;AAI5C,MAAM,UAAU,YAAY;IAC1B,OAAO,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAC/C,CAAC;AAED,MAAM,OAAO,UAAU;IACQ,KAAK;IAAlC,YAA6B,KAAY;qBAAZ,KAAK;IA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CAAC,CAAC;IACzG,CAAC;IAED,gBAAgB,CAAC,GAAW;QAC1B,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,kCAAkC,CAAC,CAAC,GAAG,CAAC,iBAAiB,GAAG,GAAG,CAAC,CAAC;IACzF,CAAC;IAED,mFAAmF;IACnF,yBAAyB;QACvB,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC;;MAEpB,CAAC,CAAC,GAAG,CAAC,GAAG,iBAAiB,GAAG,EAAE,iBAAiB,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACjE,CAAC;IAED,iFAAiF;IACjF,kBAAkB,CAAC,GAAW;QAC5B,MAAM,GAAG,GAAG,iBAAiB,GAAG,GAAG,CAAC;QACpC,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,wCAAwC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACrF,MAAM,GAAG,GAAG,GAAG,EAAE,KAAK,CAAC;QACvB,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,GAAG,CAAC;YAAE,OAAO;QACxE,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC5B,IAAI,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,IAAI,GAAG,CAAC;YAAE,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,IAAI,GAAG,CAAC,CAAC,CAAC;QACxE,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;CACF"}
@@ -4,7 +4,7 @@ import { loadConfig } from './config.js';
4
4
  import { probeAgent, liveAgentTest } from './agents.js';
5
5
  import { FeishuSetupConnection } from './feishu-setup.js';
6
6
  import { serviceStatus } from './service.js';
7
- export async function doctor(file, live = false) {
7
+ export async function doctor(file, live = false, profile) {
8
8
  const checks = [{ id: 'node', status: 'ok', message: `Node ${process.version}` }];
9
9
  if (!existsSync(file))
10
10
  return [...checks, { id: 'config', status: 'fail', message: tr("doctor.noConfiguration", file), next: tr("doctor.runNamoInitUseConfigSelectExisting") }];
@@ -16,7 +16,7 @@ export async function doctor(file, live = false) {
16
16
  return [...checks, { id: 'config', status: 'fail', message: tr("doctor.configurationInvalidUnreadableReferencesMissingDirectoryDirectory"), next: tr("doctor.runNamoInitFixSettingsConfigurationContents") }];
17
17
  }
18
18
  checks.push({ id: 'config', status: 'ok', message: tr("doctor.configuration", c.file) });
19
- checks.push(...await probeAgent(c));
19
+ checks.push(...await probeAgent(c, profile));
20
20
  const connection = new FeishuSetupConnection(c.feishu);
21
21
  try {
22
22
  const valid = !!c.feishu.appId && !!c.feishu.appSecret && await connection.credentials();
@@ -46,7 +46,7 @@ export async function doctor(file, live = false) {
46
46
  checks.push({ id: 'agent.inference', status: 'fail', message: tr("doctor.agentPrerequisitesFailedModelWasNotCalled") });
47
47
  else {
48
48
  try {
49
- const matched = await liveAgentTest(c);
49
+ const matched = await liveAgentTest(c, profile);
50
50
  checks.push({ id: 'agent.inference', status: matched ? 'ok' : 'fail', message: tr(matched ? 'doctor.replyVerified' : 'doctor.replyMismatch') });
51
51
  }
52
52
  catch {
@@ -1 +1 @@
1
- {"version":3,"file":"doctor.js","sourceRoot":"","sources":["../../src/doctor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,IAAI,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAc,MAAM,aAAa,CAAC;AACpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,IAAY,EAAE,I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QACT,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC;YAAE,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,kDAAkD,CAAC,EAAE,CAAC,CAAC;aAC3L,CAAC;YACJ,IAAI,CAAC;gBACH,MAAM,OAAO,GAAG,MAAM,aAAa,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;gBAChD,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,iBAAiB,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAC,CAAC,sBAAsB,CAAC,EAAE,CAAC,CAAC;YAClJ,CAAC;YACD,MAAM,CAAC;gBAAC,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,6CAA6C,CAAC,EAAE,CAAC,CAAC;YAAC,CAAC;QAC/H,CAAC;IACH,CAAC;;QAAM,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,2CAA2C,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,iDAAiD,CAAC,EAAE,CAAC,CAAC;IACrL,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -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
- return selected && selected.profileId !== 'codex' ? selected : selectAgent(c, bound ? 'codex' : undefined);
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
- version = this.versions.get(agentCodexConfig({ ...this.config, codex: c }, this.selectedAgent(m)));
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
- this.versions.get(agentCodexConfig({ ...this.config, codex: this.config.codex }));
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 active = new Set([...this.active.values()].map(a => a.run));
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 limit = this.config.codex?.dailyTurnLimit ?? (this.config.feishu?.access ? 100 : 0);
652
- if (limit) {
653
- const quota = `daily-turns:${new Date().toISOString().slice(0, 10)}`, saved = this.store.db.prepare('SELECT value FROM settings WHERE key=?').get(quota), used = saved ? Number(saved.value) : 0;
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 activeRuns = new Set([...this.active.values()].map(a => a.run));
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
- if (!pending.length) {
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 activeIds = new Set([...this.active.values()].map(a => a.run));
942
- const reservations = (this.runtime.reservations?.() ?? []).filter(r => !activeIds.has(r.runId));
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 activeIds = new Set([...this.active.values()].map(a => a.run));
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 activeRuns = new Set([...this.active.values()].map(a => a.run));
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.tasks.candidates().find(t => !this.active.has(this.slotKey(t)) && ![...this.active.values(), ...reservations].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)))));
1062
+ const next = this.nextRunnableTask(reservations);
964
1063
  if (!next)
965
1064
  return;
966
- const limit = this.config.codex?.dailyTurnLimit ?? (this.config.feishu?.access ? 100 : 0), day = new Date().toISOString().slice(0, 10), key = `daily-turns:${day}`;
967
- if (limit > 0) {
968
- const row = this.store.db.prepare('SELECT value FROM settings WHERE key=?').get(key), used = row ? Number(row.value) : 0;
969
- if (!Number.isSafeInteger(used) || used < 0)
970
- throw new Error('daily_turn_count_invalid');
971
- if (used >= limit) {
972
- this.store.addOutput(next.inboxKey, `quota:${day}`, `今日模型执行次数已达到服务上限(${limit} 次,按 UTC 日期统计)。任务已保留排队,将在下一 UTC 日自动继续;也可取消。`);
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 (limit > 0)
979
- this.store.db.prepare('INSERT INTO settings(key,value) VALUES(?,?)').run(`daily-turn-run:${run}`, day);
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 + reserved.filter(r => !runs.has(r.runId)).length + (this.controlRunning ? 1 : 0) + (this.titleRunning ? 1 : 0) < this.config.concurrency
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 limit = this.config.codex?.dailyTurnLimit ?? (this.config.feishu?.access ? 100 : 0);
994
- if (!limit)
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
- if (used >= limit)
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, cwd: task.cwd, abort, promise });
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
- const reservation = this.store.db.prepare('SELECT value FROM settings WHERE key=?').get(`daily-turn-run:${run}`);
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})。请检查本地 Codex 登录与服务状态;为避免重复操作,没有自动重跑。`;
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 ? agentCodexConfig({ ...this.config, codex: this.config.codex }, selection).model : this.config.codex?.model;
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}),尚未执行。请检查目录配置。`);