@oyasmi/pipiclaw 0.8.9-beta.1 → 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/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 +1 -1
- package/dist/playbooks/task-delegation.md +10 -4
- package/dist/playbooks/task-driving.md +52 -18
- package/dist/playbooks/task-planning.md +43 -18
- package/dist/runtime/bootstrap.js +24 -3
- 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-driver.d.ts +5 -0
- package/dist/runtime/task-driver.js +38 -12
- 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-ledger.d.ts +9 -7
- package/dist/shared/task-ledger.js +1 -1
- 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/transitions.js +3 -2
- 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.js +5 -4
- package/dist/tools/task-manage/lifecycle.js +12 -11
- package/dist/tools/task-manage/schema.js +2 -1
- package/dist/tools/task-manage/shared.js +13 -12
- package/dist/tools/task-manage/verification.js +14 -13
- 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 -44
- package/dist/playbooks/task-repair.md +0 -45
|
@@ -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
|
@@ -9,6 +9,11 @@ export interface TaskDriverOptions {
|
|
|
9
9
|
/** Optional observability hook. It runs after every production dispatch attempt. */
|
|
10
10
|
onDispatch?: (event: DingTalkEvent, accepted: boolean) => void;
|
|
11
11
|
getSettings: () => PipiclawTaskDriverSettings;
|
|
12
|
+
/**
|
|
13
|
+
* Externally visible effects recorded for a channel so far (spec 031, D7). Defaults to a
|
|
14
|
+
* constant, which simply makes the fingerprint depend on ledger fields alone.
|
|
15
|
+
*/
|
|
16
|
+
getEffectCount?: (channelId: string) => number;
|
|
12
17
|
/** Master autonomy switch (`tools.tasks.enabled`); re-read every tick. Defaults to on. */
|
|
13
18
|
isEnabled?: () => boolean;
|
|
14
19
|
/** Test-only override for the idle-sleep cap; production uses `settings.maxSleepMinutes`. */
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
1
2
|
import { readdir } from "node:fs/promises";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import * as log from "../log.js";
|
|
@@ -39,10 +40,19 @@ export async function discoverTaskChannels(workspaceDir, knownChannelIds = []) {
|
|
|
39
40
|
function attemptKey(channelId, taskId) {
|
|
40
41
|
return `${channelId}\0${taskId}`;
|
|
41
42
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
/**
|
|
44
|
+
* What "this task moved" means to the driver.
|
|
45
|
+
*
|
|
46
|
+
* Do not use mtime/size here. Runtime usage accounting deliberately rewrites task control after
|
|
47
|
+
* every attempt; treating that bookkeeping as progress made governed tasks retry at the short
|
|
48
|
+
* continuation interval forever.
|
|
49
|
+
*
|
|
50
|
+
* `latestNote` is deliberately absent (spec 031, D7): it is the model's own account of its work,
|
|
51
|
+
* so including it let a wake that did nothing but append a note reset the futile counter forever,
|
|
52
|
+
* and let a wake that changed real files count as stalled. The channel's effect tally stands in
|
|
53
|
+
* for the work itself instead.
|
|
54
|
+
*/
|
|
55
|
+
function taskFingerprint(entry, effects) {
|
|
46
56
|
const control = entry.frontmatter.control;
|
|
47
57
|
return [
|
|
48
58
|
entry.frontmatter.readable ? "readable" : "unreadable",
|
|
@@ -50,11 +60,11 @@ async function taskFingerprint(_channelDir, entry) {
|
|
|
50
60
|
entry.frontmatter.wake ?? "",
|
|
51
61
|
entry.frontmatter.schedule ?? "",
|
|
52
62
|
entry.frontmatter.recurrence ?? "",
|
|
53
|
-
entry.latestNote ?? "",
|
|
54
63
|
control?.nextAction ?? "",
|
|
55
64
|
control?.blockedReason ?? "",
|
|
56
65
|
control?.verification.status ?? "",
|
|
57
66
|
control?.cycleId ?? "",
|
|
67
|
+
`effects:${effects}`,
|
|
58
68
|
].join("\0");
|
|
59
69
|
}
|
|
60
70
|
function isEligible(attempt, fingerprint, nowMs, settings) {
|
|
@@ -64,6 +74,18 @@ function isEligible(attempt, fingerprint, nowMs, settings) {
|
|
|
64
74
|
const delayMinutes = changed || !attempt.accepted ? settings.continuationDelayMinutes : settings.stalledRetryMinutes;
|
|
65
75
|
return nowMs - attempt.atMs >= delayMinutes * 60_000;
|
|
66
76
|
}
|
|
77
|
+
/**
|
|
78
|
+
* Stable, provenance-derived dispatch id for a task wake (spec 031, D1).
|
|
79
|
+
*
|
|
80
|
+
* A scheduled task has a real occurrence — its `wake` — so retries of that occurrence collapse
|
|
81
|
+
* onto one durable record. A task that is simply actionable has no occurrence identity, so the
|
|
82
|
+
* dispatch time is used: two separate wakes of the same task are genuinely separate work, and
|
|
83
|
+
* collapsing them would silently drop the later one.
|
|
84
|
+
*/
|
|
85
|
+
function taskDispatchId(channelId, entry, nowMs) {
|
|
86
|
+
const occurrence = entry.frontmatter.wake ?? `t${nowMs}`;
|
|
87
|
+
return `task:${channelId}:${entry.id}:${occurrence}`;
|
|
88
|
+
}
|
|
67
89
|
export function createTaskDriverEvent(channelId, entry, nowMs) {
|
|
68
90
|
const verification = entry.frontmatter.control?.verification;
|
|
69
91
|
const verificationInstruction = entry.frontmatter.status === "verifying"
|
|
@@ -73,7 +95,7 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
|
|
|
73
95
|
: "";
|
|
74
96
|
const repair = entry.frontmatter.readable
|
|
75
97
|
? ""
|
|
76
|
-
: ` Its frontmatter is unreadable: also read ${join(PLAYBOOKS_DIR, "task-
|
|
98
|
+
: ` Its frontmatter is unreadable: also read ${join(PLAYBOOKS_DIR, "task-driving.md")}.`;
|
|
77
99
|
const control = entry.frontmatter.control;
|
|
78
100
|
const capsule = [
|
|
79
101
|
`Task capsule: title=${entry.title}; status=${entry.frontmatter.status ?? "active"};`,
|
|
@@ -96,6 +118,7 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
|
|
|
96
118
|
ts: String(nowMs),
|
|
97
119
|
conversationId: "",
|
|
98
120
|
conversationType: channelId.startsWith("group_") ? "2" : "1",
|
|
121
|
+
dispatchId: taskDispatchId(channelId, entry, nowMs),
|
|
99
122
|
};
|
|
100
123
|
}
|
|
101
124
|
/** status done + a schedule cadence + a valid wake that is due → time to open the next cycle. */
|
|
@@ -116,11 +139,14 @@ function taskEscalationEvent(channelId, entry, reason, nowMs) {
|
|
|
116
139
|
user: "TASK_DRIVER",
|
|
117
140
|
userName: "TASK_DRIVER",
|
|
118
141
|
text: `[TASK_ESCALATION:${entry.id}] Task ${entry.id} (${entry.title}) was stopped by the deterministic task ` +
|
|
119
|
-
`governor: ${reason}. Read ${join(PLAYBOOKS_DIR, "task-
|
|
142
|
+
`governor: ${reason}. Read ${join(PLAYBOOKS_DIR, "task-driving.md")}, diagnose before changing control, ` +
|
|
120
143
|
"inform the user of the cause and recovery, and do not continue implementation in this run.",
|
|
121
144
|
ts: String(nowMs),
|
|
122
145
|
conversationId: "",
|
|
123
146
|
conversationType: channelId.startsWith("group_") ? "2" : "1",
|
|
147
|
+
// Keyed on the cause, not the moment: re-detecting the same violation before the user has
|
|
148
|
+
// acted must not queue a second identical escalation, while a different cause still does.
|
|
149
|
+
dispatchId: `task:${channelId}:${entry.id}:escalation:${createHash("sha256").update(reason).digest("hex").slice(0, 12)}`,
|
|
124
150
|
};
|
|
125
151
|
}
|
|
126
152
|
function terminalDependencyReason(reason) {
|
|
@@ -302,7 +328,7 @@ export class TaskDriver {
|
|
|
302
328
|
if (accepted && (await escalateTask(channelDir, candidate.id, escalationReason))) {
|
|
303
329
|
dispatched++;
|
|
304
330
|
lastDispatchOffset = offset;
|
|
305
|
-
log.logWarning(`[${channelId}] Task driver
|
|
331
|
+
log.logWarning(`[${channelId}] Task driver paused ${candidate.id} (governor)`, escalationReason);
|
|
306
332
|
}
|
|
307
333
|
break;
|
|
308
334
|
}
|
|
@@ -363,7 +389,8 @@ export class TaskDriver {
|
|
|
363
389
|
log.logInfo(`[${channelId}] Task driver opened cycle ${opened.cycleId} for ${entry.id}`);
|
|
364
390
|
}
|
|
365
391
|
const key = attemptKey(channelId, entry.id);
|
|
366
|
-
|
|
392
|
+
const effects = this.options.getEffectCount?.(channelId) ?? 0;
|
|
393
|
+
const fingerprint = taskFingerprint(entry, effects);
|
|
367
394
|
const previous = this.attempts.get(key);
|
|
368
395
|
if (!isEligible(previous, fingerprint, nowMs, settings))
|
|
369
396
|
continue;
|
|
@@ -386,10 +413,9 @@ export class TaskDriver {
|
|
|
386
413
|
}
|
|
387
414
|
continue;
|
|
388
415
|
}
|
|
416
|
+
// Claiming an attempt only touches usage bookkeeping, which the fingerprint
|
|
417
|
+
// deliberately excludes, so there is nothing to recompute here.
|
|
389
418
|
const claim = entry.frontmatter.control ? await claimTaskAttempt(channelDir, entry.id, now) : undefined;
|
|
390
|
-
if (claim) {
|
|
391
|
-
fingerprint = await taskFingerprint(channelDir, entry);
|
|
392
|
-
}
|
|
393
419
|
const event = createTaskDriverEvent(channelId, entry, nowMs);
|
|
394
420
|
const accepted = await this.options.dispatch(event);
|
|
395
421
|
this.observeDispatch(event, accepted);
|
package/dist/settings.d.ts
CHANGED
|
@@ -129,6 +129,12 @@ export interface PipiclawSettings {
|
|
|
129
129
|
defaultThinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
130
130
|
/** Single backup model reference (`provider/model`) used when the primary model's turn fails. */
|
|
131
131
|
fallbackModel?: string | null;
|
|
132
|
+
/**
|
|
133
|
+
* Default model reference (`provider/model`) for sub-agents that don't otherwise name one
|
|
134
|
+
* (spec 032 D5). Lower priority than an invocation's `model` or a predefined agent's
|
|
135
|
+
* frontmatter `model`; falls back to the parent's current model when unset.
|
|
136
|
+
*/
|
|
137
|
+
subagentModel?: string | null;
|
|
132
138
|
compaction?: Partial<PipiclawCompactionSettings>;
|
|
133
139
|
retry?: Partial<PipiclawRetrySettings>;
|
|
134
140
|
memoryRecall?: Partial<PipiclawMemoryRecallSettings>;
|
|
@@ -187,6 +193,11 @@ export declare class PipiclawSettingsManager {
|
|
|
187
193
|
* Empty / whitespace-only values are treated as unset (fallback disabled).
|
|
188
194
|
*/
|
|
189
195
|
getFallbackModelReference(): string | null;
|
|
196
|
+
/**
|
|
197
|
+
* Default model reference (`provider/model`) for sub-agents, or null when unset.
|
|
198
|
+
* Empty / whitespace-only values are treated as unset (spec 032 D5).
|
|
199
|
+
*/
|
|
200
|
+
getSubAgentModelReference(): string | null;
|
|
190
201
|
getDefaultModel(): string | undefined;
|
|
191
202
|
getDefaultProvider(): string | undefined;
|
|
192
203
|
setDefaultModelAndProvider(provider: string, modelId: string): void;
|
package/dist/settings.js
CHANGED
|
@@ -275,6 +275,18 @@ export class PipiclawSettingsManager {
|
|
|
275
275
|
const trimmed = raw.trim();
|
|
276
276
|
return trimmed.length > 0 ? trimmed : null;
|
|
277
277
|
}
|
|
278
|
+
/**
|
|
279
|
+
* Default model reference (`provider/model`) for sub-agents, or null when unset.
|
|
280
|
+
* Empty / whitespace-only values are treated as unset (spec 032 D5).
|
|
281
|
+
*/
|
|
282
|
+
getSubAgentModelReference() {
|
|
283
|
+
const raw = this.settings.subagentModel;
|
|
284
|
+
if (typeof raw !== "string") {
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
const trimmed = raw.trim();
|
|
288
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
289
|
+
}
|
|
278
290
|
getDefaultModel() {
|
|
279
291
|
return this.settings.defaultModel;
|
|
280
292
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A tool call rejected because of *its own* arguments or an unmet precondition the model can
|
|
3
|
+
* resolve without the user: a missing required field, an id that does not exist, an illegal
|
|
4
|
+
* status transition.
|
|
5
|
+
*
|
|
6
|
+
* This is not a failure of the tool. It is the same class of outcome as bash's non-zero exit
|
|
7
|
+
* code — data the model reacts to — and it is deliberately *not* surfaced to the user as an
|
|
8
|
+
* error, because the model normally fixes it on the next call and a red bubble in the chat
|
|
9
|
+
* would report a fault that never happened.
|
|
10
|
+
*
|
|
11
|
+
* Throw a plain `Error` instead when the user genuinely has to act or know:
|
|
12
|
+
* - a security guard refused the call (the user may need to adjust security.json),
|
|
13
|
+
* - progress needs a human decision (`/tasks approve <id>`),
|
|
14
|
+
* - state is corrupt and needs manual repair,
|
|
15
|
+
* - the tool itself broke (I/O failure, a bug).
|
|
16
|
+
*
|
|
17
|
+
* The test is "can the model resolve this alone?", not "how severe is it?".
|
|
18
|
+
*
|
|
19
|
+
* Lives in `shared/` because domain code raises it (`src/tasks/` transitions) while only the
|
|
20
|
+
* tool layer interprets it: `withToolDetails` converts it at the tool boundary into a normal
|
|
21
|
+
* result carrying `recoverable: true`. That conversion is required — the pi SDK discards
|
|
22
|
+
* thrown error objects and keeps only `error.message`, so the type cannot survive on its own.
|
|
23
|
+
*/
|
|
24
|
+
export declare class RecoverableToolError extends Error {
|
|
25
|
+
constructor(message: string);
|
|
26
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A tool call rejected because of *its own* arguments or an unmet precondition the model can
|
|
3
|
+
* resolve without the user: a missing required field, an id that does not exist, an illegal
|
|
4
|
+
* status transition.
|
|
5
|
+
*
|
|
6
|
+
* This is not a failure of the tool. It is the same class of outcome as bash's non-zero exit
|
|
7
|
+
* code — data the model reacts to — and it is deliberately *not* surfaced to the user as an
|
|
8
|
+
* error, because the model normally fixes it on the next call and a red bubble in the chat
|
|
9
|
+
* would report a fault that never happened.
|
|
10
|
+
*
|
|
11
|
+
* Throw a plain `Error` instead when the user genuinely has to act or know:
|
|
12
|
+
* - a security guard refused the call (the user may need to adjust security.json),
|
|
13
|
+
* - progress needs a human decision (`/tasks approve <id>`),
|
|
14
|
+
* - state is corrupt and needs manual repair,
|
|
15
|
+
* - the tool itself broke (I/O failure, a bug).
|
|
16
|
+
*
|
|
17
|
+
* The test is "can the model resolve this alone?", not "how severe is it?".
|
|
18
|
+
*
|
|
19
|
+
* Lives in `shared/` because domain code raises it (`src/tasks/` transitions) while only the
|
|
20
|
+
* tool layer interprets it: `withToolDetails` converts it at the tool boundary into a normal
|
|
21
|
+
* result carrying `recoverable: true`. That conversion is required — the pi SDK discards
|
|
22
|
+
* thrown error objects and keeps only `error.message`, so the type cannot survive on its own.
|
|
23
|
+
*/
|
|
24
|
+
export class RecoverableToolError extends Error {
|
|
25
|
+
constructor(message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = "RecoverableToolError";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -2,12 +2,14 @@ import { type TaskControl, type TaskVerificationMode } from "../tasks/control.js
|
|
|
2
2
|
/**
|
|
3
3
|
* Shared reader for the task ledger (`workspace/<channelId>/tasks/*.md`).
|
|
4
4
|
*
|
|
5
|
-
* This is the
|
|
6
|
-
* ("Frontmatter 契约(单一事实源)").
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
5
|
+
* This is the sole implementation of the frontmatter contract documented in
|
|
6
|
+
* `docs/events-and-tasks.md` ("Frontmatter 契约(单一事实源)"). It used to be one of two
|
|
7
|
+
* halves — a dependency-free `tasks-pending.mjs` sensor under workspace/skills was the
|
|
8
|
+
* other — but the native TaskDriver (spec 022) replaced that sensor, so `actionable` now
|
|
9
|
+
* has a single owner. The parsing stays deliberately literal (flat `key: value` fields,
|
|
10
|
+
* done-vs-not-done, wake gating, fail-open on unreadable frontmatter) because task files
|
|
11
|
+
* are hand-editable and must degrade toward "wake me up so I can be fixed".
|
|
12
|
+
* `/tasks`, the task digest, and `task_manage list` all read through here.
|
|
11
13
|
*/
|
|
12
14
|
export interface TaskFrontmatter {
|
|
13
15
|
/** false => frontmatter could not be read (fail-open: the task is treated as actionable). */
|
|
@@ -81,7 +83,7 @@ export declare function parseTaskFrontmatter(content: string): TaskFrontmatter;
|
|
|
81
83
|
/**
|
|
82
84
|
* The single shared judgement: is there work to do on this task right now?
|
|
83
85
|
* Unreadable frontmatter is fail-open (actionable) so a corrupt ledger surfaces
|
|
84
|
-
* rather than being silently skipped
|
|
86
|
+
* rather than being silently skipped.
|
|
85
87
|
*/
|
|
86
88
|
export declare function isTaskActionable(frontmatter: TaskFrontmatter, now: number): boolean;
|
|
87
89
|
/** First `# ` heading after the frontmatter block, or the id when there is none. */
|