@oyasmi/pipiclaw 0.9.5-beta.2 → 0.9.5-beta.4
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.en.md +9 -11
- package/README.md +9 -11
- package/dist/agent/channel-runner.d.ts +12 -24
- package/dist/agent/channel-runner.js +74 -30
- package/dist/agent/maintenance-context.d.ts +2 -0
- package/dist/agent/maintenance-context.js +15 -0
- package/dist/agent/prompt/sections.js +8 -6
- package/dist/agent/prompt/types.d.ts +1 -1
- package/dist/agent/runner-factory.js +1 -1
- package/dist/agent/session/command-extension.js +11 -0
- package/dist/agent/session/compaction-summary.js +6 -2
- package/dist/agent/session/execution-trace.d.ts +14 -0
- package/dist/agent/session/execution-trace.js +57 -0
- package/dist/agent/session/session-events.d.ts +2 -7
- package/dist/agent/session/session-events.js +35 -12
- package/dist/agent/session/session-host.d.ts +12 -22
- package/dist/agent/session/session-host.js +46 -65
- package/dist/agent/turn/task-digest.d.ts +1 -2
- package/dist/agent/turn/task-digest.js +33 -33
- package/dist/agent/turn/turn-context.d.ts +1 -1
- package/dist/agent/turn/turn-context.js +1 -1
- package/dist/agent/turn/turn-finish.d.ts +2 -2
- package/dist/agent/turn/turn-finish.js +3 -2
- package/dist/agent/turn/turn-pipeline.d.ts +4 -2
- package/dist/agent/turn/turn-pipeline.js +33 -5
- package/dist/agent/types.d.ts +64 -14
- package/dist/agent/types.js +3 -0
- package/dist/app/home.js +3 -4
- package/dist/channel/channel-event.d.ts +4 -12
- package/dist/channel/ingress.d.ts +1 -9
- package/dist/channel/store.d.ts +1 -1
- package/dist/commands/catalog.js +25 -19
- package/dist/commands/router.d.ts +5 -2
- package/dist/commands/router.js +9 -4
- package/dist/config/settings.d.ts +5 -12
- package/dist/config/settings.js +0 -7
- package/dist/config/tools.d.ts +2 -2
- package/dist/config/tools.js +2 -2
- package/dist/dingtalk/bot.d.ts +2 -0
- package/dist/dingtalk/bot.js +4 -0
- package/dist/dingtalk/cards.d.ts +7 -0
- package/dist/dingtalk/cards.js +32 -2
- package/dist/dingtalk/delivery.d.ts +4 -1
- package/dist/dingtalk/delivery.js +104 -191
- package/dist/dingtalk/progress.d.ts +41 -6
- package/dist/dingtalk/progress.js +173 -16
- package/dist/file-store.d.ts +4 -0
- package/dist/file-store.js +6 -1
- package/dist/jobs/completion-observer.d.ts +20 -0
- package/dist/jobs/completion-observer.js +107 -0
- package/dist/jobs/completion-signal.d.ts +9 -0
- package/dist/jobs/completion-signal.js +32 -0
- package/dist/jobs/completion-wake.d.ts +1 -1
- package/dist/jobs/completion-wake.js +2 -13
- package/dist/jobs/manager.d.ts +11 -29
- package/dist/jobs/manager.js +103 -176
- package/dist/jobs/probe.d.ts +3 -0
- package/dist/jobs/probe.js +42 -0
- package/dist/jobs/record.d.ts +3 -6
- package/dist/jobs/runtime.d.ts +28 -0
- package/dist/jobs/runtime.js +69 -0
- package/dist/memory/boundary-work.d.ts +2 -0
- package/dist/memory/boundary-work.js +79 -37
- package/dist/memory/commands.js +4 -1
- package/dist/memory/index-budget.js +18 -15
- package/dist/memory/journal.js +2 -1
- package/dist/memory/lifecycle.d.ts +4 -8
- package/dist/memory/lifecycle.js +21 -51
- package/dist/memory/reflect-job.d.ts +0 -6
- package/dist/memory/reflect-job.js +13 -34
- package/dist/memory/reflect.d.ts +4 -0
- package/dist/memory/reflect.js +32 -5
- package/dist/memory/review-log.d.ts +13 -0
- package/dist/memory/review-log.js +49 -0
- package/dist/memory/search.js +7 -4
- package/dist/memory/source-window.d.ts +18 -1
- package/dist/memory/source-window.js +59 -9
- package/dist/memory/store.d.ts +2 -0
- package/dist/memory/store.js +45 -13
- package/dist/playbooks/agent-delegation.md +10 -4
- package/dist/playbooks/background-jobs.md +4 -4
- package/dist/playbooks/event-scheduling.md +2 -2
- package/dist/playbooks/memory-and-learning.md +3 -3
- package/dist/playbooks/outbound-media.md +2 -2
- package/dist/playbooks/runtime-orientation.md +10 -6
- package/dist/playbooks/task-lead.md +54 -33
- package/dist/runtime/bootstrap.d.ts +11 -24
- package/dist/runtime/bootstrap.js +92 -59
- package/dist/runtime/channel-queue.d.ts +2 -0
- package/dist/runtime/channel-queue.js +5 -1
- package/dist/runtime/durable-dispatch.d.ts +7 -0
- package/dist/runtime/durable-dispatch.js +66 -7
- package/dist/runtime/ingress-busy.d.ts +1 -2
- package/dist/runtime/ingress-busy.js +2 -35
- package/dist/runtime/ingress-commands.d.ts +1 -1
- package/dist/runtime/ingress-commands.js +28 -20
- package/dist/runtime/ingress-deps.d.ts +4 -7
- package/dist/runtime/ingress.js +23 -13
- package/dist/runtime/shutdown.d.ts +1 -1
- package/dist/runtime/shutdown.js +2 -2
- package/dist/runtime/task-close.d.ts +4 -0
- package/dist/runtime/task-close.js +102 -0
- package/dist/runtime/task-control.d.ts +34 -0
- package/dist/runtime/task-control.js +225 -0
- package/dist/runtime/task-input.d.ts +13 -0
- package/dist/runtime/task-input.js +129 -0
- package/dist/runtime/task-lane-types.d.ts +123 -0
- package/dist/runtime/task-lane-types.js +14 -0
- package/dist/runtime/task-lane.d.ts +99 -0
- package/dist/runtime/task-lane.js +703 -0
- package/dist/runtime/task-pending.d.ts +8 -0
- package/dist/runtime/task-pending.js +40 -0
- package/dist/runtime/task-spawn.d.ts +4 -4
- package/dist/runtime/task-spawn.js +4 -4
- package/dist/runtime/task-step.d.ts +32 -0
- package/dist/runtime/task-step.js +276 -0
- package/dist/runtime/turn-run.d.ts +4 -16
- package/dist/runtime/turn-run.js +17 -155
- package/dist/runtime/wake-coalescing.d.ts +1 -3
- package/dist/runtime/wake-coalescing.js +2 -4
- package/dist/shared/format.d.ts +0 -6
- package/dist/shared/format.js +0 -17
- package/dist/shared/host-process.d.ts +2 -0
- package/dist/shared/host-process.js +16 -1
- package/dist/shared/jsonl-appender.d.ts +5 -0
- package/dist/shared/jsonl-appender.js +25 -2
- package/dist/skills/catalog.d.ts +9 -0
- package/dist/skills/catalog.js +34 -0
- package/dist/skills/commands.d.ts +3 -12
- package/dist/skills/commands.js +36 -22
- package/dist/skills/loader.d.ts +2 -31
- package/dist/skills/loader.js +101 -68
- package/dist/skills/roots.d.ts +12 -0
- package/dist/skills/roots.js +18 -0
- package/dist/skills/types.d.ts +24 -0
- package/dist/skills/types.js +1 -0
- package/dist/subagents/completion-wake.js +0 -10
- package/dist/subagents/discovery.d.ts +1 -1
- package/dist/subagents/discovery.js +10 -16
- package/dist/subagents/dispatch.js +8 -16
- package/dist/subagents/external/cursor-cli.d.ts +2 -0
- package/dist/subagents/external/cursor-cli.js +256 -0
- package/dist/subagents/external/harness.d.ts +5 -5
- package/dist/subagents/external/reconciliation.d.ts +7 -0
- package/dist/subagents/external/reconciliation.js +105 -0
- package/dist/subagents/external/recovery.d.ts +20 -0
- package/dist/subagents/external/recovery.js +71 -0
- package/dist/subagents/external/registry.js +2 -0
- package/dist/subagents/external/role-warnings.d.ts +17 -0
- package/dist/subagents/external/role-warnings.js +42 -0
- package/dist/subagents/external/run.js +18 -22
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/format.js +1 -1
- package/dist/subagents/grace.d.ts +2 -2
- package/dist/subagents/grace.js +3 -3
- package/dist/subagents/internal/run.js +7 -5
- package/dist/subagents/internal/worker.js +31 -2
- package/dist/subagents/result.js +2 -3
- package/dist/subagents/run-record.d.ts +4 -7
- package/dist/subagents/run-record.js +2 -2
- package/dist/subagents/runs.d.ts +33 -46
- package/dist/subagents/runs.js +126 -245
- package/dist/subagents/task-settlement.d.ts +3 -0
- package/dist/subagents/task-settlement.js +20 -0
- package/dist/subagents/types.d.ts +1 -2
- package/dist/subagents/workspace-summary.js +5 -1
- package/dist/tasks/archive.d.ts +11 -0
- package/dist/tasks/archive.js +141 -0
- package/dist/tasks/board.d.ts +5 -12
- package/dist/tasks/board.js +4 -30
- package/dist/tasks/bound-work.d.ts +12 -6
- package/dist/tasks/bound-work.js +37 -24
- package/dist/tasks/brief.d.ts +38 -14
- package/dist/tasks/brief.js +128 -70
- package/dist/tasks/budget.d.ts +3 -3
- package/dist/tasks/budget.js +9 -4
- package/dist/tasks/commands.d.ts +14 -9
- package/dist/tasks/commands.js +190 -121
- package/dist/tasks/completion.d.ts +12 -0
- package/dist/tasks/completion.js +35 -0
- package/dist/tasks/contract.d.ts +8 -17
- package/dist/tasks/contract.js +41 -43
- package/dist/tasks/control.d.ts +138 -0
- package/dist/tasks/control.js +1 -0
- package/dist/tasks/create.d.ts +1 -1
- package/dist/tasks/create.js +3 -3
- package/dist/tasks/delivery.d.ts +24 -0
- package/dist/tasks/delivery.js +221 -0
- package/dist/tasks/file-mutation.d.ts +5 -0
- package/dist/tasks/file-mutation.js +38 -0
- package/dist/tasks/frontmatter.d.ts +43 -28
- package/dist/tasks/frontmatter.js +83 -40
- package/dist/tasks/input-receipts.d.ts +7 -0
- package/dist/tasks/input-receipts.js +60 -0
- package/dist/tasks/loop-log.d.ts +147 -28
- package/dist/tasks/loop-log.js +239 -28
- package/dist/tasks/receipts.d.ts +19 -0
- package/dist/tasks/receipts.js +48 -0
- package/dist/tasks/state.d.ts +93 -0
- package/dist/tasks/state.js +156 -0
- package/dist/tasks/store.d.ts +81 -49
- package/dist/tasks/store.js +244 -147
- package/dist/tools/bash.d.ts +3 -5
- package/dist/tools/bash.js +8 -22
- package/dist/tools/contract/details.d.ts +6 -6
- package/dist/tools/contract/details.js +6 -6
- package/dist/tools/contract/execution-trace.d.ts +4 -0
- package/dist/tools/contract/execution-trace.js +23 -0
- package/dist/tools/contract/presentation.js +6 -2
- package/dist/tools/edit.d.ts +1 -0
- package/dist/tools/edit.js +45 -42
- package/dist/tools/index.d.ts +8 -12
- package/dist/tools/index.js +16 -6
- package/dist/tools/memory-manage.js +8 -1
- package/dist/tools/registry.d.ts +7 -11
- package/dist/tools/registry.js +52 -25
- package/dist/tools/skill.d.ts +2 -2
- package/dist/tools/skill.js +24 -10
- package/dist/tools/subagent-manage.js +7 -4
- package/dist/tools/subagent.d.ts +0 -2
- package/dist/tools/subagent.js +2 -7
- package/dist/tools/task-manage/control-tools.d.ts +4 -0
- package/dist/tools/task-manage/control-tools.js +65 -0
- package/dist/tools/task-manage/create.js +2 -1
- package/dist/tools/task-manage/factory.d.ts +12 -6
- package/dist/tools/task-manage/factory.js +72 -57
- package/dist/tools/task-manage/lifecycle.d.ts +7 -12
- package/dist/tools/task-manage/lifecycle.js +118 -66
- package/dist/tools/task-manage/log-view.js +8 -5
- package/dist/tools/task-manage/schema.d.ts +21 -26
- package/dist/tools/task-manage/schema.js +29 -35
- package/dist/tools/task-manage/shared.d.ts +8 -39
- package/dist/tools/task-manage/shared.js +19 -68
- package/dist/tools/task-manage/step-tools.d.ts +5 -0
- package/dist/tools/task-manage/step-tools.js +103 -0
- package/dist/tools/task-manage/types.d.ts +25 -18
- package/dist/tools/write-content.d.ts +1 -0
- package/dist/tools/write-content.js +6 -1
- package/dist/tools/write.d.ts +1 -0
- package/dist/tools/write.js +1 -0
- package/dist/usage/ledger.d.ts +4 -4
- package/dist/usage/render.js +2 -2
- package/dist/web/search-providers.js +0 -33
- package/dist/webapi/request-policy.js +1 -1
- package/examples/sub-agents/README.md +23 -16
- package/examples/sub-agents/agents/claude-high.md +1 -1
- package/examples/sub-agents/agents/claude-main.md +1 -1
- package/examples/sub-agents/agents/codex-flash.md +1 -1
- package/examples/sub-agents/agents/codex-high.md +1 -1
- package/examples/sub-agents/agents/codex-main.md +4 -4
- package/examples/sub-agents/agents/cursor-high.md +22 -0
- package/examples/sub-agents/agents/cursor-main.md +22 -0
- package/examples/sub-agents/agents/glm-flash.md +1 -1
- package/examples/sub-agents/agents/glm-high.md +2 -2
- package/examples/sub-agents/agents/scout.md +30 -0
- package/package.json +6 -6
- package/dist/runtime/task-driver.d.ts +0 -116
- package/dist/runtime/task-driver.js +0 -443
- package/dist/runtime/task-wake.d.ts +0 -48
- package/dist/runtime/task-wake.js +0 -32
- package/dist/shared/wake-claim.d.ts +0 -23
- package/dist/shared/wake-claim.js +0 -26
- package/dist/skills/validation.d.ts +0 -8
- package/dist/skills/validation.js +0 -91
- package/dist/skills/workspace.d.ts +0 -33
- package/dist/skills/workspace.js +0 -116
- package/dist/tasks/steer.d.ts +0 -8
- package/dist/tasks/steer.js +0 -81
- package/dist/tasks/ticket.d.ts +0 -71
- package/dist/tasks/ticket.js +0 -138
- package/dist/tools/task-manage/step-end.d.ts +0 -11
- package/dist/tools/task-manage/step-end.js +0 -117
|
@@ -5,6 +5,8 @@ export type QueuedWork = () => Promise<void>;
|
|
|
5
5
|
* (`AgentRunner.beginTurn`), not by this queue.
|
|
6
6
|
*/
|
|
7
7
|
export declare class ChannelQueue {
|
|
8
|
+
private readonly onCapacity?;
|
|
9
|
+
constructor(onCapacity?: ((queue: ChannelQueue) => void) | undefined);
|
|
8
10
|
private queue;
|
|
9
11
|
private processing;
|
|
10
12
|
private stopped;
|
|
@@ -10,7 +10,8 @@ import { errorMessage } from "../shared/text-utils.js";
|
|
|
10
10
|
* (`AgentRunner.beginTurn`), not by this queue.
|
|
11
11
|
*/
|
|
12
12
|
export class ChannelQueue {
|
|
13
|
-
constructor() {
|
|
13
|
+
constructor(onCapacity) {
|
|
14
|
+
this.onCapacity = onCapacity;
|
|
14
15
|
this.queue = [];
|
|
15
16
|
this.processing = false;
|
|
16
17
|
this.stopped = false;
|
|
@@ -33,6 +34,7 @@ export class ChannelQueue {
|
|
|
33
34
|
return;
|
|
34
35
|
this.processing = true;
|
|
35
36
|
const { work } = this.queue.shift();
|
|
37
|
+
this.onCapacity?.(this);
|
|
36
38
|
try {
|
|
37
39
|
await work();
|
|
38
40
|
}
|
|
@@ -63,6 +65,8 @@ export class ChannelQueue {
|
|
|
63
65
|
if (index < 0)
|
|
64
66
|
return false;
|
|
65
67
|
this.queue.splice(index, 1);
|
|
68
|
+
if (!this.stopped)
|
|
69
|
+
this.onCapacity?.(this);
|
|
66
70
|
return true;
|
|
67
71
|
}
|
|
68
72
|
}
|
|
@@ -42,6 +42,9 @@ export declare function renderDispatchExhaustedNotice(record: DurableDispatchRec
|
|
|
42
42
|
*/
|
|
43
43
|
export declare class DurableDispatchService {
|
|
44
44
|
private readonly options;
|
|
45
|
+
private stopped;
|
|
46
|
+
private readonly capacityRejected;
|
|
47
|
+
private readonly capacityDrains;
|
|
45
48
|
private readonly queue;
|
|
46
49
|
private readonly leaseMs;
|
|
47
50
|
private timer;
|
|
@@ -72,6 +75,10 @@ export declare class DurableDispatchService {
|
|
|
72
75
|
*/
|
|
73
76
|
private drainSafely;
|
|
74
77
|
stop(): void;
|
|
78
|
+
/** Capacity is only a scheduling hint; every retry still reads disk under the per-id lock. */
|
|
79
|
+
notifyCapacity(channelId: string): void;
|
|
80
|
+
private trackRejected;
|
|
81
|
+
private untrack;
|
|
75
82
|
dispatch(event: WakeEvent): Promise<boolean>;
|
|
76
83
|
/** Reset any in-flight records for a channel so a stop/abort can redeliver on the next tick, not after the lease expires. */
|
|
77
84
|
cancelChannel(channelId: string): Promise<number>;
|
|
@@ -61,16 +61,14 @@ function withRedeliveryNotice(event, deliveries) {
|
|
|
61
61
|
}
|
|
62
62
|
/**
|
|
63
63
|
* What a wake was for, in the user's terms (spec 053, D2). The wake's own `text` is a prompt for
|
|
64
|
-
* the model and its `producer` an internal tag (`
|
|
64
|
+
* the model and its `producer` an internal tag (`SUBAGENT`, `JOB`, …), so neither
|
|
65
65
|
* may reach the chat; every in-process producer prefixes its text with a `[KIND:id…]` tag, which
|
|
66
66
|
* is what this reads instead.
|
|
67
67
|
*/
|
|
68
68
|
function describeWakeSource(event) {
|
|
69
|
-
const tag = /^\[(
|
|
69
|
+
const tag = /^\[(SUBAGENT|JOB|EVENT):([^:\]\s]+)/.exec(event.text);
|
|
70
70
|
const id = tag?.[2];
|
|
71
71
|
switch (tag?.[1]) {
|
|
72
|
-
case "TASK_DRIVER":
|
|
73
|
-
return { label: `任务 \`${id}\` 的一次后台唤醒`, nextStep: `用 \`/tasks show ${id}\` 确认任务状态` };
|
|
74
72
|
case "SUBAGENT":
|
|
75
73
|
return { label: `委派 \`${id}\` 的完成通知`, nextStep: `用 \`/subagents show ${id}\` 查看结果` };
|
|
76
74
|
case "JOB":
|
|
@@ -133,6 +131,9 @@ function parseRecord(raw) {
|
|
|
133
131
|
export class DurableDispatchService {
|
|
134
132
|
constructor(options) {
|
|
135
133
|
this.options = options;
|
|
134
|
+
this.stopped = false;
|
|
135
|
+
this.capacityRejected = new Map();
|
|
136
|
+
this.capacityDrains = new Map();
|
|
136
137
|
this.queue = createSerialQueue();
|
|
137
138
|
this.timer = null;
|
|
138
139
|
/**
|
|
@@ -158,6 +159,7 @@ export class DurableDispatchService {
|
|
|
158
159
|
start() {
|
|
159
160
|
if (this.timer)
|
|
160
161
|
return;
|
|
162
|
+
this.stopped = false;
|
|
161
163
|
this.drainSafely();
|
|
162
164
|
this.timer = setInterval(() => this.drainSafely(), this.options.intervalMs ?? DEFAULT_INTERVAL_MS);
|
|
163
165
|
this.timer.unref?.();
|
|
@@ -173,11 +175,56 @@ export class DurableDispatchService {
|
|
|
173
175
|
});
|
|
174
176
|
}
|
|
175
177
|
stop() {
|
|
178
|
+
this.stopped = true;
|
|
176
179
|
if (!this.timer)
|
|
177
180
|
return;
|
|
178
181
|
clearInterval(this.timer);
|
|
179
182
|
this.timer = null;
|
|
180
183
|
}
|
|
184
|
+
/** Capacity is only a scheduling hint; every retry still reads disk under the per-id lock. */
|
|
185
|
+
notifyCapacity(channelId) {
|
|
186
|
+
if (this.stopped || !this.capacityRejected.get(channelId)?.size)
|
|
187
|
+
return;
|
|
188
|
+
const current = this.capacityDrains.get(channelId);
|
|
189
|
+
if (current) {
|
|
190
|
+
current.dirty = true;
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const drain = { dirty: true };
|
|
194
|
+
this.capacityDrains.set(channelId, drain);
|
|
195
|
+
setImmediate(() => {
|
|
196
|
+
void (async () => {
|
|
197
|
+
do {
|
|
198
|
+
drain.dirty = false;
|
|
199
|
+
for (const id of [...(this.capacityRejected.get(channelId) ?? [])]) {
|
|
200
|
+
if (this.stopped)
|
|
201
|
+
return;
|
|
202
|
+
await this.drainRecord(id, Date.now());
|
|
203
|
+
}
|
|
204
|
+
} while (drain.dirty && !this.stopped);
|
|
205
|
+
})()
|
|
206
|
+
.catch((error) => log.logWarn("dispatch.capacity.failed", "Capacity retry failed", {
|
|
207
|
+
channelId,
|
|
208
|
+
reason: errorMessage(error),
|
|
209
|
+
}))
|
|
210
|
+
.finally(() => this.capacityDrains.delete(channelId));
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
trackRejected(channelId, id) {
|
|
214
|
+
let ids = this.capacityRejected.get(channelId);
|
|
215
|
+
if (!ids) {
|
|
216
|
+
ids = new Set();
|
|
217
|
+
this.capacityRejected.set(channelId, ids);
|
|
218
|
+
}
|
|
219
|
+
ids.add(id);
|
|
220
|
+
}
|
|
221
|
+
untrack(id) {
|
|
222
|
+
for (const [channel, ids] of this.capacityRejected) {
|
|
223
|
+
ids.delete(id);
|
|
224
|
+
if (!ids.size)
|
|
225
|
+
this.capacityRejected.delete(channel);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
181
228
|
async dispatch(event) {
|
|
182
229
|
// Spec 058, D7: every in-process producer stamps its desk. An event without one cannot be
|
|
183
230
|
// checked against the channel's binding at admission, so it is refused here, at the door.
|
|
@@ -333,6 +380,7 @@ export class DurableDispatchService {
|
|
|
333
380
|
if (wasQueued && this.stopEpoch(channelId) === epoch)
|
|
334
381
|
this.absorbed.set(id, channelId);
|
|
335
382
|
this.running.add(id);
|
|
383
|
+
this.untrack(id);
|
|
336
384
|
events.push(withRedeliveryNotice({ ...record.event, dispatchId: record.id }, record.deliveries));
|
|
337
385
|
});
|
|
338
386
|
}
|
|
@@ -360,6 +408,7 @@ export class DurableDispatchService {
|
|
|
360
408
|
if (!id)
|
|
361
409
|
return;
|
|
362
410
|
this.running.delete(id);
|
|
411
|
+
this.untrack(id);
|
|
363
412
|
await this.queue.run(id, async () => {
|
|
364
413
|
await unlink(recordPath(this.options.stateDir, id)).catch(() => undefined);
|
|
365
414
|
});
|
|
@@ -404,12 +453,18 @@ export class DurableDispatchService {
|
|
|
404
453
|
async drainRecord(id, now) {
|
|
405
454
|
await this.queue.run(id, async () => {
|
|
406
455
|
const record = await this.read(id);
|
|
407
|
-
if (!record)
|
|
456
|
+
if (!record) {
|
|
457
|
+
this.untrack(id);
|
|
408
458
|
return;
|
|
459
|
+
}
|
|
460
|
+
if (record.status === "pending")
|
|
461
|
+
this.trackRejected(record.event.channelId, id);
|
|
409
462
|
// A poison pill: give up on redelivery for good, once. Left on disk (not deleted) so
|
|
410
463
|
// `onExhausted`'s notice stays inspectable and the record is available for manual retry.
|
|
411
|
-
if (record.status === "exhausted")
|
|
464
|
+
if (record.status === "exhausted") {
|
|
465
|
+
this.untrack(id);
|
|
412
466
|
return;
|
|
467
|
+
}
|
|
413
468
|
// The turn is still running in this process: renew its lease rather than treating a
|
|
414
469
|
// long turn as a lost one and redelivering the wake underneath it (D2).
|
|
415
470
|
if (record.status === "running" && this.running.has(id)) {
|
|
@@ -435,6 +490,7 @@ export class DurableDispatchService {
|
|
|
435
490
|
return;
|
|
436
491
|
if (record.deliveries >= MAX_DELIVERIES) {
|
|
437
492
|
record.status = "exhausted";
|
|
493
|
+
this.untrack(id);
|
|
438
494
|
record.leaseExpiresAt = undefined;
|
|
439
495
|
record.nextAttemptAt = undefined;
|
|
440
496
|
await this.write(record);
|
|
@@ -455,8 +511,11 @@ export class DurableDispatchService {
|
|
|
455
511
|
record.nextAttemptAt = undefined;
|
|
456
512
|
await this.write(record);
|
|
457
513
|
const accepted = this.options.bot.enqueueEvent(withRedeliveryNotice({ ...record.event, dispatchId: record.id }, record.deliveries));
|
|
458
|
-
if (accepted)
|
|
514
|
+
if (accepted) {
|
|
515
|
+
this.untrack(id);
|
|
459
516
|
return;
|
|
517
|
+
}
|
|
518
|
+
this.trackRejected(record.event.channelId, id);
|
|
460
519
|
// Admission rejection (queue full, bot stopped) is backpressure, not a delivery attempt —
|
|
461
520
|
// the handler never ran and never got a chance to fail (R2). Counting it against
|
|
462
521
|
// MAX_DELIVERIES meant a few minutes of congestion permanently exhausted a record that
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { HumanEvent } from "../channel/channel-event.js";
|
|
2
|
-
import type { StopOutcome } from "../channel/ingress.js";
|
|
3
2
|
import type { IngressDeps } from "./ingress-deps.js";
|
|
4
3
|
/** How a message that met a busy channel ended up. */
|
|
5
4
|
export type BusyOutcome =
|
|
@@ -21,6 +20,6 @@ export declare function createBusyHandlers(deps: IngressDeps, queues: {
|
|
|
21
20
|
reset(channelId: string): number;
|
|
22
21
|
}): {
|
|
23
22
|
handleBusyMessage: (event: HumanEvent, mode: "steer" | "followUp", queueText: string, quiet?: boolean) => Promise<BusyOutcome>;
|
|
24
|
-
handleStop: (channelId: string) => Promise<
|
|
23
|
+
handleStop: (channelId: string) => Promise<void>;
|
|
25
24
|
cancelRunningTurn: (channelId: string) => boolean;
|
|
26
25
|
};
|
|
@@ -7,9 +7,7 @@ import { forceEndStuckTurnAfterStop } from "../agent/stop-watchdog.js";
|
|
|
7
7
|
import { formatMissingQueueMessage, formatSteerQueued } from "../commands/catalog.js";
|
|
8
8
|
import * as log from "../log.js";
|
|
9
9
|
import { errorMessage } from "../shared/text-utils.js";
|
|
10
|
-
import { pauseTask as pauseStoredTask } from "../tasks/store.js";
|
|
11
10
|
import { relativeImagePaths } from "./inbound-images.js";
|
|
12
|
-
import { parseDriverTaskId } from "./task-driver.js";
|
|
13
11
|
function isNoRunningTaskQueueError(err) {
|
|
14
12
|
return err instanceof Error && err.message === "No task is currently running.";
|
|
15
13
|
}
|
|
@@ -45,20 +43,6 @@ export function createBusyHandlers(deps, queues) {
|
|
|
45
43
|
});
|
|
46
44
|
return { kind: "requeue", text: trimmedQueueText };
|
|
47
45
|
}
|
|
48
|
-
// A task step runs in the task's own session and is muted: a steer here would land in
|
|
49
|
-
// the background task's context and its answer would never reach the user, while the
|
|
50
|
-
// message itself is kept out of the chat session. Run it as the next chat turn instead.
|
|
51
|
-
const taskLoop = runner.getTaskLoop();
|
|
52
|
-
if (taskLoop) {
|
|
53
|
-
if (!quiet) {
|
|
54
|
-
await say(event, `后台任务 \`${taskLoop.taskId}\` 正在执行一步,你的消息会在这一步结束后处理;要给该任务补充指示,用 \`/tasks steer ${taskLoop.taskId} <内容>\`。`);
|
|
55
|
-
}
|
|
56
|
-
log.logEvent("info", "agent.turn.followup_queued", "Message deferred past a task step", {
|
|
57
|
-
ctx: { channelId: event.channelId, userName: event.userName },
|
|
58
|
-
fields: { messageLength: trimmedQueueText.length, taskId: taskLoop.taskId },
|
|
59
|
-
});
|
|
60
|
-
return { kind: "requeue", text: trimmedQueueText };
|
|
61
|
-
}
|
|
62
46
|
if (mode === "followUp") {
|
|
63
47
|
log.logEvent("info", "agent.turn.followup_queued", "Follow-up queued", {
|
|
64
48
|
ctx: { channelId: event.channelId, userName: event.userName },
|
|
@@ -154,28 +138,12 @@ export function createBusyHandlers(deps, queues) {
|
|
|
154
138
|
log.logInfoEvent("agent.turn.cancel_requested", "Turn cancel requested", { channelId: channelId });
|
|
155
139
|
return true;
|
|
156
140
|
}
|
|
157
|
-
/** `/stop`: abort the running turn
|
|
141
|
+
/** `/stop`: abort the running turn and drop what was queued behind it. Tasks run apart from the chat and are stopped with `/tasks pause` (spec 064, D27). */
|
|
158
142
|
async function handleStop(channelId) {
|
|
159
143
|
const runner = channelRunners.get(channelId);
|
|
160
|
-
let pausedTaskId;
|
|
161
144
|
if (runner?.isBusy()) {
|
|
162
|
-
// The runner ends the turn's output at once (the card is closed, late events dropped)
|
|
163
|
-
// before the task is paused below.
|
|
145
|
+
// The runner ends the turn's output at once (the card is closed, late events dropped).
|
|
164
146
|
runner.requestStop();
|
|
165
|
-
// Stopping a task step stops the task: otherwise the driver would queue the next step
|
|
166
|
-
// straight away. The step may not be bound to its session yet, so fall back to the text.
|
|
167
|
-
const taskId = runner.getTaskLoop()?.taskId ?? parseDriverTaskId(runner.getTurnStatus().taskText);
|
|
168
|
-
if (taskId) {
|
|
169
|
-
await pauseStoredTask(runner.conversation.deskDir, taskId, {
|
|
170
|
-
by: "user",
|
|
171
|
-
reason: "用户 /stop 中止了该任务的当前步骤。",
|
|
172
|
-
});
|
|
173
|
-
pausedTaskId = taskId;
|
|
174
|
-
log.logInfoEvent("tasks.task.paused_on_stop", "Task paused on /stop", {
|
|
175
|
-
channelId: channelId,
|
|
176
|
-
fields: { taskId },
|
|
177
|
-
});
|
|
178
|
-
}
|
|
179
147
|
// Drop queued-but-not-started messages so a burst does not keep
|
|
180
148
|
// running after the user asked to halt; abort the in-flight one.
|
|
181
149
|
const dropped = queues.clearPending(channelId);
|
|
@@ -205,7 +173,6 @@ export function createBusyHandlers(deps, queues) {
|
|
|
205
173
|
});
|
|
206
174
|
log.logInfoEvent("agent.turn.stop_requested", "Stop requested", { channelId: channelId });
|
|
207
175
|
}
|
|
208
|
-
return { pausedTaskId };
|
|
209
176
|
}
|
|
210
177
|
return { handleBusyMessage, handleStop, cancelRunningTurn };
|
|
211
178
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type ChannelEvent, type HumanEvent } from "../channel/channel-event.js";
|
|
2
2
|
import { type RuntimeCommandName } from "../commands/catalog.js";
|
|
3
3
|
import type { IngressDeps } from "./ingress-deps.js";
|
|
4
4
|
export declare function createCommandHandlers(deps: IngressDeps, resetChannelQueue: (channelId: string) => number): {
|
|
@@ -3,18 +3,38 @@
|
|
|
3
3
|
* stateless report commands (`/status`, `/tasks`, …), shared by the busy and the idle path of
|
|
4
4
|
* `ingress.ts`.
|
|
5
5
|
*/
|
|
6
|
-
import {
|
|
6
|
+
import { preserveMemoryBeforeNewSession } from "../agent/maintenance-context.js";
|
|
7
7
|
import { createFreshActiveSession } from "../channel/active-session-store.js";
|
|
8
|
+
import { senderOf } from "../channel/channel-event.js";
|
|
8
9
|
import { formatNewSessionReply } from "../commands/catalog.js";
|
|
9
10
|
import { runReportCommand } from "../commands/router.js";
|
|
10
11
|
import { formatNoDeskReply } from "../desk/commands.js";
|
|
11
12
|
import * as log from "../log.js";
|
|
12
13
|
import { errorMessage } from "../shared/text-utils.js";
|
|
13
|
-
import { readActiveTasks } from "../tasks/contract.js";
|
|
14
14
|
import { relativeImagePaths } from "./inbound-images.js";
|
|
15
|
-
|
|
15
|
+
/**
|
|
16
|
+
* The lane is built after the ingress, so a command resolves it when it runs. A command that lands
|
|
17
|
+
* before the lane exists is refused with a retry hint rather than guessed at.
|
|
18
|
+
*/
|
|
19
|
+
function lazyTaskControl(get) {
|
|
20
|
+
const control = () => {
|
|
21
|
+
const current = get();
|
|
22
|
+
if (!current)
|
|
23
|
+
throw new Error("任务服务尚未就绪,请稍后重试。");
|
|
24
|
+
return current;
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
isRunning: (desk, id) => control().isRunning(desk, id),
|
|
28
|
+
created: (...args) => control().created(...args),
|
|
29
|
+
snapshot: (...args) => control().snapshot(...args),
|
|
30
|
+
message: (...args) => control().message(...args),
|
|
31
|
+
pause: (...args) => control().pause(...args),
|
|
32
|
+
resume: (...args) => control().resume(...args),
|
|
33
|
+
cancel: (...args) => control().cancel(...args),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
16
36
|
export function createCommandHandlers(deps, resetChannelQueue) {
|
|
17
|
-
const { options, channelRunners, sessionResetChains, activeTasks, archiveIncomingMessage, getRunner, resolveChannel, deskPort, describeChannel, cliVersion, startedAt, isShuttingDown,
|
|
37
|
+
const { options, channelRunners, sessionResetChains, activeTasks, archiveIncomingMessage, getRunner, resolveChannel, deskPort, describeChannel, cliVersion, startedAt, isShuttingDown, getRuns, } = deps;
|
|
18
38
|
const say = (event, text) => deps.pushTo(event.channelId, {
|
|
19
39
|
text,
|
|
20
40
|
...(event.source === "human" && event.ref !== undefined ? { ref: event.ref } : {}),
|
|
@@ -54,6 +74,7 @@ export function createCommandHandlers(deps, resetChannelQueue) {
|
|
|
54
74
|
// generation is touched. A filesystem failure therefore leaves the live
|
|
55
75
|
// session authoritative and retryable. `/new` resets only this channel's
|
|
56
76
|
// conversation in the desk.
|
|
77
|
+
await preserveMemoryBeforeNewSession(conversation);
|
|
57
78
|
const result = await createFreshActiveSession(conversation.conversationDir, conversation.cwd);
|
|
58
79
|
const oldRunner = channelRunners.get(event.channelId);
|
|
59
80
|
if (oldRunner) {
|
|
@@ -124,7 +145,7 @@ export function createCommandHandlers(deps, resetChannelQueue) {
|
|
|
124
145
|
}, name, args);
|
|
125
146
|
}
|
|
126
147
|
const { conversation } = resolution;
|
|
127
|
-
const { desk
|
|
148
|
+
const { desk } = conversation;
|
|
128
149
|
return runReportCommand({
|
|
129
150
|
kind: "bound",
|
|
130
151
|
conversation,
|
|
@@ -141,21 +162,8 @@ export function createCommandHandlers(deps, resetChannelQueue) {
|
|
|
141
162
|
return runner;
|
|
142
163
|
},
|
|
143
164
|
runManager: getRuns().get(desk),
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
// The step runs in the task's delivery channel, wherever `/tasks` was typed (D13);
|
|
147
|
-
// a suspended task is not woken at all.
|
|
148
|
-
const target = entry?.fields.channel;
|
|
149
|
-
if (!entry || !target || !describeChannel(desk, target).boundHere)
|
|
150
|
-
return false;
|
|
151
|
-
// A human asking to run a task twice means twice, so this key is deliberately
|
|
152
|
-
// unique per invocation rather than sharing the driver's occurrence key (D1).
|
|
153
|
-
const now = Date.now();
|
|
154
|
-
return ((await getDurableDispatch()?.dispatch({
|
|
155
|
-
...createTaskDriverEvent(desk, target, entry, now),
|
|
156
|
-
dispatchId: `task:${desk}:${entry.id}:manual:${new Date(now).toISOString()}`,
|
|
157
|
-
})) ?? false);
|
|
158
|
-
},
|
|
165
|
+
taskControl: lazyTaskControl(deps.getTaskControl),
|
|
166
|
+
senderName: senderOf(event).userName,
|
|
159
167
|
}, name, args);
|
|
160
168
|
}
|
|
161
169
|
return { handleNewSession, runRuntimeCommand };
|
|
@@ -12,19 +12,17 @@ import type { ChannelIndex } from "../channel/channel-index.js";
|
|
|
12
12
|
import type { ChannelStore } from "../channel/store.js";
|
|
13
13
|
import type { PushMessage } from "../channel/transport.js";
|
|
14
14
|
import type { DeskCommandPort } from "../desk/commands.js";
|
|
15
|
-
import type { JobRuntime } from "../jobs/
|
|
15
|
+
import type { JobRuntime } from "../jobs/runtime.js";
|
|
16
16
|
import type { SubAgentRuntime } from "../subagents/run-registry.js";
|
|
17
|
+
import type { TaskControl } from "../tasks/control.js";
|
|
17
18
|
import type { ChannelResolution } from "./desk-runtime.js";
|
|
18
19
|
import type { DurableDispatchService } from "./durable-dispatch.js";
|
|
19
|
-
import type { WakeTaskTransitionHooks } from "./task-wake.js";
|
|
20
20
|
import type { TransportRegistry } from "./transports.js";
|
|
21
21
|
import type { ArchivedMessage } from "./turn-run.js";
|
|
22
22
|
export interface IngressOptions {
|
|
23
23
|
paths: BootstrapPaths;
|
|
24
24
|
/** Override the `/stop` watchdog's grace window (tests use a short one). */
|
|
25
25
|
stopForceEndGraceMs?: number;
|
|
26
|
-
/** Test-only fault seams for the atomic structured-wake task transition. */
|
|
27
|
-
wakeTransitionHooks?: Partial<Record<"job" | "subagent", WakeTaskTransitionHooks>>;
|
|
28
26
|
}
|
|
29
27
|
export interface IngressDeps {
|
|
30
28
|
requestExecution?: import("./request-execution.js").RequestExecution;
|
|
@@ -54,9 +52,8 @@ export interface IngressDeps {
|
|
|
54
52
|
getDurableDispatch: () => DurableDispatchService | undefined;
|
|
55
53
|
getJobs: () => JobRuntime;
|
|
56
54
|
getRuns: () => SubAgentRuntime;
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
};
|
|
55
|
+
/** The task lane's control port; `undefined` until the runtime has built it. */
|
|
56
|
+
getTaskControl: () => TaskControl | undefined;
|
|
60
57
|
/** Say something to a channel outside any turn; whether it was delivered. */
|
|
61
58
|
pushTo: (channelId: string, message: PushMessage) => Promise<boolean>;
|
|
62
59
|
}
|
package/dist/runtime/ingress.js
CHANGED
|
@@ -26,7 +26,11 @@ export function createIngress(deps) {
|
|
|
26
26
|
const getQueue = (channelId) => {
|
|
27
27
|
let queue = queues.get(channelId);
|
|
28
28
|
if (!queue) {
|
|
29
|
-
queue = new ChannelQueue()
|
|
29
|
+
queue = new ChannelQueue((current) => {
|
|
30
|
+
if (stopped || isShuttingDown() || deps.stopWatchdogs.has(channelId) || queues.get(channelId) !== current)
|
|
31
|
+
return;
|
|
32
|
+
deps.getDurableDispatch()?.notifyCapacity(channelId);
|
|
33
|
+
});
|
|
30
34
|
queues.set(channelId, queue);
|
|
31
35
|
}
|
|
32
36
|
return queue;
|
|
@@ -52,7 +56,6 @@ export function createIngress(deps) {
|
|
|
52
56
|
const busy = createBusyHandlers(deps, { clearPending, reset: resetChannelQueue });
|
|
53
57
|
const commands = createCommandHandlers(deps, resetChannelQueue);
|
|
54
58
|
const runEventTurn = createEventTurnRunner({
|
|
55
|
-
options: deps.options,
|
|
56
59
|
transports,
|
|
57
60
|
store: deps.store,
|
|
58
61
|
activeTasks,
|
|
@@ -63,9 +66,7 @@ export function createIngress(deps) {
|
|
|
63
66
|
reservedTurns,
|
|
64
67
|
isShuttingDown,
|
|
65
68
|
getDurableDispatch: deps.getDurableDispatch,
|
|
66
|
-
|
|
67
|
-
getRuns: deps.getRuns,
|
|
68
|
-
getTaskDriver: deps.getTaskDriver,
|
|
69
|
+
getTaskControl: deps.getTaskControl,
|
|
69
70
|
runRuntimeCommand: commands.runRuntimeCommand,
|
|
70
71
|
});
|
|
71
72
|
/**
|
|
@@ -156,10 +157,8 @@ export function createIngress(deps) {
|
|
|
156
157
|
await reply(event, renderBuiltInHelp(builtIn.args), { title: "/help", markdown: true });
|
|
157
158
|
return { kind: "replied" };
|
|
158
159
|
case "stop": {
|
|
159
|
-
|
|
160
|
-
await reply(event,
|
|
161
|
-
? `已停止当前回合。任务 \`${outcome.pausedTaskId}\` 已暂停,用 \`/tasks resume ${outcome.pausedTaskId}\` 继续。`
|
|
162
|
-
: "已停止当前回合。", { title: "/stop", markdown: true });
|
|
160
|
+
await busy.handleStop(channelId);
|
|
161
|
+
await reply(event, "已停止当前回合。", { title: "/stop", markdown: true });
|
|
163
162
|
return { kind: "replied" };
|
|
164
163
|
}
|
|
165
164
|
case "steer":
|
|
@@ -301,8 +300,8 @@ export function createIngress(deps) {
|
|
|
301
300
|
},
|
|
302
301
|
async cancel(channelId) {
|
|
303
302
|
if (await deps.requestExecution?.cancel(channelId))
|
|
304
|
-
return
|
|
305
|
-
|
|
303
|
+
return;
|
|
304
|
+
await busy.handleStop(channelId);
|
|
306
305
|
},
|
|
307
306
|
async cancelTurn(channelId, ref) {
|
|
308
307
|
if (await deps.requestExecution?.cancel(channelId))
|
|
@@ -329,13 +328,24 @@ export function createIngress(deps) {
|
|
|
329
328
|
if (queue.size() >= EVENT_QUEUE_LIMIT) {
|
|
330
329
|
log.logEvent("warn", "runtime.channel_queue.full", "Discarding incoming event", {
|
|
331
330
|
ctx: { channelId: event.channelId, userName: event.producer },
|
|
332
|
-
fields: {
|
|
331
|
+
fields: {
|
|
332
|
+
messageLength: event.text.length,
|
|
333
|
+
dispatchId: event.dispatchId,
|
|
334
|
+
desk: event.desk,
|
|
335
|
+
queueLength: queue.size(),
|
|
336
|
+
reason: "capacity",
|
|
337
|
+
},
|
|
333
338
|
});
|
|
334
339
|
return false;
|
|
335
340
|
}
|
|
336
341
|
log.logEvent("debug", "runtime.channel_queue.enqueued", "Incoming event queued", {
|
|
337
342
|
ctx: { channelId: event.channelId, userName: event.producer },
|
|
338
|
-
fields: {
|
|
343
|
+
fields: {
|
|
344
|
+
messageLength: event.text.length,
|
|
345
|
+
dispatchId: event.dispatchId,
|
|
346
|
+
desk: event.desk,
|
|
347
|
+
queueLength: queue.size(),
|
|
348
|
+
},
|
|
339
349
|
});
|
|
340
350
|
queue.enqueue(async () => {
|
|
341
351
|
service.reserveEvent(event);
|
|
@@ -8,7 +8,7 @@ import type { AgentRunner } from "../agent/types.js";
|
|
|
8
8
|
import type { ChannelIndex } from "../channel/channel-index.js";
|
|
9
9
|
import type { ChannelStore } from "../channel/store.js";
|
|
10
10
|
export interface ShutdownDeps {
|
|
11
|
-
|
|
11
|
+
taskLane: {
|
|
12
12
|
stop(): void;
|
|
13
13
|
};
|
|
14
14
|
getDurableDispatch: () => {
|
package/dist/runtime/shutdown.js
CHANGED
|
@@ -20,7 +20,7 @@ function waitForTasks(tasks, timeoutMs) {
|
|
|
20
20
|
});
|
|
21
21
|
}
|
|
22
22
|
export function createShutdown(deps) {
|
|
23
|
-
const {
|
|
23
|
+
const { taskLane, memoryMaintenanceScheduler, deskRuntime, runs, jobs, transports, ingress, store, channelIndex, channelRunners, activeTasks, } = deps;
|
|
24
24
|
let shutdownPromise = null;
|
|
25
25
|
return async (reason = "manual") => {
|
|
26
26
|
if (shutdownPromise) {
|
|
@@ -29,7 +29,7 @@ export function createShutdown(deps) {
|
|
|
29
29
|
shutdownPromise = (async () => {
|
|
30
30
|
deps.markShuttingDown();
|
|
31
31
|
log.logInfoEvent("runtime.shutdown.started", "Shutting down", { fields: { reason } });
|
|
32
|
-
|
|
32
|
+
taskLane.stop();
|
|
33
33
|
deps.getDurableDispatch()?.stop();
|
|
34
34
|
memoryMaintenanceScheduler.stop();
|
|
35
35
|
deskRuntime.stop();
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { TaskStepIntent } from "../tasks/control.js";
|
|
2
|
+
import type { LaneContext, LiveTask } from "./task-lane-types.js";
|
|
3
|
+
/** Commit the leader's durable close without another model turn. Delivery failures retain that intent. */
|
|
4
|
+
export declare function finishTaskClose(ctx: LaneContext, live: LiveTask, title: string, intent: TaskStepIntent, cancelWork: (desk: string, id: string) => Promise<string[]>, dispose: (live: LiveTask) => Promise<void>): Promise<number | undefined>;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import * as log from "../log.js";
|
|
2
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
3
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
4
|
+
import { isTaskArchiving } from "../tasks/archive.js";
|
|
5
|
+
import { taskReportDelivered } from "../tasks/completion.js";
|
|
6
|
+
import { drainTaskDeliveries } from "../tasks/delivery.js";
|
|
7
|
+
import { appendTaskLog, readTaskLog } from "../tasks/loop-log.js";
|
|
8
|
+
import { cancelledByLeaderReceipt, completedReceipt } from "../tasks/receipts.js";
|
|
9
|
+
import { closeTask, pauseTask } from "../tasks/store.js";
|
|
10
|
+
import { listPendingWork } from "./task-pending.js";
|
|
11
|
+
/** Commit the leader's durable close without another model turn. Delivery failures retain that intent. */
|
|
12
|
+
export async function finishTaskClose(ctx, live, title, intent, cancelWork, dispose) {
|
|
13
|
+
let next;
|
|
14
|
+
const noteHorizon = (at) => {
|
|
15
|
+
if (at !== undefined)
|
|
16
|
+
next = Math.min(next ?? at, at);
|
|
17
|
+
};
|
|
18
|
+
const flush = async (desk, deskDir) => {
|
|
19
|
+
try {
|
|
20
|
+
noteHorizon(await drainTaskDeliveries(deskDir, (channel, text) => ctx.options.deliver(desk, channel, text), (channel) => ctx.options.isBoundTo(channel, desk) && ctx.options.isReachable(channel), ctx.now()));
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
log.logWarn("tasks.delivery.drain_failed", "Task delivery drain failed", {
|
|
24
|
+
reason: errorMessage(error),
|
|
25
|
+
fields: { desk },
|
|
26
|
+
});
|
|
27
|
+
noteHorizon(ctx.now() + 60_000);
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
const say = async (target, text) => {
|
|
31
|
+
try {
|
|
32
|
+
await ctx.options.deliver(target.desk, target.channelId, text);
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
log.logWarn("tasks.task.receipt_failed", "Task receipt delivery failed", {
|
|
36
|
+
reason: errorMessage(error),
|
|
37
|
+
channelId: target.channelId,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const close = intent.close;
|
|
42
|
+
if (!close)
|
|
43
|
+
return next;
|
|
44
|
+
try {
|
|
45
|
+
if (close.outcome === "complete") {
|
|
46
|
+
if (!close.reportId)
|
|
47
|
+
throw new RecoverableToolError("The close intent has no final report. Deliver a final task_report before completing.");
|
|
48
|
+
await flush(live.desk, live.deskDir);
|
|
49
|
+
if (!taskReportDelivered(await readTaskLog(live.deskDir, live.taskId, { strict: true }), close.reportId)) {
|
|
50
|
+
await dispose(live);
|
|
51
|
+
return next;
|
|
52
|
+
}
|
|
53
|
+
const pending = (await listPendingWork(ctx.options, live.desk, ctx.now())).get(live.taskId) ?? [];
|
|
54
|
+
if (pending.length > 0)
|
|
55
|
+
throw new RecoverableToolError("Task still has work in flight; stop that work before retrying completion.");
|
|
56
|
+
}
|
|
57
|
+
if (close.outcome === "cancel")
|
|
58
|
+
await cancelWork(live.desk, live.taskId);
|
|
59
|
+
const closed = await closeTask(live.deskDir, live.taskId, {
|
|
60
|
+
outcome: close.outcome,
|
|
61
|
+
by: "leader",
|
|
62
|
+
note: close.note,
|
|
63
|
+
reportId: close.reportId,
|
|
64
|
+
receipt: (document, closedAt) => close.outcome === "complete"
|
|
65
|
+
? completedReceipt(live.taskId, title, document, closedAt)
|
|
66
|
+
: cancelledByLeaderReceipt(live.taskId, title, close.note),
|
|
67
|
+
});
|
|
68
|
+
if (!closed) {
|
|
69
|
+
await dispose(live);
|
|
70
|
+
return next;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
log.logWarn("tasks.task.close_failed", "Closing a task failed", {
|
|
75
|
+
channelId: live.channelId,
|
|
76
|
+
reason: errorMessage(error),
|
|
77
|
+
fields: { taskId: live.taskId, desk: live.desk },
|
|
78
|
+
});
|
|
79
|
+
if (isTaskArchiving(live.deskDir, live.taskId)) {
|
|
80
|
+
noteHorizon(ctx.now() + 60_000);
|
|
81
|
+
await dispose(live);
|
|
82
|
+
return next;
|
|
83
|
+
}
|
|
84
|
+
if (error instanceof RecoverableToolError &&
|
|
85
|
+
!(await readTaskLog(live.deskDir, live.taskId)).some((record) => record.kind === "close")) {
|
|
86
|
+
await appendTaskLog(live.deskDir, live.taskId, { kind: "close_rejected", reason: errorMessage(error) });
|
|
87
|
+
await dispose(live);
|
|
88
|
+
ctx.notify();
|
|
89
|
+
return next;
|
|
90
|
+
}
|
|
91
|
+
await pauseTask(live.deskDir, live.taskId, {
|
|
92
|
+
by: "runtime",
|
|
93
|
+
reason: "任务归档或取消未完成,请联系部署者检查服务器后重试关闭",
|
|
94
|
+
});
|
|
95
|
+
await dispose(live);
|
|
96
|
+
await say(live, `⚠️ 任务 \`${live.taskId}\` 未能关闭,已暂停。请联系部署者检查服务器,再发送消息重试关闭。`);
|
|
97
|
+
return next;
|
|
98
|
+
}
|
|
99
|
+
await dispose(live);
|
|
100
|
+
await flush(live.desk, live.deskDir);
|
|
101
|
+
return next;
|
|
102
|
+
}
|