@ai-agent-forge/plugin-task-manager 0.88.29 → 0.89.0

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/index.js CHANGED
@@ -13,7 +13,7 @@
13
13
  import { createHash } from "node:crypto";
14
14
  import { existsSync, readFileSync, statSync } from "node:fs";
15
15
  import { isAbsolute, resolve } from "node:path";
16
- import { AGENT_TASK_CHILD_PROFILE_KEY, AGENT_TASK_PARENT_SESSION_KEY, AGENT_TASK_SCHEDULER_CAPABILITY_ID, AGENT_TASK_SCHEDULER_CAPABILITY_VERSION, } from "@agent-forge/plugin-sdk";
16
+ import { AGENT_TASK_CHILD_PROFILE_KEY, AGENT_TASK_PARENT_SESSION_KEY, AGENT_TASK_SCHEDULER_CAPABILITY_ID, AGENT_TASK_SCHEDULER_CAPABILITY_VERSION, WORK_ITEM_SETTLEMENT_CAPABILITY_ID, WORK_ITEM_SETTLEMENT_CAPABILITY_VERSION, } from "@agent-forge/plugin-sdk";
17
17
  import { INTENT_CANCEL_ENTRY_TYPE, LEDGER_ENTRY_TYPE, LedgerError, newOpId, newWorkItemId, replayLedger, validateApply, } from "./ledger.js";
18
18
  /** §6.3 v1 冻结值:默认单次 attempt 租期 60 分钟。 */
19
19
  const DEFAULT_LEASE_MS = 60 * 60_000;
@@ -81,11 +81,23 @@ export function createTaskManagerCapability(api) {
81
81
  .catch(() => { });
82
82
  }
83
83
  : undefined,
84
- // scheduler 不注入:延迟到首次 dispatch 经 capability 目录解析(装配顺序
84
+ // scheduler 不注入:每次 dispatch 经 capability 目录解析(装配顺序
85
85
  // 无关;宿主没有 subagent-delegate 时账本工具仍可用,派发结构化拒绝)。
86
86
  now: () => new Date(),
87
87
  });
88
88
  const registrations = [];
89
+ registrations.push(api.capabilities.provide({ id: WORK_ITEM_SETTLEMENT_CAPABILITY_ID, version: WORK_ITEM_SETTLEMENT_CAPABILITY_VERSION, kind: "service" }, async (input) => {
90
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
91
+ throw new TypeError("work-item-settlement request must be an object");
92
+ }
93
+ const request = input;
94
+ if (request.action === "list")
95
+ return [...manager.view().items.values()].map(settlementProjection);
96
+ if (request.action === "poll" && typeof request.workItemId === "string") {
97
+ return settlementProjection(await manager.poll({ workItemId: request.workItemId }));
98
+ }
99
+ throw new TypeError("work-item-settlement request must be list or poll with a workItemId");
100
+ }));
89
101
  registrations.push(api.registerTool(manager.toolDefinition()));
90
102
  // §6.1:TUI 可由同一插件提供一个 `/tasks` 命令,不新增默认快捷键(单入口规则)。
91
103
  // 只读渲染账本投影;交互控制仍走 `assistant_task` 工具动作。
@@ -111,6 +123,21 @@ export function createTaskManagerCapability(api) {
111
123
  }
112
124
  return registrations;
113
125
  }
126
+ function settlementProjection(item) {
127
+ return {
128
+ workItemId: item.workItemId,
129
+ title: item.title,
130
+ status: item.status,
131
+ recordRevision: item.recordRevision,
132
+ createdAt: item.createdAt,
133
+ updatedAt: item.updatedAt,
134
+ ...(item.note === undefined ? {} : { note: item.note }),
135
+ ...(item.lastError === undefined ? {} : { lastError: item.lastError }),
136
+ ...(item.dispatch === undefined
137
+ ? {}
138
+ : { dispatch: item.dispatch.dispatchedAt === undefined ? {} : { dispatchedAt: item.dispatch.dispatchedAt } }),
139
+ };
140
+ }
114
141
  /** `/tasks` 文本渲染:每行一个事项(id 短形态 [状态] rN 标题 + 派发事实)。 */
