@oyasmi/pipiclaw 0.9.2-beta.6 → 0.9.3-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +250 -0
- package/README.md +2 -0
- package/dist/agent/channel-runner.d.ts +43 -2
- package/dist/agent/channel-runner.js +135 -75
- package/dist/agent/job-manager.d.ts +76 -21
- package/dist/agent/job-manager.js +447 -63
- package/dist/agent/maintenance-context.js +4 -5
- package/dist/agent/prompt/manifest.d.ts +0 -2
- package/dist/agent/prompt/manifest.js +2 -3
- package/dist/agent/prompt/sections.js +3 -3
- package/dist/agent/session-events.js +4 -8
- package/dist/agent/turn-prompt.d.ts +7 -7
- package/dist/agent/turn-prompt.js +6 -9
- package/dist/agent/types.d.ts +12 -0
- package/dist/agent/types.js +1 -0
- package/dist/channel/channel-context.d.ts +13 -0
- package/dist/channel/channel-context.js +21 -1
- package/dist/commands/catalog.js +47 -20
- package/dist/memory/commands.d.ts +8 -0
- package/dist/memory/commands.js +113 -148
- package/dist/memory/index-budget.d.ts +27 -0
- package/dist/memory/index-budget.js +99 -0
- package/dist/memory/journal.d.ts +20 -0
- package/dist/memory/journal.js +78 -0
- package/dist/memory/lifecycle.d.ts +9 -15
- package/dist/memory/lifecycle.js +55 -145
- package/dist/memory/maintenance-gates.d.ts +13 -47
- package/dist/memory/maintenance-gates.js +13 -92
- package/dist/memory/maintenance-state.d.ts +10 -16
- package/dist/memory/maintenance-state.js +12 -59
- package/dist/memory/maintenance-tuning.d.ts +7 -27
- package/dist/memory/maintenance-tuning.js +11 -28
- package/dist/memory/migrate.d.ts +15 -0
- package/dist/memory/migrate.js +364 -0
- package/dist/memory/reflect-job.d.ts +43 -0
- package/dist/memory/reflect-job.js +117 -0
- package/dist/memory/reflect.d.ts +52 -0
- package/dist/memory/reflect.js +313 -0
- package/dist/memory/render.d.ts +14 -0
- package/dist/memory/render.js +28 -0
- package/dist/memory/review-log.d.ts +2 -1
- package/dist/memory/scheduler.d.ts +2 -3
- package/dist/memory/scheduler.js +14 -49
- package/dist/memory/search.d.ts +35 -0
- package/dist/memory/search.js +297 -0
- package/dist/memory/session-search.js +1 -1
- package/dist/memory/store.d.ts +108 -0
- package/dist/memory/store.js +418 -0
- package/dist/memory/task-digest.d.ts +2 -2
- package/dist/memory/task-digest.js +29 -36
- package/dist/memory/tombstones.d.ts +0 -11
- package/dist/memory/tombstones.js +6 -37
- package/dist/playbooks/agent-delegation.md +4 -2
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/event-scheduling.md +6 -2
- package/dist/playbooks/memory-and-learning.md +18 -11
- package/dist/playbooks/outbound-media.md +1 -1
- package/dist/playbooks/runtime-orientation.md +9 -8
- package/dist/playbooks/task-loop.md +88 -0
- package/dist/runtime/bootstrap.d.ts +3 -3
- package/dist/runtime/bootstrap.js +66 -41
- package/dist/runtime/events.d.ts +9 -0
- package/dist/runtime/events.js +43 -4
- package/dist/runtime/task-commands.d.ts +14 -15
- package/dist/runtime/task-commands.js +249 -485
- package/dist/runtime/task-driver.d.ts +41 -29
- package/dist/runtime/task-driver.js +170 -317
- package/dist/runtime/task-migration.d.ts +34 -30
- package/dist/runtime/task-migration.js +229 -183
- package/dist/runtime/task-wake.d.ts +6 -3
- package/dist/runtime/task-wake.js +26 -19
- package/dist/settings.d.ts +0 -29
- package/dist/settings.js +12 -35
- package/dist/shared/markdown-sections.d.ts +0 -1
- package/dist/shared/markdown-sections.js +0 -3
- package/dist/subagents/discovery.d.ts +2 -2
- package/dist/subagents/discovery.js +21 -10
- package/dist/subagents/external/progress-tail.js +6 -1
- package/dist/subagents/external/run.js +1 -0
- package/dist/subagents/runs.d.ts +19 -2
- package/dist/subagents/runs.js +73 -4
- package/dist/subagents/tool.d.ts +10 -8
- package/dist/subagents/tool.js +55 -94
- package/dist/tasks/brief.d.ts +17 -0
- package/dist/tasks/brief.js +57 -0
- package/dist/tasks/budget.d.ts +26 -0
- package/dist/tasks/budget.js +59 -0
- package/dist/tasks/cycle.d.ts +48 -0
- package/dist/tasks/cycle.js +94 -0
- package/dist/tasks/frontmatter.d.ts +73 -0
- package/dist/tasks/frontmatter.js +175 -0
- package/dist/tasks/ledger.d.ts +66 -106
- package/dist/tasks/ledger.js +90 -546
- package/dist/tasks/log.d.ts +88 -0
- package/dist/tasks/log.js +97 -0
- package/dist/tasks/rounds.d.ts +43 -0
- package/dist/tasks/rounds.js +57 -0
- package/dist/tasks/session-path.d.ts +9 -0
- package/dist/tasks/session-path.js +16 -0
- package/dist/tasks/steer.d.ts +8 -0
- package/dist/tasks/steer.js +79 -0
- package/dist/tasks/store.d.ts +60 -35
- package/dist/tasks/store.js +166 -107
- package/dist/tasks/ticket.d.ts +102 -0
- package/dist/tasks/ticket.js +209 -0
- package/dist/tasks/verification.d.ts +16 -0
- package/dist/tasks/verification.js +40 -1
- package/dist/tools/index.d.ts +13 -4
- package/dist/tools/index.js +5 -10
- package/dist/tools/memory-manage.d.ts +6 -16
- package/dist/tools/memory-manage.js +108 -129
- package/dist/tools/presentation.js +2 -1
- package/dist/tools/registry.d.ts +11 -2
- package/dist/tools/registry.js +17 -6
- package/dist/tools/subagent-manage.d.ts +0 -9
- package/dist/tools/subagent-manage.js +8 -17
- package/dist/tools/task-manage/create.js +2 -2
- package/dist/tools/task-manage/lifecycle.d.ts +9 -4
- package/dist/tools/task-manage/lifecycle.js +139 -187
- package/dist/tools/task-manage/log-view.d.ts +8 -0
- package/dist/tools/task-manage/log-view.js +24 -0
- package/dist/tools/task-manage/schema.d.ts +38 -14
- package/dist/tools/task-manage/schema.js +46 -27
- package/dist/tools/task-manage/shared.d.ts +24 -31
- package/dist/tools/task-manage/shared.js +103 -141
- package/dist/tools/task-manage/step-end.d.ts +11 -0
- package/dist/tools/task-manage/step-end.js +136 -0
- package/dist/tools/task-manage/types.d.ts +23 -32
- package/dist/tools/task-manage.d.ts +4 -3
- package/dist/tools/task-manage.js +30 -15
- package/dist/tools/tool-details.d.ts +1 -1
- package/dist/tui/app.js +0 -2
- package/package.json +1 -1
- package/dist/agent/effect-ledger.d.ts +0 -32
- package/dist/agent/effect-ledger.js +0 -89
- package/dist/memory/bootstrap.d.ts +0 -17
- package/dist/memory/bootstrap.js +0 -120
- package/dist/memory/candidates.d.ts +0 -26
- package/dist/memory/candidates.js +0 -202
- package/dist/memory/consolidation.d.ts +0 -54
- package/dist/memory/consolidation.js +0 -292
- package/dist/memory/extraction.d.ts +0 -54
- package/dist/memory/extraction.js +0 -240
- package/dist/memory/files.d.ts +0 -71
- package/dist/memory/files.js +0 -419
- package/dist/memory/maintenance-jobs.d.ts +0 -41
- package/dist/memory/maintenance-jobs.js +0 -265
- package/dist/memory/metadata.d.ts +0 -57
- package/dist/memory/metadata.js +0 -142
- package/dist/memory/probation.d.ts +0 -17
- package/dist/memory/probation.js +0 -44
- package/dist/memory/promotion.d.ts +0 -38
- package/dist/memory/promotion.js +0 -36
- package/dist/memory/recall.d.ts +0 -59
- package/dist/memory/recall.js +0 -746
- package/dist/memory/session.d.ts +0 -24
- package/dist/memory/session.js +0 -273
- package/dist/playbooks/task-driving.md +0 -92
- package/dist/playbooks/task-planning.md +0 -58
- package/dist/tasks/control.d.ts +0 -56
- package/dist/tasks/control.js +0 -169
- package/dist/tasks/transitions.d.ts +0 -16
- package/dist/tasks/transitions.js +0 -48
- package/dist/tools/task-manage/verification.d.ts +0 -19
- package/dist/tools/task-manage/verification.js +0 -91
|
@@ -4,22 +4,17 @@ import { discoverWorkspaceChannelIds } from "../channel/channel-index.js";
|
|
|
4
4
|
import { dedupeChannelIdsByDirectory, getChannelDir, isChannelId } from "../channel/channel-paths.js";
|
|
5
5
|
import * as log from "../log.js";
|
|
6
6
|
import { PLAYBOOKS_DIR } from "../paths.js";
|
|
7
|
-
import { parseLocalTime } from "../shared/local-time.js";
|
|
8
7
|
import { errorMessage } from "../shared/text-utils.js";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
8
|
+
import { checkBudget, IDLE_STEP_LIMIT } from "../tasks/budget.js";
|
|
9
|
+
import { readActiveTasks } from "../tasks/ledger.js";
|
|
10
|
+
import { readTaskLog } from "../tasks/log.js";
|
|
11
|
+
import { expireTicket, openCycle, pauseTask, redeemTicket } from "../tasks/store.js";
|
|
13
12
|
/** Short debounce so a burst of nudges collapses into a single rescan. */
|
|
14
13
|
const NUDGE_DEBOUNCE_MS = 50;
|
|
15
14
|
/** Never schedule a scan closer than this, so near-now horizons cannot spin the loop. */
|
|
16
15
|
const MIN_SLEEP_MS = 250;
|
|
17
|
-
/**
|
|
18
|
-
const
|
|
19
|
-
/** Wakes-per-cycle ceiling: a deliberately generous circuit breaker, not a normal governance
|
|
20
|
-
* path (deadline and futileCount are). Guards only against a task that keeps "progressing"
|
|
21
|
-
* without ever converging or hitting its deadline. */
|
|
22
|
-
const MAX_WAKES_PER_CYCLE = 500;
|
|
16
|
+
/** A task dispatched this recently is assumed still in flight; do not queue it twice. */
|
|
17
|
+
const REDISPATCH_GUARD_MS = 30_000;
|
|
23
18
|
/**
|
|
24
19
|
* Channels this driver should scan. Live ids come first so a channel discovered on disk under
|
|
25
20
|
* its escaped directory name never displaces the real id the runner map already knows.
|
|
@@ -33,158 +28,83 @@ export async function discoverTaskChannels(workspaceDir, knownChannelIds = []) {
|
|
|
33
28
|
function attemptKey(channelId, taskId) {
|
|
34
29
|
return `${channelId}\0${taskId}`;
|
|
35
30
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
* progress, or governed tasks would retry at the short continuation interval forever.
|
|
41
|
-
*
|
|
42
|
-
* `latestNote` is deliberately absent (spec 031, D7): it is the model's own account of its work,
|
|
43
|
-
* so including it let a wake that did nothing but append a note reset the futile counter forever,
|
|
44
|
-
* and let a wake that changed real files count as stalled. The task's own effect tally stands in
|
|
45
|
-
* for the work itself instead — per task, not per channel, so a neighbour's activity (including
|
|
46
|
-
* the user chatting) neither certifies progress here nor hides a task that is spinning.
|
|
47
|
-
*
|
|
48
|
-
* `entry.plan` is absent for the same reason (spec 037, D5): checking off a Plan step is a
|
|
49
|
-
* model-reported claim, not evidence of an effect. If plan state fed the fingerprint, ticking a
|
|
50
|
-
* checkbox would reset the futile counter and buy the short retry tier — a governor bypass this
|
|
51
|
-
* driver must not offer. The Plan is a capsule/agenda display concern only.
|
|
52
|
-
*
|
|
53
|
-
* nextAction is also a model-written explanation, not evidence of an effect. Including it would
|
|
54
|
-
* let a progress/set call reset the futile counter without changing the task's externally
|
|
55
|
-
* observable work.
|
|
56
|
-
*/
|
|
57
|
-
function taskFingerprint(entry, effects) {
|
|
58
|
-
const control = entry.frontmatter.control;
|
|
59
|
-
return [
|
|
60
|
-
entry.frontmatter.readable ? "readable" : "unreadable",
|
|
61
|
-
entry.frontmatter.status ?? "",
|
|
62
|
-
entry.frontmatter.wake ?? "",
|
|
63
|
-
entry.frontmatter.schedule ?? "",
|
|
64
|
-
control?.verification.status ?? "",
|
|
65
|
-
control?.waitingFor ?? "",
|
|
66
|
-
entry.frontmatter.enabled === false ? "disabled" : "enabled",
|
|
67
|
-
control?.stop?.reason ?? "",
|
|
68
|
-
control?.cycleId ?? "",
|
|
69
|
-
`effects:${effects}`,
|
|
70
|
-
].join("\0");
|
|
31
|
+
function channelType(channelId) {
|
|
32
|
+
return channelId.startsWith("group_")
|
|
33
|
+
? { type: "group", conversationType: "2" }
|
|
34
|
+
: { type: "dm", conversationType: "1" };
|
|
71
35
|
}
|
|
72
36
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
* the ledger — including one that wrote code — waited out the same continuation delay as one that
|
|
77
|
-
* only edited a note. A twenty-step task therefore spent well over an hour purely idle, which is
|
|
78
|
-
* fatal for the "drive an external agent in small steps" shape this driver exists for.
|
|
79
|
-
*
|
|
80
|
-
* So the tiers are keyed on evidence, not on the boolean "something changed":
|
|
81
|
-
* - this task's effect tally grew ⇒ its last wake actually did something ⇒ continue at once;
|
|
82
|
-
* - the ledger changed with no effect (status/note churn) ⇒ the ordinary continuation delay;
|
|
83
|
-
* - nothing changed ⇒ the long stalled-retry backoff, and the futile counter keeps running.
|
|
84
|
-
*
|
|
85
|
-
* Nothing here relaxes the stop-losses: the fast tier still counts toward `MAX_WAKES_PER_CYCLE`
|
|
86
|
-
* and the futile-wake limit, so a task that spins productively-looking still hits the governor —
|
|
87
|
-
* just sooner in wall time instead of an hour per step.
|
|
37
|
+
* Stable, provenance-derived dispatch id for a task step (spec 031, D1; spec 051 keeps the shape).
|
|
38
|
+
* A step inside a cycle is genuinely new work each time, so the dispatch moment disambiguates it;
|
|
39
|
+
* collapsing two steps onto one durable record would silently drop the later one.
|
|
88
40
|
*/
|
|
89
|
-
function
|
|
90
|
-
|
|
91
|
-
if (!attempt.accepted)
|
|
92
|
-
return settings.continuationDelayMinutes * 60_000;
|
|
93
|
-
if (attempt.fingerprint === fingerprint)
|
|
94
|
-
return settings.stalledRetryMinutes * 60_000;
|
|
95
|
-
if (effects > attempt.effects)
|
|
96
|
-
return 0;
|
|
97
|
-
return settings.continuationDelayMinutes * 60_000;
|
|
98
|
-
}
|
|
99
|
-
function isEligible(attempt, fingerprint, effects, nowMs, settings) {
|
|
100
|
-
if (!attempt)
|
|
101
|
-
return true;
|
|
102
|
-
return nowMs - attempt.atMs >= attemptDelayMs(attempt, fingerprint, effects, settings);
|
|
103
|
-
}
|
|
104
|
-
/**
|
|
105
|
-
* Stable, provenance-derived dispatch id for a task wake (spec 031, D1).
|
|
106
|
-
*
|
|
107
|
-
* A scheduled task has a real occurrence — its `wake` — so retries of that occurrence collapse
|
|
108
|
-
* onto one durable record. A task that is simply actionable has no occurrence identity, so the
|
|
109
|
-
* dispatch time is used: two separate wakes of the same task are genuinely separate work, and
|
|
110
|
-
* collapsing them would silently drop the later one.
|
|
111
|
-
*/
|
|
112
|
-
function taskDispatchId(channelId, entry, nowMs) {
|
|
113
|
-
const occurrence = entry.frontmatter.control?.cycleId ?? entry.frontmatter.wake ?? `t${nowMs}`;
|
|
114
|
-
return `task:${channelId}:${entry.id}:${occurrence}`;
|
|
41
|
+
function stepDispatchId(channelId, entry, nowMs) {
|
|
42
|
+
return `task:${channelId}:${entry.id}:${entry.fields.cycle?.id ?? "-"}:${nowMs}`;
|
|
115
43
|
}
|
|
116
44
|
export function createTaskDriverEvent(channelId, entry, nowMs) {
|
|
117
|
-
const repairOnly = !entry.
|
|
45
|
+
const repairOnly = !entry.readable || entry.legacy;
|
|
118
46
|
const repair = repairOnly
|
|
119
|
-
? ` Task metadata is not readable; repair only the frontmatter
|
|
120
|
-
`Do not execute the task goal or any external action. Read ${join(PLAYBOOKS_DIR, "task-
|
|
47
|
+
? ` Task metadata is not readable; repair only the frontmatter in tasks/${entry.id}.md, then stop. ` +
|
|
48
|
+
`Do not execute the task goal or any external action. Read ${join(PLAYBOOKS_DIR, "task-loop.md")} for the repair path.`
|
|
121
49
|
: "";
|
|
122
|
-
const control = entry.frontmatter.control;
|
|
123
50
|
const capsule = [
|
|
124
|
-
`Task capsule: title=${entry.title};
|
|
125
|
-
|
|
126
|
-
// model no longer has to re-derive "what step am I on" from latestNote/nextAction each wake.
|
|
51
|
+
`Task capsule: title=${entry.title}; state=${entry.fields.state};`,
|
|
52
|
+
entry.fields.cycle ? `cycle=${entry.fields.cycle.id} (${entry.fields.cycle.steps} steps);` : "",
|
|
127
53
|
entry.plan
|
|
128
54
|
? `plan=${entry.plan.done}/${entry.plan.total} done, current=${entry.plan.current?.id ?? "none"};`
|
|
129
55
|
: "",
|
|
130
|
-
entry.latestNote ? `latest=${entry.latestNote};` : "",
|
|
131
|
-
control?.nextAction ? `next=${control.nextAction};` : "",
|
|
132
56
|
]
|
|
133
57
|
.filter(Boolean)
|
|
134
58
|
.join(" ");
|
|
135
59
|
return {
|
|
136
|
-
|
|
60
|
+
...channelType(channelId),
|
|
137
61
|
channelId,
|
|
138
62
|
user: "TASK_DRIVER",
|
|
139
63
|
userName: "TASK_DRIVER",
|
|
140
64
|
text: `[TASK_DRIVER:${entry.id}] Resume task ${entry.id}. ${capsule}${repair} ` +
|
|
141
|
-
`Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-
|
|
65
|
+
`Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-loop.md")} before acting. ` +
|
|
142
66
|
(repairOnly
|
|
143
|
-
? "After the metadata is repaired, leave task work for a later
|
|
144
|
-
: "Advance the next concrete step under the task's current goal,
|
|
145
|
-
|
|
146
|
-
"For a recurring occurrence intentionally not run because it is duplicate or already satisfied, call task_close outcome=skip with the reason, then respond with exactly [SILENT]. " +
|
|
147
|
-
"If no task state or tool action is needed and this wake produces no user-visible result, respond with exactly [SILENT].",
|
|
67
|
+
? "After the metadata is repaired, leave task work for a later step. "
|
|
68
|
+
: "Advance the next concrete step under the task's current goal, plan and acceptance state. ") +
|
|
69
|
+
"End the step with task_step_end (continue / park / done / blocked).",
|
|
148
70
|
ts: String(nowMs),
|
|
149
|
-
|
|
150
|
-
dispatchId: taskDispatchId(channelId, entry, nowMs),
|
|
71
|
+
dispatchId: stepDispatchId(channelId, entry, nowMs),
|
|
151
72
|
};
|
|
152
73
|
}
|
|
153
|
-
/**
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
entry.wakeMs <= nowMs);
|
|
160
|
-
}
|
|
161
|
-
/** sleeping + schedule but no parseable wake → self-heal target (recompute wake, zero token). */
|
|
162
|
-
function needsWakeHeal(entry) {
|
|
163
|
-
return entry.frontmatter.status === "sleeping" && Boolean(entry.frontmatter.schedule) && entry.wakeMs === undefined;
|
|
164
|
-
}
|
|
165
|
-
export function taskGovernorReceipt(channelId, entry, reason, nowMs) {
|
|
74
|
+
/**
|
|
75
|
+
* The deterministic receipt a runtime stop produces (spec 051, D11). It is delivered directly,
|
|
76
|
+
* without opening a model turn: the user needs to know their task stopped, and spending an LLM
|
|
77
|
+
* call to phrase that is exactly the kind of cost this design removes.
|
|
78
|
+
*/
|
|
79
|
+
export function taskStopReceipt(channelId, entry, reason, nowMs) {
|
|
166
80
|
return {
|
|
167
|
-
|
|
81
|
+
...channelType(channelId),
|
|
168
82
|
channelId,
|
|
169
83
|
user: "TASK_DRIVER",
|
|
170
84
|
userName: "TASK_DRIVER",
|
|
171
85
|
text: `任务 ${entry.id}(${entry.title})已停止自动执行:${reason}\n` +
|
|
172
|
-
`当前阶段:${entry.
|
|
173
|
-
|
|
86
|
+
`当前阶段:${entry.fields.state}${entry.fields.cycle ? `;周期:${entry.fields.cycle.id}` : ""}\n` +
|
|
87
|
+
`查看:/tasks show ${entry.id}\n继续:/tasks resume ${entry.id}\n不再需要:让 Agent cancel 该任务。`,
|
|
174
88
|
ts: String(nowMs),
|
|
175
|
-
|
|
176
|
-
//
|
|
177
|
-
|
|
178
|
-
dispatchId: `task:${channelId}:${entry.id}:escalation:${createHash("sha256").update(reason).digest("hex").slice(0, 12)}`,
|
|
89
|
+
// Keyed on the cause, not the moment: re-detecting the same stop before the user has acted
|
|
90
|
+
// must not queue a second identical receipt, while a different cause still does.
|
|
91
|
+
dispatchId: `task:${channelId}:${entry.id}:stop:${createHash("sha256").update(reason).digest("hex").slice(0, 12)}`,
|
|
179
92
|
};
|
|
180
93
|
}
|
|
181
94
|
/**
|
|
182
|
-
* Native,
|
|
95
|
+
* Native, ticket-driven scheduler for the persistent task ledger (spec 051, D9).
|
|
96
|
+
*
|
|
97
|
+
* Four jobs, in this order per channel: redeem due `time`/`schedule` tickets, apply the backstop
|
|
98
|
+
* to expired ones, open cycles for recurring tasks, and queue one step for a runnable task.
|
|
99
|
+
* `run`/`job`/`ask`/`signal` tickets are never polled — their owners push them — so the scan
|
|
100
|
+
* stays a cheap read of a handful of frontmatters.
|
|
183
101
|
*
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
102
|
+
* What is deliberately *not* here any more: the ten-field ledger fingerprint, the process-local
|
|
103
|
+
* effect ledger, the futile-wake and wake-per-cycle counters, and the three-tier backoff table.
|
|
104
|
+
* They existed to guess whether a wake had accomplished anything; in production they fired twice
|
|
105
|
+
* in four months while the failure that actually happened — a task parked with no redeemable
|
|
106
|
+
* source, silent for 13 days — was invisible to all of them. Stopping is now the loop's own job
|
|
107
|
+
* (a budget it can see) and liveness is the ticket's (a backstop the runtime enforces).
|
|
188
108
|
*/
|
|
189
109
|
export class TaskDriver {
|
|
190
110
|
constructor(options) {
|
|
@@ -194,14 +114,12 @@ export class TaskDriver {
|
|
|
194
114
|
this.loopActive = false;
|
|
195
115
|
this.running = false;
|
|
196
116
|
this.nextChannelIndex = 0;
|
|
197
|
-
|
|
117
|
+
/** Last dispatch time per task, so one in-flight step is not queued again on the next tick. */
|
|
118
|
+
this.lastDispatchMs = new Map();
|
|
198
119
|
/**
|
|
199
|
-
* Last task id dispatched per channel.
|
|
200
|
-
*
|
|
201
|
-
*
|
|
202
|
-
* starving every other ready task (including its own unlocked dependents) in the same
|
|
203
|
-
* channel. Remembering the last pick and starting the search just after it gives ready
|
|
204
|
-
* candidates in a channel the same round-robin fairness across ticks.
|
|
120
|
+
* Last task id dispatched per channel. Starting the search just after it gives every ready
|
|
121
|
+
* task in a channel the same round-robin fairness an actively-progressing task would
|
|
122
|
+
* otherwise monopolise.
|
|
205
123
|
*/
|
|
206
124
|
this.lastDispatchedTaskId = new Map();
|
|
207
125
|
}
|
|
@@ -232,9 +150,9 @@ export class TaskDriver {
|
|
|
232
150
|
}
|
|
233
151
|
}
|
|
234
152
|
/**
|
|
235
|
-
* In-process wake: after a
|
|
236
|
-
*
|
|
237
|
-
*
|
|
153
|
+
* In-process wake: after a step ends or a task file is written, re-scan promptly instead of
|
|
154
|
+
* waiting out the current sleep. This is what makes `outcome: continue` cost nothing — the
|
|
155
|
+
* next step is queued on the same nudge rather than after a continuation delay.
|
|
238
156
|
*/
|
|
239
157
|
nudge() {
|
|
240
158
|
if (!this.loopActive || this.nudgeTimer)
|
|
@@ -278,36 +196,91 @@ export class TaskDriver {
|
|
|
278
196
|
if (this.nextWakeMs === undefined || candidate < this.nextWakeMs)
|
|
279
197
|
this.nextWakeMs = candidate;
|
|
280
198
|
}
|
|
281
|
-
|
|
199
|
+
/** Stop one task and notify. Delivery failure is logged, never fatal: the durable stop already happened. */
|
|
200
|
+
async notifyStop(channelId, entry, reason, nowMs) {
|
|
201
|
+
try {
|
|
202
|
+
await this.options.notify?.(taskStopReceipt(channelId, entry, reason, nowMs));
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
log.logWarning(`[${channelId}] Task stop receipt failed`, errorMessage(error));
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Deterministic, zero-token maintenance for one channel: redeem due tickets, apply expiry
|
|
210
|
+
* backstops, open recurring cycles. Runs whether or not the channel is busy — only model
|
|
211
|
+
* dispatch is gated on an idle channel.
|
|
212
|
+
*/
|
|
213
|
+
async maintain(channelDir, channelId, entries, now) {
|
|
214
|
+
const nowMs = now.getTime();
|
|
215
|
+
let changed = false;
|
|
282
216
|
for (const entry of entries) {
|
|
283
|
-
if (entry.
|
|
284
|
-
|
|
285
|
-
const
|
|
286
|
-
if (
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
217
|
+
if (entry.fields.paused || entry.fields.state !== "parked")
|
|
218
|
+
continue;
|
|
219
|
+
const ticket = entry.fields.ticket;
|
|
220
|
+
if (!ticket)
|
|
221
|
+
continue;
|
|
222
|
+
// A due timer redeems into an open task; a due schedule opens the next cycle outright.
|
|
223
|
+
if (entry.dueMs !== undefined && entry.dueMs <= nowMs) {
|
|
224
|
+
if (ticket.kind === "schedule") {
|
|
225
|
+
const opened = await openCycle(channelDir, entry.id, now).catch((error) => {
|
|
226
|
+
log.logWarning(`[${channelId}] Could not open next cycle for ${entry.id}`, errorMessage(error));
|
|
227
|
+
return undefined;
|
|
228
|
+
});
|
|
229
|
+
if (opened) {
|
|
230
|
+
changed = true;
|
|
231
|
+
log.logInfo(`[${channelId}] Task driver opened cycle ${opened.cycleId} for ${entry.id}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
else if (await redeemTicket(channelDir, entry.id, (current) => current.kind === ticket.kind)) {
|
|
235
|
+
changed = true;
|
|
236
|
+
}
|
|
237
|
+
continue;
|
|
291
238
|
}
|
|
239
|
+
if (entry.expired) {
|
|
240
|
+
const expiry = await expireTicket(channelDir, entry.id);
|
|
241
|
+
if (!expiry)
|
|
242
|
+
continue;
|
|
243
|
+
changed = true;
|
|
244
|
+
if (expiry.outcome === "paused") {
|
|
245
|
+
log.logWarning(`[${channelId}] Task ${entry.id} paused: ticket expired twice`, expiry.ticket);
|
|
246
|
+
await this.notifyStop(channelId, entry, `等待未兑现(${expiry.ticket}),已连续两次超过兜底时限`, nowMs);
|
|
247
|
+
}
|
|
248
|
+
else {
|
|
249
|
+
log.logInfo(`[${channelId}] Task ${entry.id} reopened after its ticket expired`, expiry.ticket);
|
|
250
|
+
}
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
this.noteHorizon(entry.dueMs, nowMs);
|
|
254
|
+
this.noteHorizon(new Date(ticket.by).getTime(), nowMs);
|
|
292
255
|
}
|
|
256
|
+
return changed;
|
|
293
257
|
}
|
|
294
258
|
/**
|
|
295
|
-
*
|
|
296
|
-
*
|
|
297
|
-
*
|
|
298
|
-
*
|
|
259
|
+
* Stop a loop that is talking to itself: two consecutive steps that produced no tool call at
|
|
260
|
+
* all. This is the honest replacement for v3's futile-wake counter — the loop log records what
|
|
261
|
+
* each step actually did, so "no progress" is an observed fact rather than a fingerprint
|
|
262
|
+
* comparison a `echo x` could defeat.
|
|
299
263
|
*/
|
|
300
|
-
async
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
264
|
+
async detectIdleLoop(channelDir, channelId, entries, nowMs) {
|
|
265
|
+
let paused = false;
|
|
266
|
+
for (const entry of entries) {
|
|
267
|
+
const cycle = entry.fields.cycle;
|
|
268
|
+
if (!cycle || cycle.steps < IDLE_STEP_LIMIT)
|
|
269
|
+
continue;
|
|
270
|
+
const steps = (await readTaskLog(channelDir, entry.id, { cycle: cycle.id, kinds: ["step"] })).slice(-IDLE_STEP_LIMIT);
|
|
271
|
+
if (steps.length < IDLE_STEP_LIMIT)
|
|
272
|
+
continue;
|
|
273
|
+
const idle = steps.every((record) => record.kind === "step" && record.tools.length === 0);
|
|
274
|
+
if (!idle)
|
|
275
|
+
continue;
|
|
276
|
+
const reason = `连续 ${IDLE_STEP_LIMIT} 步没有任何工具调用,循环已停下等你确认`;
|
|
277
|
+
if (await pauseTask(channelDir, entry.id, { by: "runtime", reason })) {
|
|
278
|
+
paused = true;
|
|
279
|
+
log.logWarning(`[${channelId}] Task ${entry.id} paused: idle loop`, reason);
|
|
280
|
+
await this.notifyStop(channelId, entry, reason, nowMs);
|
|
281
|
+
}
|
|
309
282
|
}
|
|
310
|
-
return
|
|
283
|
+
return paused;
|
|
311
284
|
}
|
|
312
285
|
async runOnce(now = new Date()) {
|
|
313
286
|
if (this.options.isEnabled?.() === false || this.running)
|
|
@@ -319,7 +292,7 @@ export class TaskDriver {
|
|
|
319
292
|
try {
|
|
320
293
|
const channels = await discoverTaskChannels(this.options.workspaceDir, this.options.getKnownChannelIds?.());
|
|
321
294
|
if (channels.length === 0) {
|
|
322
|
-
this.
|
|
295
|
+
this.lastDispatchMs.clear();
|
|
323
296
|
return;
|
|
324
297
|
}
|
|
325
298
|
const seen = new Set();
|
|
@@ -336,166 +309,56 @@ export class TaskDriver {
|
|
|
336
309
|
let entries = await readActiveTasks(join(channelDir, "tasks"), nowMs);
|
|
337
310
|
for (const entry of entries)
|
|
338
311
|
seen.add(attemptKey(channelId, entry.id));
|
|
339
|
-
this.
|
|
340
|
-
|
|
341
|
-
if (entry.frontmatter.enabled !== false &&
|
|
342
|
-
recurringTaskMissedOccurrence({
|
|
343
|
-
status: entry.frontmatter.status ?? "active",
|
|
344
|
-
schedule: entry.frontmatter.schedule,
|
|
345
|
-
control: entry.frontmatter.control,
|
|
346
|
-
}, now)) {
|
|
347
|
-
log.logWarning(`[${channelId}] Task ${entry.id} has a missed recurring occurrence; keeping the current cycle open`);
|
|
348
|
-
}
|
|
312
|
+
if (await this.maintain(channelDir, channelId, entries, now)) {
|
|
313
|
+
entries = await readActiveTasks(join(channelDir, "tasks"), nowMs);
|
|
349
314
|
}
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
//
|
|
315
|
+
if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
|
|
316
|
+
continue;
|
|
317
|
+
// A task that has already run out of budget must not spend one more model call to
|
|
318
|
+
// discover that (D6). Checked before dispatch, and paired with a receipt so the user
|
|
319
|
+
// learns why it stopped and what to type to give it more rope.
|
|
320
|
+
const budgeted = [];
|
|
353
321
|
for (const entry of entries) {
|
|
354
|
-
if (entry.
|
|
322
|
+
if (!entry.runnable)
|
|
355
323
|
continue;
|
|
356
|
-
|
|
357
|
-
|
|
324
|
+
const status = checkBudget(entry.fields, now);
|
|
325
|
+
if (!status.breach || !status.reason) {
|
|
326
|
+
budgeted.push(entry);
|
|
358
327
|
continue;
|
|
359
328
|
}
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
await this.
|
|
363
|
-
continue;
|
|
329
|
+
if (await pauseTask(channelDir, entry.id, { by: "runtime", reason: status.reason })) {
|
|
330
|
+
log.logWarning(`[${channelId}] Task ${entry.id} paused: budget ${status.breach}`, status.reason);
|
|
331
|
+
await this.notifyStop(channelId, entry, status.reason, nowMs);
|
|
364
332
|
}
|
|
365
|
-
if (!needsWakeHeal(entry))
|
|
366
|
-
continue;
|
|
367
|
-
let healedWake;
|
|
368
|
-
await updateStoredTask(channelDir, entry.id, (task) => {
|
|
369
|
-
healedWake = normalizeTaskFields(task.fields, now).wake;
|
|
370
|
-
task.fields.wake = healedWake;
|
|
371
|
-
});
|
|
372
|
-
if (!healedWake) {
|
|
373
|
-
log.logWarning(`[${channelId}] Task ${entry.id} has an unparseable schedule`, entry.frontmatter.schedule);
|
|
374
|
-
continue;
|
|
375
|
-
}
|
|
376
|
-
this.noteHorizon(new Date(healedWake).getTime(), nowMs);
|
|
377
|
-
log.logInfo(`[${channelId}] Task driver healed wake for ${entry.id}`, healedWake);
|
|
378
333
|
}
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
continue;
|
|
385
|
-
const escalationReason = taskBudgetViolation(control, nowMs, status);
|
|
386
|
-
if (!escalationReason)
|
|
387
|
-
continue;
|
|
388
|
-
governanceHandled = true;
|
|
389
|
-
if (await this.escalateAndNotify(channelDir, channelId, candidate, escalationReason, nowMs)) {
|
|
390
|
-
log.logWarning(`[${channelId}] Task driver disabled ${candidate.id} (governor)`, escalationReason);
|
|
391
|
-
}
|
|
392
|
-
break;
|
|
393
|
-
}
|
|
394
|
-
if (governanceHandled)
|
|
395
|
-
continue;
|
|
396
|
-
// Deterministic maintenance above must not wait for an idle channel. Only model dispatch
|
|
397
|
-
// and the transitions immediately preceding it are gated by the channel's busy state.
|
|
398
|
-
if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
|
|
399
|
-
continue;
|
|
400
|
-
// Timed waits become active atomically before dispatch. Sleeping due tasks use the same
|
|
401
|
-
// runtime cycle-open path as the first occurrence.
|
|
402
|
-
let hadDueWaiting = false;
|
|
403
|
-
for (const candidate of entries) {
|
|
404
|
-
if (candidate.frontmatter.status !== "waiting" || candidate.frontmatter.enabled === false)
|
|
405
|
-
continue;
|
|
406
|
-
if (candidate.wakeMs !== undefined && candidate.wakeMs <= nowMs) {
|
|
407
|
-
hadDueWaiting = true;
|
|
408
|
-
await activateWaitingTask(channelDir, candidate.id);
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
// A failed activation means another writer won the transition (or disabled the
|
|
412
|
-
// task). Re-read before choosing a candidate so a stale waiting capsule can never
|
|
413
|
-
// be dispatched as if its atomic active transition had succeeded.
|
|
414
|
-
if (hadDueWaiting)
|
|
415
|
-
entries = await readActiveTasks(join(channelDir, "tasks"), nowMs);
|
|
416
|
-
// Actionable tasks and cycle-start-ready recurring tasks share one per-channel slot
|
|
417
|
-
// and the same round-robin fairness. A cycle-start-ready task is folded into its next
|
|
418
|
-
// cycle deterministically by the runtime (D2) and then dispatched as an ordinary wake.
|
|
419
|
-
const candidates = entries.filter((candidate) => candidate.actionable || isCycleStartReady(candidate, nowMs));
|
|
334
|
+
const idled = await this.detectIdleLoop(channelDir, channelId, budgeted, nowMs);
|
|
335
|
+
const ready = idled
|
|
336
|
+
? (await readActiveTasks(join(channelDir, "tasks"), nowMs)).filter((entry) => entry.runnable)
|
|
337
|
+
: budgeted;
|
|
338
|
+
const candidates = ready.filter((entry) => !entry.fields.paused);
|
|
420
339
|
if (candidates.length === 0)
|
|
421
340
|
continue;
|
|
422
341
|
const lastId = this.lastDispatchedTaskId.get(channelId);
|
|
423
342
|
const lastIndex = lastId ? candidates.findIndex((candidate) => candidate.id === lastId) : -1;
|
|
424
|
-
const
|
|
343
|
+
const rotated = lastIndex >= 0
|
|
425
344
|
? [...candidates.slice(lastIndex + 1), ...candidates.slice(0, lastIndex + 1)]
|
|
426
345
|
: candidates;
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
opened = await openRecurringTaskCycle(channelDir, entry.id, now);
|
|
437
|
-
}
|
|
438
|
-
catch (error) {
|
|
439
|
-
// A malformed recurring body (e.g. missing History) must not stall the whole tick.
|
|
440
|
-
log.logWarning(`[${channelId}] Task driver could not open next cycle for ${entry.id}`, errorMessage(error));
|
|
441
|
-
continue;
|
|
442
|
-
}
|
|
443
|
-
if (!opened) {
|
|
444
|
-
log.logWarning(`[${channelId}] Task driver could not open next cycle for ${entry.id}`);
|
|
445
|
-
continue;
|
|
446
|
-
}
|
|
447
|
-
// Re-read after the atomic open so the capsule contains the new Current Cycle/Plan,
|
|
448
|
-
// rather than the sleeping occurrence's just-closed note.
|
|
449
|
-
const refreshed = (await readActiveTasks(join(channelDir, "tasks"), nowMs)).find((candidate) => candidate.id === entry?.id);
|
|
450
|
-
entry = refreshed ?? {
|
|
451
|
-
...entry,
|
|
452
|
-
frontmatter: {
|
|
453
|
-
...entry.frontmatter,
|
|
454
|
-
status: "active",
|
|
455
|
-
wake: undefined,
|
|
456
|
-
control: opened.document.fields.control,
|
|
457
|
-
},
|
|
458
|
-
wakeMs: undefined,
|
|
459
|
-
actionable: true,
|
|
460
|
-
};
|
|
461
|
-
log.logInfo(`[${channelId}] Task driver opened cycle ${opened.cycleId} for ${entry.id}`);
|
|
462
|
-
}
|
|
463
|
-
const key = attemptKey(channelId, entry.id);
|
|
464
|
-
const repairOnly = !entry.frontmatter.readable || entry.frontmatter.controlReadable === false;
|
|
465
|
-
const effects = this.options.getEffectCount?.(channelId, entry.id) ?? 0;
|
|
466
|
-
const fingerprint = taskFingerprint(entry, effects);
|
|
467
|
-
const previous = this.attempts.get(key);
|
|
468
|
-
if (!isEligible(previous, fingerprint, effects, nowMs, settings))
|
|
469
|
-
continue;
|
|
470
|
-
// D5: a wake that was accepted and left the ledger fingerprint unchanged made no
|
|
471
|
-
// visible progress. Count consecutive such wakes (a changed fingerprint — including
|
|
472
|
-
// a progress note or a failure — resets the count); after the limit the governor
|
|
473
|
-
// pauses the task and notifies the user, so no silent loop burns tokens forever.
|
|
474
|
-
const futileCount = !repairOnly && previous?.accepted && previous.fingerprint === fingerprint ? previous.futileCount + 1 : 0;
|
|
475
|
-
if (futileCount >= FUTILE_WAKE_LIMIT) {
|
|
476
|
-
const reason = `task made no visible progress in ${FUTILE_WAKE_LIMIT} consecutive wakes`;
|
|
477
|
-
if (await this.escalateAndNotify(channelDir, channelId, entry, reason, nowMs)) {
|
|
478
|
-
this.attempts.delete(key);
|
|
479
|
-
this.lastDispatchedTaskId.set(channelId, entry.id);
|
|
480
|
-
log.logWarning(`[${channelId}] Task driver disabled ${entry.id} (governor)`, reason);
|
|
481
|
-
}
|
|
482
|
-
continue;
|
|
483
|
-
}
|
|
484
|
-
const cycleId = entry.frontmatter.control?.cycleId;
|
|
485
|
-
const wakeCount = !repairOnly && previous && previous.cycleId === cycleId ? previous.wakeCount + 1 : 1;
|
|
486
|
-
if (wakeCount > MAX_WAKES_PER_CYCLE) {
|
|
487
|
-
const reason = `task exceeded ${MAX_WAKES_PER_CYCLE} wakes in this cycle (runaway failsafe)`;
|
|
488
|
-
if (await this.escalateAndNotify(channelDir, channelId, entry, reason, nowMs)) {
|
|
489
|
-
this.attempts.delete(key);
|
|
490
|
-
this.lastDispatchedTaskId.set(channelId, entry.id);
|
|
491
|
-
log.logWarning(`[${channelId}] Task driver disabled ${entry.id} (governor)`, reason);
|
|
346
|
+
const entry = rotated.find((candidate) => {
|
|
347
|
+
const previous = this.lastDispatchMs.get(attemptKey(channelId, candidate.id));
|
|
348
|
+
return previous === undefined || nowMs - previous >= REDISPATCH_GUARD_MS;
|
|
349
|
+
});
|
|
350
|
+
if (!entry) {
|
|
351
|
+
for (const candidate of rotated) {
|
|
352
|
+
const previous = this.lastDispatchMs.get(attemptKey(channelId, candidate.id));
|
|
353
|
+
if (previous !== undefined)
|
|
354
|
+
this.noteHorizon(previous + REDISPATCH_GUARD_MS, nowMs);
|
|
492
355
|
}
|
|
493
356
|
continue;
|
|
494
357
|
}
|
|
495
358
|
const event = createTaskDriverEvent(channelId, entry, nowMs);
|
|
496
359
|
const accepted = await this.options.dispatch(event);
|
|
497
360
|
this.observeDispatch(event, accepted);
|
|
498
|
-
this.
|
|
361
|
+
this.lastDispatchMs.set(attemptKey(channelId, entry.id), nowMs);
|
|
499
362
|
this.lastDispatchedTaskId.set(channelId, entry.id);
|
|
500
363
|
if (accepted) {
|
|
501
364
|
dispatched++;
|
|
@@ -506,19 +369,9 @@ export class TaskDriver {
|
|
|
506
369
|
log.logWarning(`[${channelId}] Task driver could not enqueue ${entry.id}`, "channel queue unavailable");
|
|
507
370
|
}
|
|
508
371
|
}
|
|
509
|
-
for (const key of this.
|
|
372
|
+
for (const key of this.lastDispatchMs.keys()) {
|
|
510
373
|
if (!seen.has(key))
|
|
511
|
-
this.
|
|
512
|
-
}
|
|
513
|
-
// A backed-off task becomes eligible again at attempt time + its retry delay; wake then
|
|
514
|
-
// so an unchanged ledger is still retried without polling. Changed ledgers arrive via
|
|
515
|
-
// nudge. Both tiers are noted because which one applies depends on the ledger as it will
|
|
516
|
-
// be *then*: `noteHorizon` keeps whichever is next in the future, so the short tier is
|
|
517
|
-
// honored on time and the long one is still not missed.
|
|
518
|
-
for (const attempt of this.attempts.values()) {
|
|
519
|
-
this.noteHorizon(attempt.atMs + settings.continuationDelayMinutes * 60_000, nowMs);
|
|
520
|
-
if (attempt.accepted)
|
|
521
|
-
this.noteHorizon(attempt.atMs + settings.stalledRetryMinutes * 60_000, nowMs);
|
|
374
|
+
this.lastDispatchMs.delete(key);
|
|
522
375
|
}
|
|
523
376
|
const channelSet = new Set(channels);
|
|
524
377
|
for (const channelId of this.lastDispatchedTaskId.keys()) {
|