@oyasmi/pipiclaw 0.8.8 → 0.8.9-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -3
- package/dist/agent/channel-runner.d.ts +1 -0
- package/dist/agent/channel-runner.js +3 -2
- package/dist/agent/effect-ledger.d.ts +11 -0
- package/dist/agent/effect-ledger.js +42 -0
- package/dist/agent/job-manager.d.ts +90 -13
- package/dist/agent/job-manager.js +235 -20
- package/dist/agent/prompt/sections.js +11 -2
- package/dist/agent/prompt/types.d.ts +7 -1
- package/dist/agent/runner-factory.d.ts +7 -0
- package/dist/agent/session-events.js +20 -1
- package/dist/index.d.ts +1 -1
- package/dist/log.d.ts +6 -0
- package/dist/log.js +12 -0
- package/dist/memory/consolidation.d.ts +5 -0
- package/dist/memory/consolidation.js +35 -147
- package/dist/memory/extraction.d.ts +45 -0
- package/dist/memory/extraction.js +227 -0
- package/dist/memory/lifecycle.js +5 -0
- package/dist/memory/maintenance-jobs.js +7 -0
- package/dist/memory/post-turn-review.d.ts +3 -1
- package/dist/memory/post-turn-review.js +20 -189
- package/dist/memory/recall.d.ts +0 -1
- package/dist/memory/recall.js +135 -77
- package/dist/memory/sidecar-worker.d.ts +7 -0
- package/dist/memory/sidecar-worker.js +23 -5
- package/dist/memory/task-digest.js +1 -1
- package/dist/paths.d.ts +1 -0
- package/dist/paths.js +11 -0
- package/dist/playbooks/background-jobs.md +40 -0
- package/dist/playbooks/catalog.d.ts +1 -7
- package/dist/playbooks/catalog.js +4 -14
- package/dist/playbooks/event-scheduling.md +8 -4
- package/dist/playbooks/memory-and-learning.md +1 -1
- package/dist/playbooks/outbound-media.md +45 -0
- package/dist/playbooks/runtime-orientation.md +1 -1
- package/dist/playbooks/task-closeout.md +12 -11
- package/dist/playbooks/task-delegation.md +11 -5
- package/dist/playbooks/task-driving.md +54 -21
- package/dist/playbooks/task-planning.md +46 -19
- package/dist/runtime/bootstrap.js +29 -4
- package/dist/runtime/channel-context.d.ts +33 -0
- package/dist/runtime/dingtalk.d.ts +22 -2
- package/dist/runtime/dingtalk.js +141 -0
- package/dist/runtime/durable-dispatch.d.ts +10 -0
- package/dist/runtime/durable-dispatch.js +42 -1
- package/dist/runtime/event-validation.d.ts +48 -0
- package/dist/runtime/event-validation.js +81 -0
- package/dist/runtime/events.d.ts +17 -8
- package/dist/runtime/events.js +96 -22
- package/dist/runtime/store.d.ts +1 -1
- package/dist/runtime/task-commands.js +29 -51
- package/dist/runtime/task-driver.d.ts +5 -8
- package/dist/runtime/task-driver.js +120 -93
- package/dist/runtime/task-migration.d.ts +11 -0
- package/dist/runtime/task-migration.js +70 -0
- package/dist/settings.d.ts +11 -0
- package/dist/settings.js +12 -0
- package/dist/shared/recoverable-error.d.ts +26 -0
- package/dist/shared/recoverable-error.js +29 -0
- package/dist/shared/task-events.d.ts +0 -26
- package/dist/shared/task-events.js +0 -15
- package/dist/shared/task-ledger.d.ts +32 -8
- package/dist/shared/task-ledger.js +66 -17
- package/dist/subagents/builtin/explorer.md +16 -0
- package/dist/subagents/builtin/researcher.md +17 -0
- package/dist/subagents/builtin/verifier.md +17 -0
- package/dist/subagents/discovery.d.ts +17 -3
- package/dist/subagents/discovery.js +88 -15
- package/dist/subagents/tool.d.ts +21 -1
- package/dist/subagents/tool.js +140 -12
- package/dist/tasks/control.d.ts +4 -0
- package/dist/tasks/control.js +3 -0
- package/dist/tasks/store.d.ts +28 -1
- package/dist/tasks/store.js +63 -6
- package/dist/tasks/transitions.d.ts +40 -0
- package/dist/tasks/transitions.js +82 -0
- package/dist/tools/bash.d.ts +2 -0
- package/dist/tools/bash.js +18 -5
- package/dist/tools/event-manage.js +28 -77
- package/dist/tools/index.d.ts +4 -0
- package/dist/tools/index.js +7 -2
- package/dist/tools/job.js +2 -2
- package/dist/tools/memory-manage.js +0 -1
- package/dist/tools/registry.d.ts +29 -8
- package/dist/tools/registry.js +39 -22
- package/dist/tools/send-media.d.ts +28 -0
- package/dist/tools/send-media.js +88 -0
- package/dist/tools/task-manage/create.d.ts +2 -0
- package/dist/tools/task-manage/create.js +35 -0
- package/dist/tools/task-manage/lifecycle.d.ts +6 -0
- package/dist/tools/task-manage/lifecycle.js +197 -0
- package/dist/tools/task-manage/schema.d.ts +43 -0
- package/dist/tools/task-manage/schema.js +90 -0
- package/dist/tools/task-manage/shared.d.ts +36 -0
- package/dist/tools/task-manage/shared.js +247 -0
- package/dist/tools/task-manage/types.d.ts +53 -0
- package/dist/tools/task-manage/types.js +1 -0
- package/dist/tools/task-manage/verification.d.ts +16 -0
- package/dist/tools/task-manage/verification.js +112 -0
- package/dist/tools/task-manage.d.ts +9 -89
- package/dist/tools/task-manage.js +8 -696
- package/dist/tools/tool-details.d.ts +44 -0
- package/dist/tools/tool-details.js +62 -0
- package/dist/tui/app.js +2 -0
- package/dist/tui/terminal-media-sender.d.ts +9 -0
- package/dist/tui/terminal-media-sender.js +15 -0
- package/package.json +2 -2
- package/dist/playbooks/task-recurring.md +0 -41
- package/dist/playbooks/task-repair.md +0 -45
|
@@ -9,6 +9,25 @@ const DEFAULT_INTERVAL_MS = 30_000;
|
|
|
9
9
|
function recordPath(stateDir, id) {
|
|
10
10
|
return join(stateDir, `${id}.json`);
|
|
11
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* Prefix a redelivered wake with what the runtime already knows (spec 031, D3).
|
|
14
|
+
*
|
|
15
|
+
* At-least-once delivery means a wake can arrive after a previous attempt already ran part of
|
|
16
|
+
* it. The runtime knows this; the model did not. Surfacing the delivery count is the whole
|
|
17
|
+
* mechanism — no new protocol, no reply marker, just enough for the model to check for its own
|
|
18
|
+
* prior side effects before repeating them. The stored record keeps the original text, so the
|
|
19
|
+
* dispatch id is unaffected.
|
|
20
|
+
*/
|
|
21
|
+
function withRedeliveryNotice(event, deliveries) {
|
|
22
|
+
if (deliveries <= 1)
|
|
23
|
+
return event;
|
|
24
|
+
return {
|
|
25
|
+
...event,
|
|
26
|
+
text: `[REDELIVERY:${deliveries}] This wake is delivery #${deliveries}; a previous delivery may have partially run. ` +
|
|
27
|
+
"Before acting, check whether its side effects (files, messages, external calls) already exist, and do not repeat them.\n" +
|
|
28
|
+
event.text,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
12
31
|
function dispatchId(event) {
|
|
13
32
|
return createHash("sha256")
|
|
14
33
|
.update(JSON.stringify([event.channelId, event.user, event.ts, event.text, event.conversationId]))
|
|
@@ -45,6 +64,16 @@ export class DurableDispatchService {
|
|
|
45
64
|
this.options = options;
|
|
46
65
|
this.queue = createSerialQueue();
|
|
47
66
|
this.timer = null;
|
|
67
|
+
/**
|
|
68
|
+
* Dispatch ids whose turn this process is still running (spec 031, D2).
|
|
69
|
+
*
|
|
70
|
+
* The lease expresses "the holder is alive", not "a turn takes at most N minutes". A fixed
|
|
71
|
+
* lease is a guess about turn duration, and any turn that outran it redelivered its own wake.
|
|
72
|
+
* Membership here is renewed on every drain instead, so a long turn is safe; the set is empty
|
|
73
|
+
* after a restart, so a turn that died with the process is correctly redelivered once its
|
|
74
|
+
* lease lapses.
|
|
75
|
+
*/
|
|
76
|
+
this.running = new Set();
|
|
48
77
|
this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;
|
|
49
78
|
}
|
|
50
79
|
start() {
|
|
@@ -100,6 +129,9 @@ export class DurableDispatchService {
|
|
|
100
129
|
return;
|
|
101
130
|
if (record.status !== "queued" && record.status !== "running")
|
|
102
131
|
return;
|
|
132
|
+
// Drop the liveness claim too, or the renew branch above would keep this record
|
|
133
|
+
// alive forever and the cancelled turn would never be redelivered.
|
|
134
|
+
this.running.delete(id);
|
|
103
135
|
record.leaseExpiresAt = undefined;
|
|
104
136
|
await this.write(record);
|
|
105
137
|
canceled++;
|
|
@@ -110,6 +142,7 @@ export class DurableDispatchService {
|
|
|
110
142
|
async markStarted(id) {
|
|
111
143
|
if (!id)
|
|
112
144
|
return;
|
|
145
|
+
this.running.add(id);
|
|
113
146
|
await this.queue.run(id, async () => {
|
|
114
147
|
const record = await this.read(id);
|
|
115
148
|
if (!record)
|
|
@@ -122,6 +155,7 @@ export class DurableDispatchService {
|
|
|
122
155
|
async markCompleted(id) {
|
|
123
156
|
if (!id)
|
|
124
157
|
return;
|
|
158
|
+
this.running.delete(id);
|
|
125
159
|
await this.queue.run(id, async () => {
|
|
126
160
|
await unlink(recordPath(this.options.stateDir, id)).catch(() => undefined);
|
|
127
161
|
});
|
|
@@ -140,6 +174,13 @@ export class DurableDispatchService {
|
|
|
140
174
|
const record = await this.read(id);
|
|
141
175
|
if (!record)
|
|
142
176
|
return;
|
|
177
|
+
// The turn is still running in this process: renew its lease rather than treating a
|
|
178
|
+
// long turn as a lost one and redelivering the wake underneath it (D2).
|
|
179
|
+
if (record.status === "running" && this.running.has(id)) {
|
|
180
|
+
record.leaseExpiresAt = new Date(now + this.leaseMs).toISOString();
|
|
181
|
+
await this.write(record);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
143
184
|
const leaseMs = record.leaseExpiresAt ? new Date(record.leaseExpiresAt).getTime() : undefined;
|
|
144
185
|
if ((record.status === "queued" || record.status === "running") && leaseMs && leaseMs > now)
|
|
145
186
|
return;
|
|
@@ -147,7 +188,7 @@ export class DurableDispatchService {
|
|
|
147
188
|
record.deliveries++;
|
|
148
189
|
record.leaseExpiresAt = new Date(now + this.leaseMs).toISOString();
|
|
149
190
|
await this.write(record);
|
|
150
|
-
const accepted = this.options.bot.enqueueEvent({ ...record.event, dispatchId: record.id });
|
|
191
|
+
const accepted = this.options.bot.enqueueEvent(withRedeliveryNotice({ ...record.event, dispatchId: record.id }, record.deliveries));
|
|
151
192
|
if (accepted)
|
|
152
193
|
return;
|
|
153
194
|
record.status = "pending";
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { SecurityConfig } from "../security/types.js";
|
|
2
|
+
import type { ScheduledEvent } from "./events.js";
|
|
3
|
+
/**
|
|
4
|
+
* Admission rules for scheduled events (spec 031, D4).
|
|
5
|
+
*
|
|
6
|
+
* These used to live only in the `event_manage` tool, but the events directory sits inside the
|
|
7
|
+
* agent-writable workspace, so a plain `write` bypassed every one of them — the self-triggering
|
|
8
|
+
* guard was advisory rather than enforced. The rules therefore live here and are applied by
|
|
9
|
+
* both the tool (fail early, with a recoverable message) and `EventsWatcher` (the actual trust
|
|
10
|
+
* boundary, which has the final say).
|
|
11
|
+
*/
|
|
12
|
+
/** one-shot events must be scheduled at least this far out; anything sooner is effectively self-triggering. */
|
|
13
|
+
export declare const MIN_ONE_SHOT_LEAD_MS: number;
|
|
14
|
+
/** periodic events without a preAction gate may fire no more often than this. */
|
|
15
|
+
export declare const MIN_PERIODIC_INTERVAL_MS: number;
|
|
16
|
+
/**
|
|
17
|
+
* periodic events WITH a preAction gate may fire this often: the sensor is the token guard
|
|
18
|
+
* (it exits non-zero and stays silent when there is nothing to do), so a tighter cadence is
|
|
19
|
+
* safe and is exactly the design-endorsed posture for completion-driven checks. A hard
|
|
20
|
+
* sub-floor still applies so a bogus always-pass preAction cannot drive an arbitrarily hot loop.
|
|
21
|
+
*/
|
|
22
|
+
export declare const MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS: number;
|
|
23
|
+
/** sanity cap on total scheduled events to keep the directory (and the scheduler) from being flooded. */
|
|
24
|
+
export declare const MAX_EVENT_FILES = 50;
|
|
25
|
+
export declare class EventValidationError extends Error {
|
|
26
|
+
/** Whether the model can usefully retry with a corrected definition. */
|
|
27
|
+
readonly recoverable: boolean;
|
|
28
|
+
constructor(message: string, recoverable?: boolean);
|
|
29
|
+
}
|
|
30
|
+
export declare function validateOneShotLead(event: ScheduledEvent & {
|
|
31
|
+
type: "one-shot";
|
|
32
|
+
}, now?: number): void;
|
|
33
|
+
export declare function validatePeriodicCadence(event: ScheduledEvent & {
|
|
34
|
+
type: "periodic";
|
|
35
|
+
}): void;
|
|
36
|
+
export declare function validatePreActionCommand(event: ScheduledEvent, commandGuardConfig: SecurityConfig["commandGuard"] | undefined): void;
|
|
37
|
+
export interface ScheduledEventValidationOptions {
|
|
38
|
+
commandGuardConfig?: SecurityConfig["commandGuard"];
|
|
39
|
+
/**
|
|
40
|
+
* Whether to enforce the one-shot lead time. It is a *creation-time* rule: a one-shot whose
|
|
41
|
+
* `at` has already passed is a legitimate post-restart recovery, not a self-trigger, so the
|
|
42
|
+
* watcher only enforces it for files written while this process was running.
|
|
43
|
+
*/
|
|
44
|
+
enforceOneShotLead?: boolean;
|
|
45
|
+
now?: number;
|
|
46
|
+
}
|
|
47
|
+
/** Apply every admission rule that depends only on the definition itself. */
|
|
48
|
+
export declare function validateScheduledEvent(event: ScheduledEvent, options?: ScheduledEventValidationOptions): void;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { Cron } from "croner";
|
|
2
|
+
import { guardCommand } from "../security/command-guard.js";
|
|
3
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
4
|
+
/**
|
|
5
|
+
* Admission rules for scheduled events (spec 031, D4).
|
|
6
|
+
*
|
|
7
|
+
* These used to live only in the `event_manage` tool, but the events directory sits inside the
|
|
8
|
+
* agent-writable workspace, so a plain `write` bypassed every one of them — the self-triggering
|
|
9
|
+
* guard was advisory rather than enforced. The rules therefore live here and are applied by
|
|
10
|
+
* both the tool (fail early, with a recoverable message) and `EventsWatcher` (the actual trust
|
|
11
|
+
* boundary, which has the final say).
|
|
12
|
+
*/
|
|
13
|
+
/** one-shot events must be scheduled at least this far out; anything sooner is effectively self-triggering. */
|
|
14
|
+
export const MIN_ONE_SHOT_LEAD_MS = 2 * 60 * 1000;
|
|
15
|
+
/** periodic events without a preAction gate may fire no more often than this. */
|
|
16
|
+
export const MIN_PERIODIC_INTERVAL_MS = 30 * 60 * 1000;
|
|
17
|
+
/**
|
|
18
|
+
* periodic events WITH a preAction gate may fire this often: the sensor is the token guard
|
|
19
|
+
* (it exits non-zero and stays silent when there is nothing to do), so a tighter cadence is
|
|
20
|
+
* safe and is exactly the design-endorsed posture for completion-driven checks. A hard
|
|
21
|
+
* sub-floor still applies so a bogus always-pass preAction cannot drive an arbitrarily hot loop.
|
|
22
|
+
*/
|
|
23
|
+
export const MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS = 5 * 60 * 1000;
|
|
24
|
+
/** sanity cap on total scheduled events to keep the directory (and the scheduler) from being flooded. */
|
|
25
|
+
export const MAX_EVENT_FILES = 50;
|
|
26
|
+
export class EventValidationError extends Error {
|
|
27
|
+
constructor(message, recoverable = true) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.name = "EventValidationError";
|
|
30
|
+
this.recoverable = recoverable;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export function validateOneShotLead(event, now = Date.now()) {
|
|
34
|
+
const atTime = new Date(event.at).getTime();
|
|
35
|
+
if (!Number.isFinite(atTime)) {
|
|
36
|
+
throw new EventValidationError(`one-shot 'at' is not a valid date: ${event.at}`);
|
|
37
|
+
}
|
|
38
|
+
if (atTime < now + MIN_ONE_SHOT_LEAD_MS) {
|
|
39
|
+
throw new EventValidationError("one-shot 'at' must be at least 2 minutes in the future (self-triggering guard).");
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export function validatePeriodicCadence(event) {
|
|
43
|
+
let runs;
|
|
44
|
+
try {
|
|
45
|
+
const cron = new Cron(event.schedule);
|
|
46
|
+
runs = cron.nextRuns(3);
|
|
47
|
+
cron.stop();
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
throw new EventValidationError(`Invalid cron schedule "${event.schedule}": ${errorMessage(error)}`);
|
|
51
|
+
}
|
|
52
|
+
// A preAction gate makes a tighter cadence safe (the sensor keeps most fires silent);
|
|
53
|
+
// without one, hold the 30-minute floor so a bare high-frequency cron can't burn tokens.
|
|
54
|
+
const floorMs = event.preAction ? MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS : MIN_PERIODIC_INTERVAL_MS;
|
|
55
|
+
const floorMinutes = Math.round(floorMs / 60000);
|
|
56
|
+
// Fewer than two upcoming runs means no meaningful cadence to rate-limit (e.g. a one-off cron); allow it.
|
|
57
|
+
for (let i = 1; i < runs.length; i++) {
|
|
58
|
+
if (runs[i].getTime() - runs[i - 1].getTime() < floorMs) {
|
|
59
|
+
throw new EventValidationError(`periodic events must fire no more often than every ${floorMinutes} minutes` +
|
|
60
|
+
`${event.preAction ? " (even with a preAction gate)" : "; for tighter checks add a preAction gate (min 5 minutes) instead of a high-frequency cron"}.`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export function validatePreActionCommand(event, commandGuardConfig) {
|
|
65
|
+
if (!event.preAction || !commandGuardConfig)
|
|
66
|
+
return;
|
|
67
|
+
const result = guardCommand(event.preAction.command, commandGuardConfig);
|
|
68
|
+
if (!result.allowed) {
|
|
69
|
+
throw new EventValidationError(`preAction command blocked by guard: ${result.reason ?? "not allowed"}`, false);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Apply every admission rule that depends only on the definition itself. */
|
|
73
|
+
export function validateScheduledEvent(event, options = {}) {
|
|
74
|
+
if (event.type === "one-shot" && options.enforceOneShotLead !== false) {
|
|
75
|
+
validateOneShotLead(event, options.now);
|
|
76
|
+
}
|
|
77
|
+
if (event.type === "periodic") {
|
|
78
|
+
validatePeriodicCadence(event);
|
|
79
|
+
}
|
|
80
|
+
validatePreActionCommand(event, options.commandGuardConfig);
|
|
81
|
+
}
|
package/dist/runtime/events.d.ts
CHANGED
|
@@ -6,12 +6,6 @@ export interface EventAction {
|
|
|
6
6
|
command: string;
|
|
7
7
|
timeout?: number;
|
|
8
8
|
}
|
|
9
|
-
export interface ImmediateEvent {
|
|
10
|
-
type: "immediate";
|
|
11
|
-
channelId: string;
|
|
12
|
-
text: string;
|
|
13
|
-
preAction?: EventAction;
|
|
14
|
-
}
|
|
15
9
|
export interface OneShotEvent {
|
|
16
10
|
type: "one-shot";
|
|
17
11
|
channelId: string;
|
|
@@ -32,7 +26,7 @@ export interface PeriodicEvent {
|
|
|
32
26
|
legacyTimezone?: string;
|
|
33
27
|
preAction?: EventAction;
|
|
34
28
|
}
|
|
35
|
-
export type ScheduledEvent =
|
|
29
|
+
export type ScheduledEvent = OneShotEvent | PeriodicEvent;
|
|
36
30
|
export type EventHistoryAction = "loaded" | "scheduled" | "triggered" | "skipped" | "enqueued" | "queue_full" | "deleted" | "invalid" | "pre_action_started" | "pre_action_passed" | "pre_action_blocked" | "pre_action_failed" | "cancelled";
|
|
37
31
|
export type EventHistoryResult = "ok" | "error" | "skipped";
|
|
38
32
|
export interface EventHistoryRecord {
|
|
@@ -93,9 +87,24 @@ export declare class EventsWatcher {
|
|
|
93
87
|
private cancelScheduled;
|
|
94
88
|
private handleFile;
|
|
95
89
|
private parseEvent;
|
|
96
|
-
|
|
90
|
+
/**
|
|
91
|
+
* The admission gate (spec 031, D4). `event_manage` applies the same rules first, but the
|
|
92
|
+
* events directory is agent-writable, so a file that arrived any other way is only ever
|
|
93
|
+
* stopped here. Returns the rejection reason, or undefined when the event may be scheduled.
|
|
94
|
+
*/
|
|
95
|
+
private admissionFailure;
|
|
96
|
+
private wasWrittenAfterStart;
|
|
97
97
|
private handleOneShot;
|
|
98
98
|
private handlePeriodic;
|
|
99
|
+
/**
|
|
100
|
+
* A task-owned event outlives its task whenever close-out fails or the task file is deleted
|
|
101
|
+
* by hand, and then wakes the channel forever about work that no longer exists. Checking the
|
|
102
|
+
* owner at trigger time turns that permanent noise into self-healing (spec 031, D5).
|
|
103
|
+
*
|
|
104
|
+
* The name alone is ambiguous (a channelId may contain dots), so the owning channel is taken
|
|
105
|
+
* from the event definition and only the task id is parsed out of the remainder.
|
|
106
|
+
*/
|
|
107
|
+
private orphanedOwnerReason;
|
|
99
108
|
private execute;
|
|
100
109
|
private runPreAction;
|
|
101
110
|
private deleteFile;
|
package/dist/runtime/events.js
CHANGED
|
@@ -5,7 +5,11 @@ import { dirname, join, resolve } from "path";
|
|
|
5
5
|
import * as log from "../log.js";
|
|
6
6
|
import { guardCommand } from "../security/command-guard.js";
|
|
7
7
|
import { createJsonlAppender } from "../shared/jsonl-appender.js";
|
|
8
|
+
import { taskEventPrefix } from "../shared/task-events.js";
|
|
9
|
+
import { parseTaskFrontmatter } from "../shared/task-ledger.js";
|
|
8
10
|
import { errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
|
|
11
|
+
import { TERMINAL_TASK_STATUSES } from "../tasks/transitions.js";
|
|
12
|
+
import { MAX_EVENT_FILES, validateScheduledEvent } from "./event-validation.js";
|
|
9
13
|
// ============================================================================
|
|
10
14
|
// EventsWatcher
|
|
11
15
|
// ============================================================================
|
|
@@ -79,8 +83,13 @@ export function parseScheduledEventContent(content, filename) {
|
|
|
79
83
|
const text = readRequiredString(data, "text", filename);
|
|
80
84
|
const preAction = parsePreAction(data, filename);
|
|
81
85
|
switch (type) {
|
|
86
|
+
// Removed in spec 031 (D4): an event that fires the moment it is written is a
|
|
87
|
+
// self-triggering loop with no gate in front of it, and nothing in the runtime produced
|
|
88
|
+
// one. Rejecting it here — rather than only in `event_manage` — is what makes the guard
|
|
89
|
+
// enforced, since the events directory is agent-writable.
|
|
82
90
|
case "immediate":
|
|
83
|
-
|
|
91
|
+
throw new Error(`Immediate events are no longer supported (${filename}); do the work in the current turn, ` +
|
|
92
|
+
"or schedule a one-shot at least 2 minutes out via event_manage.");
|
|
84
93
|
case "one-shot": {
|
|
85
94
|
if (typeof data.at !== "string" || data.at.trim().length === 0) {
|
|
86
95
|
throw new Error(`Missing 'at' field for one-shot event in ${filename}`);
|
|
@@ -107,6 +116,20 @@ export function parseScheduledEventContent(content, filename) {
|
|
|
107
116
|
throw new Error(`Unknown event type '${type}' in ${filename}`);
|
|
108
117
|
}
|
|
109
118
|
}
|
|
119
|
+
/**
|
|
120
|
+
* Stable, provenance-derived dispatch id (spec 031, D1).
|
|
121
|
+
*
|
|
122
|
+
* The identity of a wake is its *occurrence*, never the moment it happened to be executed.
|
|
123
|
+
* A one-shot keyed on its own `at` therefore lands on the same durable record whether it
|
|
124
|
+
* arrives via the outbox retry or via the post-restart file recovery path, so the two
|
|
125
|
+
* independent retry systems can no longer deliver the same occurrence twice. A periodic is
|
|
126
|
+
* keyed on the cron trigger time, so retries of one occurrence collapse while the next
|
|
127
|
+
* occurrence is a genuinely new record.
|
|
128
|
+
*/
|
|
129
|
+
function eventDispatchId(filename, event, occurrence) {
|
|
130
|
+
const name = eventNameFromFilename(filename);
|
|
131
|
+
return event.type === "one-shot" ? `event:${name}:${event.at}` : `event:${name}:${occurrence.toISOString()}`;
|
|
132
|
+
}
|
|
110
133
|
class EventPreActionError extends Error {
|
|
111
134
|
constructor(kind, message, options = {}) {
|
|
112
135
|
super(message);
|
|
@@ -318,13 +341,17 @@ export class EventsWatcher {
|
|
|
318
341
|
this.markInvalid(filename, lastError?.message ?? "Unknown event parse error");
|
|
319
342
|
return;
|
|
320
343
|
}
|
|
344
|
+
const rejection = this.admissionFailure(filename, event);
|
|
345
|
+
if (rejection) {
|
|
346
|
+
log.logWarning(`Rejected event file: ${filename}`, rejection);
|
|
347
|
+
this.appendEventHistory(filename, event, "invalid", "error", { reason: rejection });
|
|
348
|
+
this.markInvalid(filename, rejection);
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
321
351
|
this.knownFiles.add(filename);
|
|
322
352
|
this.clearInvalidMarker(filename);
|
|
323
353
|
this.appendEventHistory(filename, event, "loaded", "ok");
|
|
324
354
|
switch (event.type) {
|
|
325
|
-
case "immediate":
|
|
326
|
-
this.handleImmediate(filename, event);
|
|
327
|
-
break;
|
|
328
355
|
case "one-shot":
|
|
329
356
|
await this.handleOneShot(filename, event);
|
|
330
357
|
break;
|
|
@@ -336,23 +363,36 @@ export class EventsWatcher {
|
|
|
336
363
|
parseEvent(content, filename) {
|
|
337
364
|
return parseScheduledEventContent(content, filename);
|
|
338
365
|
}
|
|
339
|
-
|
|
340
|
-
|
|
366
|
+
/**
|
|
367
|
+
* The admission gate (spec 031, D4). `event_manage` applies the same rules first, but the
|
|
368
|
+
* events directory is agent-writable, so a file that arrived any other way is only ever
|
|
369
|
+
* stopped here. Returns the rejection reason, or undefined when the event may be scheduled.
|
|
370
|
+
*/
|
|
371
|
+
admissionFailure(filename, event) {
|
|
372
|
+
if (!this.knownFiles.has(filename) && this.timers.size + this.crons.size >= MAX_EVENT_FILES) {
|
|
373
|
+
return `Too many scheduled events (>= ${MAX_EVENT_FILES}); delete stale events before adding more.`;
|
|
374
|
+
}
|
|
341
375
|
try {
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
}
|
|
376
|
+
validateScheduledEvent(event, {
|
|
377
|
+
commandGuardConfig: this.commandGuardConfig,
|
|
378
|
+
// A one-shot whose `at` has already passed is a legitimate post-restart recovery,
|
|
379
|
+
// not a self-trigger, so the lead time only binds files written while this process
|
|
380
|
+
// was running — which is exactly the case the guard exists for.
|
|
381
|
+
enforceOneShotLead: this.wasWrittenAfterStart(filename),
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
catch (error) {
|
|
385
|
+
return errorMessage(error);
|
|
386
|
+
}
|
|
387
|
+
return undefined;
|
|
388
|
+
}
|
|
389
|
+
wasWrittenAfterStart(filename) {
|
|
390
|
+
try {
|
|
391
|
+
return statSync(join(this.eventsDir, filename)).mtimeMs >= this.startTime;
|
|
349
392
|
}
|
|
350
393
|
catch {
|
|
351
|
-
return;
|
|
394
|
+
return false;
|
|
352
395
|
}
|
|
353
|
-
log.logInfo(`Executing immediate event: ${filename}`);
|
|
354
|
-
this.appendEventHistory(filename, event, "triggered", "ok");
|
|
355
|
-
await this.execute(filename, event);
|
|
356
396
|
}
|
|
357
397
|
async handleOneShot(filename, event) {
|
|
358
398
|
const atTime = new Date(event.at).getTime();
|
|
@@ -415,7 +455,8 @@ export class EventsWatcher {
|
|
|
415
455
|
try {
|
|
416
456
|
log.logInfo(`Executing periodic event: ${filename}`);
|
|
417
457
|
this.appendEventHistory(filename, event, "triggered", "ok");
|
|
418
|
-
|
|
458
|
+
// The cron trigger time — not "now" — is this occurrence's identity (D1).
|
|
459
|
+
await this.execute(filename, event, false, cron.currentRun() ?? new Date());
|
|
419
460
|
}
|
|
420
461
|
catch (err) {
|
|
421
462
|
log.logWarning(`Periodic event execution failed: ${filename}`, String(err));
|
|
@@ -437,7 +478,42 @@ export class EventsWatcher {
|
|
|
437
478
|
this.markInvalid(filename, `Invalid cron schedule: ${event.schedule}\n${String(err)}`);
|
|
438
479
|
}
|
|
439
480
|
}
|
|
440
|
-
|
|
481
|
+
/**
|
|
482
|
+
* A task-owned event outlives its task whenever close-out fails or the task file is deleted
|
|
483
|
+
* by hand, and then wakes the channel forever about work that no longer exists. Checking the
|
|
484
|
+
* owner at trigger time turns that permanent noise into self-healing (spec 031, D5).
|
|
485
|
+
*
|
|
486
|
+
* The name alone is ambiguous (a channelId may contain dots), so the owning channel is taken
|
|
487
|
+
* from the event definition and only the task id is parsed out of the remainder.
|
|
488
|
+
*/
|
|
489
|
+
async orphanedOwnerReason(filename, event) {
|
|
490
|
+
const prefix = taskEventPrefix(event.channelId);
|
|
491
|
+
const name = eventNameFromFilename(filename);
|
|
492
|
+
if (!name.startsWith(prefix))
|
|
493
|
+
return undefined;
|
|
494
|
+
const taskId = name.slice(prefix.length).split(".")[0];
|
|
495
|
+
if (!taskId)
|
|
496
|
+
return undefined;
|
|
497
|
+
const taskPath = join(dirname(this.eventsDir), event.channelId, "tasks", `${taskId}.md`);
|
|
498
|
+
let content;
|
|
499
|
+
try {
|
|
500
|
+
content = await readFile(taskPath, "utf-8");
|
|
501
|
+
}
|
|
502
|
+
catch {
|
|
503
|
+
return `owning task ${taskId} no longer exists`;
|
|
504
|
+
}
|
|
505
|
+
const status = parseTaskFrontmatter(content).status ?? "";
|
|
506
|
+
return TERMINAL_TASK_STATUSES.has(status) ? `owning task ${taskId} is ${status}` : undefined;
|
|
507
|
+
}
|
|
508
|
+
async execute(filename, event, deleteAfter = true, occurrence = new Date()) {
|
|
509
|
+
const orphaned = await this.orphanedOwnerReason(filename, event);
|
|
510
|
+
if (orphaned) {
|
|
511
|
+
log.logInfo(`Retiring orphaned task event: ${filename} (${orphaned})`);
|
|
512
|
+
this.appendEventHistory(filename, event, "skipped", "skipped", { reason: orphaned });
|
|
513
|
+
this.cancelScheduled(filename);
|
|
514
|
+
this.deleteFile(filename);
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
441
517
|
if (event.preAction) {
|
|
442
518
|
try {
|
|
443
519
|
this.appendEventHistory(filename, event, "pre_action_started", "ok", {
|
|
@@ -477,9 +553,6 @@ export class EventsWatcher {
|
|
|
477
553
|
}
|
|
478
554
|
let scheduleInfo;
|
|
479
555
|
switch (event.type) {
|
|
480
|
-
case "immediate":
|
|
481
|
-
scheduleInfo = "immediate";
|
|
482
|
-
break;
|
|
483
556
|
case "one-shot":
|
|
484
557
|
scheduleInfo = event.at;
|
|
485
558
|
break;
|
|
@@ -503,6 +576,7 @@ export class EventsWatcher {
|
|
|
503
576
|
ts: Date.now().toString(),
|
|
504
577
|
conversationId: "",
|
|
505
578
|
conversationType: "1",
|
|
579
|
+
dispatchId: eventDispatchId(filename, event, occurrence),
|
|
506
580
|
};
|
|
507
581
|
const enqueued = this.options.dispatch
|
|
508
582
|
? await this.options.dispatch(syntheticEvent)
|
package/dist/runtime/store.d.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
2
|
import { readdir, readFile } from "node:fs/promises";
|
|
3
3
|
import { join, resolve, sep } from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
|
|
5
5
|
import { extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../shared/task-ledger.js";
|
|
6
6
|
import { errorMessage } from "../shared/text-utils.js";
|
|
7
7
|
import { taskBudgetViolation } from "../tasks/control.js";
|
|
8
8
|
import { claimTaskAttempt, readStoredTask, releaseTaskAttemptClaim, taskBodyHash, writeStoredTask, } from "../tasks/store.js";
|
|
9
|
+
import { normalizeStoredStatus, resolveTaskTransition } from "../tasks/transitions.js";
|
|
9
10
|
import { readVerificationAttestation } from "../tasks/verification.js";
|
|
10
11
|
import { parseScheduledEventContent } from "./events.js";
|
|
11
12
|
function usage() {
|
|
@@ -133,13 +134,6 @@ async function readTaskEvents(workspaceDir, channelId) {
|
|
|
133
134
|
}
|
|
134
135
|
return events;
|
|
135
136
|
}
|
|
136
|
-
function eventKey(events, id, use) {
|
|
137
|
-
return events.find((event) => event.id === id && event.use === use);
|
|
138
|
-
}
|
|
139
|
-
function isParseableSchedule(events, id) {
|
|
140
|
-
const schedule = eventKey(events, id, "schedule");
|
|
141
|
-
return schedule ? isTaskScheduleEvent(schedule) : false;
|
|
142
|
-
}
|
|
143
137
|
function validWakeMs(entry) {
|
|
144
138
|
const wake = entry.frontmatter.wake;
|
|
145
139
|
if (!wake)
|
|
@@ -195,7 +189,7 @@ async function listTasks(channelDir) {
|
|
|
195
189
|
return "# Tasks\n\nNo active tasks.";
|
|
196
190
|
}
|
|
197
191
|
const blocks = entries.map((entry) => {
|
|
198
|
-
const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "
|
|
192
|
+
const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "active") : "⚠ unreadable frontmatter";
|
|
199
193
|
const detail = [` status: ${status}`, `wake: ${relativeWake(entry.wakeMs, now)}`];
|
|
200
194
|
const control = entry.frontmatter.control;
|
|
201
195
|
if (control) {
|
|
@@ -232,7 +226,7 @@ async function approveTask(options, idInput) {
|
|
|
232
226
|
const control = task.fields.control;
|
|
233
227
|
if (!control)
|
|
234
228
|
return `Task ${id} has no governed control metadata. Ask the agent to normalize it before approval.`;
|
|
235
|
-
if (task.fields.status === "done" || task.fields.status === "cancelled"
|
|
229
|
+
if (task.fields.status === "done" || task.fields.status === "cancelled") {
|
|
236
230
|
return `Task ${id} is ${task.fields.status} and cannot receive a new external-action approval.`;
|
|
237
231
|
}
|
|
238
232
|
if (control.sideEffects !== "external") {
|
|
@@ -253,14 +247,19 @@ export async function pauseTask(options, idInput) {
|
|
|
253
247
|
const task = await readStoredTask(options.channelDir, id);
|
|
254
248
|
if (!task)
|
|
255
249
|
return `Task not found: ${id}`;
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
}
|
|
259
|
-
if (task.fields.status === "paused")
|
|
250
|
+
const from = normalizeStoredStatus(task.fields.status);
|
|
251
|
+
if (from === "paused")
|
|
260
252
|
return `Task ${id} is already paused.`;
|
|
253
|
+
try {
|
|
254
|
+
resolveTaskTransition("pause", id, from);
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
return errorMessage(error);
|
|
258
|
+
}
|
|
261
259
|
task.fields.status = "paused";
|
|
262
260
|
task.fields.wake = undefined;
|
|
263
261
|
if (task.fields.control) {
|
|
262
|
+
task.fields.control.pausedBy = "user";
|
|
264
263
|
task.fields.control.lastOutcome = "blocked";
|
|
265
264
|
task.fields.control.blockedReason = `Paused by ${options.approver?.trim() || "a user"}.`;
|
|
266
265
|
}
|
|
@@ -272,11 +271,14 @@ export async function resumeTask(options, idInput) {
|
|
|
272
271
|
const task = await readStoredTask(options.channelDir, id);
|
|
273
272
|
if (!task)
|
|
274
273
|
return `Task not found: ${id}`;
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
274
|
+
const from = normalizeStoredStatus(task.fields.status);
|
|
275
|
+
if (from !== "paused")
|
|
276
|
+
return `Task ${id} is ${from}, not paused.`;
|
|
277
|
+
resolveTaskTransition("resume", id, from);
|
|
278
|
+
task.fields.status = "active";
|
|
278
279
|
task.fields.wake = undefined;
|
|
279
280
|
if (task.fields.control) {
|
|
281
|
+
task.fields.control.pausedBy = undefined;
|
|
280
282
|
task.fields.control.lastOutcome = "pending";
|
|
281
283
|
task.fields.control.blockedReason = undefined;
|
|
282
284
|
}
|
|
@@ -288,13 +290,17 @@ async function runTask(options, idInput) {
|
|
|
288
290
|
const task = await readStoredTask(options.channelDir, id);
|
|
289
291
|
if (!task)
|
|
290
292
|
return `Task not found: ${id}`;
|
|
291
|
-
|
|
292
|
-
|
|
293
|
+
const from = normalizeStoredStatus(task.fields.status);
|
|
294
|
+
try {
|
|
295
|
+
resolveTaskTransition("run", id, from);
|
|
293
296
|
}
|
|
294
|
-
|
|
295
|
-
|
|
297
|
+
catch (error) {
|
|
298
|
+
return errorMessage(error);
|
|
299
|
+
}
|
|
300
|
+
task.fields.status = "active";
|
|
296
301
|
task.fields.wake = undefined;
|
|
297
302
|
if (task.fields.control) {
|
|
303
|
+
task.fields.control.pausedBy = undefined;
|
|
298
304
|
task.fields.control.lastOutcome = "pending";
|
|
299
305
|
task.fields.control.blockedReason = undefined;
|
|
300
306
|
}
|
|
@@ -409,14 +415,13 @@ async function doctor(options) {
|
|
|
409
415
|
return "# Task Doctor\n\nNot available: workspaceDir and channelId are required.";
|
|
410
416
|
}
|
|
411
417
|
const now = Date.now();
|
|
412
|
-
const hostTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
413
418
|
const entries = await readActiveTasks(tasksDir(options.channelDir), now);
|
|
414
419
|
const activeIds = new Set(entries.map((entry) => entry.id));
|
|
415
420
|
const archivedIds = await readArchivedTaskIds(options.channelDir);
|
|
416
421
|
const events = await readTaskEvents(options.workspaceDir, options.channelId);
|
|
417
422
|
const issues = [];
|
|
418
423
|
for (const entry of entries) {
|
|
419
|
-
const status = entry.frontmatter.status ?? "
|
|
424
|
+
const status = entry.frontmatter.status ?? "active";
|
|
420
425
|
if (!entry.frontmatter.readable) {
|
|
421
426
|
issues.push(issue(`tasks/${entry.id}.md has unreadable frontmatter; wake/status cannot be trusted.`, `Fix tasks/${entry.id}.md so it starts with readable status/wake/recurrence frontmatter.`));
|
|
422
427
|
continue;
|
|
@@ -464,19 +469,10 @@ async function doctor(options) {
|
|
|
464
469
|
}
|
|
465
470
|
}
|
|
466
471
|
}
|
|
467
|
-
const
|
|
468
|
-
const recurring = Boolean(entry.frontmatter.schedule) || isParseableSchedule(events, entry.id);
|
|
472
|
+
const recurring = Boolean(entry.frontmatter.schedule);
|
|
469
473
|
if (status === "done" && !recurring) {
|
|
470
474
|
issues.push(issue(`tasks/${entry.id}.md is done but still in the active directory.`, `Archive one-shot task ${entry.id}, or add a schedule cron with task_manage set if it is recurring.`));
|
|
471
475
|
}
|
|
472
|
-
// Migration (027): recurrence cadence now lives in the task's `schedule` frontmatter.
|
|
473
|
-
// A remaining canonical .schedule event should be folded in and deleted.
|
|
474
|
-
if (legacySchedule && isTaskScheduleEvent(legacySchedule)) {
|
|
475
|
-
issues.push(issue(`events/${legacySchedule.filename} is a legacy task .schedule event; cadence is now native to tasks/${entry.id}.md.`, `Fold its cron "${legacySchedule.event.schedule}" into the task's schedule frontmatter with task_manage set, then delete events/${legacySchedule.filename}.`));
|
|
476
|
-
if (legacySchedule.event.legacyTimezone && legacySchedule.event.legacyTimezone !== hostTimezone) {
|
|
477
|
-
issues.push(issue(`events/${legacySchedule.filename} declares timezone ${legacySchedule.event.legacyTimezone}, which differs from the host ${hostTimezone}.`, `Confirm the intended cadence after folding into frontmatter; the cron will run in the host timezone.`));
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
476
|
const content = await readActiveTaskContent(options.channelDir, entry.id);
|
|
481
477
|
if (content === undefined) {
|
|
482
478
|
issues.push(issue(`tasks/${entry.id}.md could not be read during doctor checks.`, `Open tasks/${entry.id}.md manually and repair permissions or file contents.`));
|
|
@@ -490,18 +486,6 @@ async function doctor(options) {
|
|
|
490
486
|
if (entry.frontmatter.wake && validWakeMs(entry) === undefined) {
|
|
491
487
|
issues.push(issue(`tasks/${entry.id}.md has an invalid wake value (${entry.frontmatter.wake}); the native driver will treat it as due.`, `Use task_manage set or progress to replace wake with ISO8601, or clear it if the task should continue now.`));
|
|
492
488
|
}
|
|
493
|
-
const checkin = eventKey(events, entry.id, "checkin");
|
|
494
|
-
if (checkin && isTaskCheckinEvent(checkin)) {
|
|
495
|
-
issues.push(issue(`events/${checkin.filename} is a legacy task checkin; native wake handling makes it redundant.`, `Delete events/${checkin.filename} and keep the task wake value as the single resume condition.`));
|
|
496
|
-
const wakeMs = validWakeMs(entry);
|
|
497
|
-
const atMs = new Date(checkin.event.at).getTime();
|
|
498
|
-
if (wakeMs === undefined) {
|
|
499
|
-
issues.push(issue(`tasks/${entry.id}.md has a .checkin event but no valid wake value.`, `Set tasks/${entry.id}.md wake to ${checkin.event.at}, or delete the stale .checkin event.`));
|
|
500
|
-
}
|
|
501
|
-
else if (Number.isFinite(atMs) && Math.abs(atMs - wakeMs) > 60_000) {
|
|
502
|
-
issues.push(issue(`tasks/${entry.id}.md wake does not match its .checkin event time.`, `Sync tasks/${entry.id}.md wake with events/${checkin.filename} at ${checkin.event.at}.`));
|
|
503
|
-
}
|
|
504
|
-
}
|
|
505
489
|
}
|
|
506
490
|
const parentGraph = new Map();
|
|
507
491
|
const dependencyGraph = new Map();
|
|
@@ -534,12 +518,6 @@ async function doctor(options) {
|
|
|
534
518
|
if (archivedIds.has(event.id)) {
|
|
535
519
|
issues.push(issue(`events/${event.filename} points to archived task ${event.id}; closed tasks should have no live events.`, `Delete events/${event.filename}; archived tasks should not wake the agent.`));
|
|
536
520
|
}
|
|
537
|
-
if (event.use === "schedule" && !isTaskScheduleEvent(event)) {
|
|
538
|
-
issues.push(issue(`events/${event.filename} is a schedule event but is not periodic.`, `Change events/${event.filename} to type periodic, or rename it away from .schedule.`));
|
|
539
|
-
}
|
|
540
|
-
if (event.use === "checkin" && !isTaskCheckinEvent(event)) {
|
|
541
|
-
issues.push(issue(`events/${event.filename} is a checkin event but is not one-shot.`, `Change events/${event.filename} to type one-shot, or rename it away from .checkin.`));
|
|
542
|
-
}
|
|
543
521
|
}
|
|
544
522
|
if (issues.length === 0) {
|
|
545
523
|
return "# Task Doctor\n\nNo task ledger issues found.";
|