115
142
  export function renderWorkItems(manager) {
116
143
  const view = manager.view();
@@ -152,15 +179,16 @@ export class TaskManager {
152
179
  reviewNotifiedKeys = new Set();
153
180
  /** §12 AC-04 capacity 队列:workItemId → 槽满待复查的原始派发输入(内存;重启后由模型重新派发)。 */
154
181
  pendingDispatch = new Map();
182
+ dispatchSchedulers = new Map();
155
183
  constructor(api, options) {
156
184
  this.api = api;
157
185
  this.options = options;
158
186
  }
159
- /** 调度器解析:装配注入优先;否则经 capability 目录延迟解析(解析失败在 dispatch 时结构化拒绝)。 */
160
- scheduler() {
187
+ /** 装配注入优先;派发时刷新目录句柄,其他操作沿用现有句柄。 */
188
+ scheduler(refresh = false) {
161
189
  if (this.options.scheduler !== undefined)
162
190
  return this.options.scheduler;
163
- if (this.schedulerCache === undefined) {
191
+ if (refresh || this.schedulerCache === undefined) {
164
192
  if (this.api === undefined) {
165
193
  throw new LedgerError("ledger_invalid_transition", "dispatch unavailable: agent-forge.agent-task-scheduler@2 is not present in this host (no scheduler provider loaded)");
166
194
  }
@@ -168,6 +196,16 @@ export class TaskManager {
168
196
  }
169
197
  return this.schedulerCache;
170
198
  }
199
+ schedulerFor(item) {
200
+ const bound = this.dispatchSchedulers.get(item.workItemId);
201
+ if (bound !== undefined && bound.generation === item.dispatch?.generation)
202
+ return bound.scheduler;
203
+ const scheduler = this.scheduler();
204
+ if (item.dispatch !== undefined) {
205
+ this.dispatchSchedulers.set(item.workItemId, { generation: item.dispatch.generation, scheduler });
206
+ }
207
+ return scheduler;
208
+ }
171
209
  now() {
172
210
  return this.options.now?.() ?? new Date();
173
211
  }
@@ -490,13 +528,18 @@ export class TaskManager {
490
528
  ...(dependsOn === undefined ? {} : { dependsOn }),
491
529
  },
492
530
  });
493
- return this.replay(workItemId);
531
+ const updated = this.replay(workItemId);
532
+ const pending = this.pendingDispatch.get(workItemId);
533
+ if (pending !== undefined && pending.requirementsRevision !== updated.requirementsRevision) {
534
+ this.pendingDispatch.delete(workItemId);
535
+ }
536
+ return updated;
494
537
  }
495
538
  /**
496
539
  * 派发负责人(草案 §5.3):requestId 绑定要求版本,调度器幂等吸收同版本重放;
497
540
  * dispatchScope(owner/workItem)随 metadata 过线,后代沿用。
498
541
  */
499
- async dispatch(input) {
542
+ async dispatch(input, pendingScheduler) {
500
543
  const workItemId = this.workItemId(input);
501
544
  const expected = requiredRevision(input.expectedRecordRevision);
502
545
  const item = this.replay(workItemId);
@@ -559,19 +602,25 @@ export class TaskManager {
559
602
  // 账本据此绑定原 attempt;同键异内容则由调度器结构化冲突显式拒绝——attempt
560
603
  // 身份与内容一致性归调度器,账本不提前判收(复审裁决 2026-11-15)。
561
604
  let response;
605
+ let scheduler;
562
606
  try {
563
- response = await this.scheduler().call(request);
607
+ const pending = this.pendingDispatch.get(workItemId);
608
+ scheduler =
609
+ pendingScheduler ??
610
+ (pending?.requirementsRevision === item.requirementsRevision ? pending.scheduler : undefined) ??
611
+ this.scheduler(true);
612
+ response = await scheduler.call(request);
564
613
  }
565
614
  catch (error) {
566
615
  const message = error instanceof Error ? error.message : String(error);
567
616
  // §12 AC-04:槽满不静默丢弃——事项带 capacity-wait 备注留在队列,poll
568
617
  // 自动复查重派(同一 requestId 幂等安全:失败提交没有受理回执)。
569
- if (/queue depth|queue full|capacity/i.test(message)) {
618
+ if (scheduler !== undefined && /queue depth|queue full|capacity/i.test(message)) {
570
619
  this.append(workItemId, "note", {
571
620
  kind: "note",
572
621
  control: { expectedRecordRevision: item.recordRevision, reason: `capacity-wait: ${message}` },
573
622
  });
574
- this.pendingDispatch.set(workItemId, { input, requirementsRevision: item.requirementsRevision });
623
+ this.pendingDispatch.set(workItemId, { input, requirementsRevision: item.requirementsRevision, scheduler });
575
624
  return this.replay(workItemId);
576
625
  }
577
626
  throw new LedgerError("ledger_invalid_transition", `scheduler submit failed: ${message}`);
@@ -597,6 +646,8 @@ export class TaskManager {
597
646
  },
598
647
  },
599
648
  });
649
+ this.pendingDispatch.delete(workItemId);
650
+ this.dispatchSchedulers.set(workItemId, { generation: item.executionGeneration + 1, scheduler: scheduler });
600
651
  return this.replay(workItemId);
601
652
  }
602
653
  /**
@@ -613,6 +664,7 @@ export class TaskManager {
613
664
  this.maybeNotifyReviewPoint(item);
614
665
  if (item.dispatch === undefined) {
615
666
  this.healthStates.delete(workItemId);
667
+ this.dispatchSchedulers.delete(workItemId);
616
668
  // §12 AC-04 capacity 队列复查:槽满的事项在下一轮 poll 自动重派。
617
669
  await this.retryCapacityWait(workItemId, item);
618
670
  return this.replay(workItemId);
@@ -635,9 +687,9 @@ export class TaskManager {
635
687
  while (item.status === "running" &&
636
688
  item.dispatch !== undefined &&
637
689
  this.now().getTime() >= effectiveDeadline(item.dispatch)) {
638
- const settled = await this.peekSettled(item.dispatch.taskId);
690
+ const settled = await this.peekSettled(item, item.dispatch.taskId);
639
691
  if (settled !== undefined) {
640
- item = await this.settleDispatch(workItemId, settled.taskId, settled.outcome, settled.sessionId);
692
+ item = await this.settleDispatch(item, settled.taskId, settled.outcome, settled.sessionId);
641
693
  break;
642
694
  }
643
695
  const deadlineExceeded = `deadline_exceeded at ${new Date(effectiveDeadline(item.dispatch)).toISOString()}`;
@@ -653,6 +705,7 @@ export class TaskManager {
653
705
  const reread = this.replay(workItemId);
654
706
  if (reread.status === "running" &&
655
707
  reread.dispatch !== undefined &&
708
+ reread.dispatch.generation === item.dispatch.generation &&
656
709
  this.now().getTime() >= reread.dispatch.expiresAt) {
657
710
  item = reread;
658
711
  continue;
@@ -661,20 +714,21 @@ export class TaskManager {
661
714
  }
662
715
  throw error;
663
716
  }
664
- await this.scheduler().call({
717
+ const scheduler = this.schedulerFor(item);
718
+ await scheduler.call({
665
719
  version: 2,
666
720
  action: "cancel",
667
721
  taskId: item.dispatch.taskId,
668
722
  reason: deadlineExceeded,
669
723
  });
670
- item = await this.confirmStop(workItemId, item.dispatch.taskId);
724
+ item = await this.confirmStop(item, scheduler);
671
725
  break;
672
726
  }
673
727
  if (item.dispatch === undefined)
674
728
  return item;
675
729
  let response;
676
730
  try {
677
- response = await this.scheduler().call({ version: 2, action: "peek", taskId: item.dispatch.taskId });
731
+ response = await this.schedulerFor(item).call({ version: 2, action: "peek", taskId: item.dispatch.taskId });
678
732
  }
679
733
  catch {
680
734
  return item; // 调度器故障时保守返回当前投影,不伪造结果。
@@ -687,7 +741,7 @@ export class TaskManager {
687
741
  if (outcome !== "succeeded" && outcome !== "failed" && outcome !== "cancelled" && outcome !== "timed_out") {
688
742
  return item; // unknown/意外词汇:不写账本,保守返回当前投影。
689
743
  }
690
- return this.settleDispatch(workItemId, item.dispatch.taskId, outcome);
744
+ return this.settleDispatch(item, item.dispatch.taskId, outcome);
691
745
  }
692
746
  /** 验收(AC-16):CAS + 逐条 AC + 证据齐备。 */
693
747
  accept(input) {
@@ -793,12 +847,14 @@ export class TaskManager {
793
847
  ...(typeof input.reason === "string" ? { reason: input.reason } : {}),
794
848
  },
795
849
  });
850
+ if (op === "cancel" || op === "fence")
851
+ this.pendingDispatch.delete(workItemId);
796
852
  return this.replay(workItemId);
797
853
  }
798
854
  /** peek 查询:settled 时返回终态词汇;在途/未知返回 undefined。 */
799
- async peekSettled(taskId) {
855
+ async peekSettled(item, taskId, scheduler) {
800
856
  try {
801
- const response = await this.scheduler().call({ version: 2, action: "peek", taskId });
857
+ const response = await (scheduler ?? this.schedulerFor(item)).call({ version: 2, action: "peek", taskId });
802
858
  if (!isPeekEnvelope(response) || !response.settled)
803
859
  return undefined;
804
860
  const outcome = response.status;
@@ -815,13 +871,16 @@ export class TaskManager {
815
871
  * 都回读 result——成功取报告/会话,失败取结构化错误码(`subagent_runner_lost`
816
872
  * 是 health:exited 落账的依据,§5.2 记录维度分离)。
817
873
  */
818
- async settleDispatch(workItemId, taskId, outcome, sessionId) {
874
+ async settleDispatch(attempt, taskId, outcome, sessionId) {
875
+ const workItemId = attempt.workItemId;
819
876
  const item = this.replay(workItemId);
877
+ if (item.dispatch?.generation !== attempt.dispatch?.generation || item.dispatch?.taskId !== taskId)
878
+ return item;
820
879
  let report;
821
880
  let error;
822
881
  let errorCode;
823
882
  if (item.fence === undefined) {
824
- const resultEnvelope = await this.scheduler().call({ version: 2, action: "result", taskId });
883
+ const resultEnvelope = await this.schedulerFor(item).call({ version: 2, action: "result", taskId });
825
884
  const result = extractResult(resultEnvelope);
826
885
  if (result !== undefined) {
827
886
  sessionId = result.sessionId ?? sessionId;
@@ -862,6 +921,7 @@ export class TaskManager {
862
921
  this.lastSemanticProgressAt.set(workItemId, this.now().getTime());
863
922
  this.stalledNotified.delete(workItemId);
864
923
  this.healthStates.delete(workItemId); // 派发已终态:probe 健康判定随之结束。
924
+ this.dispatchSchedulers.delete(workItemId);
865
925
  return this.replay(workItemId);
866
926
  }
867
927
  /**
@@ -869,12 +929,17 @@ export class TaskManager {
869
929
  * 收敛 cancelled;无法证停保持 stopping(blocked 语义的账本层,草案 §8.2 40 秒
870
930
  * 等待与升级终止由宿主 runner 协议承担,账本只记事实)。
871
931
  */
872
- async confirmStop(workItemId, taskId) {
873
- const settled = await this.peekSettled(taskId);
932
+ async confirmStop(attempt, scheduler) {
933
+ const item = this.replay(attempt.workItemId);
934
+ if (item.dispatch?.generation !== attempt.dispatch?.generation ||
935
+ item.dispatch?.taskId !== attempt.dispatch?.taskId)
936
+ return item;
937
+ const taskId = attempt.dispatch.taskId;
938
+ const settled = await this.peekSettled(attempt, taskId, scheduler);
874
939
  if (settled !== undefined && settled.outcome === "cancelled") {
875
- return this.settleDispatch(workItemId, taskId, "cancelled", settled.sessionId);
940
+ return this.settleDispatch(attempt, taskId, "cancelled", settled.sessionId);
876
941
  }
877
- return this.replay(workItemId); // 仍未证停:stopping 保持,写域占用、不再派发。
942
+ return this.replay(attempt.workItemId); // 仍未证停:stopping 保持,写域占用、不再派发。
878
943
  }
879
944
  /** §6.2 停滞提示:连续 15 分钟无可核对进展 → 提示一次(不杀、不重派)。 */
880
945
  maybeNotifyStall(item) {
@@ -962,11 +1027,11 @@ export class TaskManager {
962
1027
  (state.lastSentAt === undefined || now - state.lastSentAt >= PROBE_INTERVAL_MS)) {
963
1028
  state.lastSentAt = now;
964
1029
  state.pendingSince = now;
965
- void this.scheduler()
1030
+ void this.schedulerFor(item)
966
1031
  .call({ version: 2, action: "probe" })
967
1032
  .then(() => {
968
1033
  const fresh = this.healthStates.get(workItemId);
969
- if (fresh === undefined)
1034
+ if (fresh !== state)
970
1035
  return;
971
1036
  fresh.pendingSince = undefined;
972
1037
  fresh.strikes = 0; // 任一有效新回执清零(§6.2)。
@@ -975,7 +1040,7 @@ export class TaskManager {
975
1040
  })
976
1041
  .catch(() => {
977
1042
  const fresh = this.healthStates.get(workItemId);
978
- if (fresh === undefined)
1043
+ if (fresh !== state)
979
1044
  return;
980
1045
  fresh.pendingSince = undefined; // 发送失败 ≠ 超时:不计数,按节奏重试。
981
1046
  });
@@ -1021,7 +1086,7 @@ export class TaskManager {
1021
1086
  }
1022
1087
  const fresh = this.replay(workItemId);
1023
1088
  try {
1024
- const after = await this.dispatch({ ...pending.input, expectedRecordRevision: fresh.recordRevision });
1089
+ const after = await this.dispatch({ ...pending.input, expectedRecordRevision: fresh.recordRevision }, pending.scheduler);
1025
1090
  // 只在派发记录真正落地时清除登记:dispatch 对"仍槽满"不抛错(写备注后
1026
1091
  // 正常返回 queued),无条件 delete 会把刚重挂的重试抹掉——复查只跑一次
1027
1092
  // 就永久搁浅(真实压测 butler-capacity 取证的 AC-04 缺陷,2026-11-15)。
@@ -1091,8 +1156,9 @@ export class TaskManager {
1091
1156
  }
1092
1157
  throw error;
1093
1158
  }
1094
- await this.scheduler().call({ version: 2, action: "cancel", taskId: item.dispatch.taskId, reason });
1095
- return this.confirmStop(workItemId, item.dispatch.taskId);
1159
+ const scheduler = this.schedulerFor(item);
1160
+ await scheduler.call({ version: 2, action: "cancel", taskId: item.dispatch.taskId, reason });
1161
+ return this.confirmStop(item, scheduler);
1096
1162
  }
1097
1163
  workItemId(input) {
1098
1164
  const value = input.workItemId;