@oyasmi/pipiclaw 0.9.1-beta.1 → 0.9.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/dist/agent/channel-runner.d.ts +7 -1
- package/dist/agent/channel-runner.js +42 -15
- package/dist/agent/command-extension.js +24 -27
- package/dist/agent/commands.d.ts +51 -7
- package/dist/agent/commands.js +199 -59
- package/dist/agent/prompt/manifest.js +5 -6
- package/dist/agent/prompt/sections.js +1 -0
- package/dist/agent/reply-limits.d.ts +16 -0
- package/dist/agent/reply-limits.js +17 -0
- package/dist/agent/runner-factory.d.ts +0 -2
- package/dist/agent/session-events.js +2 -2
- package/dist/agent/status-render.js +12 -12
- package/dist/executor.d.ts +14 -0
- package/dist/executor.js +36 -6
- package/dist/main.js +3 -4
- package/dist/memory/commands.js +79 -38
- package/dist/memory/consolidation.d.ts +5 -1
- package/dist/memory/consolidation.js +33 -12
- package/dist/memory/extraction.d.ts +8 -1
- package/dist/memory/extraction.js +47 -4
- package/dist/memory/files.d.ts +0 -1
- package/dist/memory/files.js +24 -5
- package/dist/memory/lifecycle.js +9 -2
- package/dist/memory/maintenance-jobs.js +14 -4
- package/dist/memory/metadata.d.ts +3 -0
- package/dist/memory/metadata.js +7 -0
- package/dist/memory/recall.d.ts +9 -0
- package/dist/memory/recall.js +101 -17
- package/dist/memory/review-log.d.ts +0 -2
- package/dist/memory/review-log.js +0 -0
- package/dist/memory/session-corpus.js +5 -0
- package/dist/memory/session-search.js +9 -0
- package/dist/memory/sidecar-worker.js +4 -0
- package/dist/memory/source-window.d.ts +0 -1
- package/dist/memory/source-window.js +0 -5
- package/dist/memory/task-digest.js +0 -2
- package/dist/playbooks/agent-delegation.md +32 -24
- package/dist/playbooks/background-jobs.md +8 -16
- package/dist/playbooks/event-scheduling.md +13 -15
- package/dist/playbooks/memory-and-learning.md +29 -22
- package/dist/playbooks/outbound-media.md +15 -8
- package/dist/playbooks/runtime-orientation.md +40 -37
- package/dist/playbooks/task-driving.md +34 -38
- package/dist/playbooks/task-planning.md +18 -20
- package/dist/runtime/app-home.d.ts +6 -0
- package/dist/runtime/app-home.js +15 -6
- package/dist/runtime/bootstrap.d.ts +1 -1
- package/dist/runtime/bootstrap.js +57 -62
- package/dist/runtime/channel-context.d.ts +2 -1
- package/dist/runtime/channel-event.d.ts +0 -6
- package/dist/runtime/delivery.js +3 -3
- package/dist/runtime/dingtalk.d.ts +9 -1
- package/dist/runtime/dingtalk.js +27 -13
- package/dist/runtime/event-commands.d.ts +15 -0
- package/dist/runtime/event-commands.js +48 -40
- package/dist/runtime/project-commands.d.ts +16 -0
- package/dist/runtime/project-commands.js +13 -17
- package/dist/runtime/subagent-commands.d.ts +20 -0
- package/dist/runtime/subagent-commands.js +61 -58
- package/dist/runtime/task-commands.d.ts +38 -1
- package/dist/runtime/task-commands.js +135 -234
- package/dist/runtime/task-driver.d.ts +1 -3
- package/dist/runtime/task-driver.js +34 -40
- package/dist/runtime/task-migration.d.ts +7 -6
- package/dist/runtime/task-migration.js +85 -19
- package/dist/runtime/task-wake.d.ts +3 -5
- package/dist/runtime/task-wake.js +7 -15
- package/dist/security/path-guard.js +33 -2
- package/dist/security/types.d.ts +9 -0
- package/dist/subagents/discovery.d.ts +7 -2
- package/dist/subagents/discovery.js +31 -7
- package/dist/subagents/external/claude-code.js +42 -2
- package/dist/subagents/external/run.js +72 -2
- package/dist/subagents/runs.js +28 -3
- package/dist/subagents/tool.d.ts +11 -0
- package/dist/subagents/tool.js +89 -55
- package/dist/subagents/verification-outcome.js +17 -10
- package/dist/tasks/control.d.ts +18 -67
- package/dist/tasks/control.js +44 -176
- package/dist/tasks/ledger.d.ts +7 -13
- package/dist/tasks/ledger.js +13 -49
- package/dist/tasks/store.d.ts +15 -48
- package/dist/tasks/store.js +22 -154
- package/dist/tasks/transitions.d.ts +3 -4
- package/dist/tasks/transitions.js +8 -27
- package/dist/tasks/verification.d.ts +7 -5
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.js +77 -59
- package/dist/tools/edit.js +17 -4
- package/dist/tools/grep.js +3 -2
- package/dist/tools/index.d.ts +0 -2
- package/dist/tools/index.js +6 -1
- package/dist/tools/job.js +2 -1
- package/dist/tools/memory-manage.d.ts +1 -0
- package/dist/tools/memory-manage.js +54 -16
- package/dist/tools/read.js +21 -5
- package/dist/tools/registry.d.ts +0 -1
- package/dist/tools/registry.js +0 -1
- package/dist/tools/send-media.js +17 -6
- package/dist/tools/skill-manage.js +12 -11
- package/dist/tools/skill-security.js +1 -1
- package/dist/tools/subagent-manage.d.ts +8 -1
- package/dist/tools/subagent-manage.js +77 -7
- package/dist/tools/task-manage/lifecycle.js +19 -17
- package/dist/tools/task-manage/schema.d.ts +2 -6
- package/dist/tools/task-manage/schema.js +4 -17
- package/dist/tools/task-manage/shared.js +1 -6
- package/dist/tools/task-manage/types.d.ts +0 -3
- package/dist/tools/task-manage/verification.d.ts +9 -6
- package/dist/tools/task-manage/verification.js +19 -71
- package/dist/tools/task-manage.d.ts +1 -1
- package/dist/tools/task-manage.js +3 -5
- package/dist/tools/truncate.d.ts +8 -0
- package/dist/tools/truncate.js +8 -0
- package/dist/tools/web-fetch.js +9 -1
- package/dist/tools/write-content.js +11 -1
- package/dist/tui/app.js +1 -1
- package/dist/tui/commands.d.ts +1 -1
- package/dist/tui/commands.js +1 -1
- package/dist/tui/turn-controller.d.ts +1 -1
- package/dist/tui/turn-controller.js +14 -4
- package/dist/usage/ledger.d.ts +4 -0
- package/dist/usage/ledger.js +3 -0
- package/dist/usage/render.js +10 -8
- package/examples/sub-agents/README.md +2 -0
- package/package.json +3 -2
package/dist/tasks/store.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type TaskWaitingFor } from "./control.js";
|
|
2
2
|
import { type TaskDocumentFields } from "./ledger.js";
|
|
3
3
|
export interface StoredTaskDocument {
|
|
4
4
|
id: string;
|
|
@@ -17,61 +17,28 @@ export declare function taskBodyHash(body: string): string;
|
|
|
17
17
|
export declare function readStoredTask(channelDir: string, idInput: string, includeArchive?: boolean, allowInvalidControl?: boolean): Promise<StoredTaskDocument | undefined>;
|
|
18
18
|
export declare function writeStoredTask(document: StoredTaskDocument): Promise<void>;
|
|
19
19
|
export declare function updateStoredTask(channelDir: string, id: string, update: (document: StoredTaskDocument) => void, includeArchive?: boolean): Promise<StoredTaskDocument | undefined>;
|
|
20
|
-
export interface TaskAttemptClaim {
|
|
21
|
-
control: TaskControl;
|
|
22
|
-
previousLastOutcome: TaskOutcome;
|
|
23
|
-
previousBlockedReason?: string;
|
|
24
|
-
previousLastStartedAt?: string;
|
|
25
|
-
generation: number;
|
|
26
|
-
}
|
|
27
|
-
export declare function claimTaskAttempt(channelDir: string, id: string, now: Date): Promise<TaskAttemptClaim | undefined>;
|
|
28
|
-
export declare function releaseTaskAttemptClaim(channelDir: string, id: string, claim: TaskAttemptClaim): Promise<void>;
|
|
29
|
-
export declare function finishTaskAttempt(channelDir: string, id: string, result: {
|
|
30
|
-
tokens: number;
|
|
31
|
-
costUsd: number;
|
|
32
|
-
costKnown: boolean;
|
|
33
|
-
wallTimeMinutes: number;
|
|
34
|
-
failed: boolean;
|
|
35
|
-
silent?: boolean;
|
|
36
|
-
finishedAt: Date;
|
|
37
|
-
/**
|
|
38
|
-
* The `attemptGeneration` this turn's claim recorded (spec 029's monotonic claim
|
|
39
|
-
* identity, see `TaskControl.attemptGeneration`). When present and stale — a newer
|
|
40
|
-
* claim has since superseded it — usage is still tallied (the spend genuinely
|
|
41
|
-
* happened), but the outcome/finish fields are left alone so a slow, superseded turn
|
|
42
|
-
* cannot overwrite the newer attempt's in-flight or already-finished state. Absent
|
|
43
|
-
* (e.g. legacy callers) means "apply unconditionally", matching prior behavior.
|
|
44
|
-
*/
|
|
45
|
-
generation?: number;
|
|
46
|
-
}): Promise<void>;
|
|
47
20
|
/**
|
|
48
21
|
* A governor stop: disable the task without changing its lifecycle stage or wake. The structured
|
|
49
22
|
* stop record is the durable recovery receipt; notification is handled by the runtime driver.
|
|
50
23
|
*/
|
|
51
24
|
export declare function escalateTask(channelDir: string, id: string, reason: string): Promise<boolean>;
|
|
52
|
-
/** Atomically convert a due timed wait to active before any wake is dispatched. */
|
|
53
|
-
export declare function activateWaitingTask(channelDir: string, id: string, expectedWaitingFor?: TaskWaitingFor): Promise<StoredTaskDocument | undefined>;
|
|
54
25
|
export interface WakeTaskTransitionHooks {
|
|
55
|
-
/** Test-only fault seam
|
|
26
|
+
/** Test-only fault seam, called immediately before the atomic activation write. */
|
|
56
27
|
beforeActivation?: () => void;
|
|
57
|
-
beforeAttemptClaim?: () => void;
|
|
58
|
-
}
|
|
59
|
-
export interface WakeTaskHandoffInput {
|
|
60
|
-
kind: "subagent";
|
|
61
|
-
resourceId: string;
|
|
62
|
-
dispatchId: string;
|
|
63
28
|
}
|
|
64
|
-
/**
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
export declare function
|
|
29
|
+
/**
|
|
30
|
+
* Atomically convert a due/completion-woken task to active. Idempotent by construction: once a
|
|
31
|
+
* task is no longer `waiting`, a redelivered wake or retry finds `status !== "waiting"` and is a
|
|
32
|
+
* safe no-op, so no separate claim/handoff bookkeeping is needed to detect a duplicate activation.
|
|
33
|
+
*
|
|
34
|
+
* Wake legitimacy is entirely the caller's responsibility (spec 043's `waitingFor`
|
|
35
|
+
* de-authorization): a completion wake reaches here only after the caller has verified an
|
|
36
|
+
* actually-settled run/job whose own recorded `taskId` names this task (`task-wake.ts`'s
|
|
37
|
+
* `isVerified*Wake`). `waitingFor` itself is display-only and never gates activation.
|
|
38
|
+
*/
|
|
39
|
+
export declare function activateWaitingTask(channelDir: string, id: string, hooks?: WakeTaskTransitionHooks): Promise<StoredTaskDocument | undefined>;
|
|
40
|
+
/** Return a task to waiting after a transport failed to accept its just-activated turn. */
|
|
41
|
+
export declare function rollbackWaitingTask(channelDir: string, id: string, waitingFor: TaskWaitingFor): Promise<void>;
|
|
75
42
|
/**
|
|
76
43
|
* A stable cycle id for a runtime-opened recurring cycle: `cycle-YYYY-MM-DD`, disambiguated
|
|
77
44
|
* with a `-N` suffix when the same task is reopened more than once on the same local day.
|
package/dist/tasks/store.js
CHANGED
|
@@ -4,7 +4,7 @@ import { readFile } from "node:fs/promises";
|
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
6
6
|
import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
|
|
7
|
-
import { createDefaultTaskControl, resetTaskControlForCycle
|
|
7
|
+
import { createDefaultTaskControl, resetTaskControlForCycle } from "./control.js";
|
|
8
8
|
import { normalizeTaskId, parseTaskFrontmatter, renderTaskDocument, startTaskCycle, taskBody, taskContractSegment, } from "./ledger.js";
|
|
9
9
|
import { withTaskMutation } from "./mutation-lock.js";
|
|
10
10
|
import { normalizeStoredStatus, resolveTaskTransition } from "./transitions.js";
|
|
@@ -45,7 +45,6 @@ export async function readStoredTask(channelDir, idInput, includeArchive = false
|
|
|
45
45
|
enabled: frontmatter.enabled,
|
|
46
46
|
wake: frontmatter.wake,
|
|
47
47
|
schedule: frontmatter.schedule,
|
|
48
|
-
recurrence: frontmatter.recurrence,
|
|
49
48
|
control: frontmatter.control,
|
|
50
49
|
outcome: frontmatter.archiveOutcome,
|
|
51
50
|
closedAt: frontmatter.closedAt,
|
|
@@ -66,186 +65,55 @@ export async function updateStoredTask(channelDir, id, update, includeArchive =
|
|
|
66
65
|
return document;
|
|
67
66
|
});
|
|
68
67
|
}
|
|
69
|
-
export async function claimTaskAttempt(channelDir, id, now) {
|
|
70
|
-
let claim;
|
|
71
|
-
const document = await updateStoredTask(channelDir, id, (task) => {
|
|
72
|
-
const status = normalizeStoredStatus(task.fields.status, Boolean(task.fields.schedule));
|
|
73
|
-
if (status !== "active" || task.fields.enabled === false)
|
|
74
|
-
return;
|
|
75
|
-
task.fields.control ??= createDefaultTaskControl();
|
|
76
|
-
claim = {
|
|
77
|
-
control: task.fields.control,
|
|
78
|
-
previousLastOutcome: task.fields.control.lastOutcome,
|
|
79
|
-
previousBlockedReason: task.fields.control.blockedReason,
|
|
80
|
-
previousLastStartedAt: task.fields.control.lastStartedAt,
|
|
81
|
-
generation: task.fields.control.attemptGeneration + 1,
|
|
82
|
-
};
|
|
83
|
-
task.fields.control.usage.attempts++;
|
|
84
|
-
task.fields.control.attemptGeneration = claim.generation;
|
|
85
|
-
task.fields.control.lastStartedAt = formatLocalTime(now);
|
|
86
|
-
task.fields.control.lastOutcome = "running";
|
|
87
|
-
});
|
|
88
|
-
if (claim && document?.fields.control)
|
|
89
|
-
claim.control = document.fields.control;
|
|
90
|
-
return claim;
|
|
91
|
-
}
|
|
92
|
-
export async function releaseTaskAttemptClaim(channelDir, id, claim) {
|
|
93
|
-
await updateStoredTask(channelDir, id, (task) => {
|
|
94
|
-
const control = task.fields.control;
|
|
95
|
-
if (!control || control.attemptGeneration !== claim.generation)
|
|
96
|
-
return;
|
|
97
|
-
control.usage.attempts = Math.max(0, control.usage.attempts - 1);
|
|
98
|
-
control.lastStartedAt = claim.previousLastStartedAt;
|
|
99
|
-
control.lastOutcome = claim.previousLastOutcome;
|
|
100
|
-
control.blockedReason = claim.previousBlockedReason;
|
|
101
|
-
});
|
|
102
|
-
}
|
|
103
|
-
export async function finishTaskAttempt(channelDir, id, result) {
|
|
104
|
-
await updateStoredTask(channelDir, id, (task) => {
|
|
105
|
-
const control = task.fields.control;
|
|
106
|
-
if (!control)
|
|
107
|
-
return;
|
|
108
|
-
control.usage.tokens += Math.max(0, Math.floor(result.tokens));
|
|
109
|
-
control.usage.costUsd += Math.max(0, result.costUsd);
|
|
110
|
-
control.usage.costKnown &&= result.costKnown;
|
|
111
|
-
control.usage.wallTimeMinutes += Math.max(0, result.wallTimeMinutes);
|
|
112
|
-
if (result.generation !== undefined && control.attemptGeneration !== result.generation)
|
|
113
|
-
return;
|
|
114
|
-
control.lastFinishedAt = formatLocalTime(result.finishedAt);
|
|
115
|
-
if (result.silent) {
|
|
116
|
-
// The driver claimed before dispatch to prevent concurrent work. A silent
|
|
117
|
-
// turn performed no task advancement, so retain its cost audit but not its
|
|
118
|
-
// attempt charge.
|
|
119
|
-
control.usage.attempts = Math.max(0, control.usage.attempts - 1);
|
|
120
|
-
if (control.lastOutcome === "running") {
|
|
121
|
-
control.lastOutcome = "pending";
|
|
122
|
-
control.blockedReason = undefined;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
else if (result.failed) {
|
|
126
|
-
control.lastOutcome = "failed";
|
|
127
|
-
control.blockedReason = "The previous agent run failed; inspect the runtime error before retrying.";
|
|
128
|
-
}
|
|
129
|
-
else if (control.lastOutcome === "running") {
|
|
130
|
-
control.lastOutcome = "progress";
|
|
131
|
-
control.blockedReason = undefined;
|
|
132
|
-
}
|
|
133
|
-
}, true);
|
|
134
|
-
}
|
|
135
68
|
/**
|
|
136
69
|
* A governor stop: disable the task without changing its lifecycle stage or wake. The structured
|
|
137
70
|
* stop record is the durable recovery receipt; notification is handled by the runtime driver.
|
|
138
71
|
*/
|
|
139
72
|
export async function escalateTask(channelDir, id, reason) {
|
|
140
73
|
const document = await updateStoredTask(channelDir, id, (task) => {
|
|
141
|
-
const status = normalizeStoredStatus(task.fields.status
|
|
74
|
+
const status = normalizeStoredStatus(task.fields.status);
|
|
142
75
|
resolveTaskTransition("governor-stop", id, status);
|
|
143
76
|
task.fields.enabled = false;
|
|
144
77
|
task.fields.control ??= createDefaultTaskControl();
|
|
145
78
|
task.fields.control.stop = { by: "governor", reason, at: formatLocalTime() };
|
|
146
|
-
task.fields.control.lastOutcome = "blocked";
|
|
147
|
-
task.fields.control.blockedReason = reason;
|
|
148
79
|
});
|
|
149
80
|
return document !== undefined;
|
|
150
81
|
}
|
|
151
|
-
/**
|
|
152
|
-
|
|
82
|
+
/**
|
|
83
|
+
* Atomically convert a due/completion-woken task to active. Idempotent by construction: once a
|
|
84
|
+
* task is no longer `waiting`, a redelivered wake or retry finds `status !== "waiting"` and is a
|
|
85
|
+
* safe no-op, so no separate claim/handoff bookkeeping is needed to detect a duplicate activation.
|
|
86
|
+
*
|
|
87
|
+
* Wake legitimacy is entirely the caller's responsibility (spec 043's `waitingFor`
|
|
88
|
+
* de-authorization): a completion wake reaches here only after the caller has verified an
|
|
89
|
+
* actually-settled run/job whose own recorded `taskId` names this task (`task-wake.ts`'s
|
|
90
|
+
* `isVerified*Wake`). `waitingFor` itself is display-only and never gates activation.
|
|
91
|
+
*/
|
|
92
|
+
export async function activateWaitingTask(channelDir, id, hooks) {
|
|
153
93
|
let activated = false;
|
|
154
94
|
const document = await updateStoredTask(channelDir, id, (task) => {
|
|
155
|
-
const status = normalizeStoredStatus(task.fields.status
|
|
95
|
+
const status = normalizeStoredStatus(task.fields.status);
|
|
156
96
|
if (status !== "waiting" || task.fields.enabled === false)
|
|
157
97
|
return;
|
|
158
|
-
|
|
159
|
-
return;
|
|
98
|
+
hooks?.beforeActivation?.();
|
|
160
99
|
activated = true;
|
|
161
100
|
task.fields.control ??= createDefaultTaskControl();
|
|
162
101
|
task.fields.status = "active";
|
|
163
102
|
task.fields.wake = undefined;
|
|
164
|
-
if (task.fields.control)
|
|
103
|
+
if (task.fields.control)
|
|
165
104
|
task.fields.control.waitingFor = undefined;
|
|
166
|
-
task.fields.control.blockedReason = undefined;
|
|
167
|
-
}
|
|
168
105
|
});
|
|
169
106
|
return activated ? document : undefined;
|
|
170
107
|
}
|
|
171
|
-
/**
|
|
172
|
-
|
|
173
|
-
* but unclaimed, which would make a retry of the same durable wake look ineligible. */
|
|
174
|
-
export async function activateWaitingTaskAndClaimAttempt(channelDir, id, expectedWaitingFor, now, hooks, handoff) {
|
|
175
|
-
let generation;
|
|
176
|
-
const document = await updateStoredTask(channelDir, id, (task) => {
|
|
177
|
-
const status = normalizeStoredStatus(task.fields.status, Boolean(task.fields.schedule));
|
|
178
|
-
const existingHandoff = task.fields.control?.wakeHandoff;
|
|
179
|
-
if (handoff &&
|
|
180
|
-
status === "active" &&
|
|
181
|
-
existingHandoff?.kind === handoff.kind &&
|
|
182
|
-
existingHandoff.resourceId === handoff.resourceId &&
|
|
183
|
-
existingHandoff.dispatchId === handoff.dispatchId &&
|
|
184
|
-
task.fields.control?.attemptGeneration === existingHandoff.generation) {
|
|
185
|
-
generation = existingHandoff.generation;
|
|
186
|
-
return;
|
|
187
|
-
}
|
|
188
|
-
if (status !== "waiting" || task.fields.enabled === false)
|
|
189
|
-
return;
|
|
190
|
-
if (task.fields.control?.waitingFor !== expectedWaitingFor)
|
|
191
|
-
return;
|
|
192
|
-
hooks?.beforeActivation?.();
|
|
193
|
-
task.fields.control ??= createDefaultTaskControl();
|
|
194
|
-
task.fields.status = "active";
|
|
195
|
-
task.fields.wake = undefined;
|
|
196
|
-
task.fields.control.waitingFor = undefined;
|
|
197
|
-
task.fields.control.blockedReason = undefined;
|
|
198
|
-
hooks?.beforeAttemptClaim?.();
|
|
199
|
-
generation = task.fields.control.attemptGeneration + 1;
|
|
200
|
-
const previousLastOutcome = task.fields.control.lastOutcome;
|
|
201
|
-
const previousBlockedReason = task.fields.control.blockedReason;
|
|
202
|
-
const previousLastStartedAt = task.fields.control.lastStartedAt;
|
|
203
|
-
task.fields.control.usage.attempts++;
|
|
204
|
-
task.fields.control.attemptGeneration = generation;
|
|
205
|
-
task.fields.control.lastStartedAt = formatLocalTime(now);
|
|
206
|
-
task.fields.control.lastOutcome = "running";
|
|
207
|
-
if (handoff) {
|
|
208
|
-
task.fields.control.wakeHandoff = {
|
|
209
|
-
...handoff,
|
|
210
|
-
generation,
|
|
211
|
-
previousLastOutcome,
|
|
212
|
-
previousBlockedReason,
|
|
213
|
-
previousLastStartedAt,
|
|
214
|
-
};
|
|
215
|
-
}
|
|
216
|
-
});
|
|
217
|
-
return document && generation !== undefined ? { document, generation } : undefined;
|
|
218
|
-
}
|
|
219
|
-
function isMatchingWakeHandoff(handoff, expected) {
|
|
220
|
-
return (handoff?.kind === expected.kind &&
|
|
221
|
-
handoff.resourceId === expected.resourceId &&
|
|
222
|
-
handoff.dispatchId === expected.dispatchId);
|
|
223
|
-
}
|
|
224
|
-
/** Return a transport-rejected structured wake to its exact pre-activation task state. */
|
|
225
|
-
export async function rollbackWakeTaskActivation(channelDir, id, expected) {
|
|
108
|
+
/** Return a task to waiting after a transport failed to accept its just-activated turn. */
|
|
109
|
+
export async function rollbackWaitingTask(channelDir, id, waitingFor) {
|
|
226
110
|
await updateStoredTask(channelDir, id, (task) => {
|
|
227
|
-
|
|
228
|
-
const handoff = control?.wakeHandoff;
|
|
229
|
-
if (!control || !isMatchingWakeHandoff(handoff, expected) || control.attemptGeneration !== handoff.generation) {
|
|
111
|
+
if (task.fields.status !== "active")
|
|
230
112
|
return;
|
|
231
|
-
}
|
|
232
113
|
task.fields.status = "waiting";
|
|
233
114
|
task.fields.wake = undefined;
|
|
234
|
-
control
|
|
235
|
-
|
|
236
|
-
control.attemptGeneration = Math.max(0, handoff.generation - 1);
|
|
237
|
-
control.lastOutcome = handoff.previousLastOutcome;
|
|
238
|
-
control.blockedReason = handoff.previousBlockedReason;
|
|
239
|
-
control.lastStartedAt = handoff.previousLastStartedAt;
|
|
240
|
-
control.wakeHandoff = undefined;
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
/** Clear the durable handoff after the transport has accepted the activated turn. */
|
|
244
|
-
export async function finishWakeTaskActivation(channelDir, id, expected) {
|
|
245
|
-
await updateStoredTask(channelDir, id, (task) => {
|
|
246
|
-
if (isMatchingWakeHandoff(task.fields.control?.wakeHandoff, expected) && task.fields.control) {
|
|
247
|
-
task.fields.control.wakeHandoff = undefined;
|
|
248
|
-
}
|
|
115
|
+
if (task.fields.control)
|
|
116
|
+
task.fields.control.waitingFor = waitingFor;
|
|
249
117
|
});
|
|
250
118
|
}
|
|
251
119
|
/**
|
|
@@ -270,7 +138,7 @@ export function nextCycleId(previousCycleId, occurrence) {
|
|
|
270
138
|
export async function openRecurringTaskCycle(channelDir, id, now, force = false) {
|
|
271
139
|
let cycleId;
|
|
272
140
|
const document = await updateStoredTask(channelDir, id, (task) => {
|
|
273
|
-
const status = normalizeStoredStatus(task.fields.status
|
|
141
|
+
const status = normalizeStoredStatus(task.fields.status);
|
|
274
142
|
if (status !== "sleeping" || !task.fields.schedule)
|
|
275
143
|
return;
|
|
276
144
|
const wakeMs = task.fields.wake ? parseLocalTime(task.fields.wake) : undefined;
|
|
@@ -4,10 +4,9 @@ export type TaskStatus = (typeof TASK_STATUSES)[number];
|
|
|
4
4
|
/** Statuses a model/user may set directly; recurring sleeping is runtime-owned but repairable. */
|
|
5
5
|
export declare const SETTABLE_TASK_STATUSES: readonly ["active", "waiting", "sleeping"];
|
|
6
6
|
export type SettableTaskStatus = (typeof SETTABLE_TASK_STATUSES)[number];
|
|
7
|
-
export type TaskLifecycleAction = "create" | "progress" | "
|
|
8
|
-
/**
|
|
9
|
-
export declare function normalizeStoredStatus(raw: string | undefined
|
|
10
|
-
export declare function wasLegacyEscalated(raw: string | undefined): boolean;
|
|
7
|
+
export type TaskLifecycleAction = "create" | "progress" | "verify" | "complete" | "skip" | "cancel" | "set" | "pause" | "resume" | "run" | "governor-stop" | "wait-due" | "cycle-due";
|
|
8
|
+
/** Canonicalize a stored status value, fail-open to `active` for anything not in the current vocabulary. */
|
|
9
|
+
export declare function normalizeStoredStatus(raw: string | undefined): TaskStatus;
|
|
11
10
|
export declare function isSettableTaskStatus(value: string): value is SettableTaskStatus;
|
|
12
11
|
/** Assert an action is legal and resolve caller-supplied target status. */
|
|
13
12
|
export declare function resolveTaskTransition(action: TaskLifecycleAction, id: string, from: TaskStatus, requestedStatus?: string): TaskStatus;
|
|
@@ -8,8 +8,11 @@ const WORKABLE = ["active", "waiting"];
|
|
|
8
8
|
const TRANSITIONS = {
|
|
9
9
|
create: { from: [], to: "active" },
|
|
10
10
|
progress: { from: WORKABLE, to: "caller" },
|
|
11
|
-
|
|
12
|
-
verify
|
|
11
|
+
// Not gated on a specific waitingFor value: the wake that reactivates a task parked for a
|
|
12
|
+
// purpose=verify sub-agent already flips it to active before this runs (the same as any other
|
|
13
|
+
// delegation wake), but `verify` also accepts waiting so it is not sensitive to exactly when
|
|
14
|
+
// that reactivation lands relative to the model's own turn.
|
|
15
|
+
verify: { from: WORKABLE, to: "active" },
|
|
13
16
|
complete: { from: ["active"], to: "caller" },
|
|
14
17
|
skip: { from: WORKABLE, to: "sleeping" },
|
|
15
18
|
cancel: { from: LIVE, to: "caller" },
|
|
@@ -21,31 +24,9 @@ const TRANSITIONS = {
|
|
|
21
24
|
"wait-due": { from: ["waiting"], to: "active" },
|
|
22
25
|
"cycle-due": { from: ["sleeping"], to: "active" },
|
|
23
26
|
};
|
|
24
|
-
/**
|
|
25
|
-
export function normalizeStoredStatus(raw
|
|
26
|
-
|
|
27
|
-
case undefined:
|
|
28
|
-
case "":
|
|
29
|
-
case "open":
|
|
30
|
-
case "in-progress":
|
|
31
|
-
case "verifying":
|
|
32
|
-
return "active";
|
|
33
|
-
case "awaiting-user":
|
|
34
|
-
case "blocked":
|
|
35
|
-
return "waiting";
|
|
36
|
-
case "paused":
|
|
37
|
-
case "escalated":
|
|
38
|
-
return "active";
|
|
39
|
-
case "done":
|
|
40
|
-
return recurring ? "sleeping" : "active";
|
|
41
|
-
case "cancelled":
|
|
42
|
-
return "active";
|
|
43
|
-
default:
|
|
44
|
-
return TASK_STATUSES.includes(raw) ? raw : "active";
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
export function wasLegacyEscalated(raw) {
|
|
48
|
-
return raw === "escalated";
|
|
27
|
+
/** Canonicalize a stored status value, fail-open to `active` for anything not in the current vocabulary. */
|
|
28
|
+
export function normalizeStoredStatus(raw) {
|
|
29
|
+
return raw !== undefined && TASK_STATUSES.includes(raw) ? raw : "active";
|
|
49
30
|
}
|
|
50
31
|
export function isSettableTaskStatus(value) {
|
|
51
32
|
return SETTABLE_TASK_STATUSES.includes(value);
|
|
@@ -28,11 +28,13 @@ export interface VerificationAttestation {
|
|
|
28
28
|
*/
|
|
29
29
|
subjectDir?: string;
|
|
30
30
|
/**
|
|
31
|
-
* `enforced` — a built-in verifier
|
|
32
|
-
* runs (a real gate). `advisory` —
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
31
|
+
* `enforced` — a built-in verifier that could not write at all: write/edit are structurally
|
|
32
|
+
* removed before it runs, and its role declared no `bash` either (a real gate). `advisory` —
|
|
33
|
+
* every other shape: an external verifier (spec 040, D9), whose tools cannot be removed so the
|
|
34
|
+
* verdict rests on the target CLI's own sandbox flag plus the workspace hash, and a built-in
|
|
35
|
+
* verifier that kept `bash`, which can write files just as well as `write` can. Defaults to
|
|
36
|
+
* `enforced` for attestations written before this field existed — every verifier was built-in
|
|
37
|
+
* and this distinction did not exist then.
|
|
36
38
|
*/
|
|
37
39
|
verificationStrength: "enforced" | "advisory";
|
|
38
40
|
}
|
package/dist/tools/bash.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
import type { ChannelJobManager } from "../agent/job-manager.js";
|
|
4
|
-
import type
|
|
4
|
+
import { type Executor } from "../executor.js";
|
|
5
5
|
import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
|
|
6
6
|
/**
|
|
7
7
|
* Default wall-clock timeout for bash commands when the caller supplies neither a
|
package/dist/tools/bash.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
2
|
import { writeFile } from "node:fs/promises";
|
|
3
3
|
import { Type } from "typebox";
|
|
4
|
+
import { CommandTerminatedError } from "../executor.js";
|
|
4
5
|
import { guardCommand } from "../security/command-guard.js";
|
|
5
6
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
6
7
|
import { logSecurityEvent } from "../security/logger.js";
|
|
8
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
7
9
|
import { maybeOptimizeCommand } from "./command-optimizer.js";
|
|
8
10
|
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
|
|
9
11
|
/**
|
|
@@ -120,7 +122,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
120
122
|
if (options.interceptorEnabled) {
|
|
121
123
|
const intercepted = checkBashInterception(command);
|
|
122
124
|
if (intercepted) {
|
|
123
|
-
throw new
|
|
125
|
+
throw new RecoverableToolError(intercepted);
|
|
124
126
|
}
|
|
125
127
|
}
|
|
126
128
|
// Optimize *after* the security guard: the guard must inspect the operator's real
|
|
@@ -133,7 +135,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
133
135
|
// (the main path supplies a jobManager; the sub-agent path never does).
|
|
134
136
|
if (runAsync) {
|
|
135
137
|
if (!options.jobManager) {
|
|
136
|
-
throw new
|
|
138
|
+
throw new RecoverableToolError("Background execution is not available here (enable tools.jobs.enabled, and note it is off for sub-agents). Run the command without async, or shorten it.");
|
|
137
139
|
}
|
|
138
140
|
const willNotify = notify ?? true;
|
|
139
141
|
const job = await options.jobManager.start(effectiveCommand, label, effectiveTimeout, {
|
|
@@ -155,69 +157,85 @@ export function createBashTool(executor, options = {}) {
|
|
|
155
157
|
details: { async: { state: "running", jobId: job.id } },
|
|
156
158
|
};
|
|
157
159
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
// through a second `sh -c 'cat > file'`: that spawned a process and copied the whole
|
|
171
|
-
// (up to 10MB) buffer over a pipe to reach the same local filesystem the executor
|
|
172
|
-
// already runs on. Best-effort: on failure we simply omit the path hint.
|
|
173
|
-
let tempFilePath;
|
|
174
|
-
if (totalBytes > DEFAULT_MAX_BYTES) {
|
|
175
|
-
const candidatePath = getSpillFilePath();
|
|
176
|
-
try {
|
|
177
|
-
await writeFile(candidatePath, output, { mode: 0o600 });
|
|
178
|
-
tempFilePath = candidatePath;
|
|
160
|
+
// Spill + tail-truncate a combined stdout/stderr blob, sharing the same path for a normal
|
|
161
|
+
// result and one cut short by timeout/abort (fix plan §2.2): a timed-out `npm test` used
|
|
162
|
+
// to reject with up to 10MB of raw output stuffed straight into the tool-call error
|
|
163
|
+
// message, which the pi SDK puts into the model's context verbatim and unbounded.
|
|
164
|
+
const buildOutputText = async (stdout, stderr) => {
|
|
165
|
+
let output = "";
|
|
166
|
+
if (stdout)
|
|
167
|
+
output += stdout;
|
|
168
|
+
if (stderr) {
|
|
169
|
+
if (output)
|
|
170
|
+
output += "\n";
|
|
171
|
+
output += stderr;
|
|
179
172
|
}
|
|
180
|
-
|
|
181
|
-
|
|
173
|
+
const totalBytes = Buffer.byteLength(output, "utf-8");
|
|
174
|
+
// Spill the full output to a temp file when it exceeds the inline limit, so the model
|
|
175
|
+
// can page through the rest with `read`. Written straight to disk rather than piped
|
|
176
|
+
// through a second `sh -c 'cat > file'`: that spawned a process and copied the whole
|
|
177
|
+
// (up to 10MB) buffer over a pipe to reach the same local filesystem the executor
|
|
178
|
+
// already runs on. Best-effort: on failure we simply omit the path hint.
|
|
179
|
+
let tempFilePath;
|
|
180
|
+
if (totalBytes > DEFAULT_MAX_BYTES) {
|
|
181
|
+
const candidatePath = getSpillFilePath();
|
|
182
|
+
try {
|
|
183
|
+
await writeFile(candidatePath, output, { mode: 0o600 });
|
|
184
|
+
tempFilePath = candidatePath;
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// Ignore spill failures; the truncated output is still returned.
|
|
188
|
+
}
|
|
182
189
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
truncation
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
outputText += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}).${fullOutputHint}]`;
|
|
190
|
+
const truncation = truncateTail(output);
|
|
191
|
+
let text = truncation.content || "(no output)";
|
|
192
|
+
let details;
|
|
193
|
+
if (truncation.truncated) {
|
|
194
|
+
details = { truncation, fullOutputPath: tempFilePath };
|
|
195
|
+
const startLine = truncation.totalLines - truncation.outputLines + 1;
|
|
196
|
+
const endLine = truncation.totalLines;
|
|
197
|
+
const fullOutputHint = tempFilePath ? ` Full output: ${tempFilePath}` : "";
|
|
198
|
+
if (truncation.lastLinePartial) {
|
|
199
|
+
const lastLineSize = formatSize(Buffer.byteLength(output.split("\n").pop() || "", "utf-8"));
|
|
200
|
+
text += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}).${fullOutputHint}]`;
|
|
201
|
+
}
|
|
202
|
+
else if (truncation.truncatedBy === "lines") {
|
|
203
|
+
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}.${fullOutputHint}]`;
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit).${fullOutputHint}]`;
|
|
207
|
+
}
|
|
202
208
|
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
209
|
+
return { text, details: { ...details, producedOutput: output.trim().length > 0 } };
|
|
210
|
+
};
|
|
211
|
+
try {
|
|
212
|
+
const result = await executor.exec(effectiveCommand, { timeout: effectiveTimeout, signal });
|
|
213
|
+
const built = await buildOutputText(result.stdout, result.stderr);
|
|
214
|
+
let outputText = built.text;
|
|
215
|
+
// A non-zero exit code is a normal result, not a tool failure: commands like
|
|
216
|
+
// `grep` (no match), `diff` (differences), and `test` use exit codes as data.
|
|
217
|
+
// Report the code inline so the model can react without treating it as an error.
|
|
218
|
+
if (result.code !== 0) {
|
|
219
|
+
outputText += `\n\nExit code: ${result.code}`;
|
|
208
220
|
}
|
|
221
|
+
// Recorded unconditionally (not only on failure) because the task governor judges a
|
|
222
|
+
// wake's productivity from it: a command that ran clean and returned something is the
|
|
223
|
+
// evidence that a turn spent driving an external tool was not idle.
|
|
224
|
+
const details = { ...built.details, exitCode: result.code };
|
|
225
|
+
return { content: [{ type: "text", text: outputText }], details };
|
|
209
226
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
227
|
+
catch (error) {
|
|
228
|
+
if (!(error instanceof CommandTerminatedError)) {
|
|
229
|
+
throw error;
|
|
230
|
+
}
|
|
231
|
+
const built = await buildOutputText(error.stdout, error.stderr);
|
|
232
|
+
const nextStep = error.reason === "timeout"
|
|
233
|
+
? `Retry with a larger \`timeout\` (currently ${error.timeoutSeconds}s), or pass \`async: true\` to run it in the background and be woken when it finishes.`
|
|
234
|
+
: "The command was stopped (e.g. by /stop or a run cancellation); partial output above.";
|
|
235
|
+
const outputText = `${built.text}\n\n[${error.message}; partial output above. ${nextStep}]`;
|
|
236
|
+
const details = { ...built.details, timedOut: true };
|
|
237
|
+
return { content: [{ type: "text", text: outputText }], details };
|
|
215
238
|
}
|
|
216
|
-
// Recorded unconditionally (not only on failure) because the task governor judges a
|
|
217
|
-
// wake's productivity from it: a command that ran clean and returned something is the
|
|
218
|
-
// evidence that a turn spent driving an external tool was not idle.
|
|
219
|
-
details = { ...details, exitCode: result.code, producedOutput: output.trim().length > 0 };
|
|
220
|
-
return { content: [{ type: "text", text: outputText }], details };
|
|
221
239
|
},
|
|
222
240
|
};
|
|
223
241
|
}
|