@abhishek944/pi-tasks 0.15.0 → 0.17.0
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 +63 -14
- package/dist/agents/delegation.d.ts +4 -0
- package/dist/agents/delegation.js +130 -0
- package/dist/agents/herdr.d.ts +10 -3
- package/dist/agents/herdr.js +39 -12
- package/dist/agents/links.d.ts +3 -3
- package/dist/agents/links.js +42 -19
- package/dist/auto-continue.js +409 -33
- package/dist/blocked.d.ts +29 -0
- package/dist/blocked.js +100 -0
- package/dist/command.d.ts +2 -2
- package/dist/command.js +7 -3
- package/dist/delegated-time.d.ts +12 -1
- package/dist/delegated-time.js +96 -15
- package/dist/dependency.d.ts +7 -0
- package/dist/dependency.js +13 -0
- package/dist/durable.d.ts +42 -0
- package/dist/durable.js +577 -0
- package/dist/herdr-header.d.ts +3 -0
- package/dist/herdr-header.js +100 -0
- package/dist/herdr-panel.d.ts +15 -0
- package/dist/herdr-panel.js +219 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +125 -56
- package/dist/markdown.js +3 -1
- package/dist/panel-settings.d.ts +11 -0
- package/dist/panel-settings.js +30 -0
- package/dist/progress.js +1 -1
- package/dist/snapshot.d.ts +23 -0
- package/dist/snapshot.js +166 -0
- package/dist/state.d.ts +43 -18
- package/dist/state.js +581 -289
- package/dist/thoughts.d.ts +11 -0
- package/dist/thoughts.js +14 -0
- package/dist/timing.js +9 -2
- package/dist/tools.js +295 -34
- package/dist/tracking.js +25 -13
- package/dist/transition.d.ts +9 -0
- package/dist/transition.js +26 -0
- package/dist/types.d.ts +76 -3
- package/dist/ui/panel.js +38 -19
- package/dist/ui/task-view.d.ts +7 -0
- package/dist/ui/task-view.js +10 -0
- package/dist/ui/works-dashboard.js +37 -19
- package/docs/REFERENCE.md +85 -31
- package/docs/USAGE_GUIDE.md +129 -55
- package/herdr/pi-tasks/README.md +46 -0
- package/herdr/pi-tasks/header.js +212 -0
- package/herdr/pi-tasks/main.js +488 -0
- package/herdr/pi-tasks/mod.json +3 -0
- package/herdr/pi-tasks/spinner.svg +1 -0
- package/package.json +26 -1
- package/dist/agents/tools.d.ts +0 -3
- package/dist/agents/tools.js +0 -143
package/dist/durable.js
ADDED
|
@@ -0,0 +1,577 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Settings-only native Durable entrypoint for pi-tasks.
|
|
3
|
+
*
|
|
4
|
+
* `createTasksDurableExtension(settings)` returns a native Durable {@link Extension}
|
|
5
|
+
* that registers real, working Work/Todo record tools. Records live in one
|
|
6
|
+
* conversation-scoped Durable document (`pi-tasks.state`, `history: "latest"`,
|
|
7
|
+
* `fork: "initial"`), so every conversation has isolated tracking and a fork starts
|
|
8
|
+
* empty. All mutations go through atomic `api.commit()` transactions; the
|
|
9
|
+
* invocation-bound `api` is never retained.
|
|
10
|
+
*
|
|
11
|
+
* Desktop-only surfaces are intentionally absent here, not stubbed:
|
|
12
|
+
* - AgentCreate/Resume/List/Status/Output/Send/Interrupt/Close/Focus need the Herdr CLI
|
|
13
|
+
* plus Pi nested `executeTool`, which Durable 1.1 `ToolExecutionApi` does not expose.
|
|
14
|
+
* - TaskTimeExport/Import need repository `var/` timing files plus a parent Pi session.
|
|
15
|
+
* - Auto-continuation and TodoUpdate transition review need Pi's `agent_before_settle`/`turn_end` boundaries; the `/works`
|
|
16
|
+
* command and the TUI panel/overlay are desktop Pi surfaces.
|
|
17
|
+
* - Effort timing (`working` selection, elapsed measurement) needs the Pi agent
|
|
18
|
+
* lifecycle that pauses timers at loop boundaries; no native equivalent exists, so
|
|
19
|
+
* the native schema carries no timing fields and reports no times rather than
|
|
20
|
+
* fabricated zeros. Desktop timing is unchanged.
|
|
21
|
+
* - Durable 1.1 has no generic `executeTool`, and its `ToolTask` input requires an
|
|
22
|
+
* existing assistant entry, so no cross-tool bridge is fabricated.
|
|
23
|
+
*/
|
|
24
|
+
import { StringEnum } from "@earendil-works/pi-ai";
|
|
25
|
+
import { defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
|
|
26
|
+
import { Type } from "typebox";
|
|
27
|
+
import { blockedAgeMs, formatBlockedAge } from "./blocked.js";
|
|
28
|
+
import { DEPENDENCY_GUIDANCE, dependentOnLabel, isTaskDependency, TASK_DEPENDENCIES } from "./dependency.js";
|
|
29
|
+
import { taskOwner } from "./ownership.js";
|
|
30
|
+
import { safeSingleLine } from "./text.js";
|
|
31
|
+
import { finalThoughtsFor } from "./thoughts.js";
|
|
32
|
+
import { todoTransition } from "./transition.js";
|
|
33
|
+
const STATE_KIND = "pi-tasks.state";
|
|
34
|
+
const STATE_VERSION = 1;
|
|
35
|
+
const tasksDoc = defineDoc({
|
|
36
|
+
kind: STATE_KIND,
|
|
37
|
+
version: STATE_VERSION,
|
|
38
|
+
scope: "conversation",
|
|
39
|
+
history: "latest",
|
|
40
|
+
fork: "initial",
|
|
41
|
+
initial: () => ({ works: [], todos: [], nextWorkId: 1, nextTaskId: 1 }),
|
|
42
|
+
});
|
|
43
|
+
const StatusSchema = StringEnum(["active", "blocked", "completed", "closed", "cancelled"]);
|
|
44
|
+
const InfoSchema = Type.String({ minLength: 1, maxLength: 10_000 });
|
|
45
|
+
const TaskInfoSchema = Type.String({ minLength: 1, maxLength: 10_000, description: "Hidden coordination metadata for resumption: owner declaration, canonical artifact paths, parent IDs, and necessary execution constraints. Never shown as task text; do not narrate goals or progress here." });
|
|
46
|
+
const FinalThoughtsSchema = Type.String({ description: "The only user-visible task text. One concise update, not a goal, history, list, or section. Completed tasks state the actual result, verification, and remaining limits; active tasks update only for significant changes with no filler; blocked tasks use blockedReason as the authoritative dependency. Never include owner declarations, links, paths, or parent IDs." });
|
|
47
|
+
const NameSchema = Type.String({ minLength: 1, maxLength: 240 });
|
|
48
|
+
const CompletionSchema = Type.Union([Type.Integer({ minimum: 0, maximum: 100 }), Type.Null()]);
|
|
49
|
+
const BlockedReasonSchema = Type.Union([Type.String({ minLength: 1, maxLength: 10_000 }), Type.Null()]);
|
|
50
|
+
const DependencySchema = Type.Union([StringEnum(TASK_DEPENDENCIES), Type.Null()], { description: DEPENDENCY_GUIDANCE });
|
|
51
|
+
const DecisionQuestionSchema = Type.String({ minLength: 1, description: "The pi-decisions questionId this user-decision blocker waits on. Set it when the blocker was presented with SubmitQuestion so a pending page can be re-armed or withdrawn and every linked task reconciled together. Only valid while blocked on user-decision." });
|
|
52
|
+
const MAX_TEXT_BYTES = 50_000;
|
|
53
|
+
const MAX_TEXT_LINES = 2_000;
|
|
54
|
+
function bounded(text) {
|
|
55
|
+
const lines = text.split("\n");
|
|
56
|
+
const clipped = lines.length > MAX_TEXT_LINES ? [...lines.slice(0, MAX_TEXT_LINES), "[Output truncated.]"] : lines;
|
|
57
|
+
const joined = clipped.join("\n");
|
|
58
|
+
return joined.length > MAX_TEXT_BYTES ? `${joined.slice(0, MAX_TEXT_BYTES)}\n[Output truncated.]` : joined;
|
|
59
|
+
}
|
|
60
|
+
function validLimit(value, fallback) {
|
|
61
|
+
if (value === undefined)
|
|
62
|
+
return fallback;
|
|
63
|
+
if (!Number.isInteger(value) || value < 1 || value > 10_000) {
|
|
64
|
+
throw new Error("Task limits must be integers from 1 to 10000.");
|
|
65
|
+
}
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
68
|
+
function requiredName(value) {
|
|
69
|
+
const text = safeSingleLine(value);
|
|
70
|
+
if (!text)
|
|
71
|
+
throw new Error("Names must not be empty.");
|
|
72
|
+
return text;
|
|
73
|
+
}
|
|
74
|
+
function requiredText(value) {
|
|
75
|
+
const text = value.trim();
|
|
76
|
+
if (!text)
|
|
77
|
+
throw new Error("Details must not be empty.");
|
|
78
|
+
return text;
|
|
79
|
+
}
|
|
80
|
+
function optionalThoughts(value) {
|
|
81
|
+
if (value === undefined)
|
|
82
|
+
return undefined;
|
|
83
|
+
const text = value.trim();
|
|
84
|
+
return text || undefined;
|
|
85
|
+
}
|
|
86
|
+
function checkCompletion(status, value) {
|
|
87
|
+
if (value === undefined || value === null)
|
|
88
|
+
return;
|
|
89
|
+
if (!Number.isInteger(value) || value < 0 || value > 100) {
|
|
90
|
+
throw new Error("completionPercent must be an integer from 0 to 100, or null for unknown.");
|
|
91
|
+
}
|
|
92
|
+
if (value === 100 && status !== "completed" && status !== "closed") {
|
|
93
|
+
throw new Error("100% requires verified completion. Set status to completed after verification.");
|
|
94
|
+
}
|
|
95
|
+
if ((status === "completed" || status === "closed") && value !== 100) {
|
|
96
|
+
throw new Error("Completed tasks have 100% progress. Reopen the task before reporting partial progress.");
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** Mirrors the desktop completion policy: completed is 100, missing estimates stay unknown. */
|
|
100
|
+
function taskCompletion(status, completionPercent) {
|
|
101
|
+
if (status === "completed" || status === "closed")
|
|
102
|
+
return 100;
|
|
103
|
+
return typeof completionPercent === "number" && Number.isInteger(completionPercent)
|
|
104
|
+
&& completionPercent >= 0 && completionPercent < 100 ? completionPercent : null;
|
|
105
|
+
}
|
|
106
|
+
function workCompletion(todos, workId) {
|
|
107
|
+
const tasks = todos.filter((todo) => todo.workId === workId && todo.status !== "cancelled");
|
|
108
|
+
if (tasks.length === 0)
|
|
109
|
+
return null;
|
|
110
|
+
let total = 0;
|
|
111
|
+
for (const todo of tasks) {
|
|
112
|
+
const value = taskCompletion(todo.status, todo.completionPercent);
|
|
113
|
+
if (value === null)
|
|
114
|
+
return null;
|
|
115
|
+
total += value;
|
|
116
|
+
}
|
|
117
|
+
return Math.floor(total / tasks.length);
|
|
118
|
+
}
|
|
119
|
+
function formatCompletion(value) {
|
|
120
|
+
return value === null ? "—" : `${value}%`;
|
|
121
|
+
}
|
|
122
|
+
function normalizeBlockedReason(status, supplied, current) {
|
|
123
|
+
if (status !== "blocked") {
|
|
124
|
+
if (supplied !== undefined && supplied !== null) {
|
|
125
|
+
throw new Error("blockedReason is only valid for blocked tasks.");
|
|
126
|
+
}
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
if (supplied === undefined && current?.status === "blocked")
|
|
130
|
+
return current.blockedReason;
|
|
131
|
+
if (typeof supplied !== "string" || !supplied.trim()) {
|
|
132
|
+
throw new Error("Blocked tasks require a nonempty blockedReason explaining the obstacle and what will allow work to resume.");
|
|
133
|
+
}
|
|
134
|
+
return supplied.trim();
|
|
135
|
+
}
|
|
136
|
+
function normalizeDependency(status, supplied, current) {
|
|
137
|
+
if (status !== "blocked") {
|
|
138
|
+
if (supplied !== undefined && supplied !== null) {
|
|
139
|
+
throw new Error("dependentOn is only valid for blocked tasks.");
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
if (supplied === undefined && current?.status === "blocked")
|
|
144
|
+
return current.dependentOn ?? null;
|
|
145
|
+
if (!isTaskDependency(supplied)) {
|
|
146
|
+
throw new Error("Blocked tasks require dependentOn=\"user-decision\" or dependentOn=\"another-agent\".");
|
|
147
|
+
}
|
|
148
|
+
return supplied;
|
|
149
|
+
}
|
|
150
|
+
function normalizeDecisionQuestionId(status, dependency, supplied, current) {
|
|
151
|
+
if (status !== "blocked" || dependency !== "user-decision") {
|
|
152
|
+
if (supplied !== undefined) {
|
|
153
|
+
throw new Error("decisionQuestionId is only valid for a task blocked on user-decision.");
|
|
154
|
+
}
|
|
155
|
+
return undefined;
|
|
156
|
+
}
|
|
157
|
+
if (supplied === undefined) {
|
|
158
|
+
return current?.status === "blocked" && current.dependentOn === "user-decision" ? current.decisionQuestionId : undefined;
|
|
159
|
+
}
|
|
160
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/u.test(supplied)) {
|
|
161
|
+
throw new Error("decisionQuestionId must be a pi-decisions question ID.");
|
|
162
|
+
}
|
|
163
|
+
return supplied;
|
|
164
|
+
}
|
|
165
|
+
function formatTodo(todo) {
|
|
166
|
+
const owner = taskOwner(todo.taskInfo);
|
|
167
|
+
const dependency = dependentOnLabel(todo.dependentOn);
|
|
168
|
+
const blockedAge = todo.status === "blocked" ? formatBlockedAge(blockedAgeMs(todo)) : undefined;
|
|
169
|
+
const blockedSince = blockedAge === undefined ? "" : ` · ${blockedAge}`;
|
|
170
|
+
const question = todo.status === "blocked" && todo.decisionQuestionId !== undefined
|
|
171
|
+
? `Decision question: ${todo.decisionQuestionId}\n` : "";
|
|
172
|
+
return `${todo.taskId} [${todo.status}] [${owner === "self" || owner === "delegate" ? owner : "unassigned"}] ${todo.taskName} · ${formatCompletion(taskCompletion(todo.status, todo.completionPercent))}\nWork: ${todo.workId}\nFinal thoughts:\n${finalThoughtsFor(todo) ?? "None recorded."}\n${dependency === undefined ? "" : `Dependent on: ${dependency}${blockedSince}\n`}${question}Task info (hidden coordination metadata):\n${todo.taskInfo}`;
|
|
173
|
+
}
|
|
174
|
+
function formatWork(doc, work, filter) {
|
|
175
|
+
const todos = doc.todos
|
|
176
|
+
.filter((todo) => todo.workId === work.workId)
|
|
177
|
+
.filter((todo) => !filter?.status || todo.status === filter.status);
|
|
178
|
+
return [
|
|
179
|
+
`${work.workId} ${work.workName} · ${formatCompletion(workCompletion(doc.todos, work.workId))}`,
|
|
180
|
+
`Work info:\n${work.workInfo}`,
|
|
181
|
+
todos.length ? `Todos:\n${todos.map((todo) => formatTodo(todo)).join("\n\n")}` : "Todos: none",
|
|
182
|
+
].join("\n");
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Create a native Work/Todo tracking extension from serializable settings.
|
|
186
|
+
* The host opens its own Harness with models/storage/env and installs the result.
|
|
187
|
+
* Record tools only: effort timing is unsupported natively (see module docs).
|
|
188
|
+
*/
|
|
189
|
+
export function createTasksDurableExtension(settings = {}) {
|
|
190
|
+
const maxWorks = validLimit(settings.maxWorks, 100);
|
|
191
|
+
const maxTodos = validLimit(settings.maxTodos, 500);
|
|
192
|
+
const workCreate = defineTool({
|
|
193
|
+
name: "WorkCreate",
|
|
194
|
+
description: "Create a work collection: shared goal, context, and constraints for its todos. Works have no status; todos own status. Takes workName and detailed workInfo.",
|
|
195
|
+
parameters: Type.Object({ workName: NameSchema, workInfo: InfoSchema }, { additionalProperties: false }),
|
|
196
|
+
replay: "unsafe",
|
|
197
|
+
executionMode: "sequential",
|
|
198
|
+
async execute(args, api, context) {
|
|
199
|
+
if (context.abortSignal?.aborted)
|
|
200
|
+
throw new Error("WorkCreate aborted before its transaction.");
|
|
201
|
+
const created = await api.commit(async (tx) => {
|
|
202
|
+
const doc = await tx.doc(tasksDoc, api.conversationId);
|
|
203
|
+
if (doc.works.length >= maxWorks)
|
|
204
|
+
throw new Error(`Maximum of ${maxWorks} works reached.`);
|
|
205
|
+
const now = Date.now();
|
|
206
|
+
const work = {
|
|
207
|
+
workId: `W${doc.nextWorkId}`,
|
|
208
|
+
workName: requiredName(args.workName),
|
|
209
|
+
workInfo: requiredText(args.workInfo),
|
|
210
|
+
createdAt: now,
|
|
211
|
+
updatedAt: now,
|
|
212
|
+
};
|
|
213
|
+
doc.works.push(work);
|
|
214
|
+
doc.nextWorkId += 1;
|
|
215
|
+
return { ...work };
|
|
216
|
+
}, context);
|
|
217
|
+
return {
|
|
218
|
+
content: [{ type: "text", text: `Created work ${created.workId}: ${created.workName}` }],
|
|
219
|
+
details: { workId: created.workId, workName: created.workName },
|
|
220
|
+
};
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
const workList = defineTool({
|
|
224
|
+
name: "WorkList",
|
|
225
|
+
description: "List works and their todos for this conversation. Optional workId filter and limit return the newest N matching works. Reports progress and status; effort timing is unsupported natively. Read-only.",
|
|
226
|
+
parameters: Type.Object({
|
|
227
|
+
workId: Type.Optional(Type.String()),
|
|
228
|
+
limit: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
229
|
+
}, { additionalProperties: false }),
|
|
230
|
+
replay: "safe",
|
|
231
|
+
executionMode: "sequential",
|
|
232
|
+
async execute(args, api, context) {
|
|
233
|
+
const snapshot = await api.snapshot(tasksDoc, api.conversationId, context);
|
|
234
|
+
const matches = (snapshot?.works ?? [])
|
|
235
|
+
.filter((work) => args.workId === undefined || work.workId === args.workId)
|
|
236
|
+
.sort((left, right) => left.createdAt - right.createdAt);
|
|
237
|
+
const works = args.limit === undefined ? matches : matches.slice(-args.limit);
|
|
238
|
+
const doc = snapshot ?? { works: [], todos: [], nextWorkId: 1, nextTaskId: 1 };
|
|
239
|
+
const text = works.length === 0
|
|
240
|
+
? "No works found in this conversation."
|
|
241
|
+
: works.map((work) => formatWork(doc, work)).join("\n\n---\n\n");
|
|
242
|
+
return {
|
|
243
|
+
content: [{ type: "text", text: bounded(`Showing ${works.length} of ${matches.length} matching works\n\n${text}`) }],
|
|
244
|
+
details: { count: works.length, total: matches.length },
|
|
245
|
+
};
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
const workUpdate = defineTool({
|
|
249
|
+
name: "WorkUpdate",
|
|
250
|
+
description: "Update a work's name or shared context when scope or decisions change. Requires at least one changed field. Works have no status. It is not the record for a new user request; create that request's todo first.",
|
|
251
|
+
parameters: Type.Object({
|
|
252
|
+
workId: Type.String({ minLength: 1 }),
|
|
253
|
+
workName: Type.Optional(NameSchema),
|
|
254
|
+
workInfo: Type.Optional(InfoSchema),
|
|
255
|
+
}, { additionalProperties: false }),
|
|
256
|
+
replay: "unsafe",
|
|
257
|
+
executionMode: "sequential",
|
|
258
|
+
async execute(args, api, context) {
|
|
259
|
+
if (context.abortSignal?.aborted)
|
|
260
|
+
throw new Error("WorkUpdate aborted before its transaction.");
|
|
261
|
+
const updated = await api.commit(async (tx) => {
|
|
262
|
+
const doc = await tx.doc(tasksDoc, api.conversationId);
|
|
263
|
+
const work = doc.works.find((entry) => entry.workId === args.workId);
|
|
264
|
+
if (!work)
|
|
265
|
+
throw new Error(`Work ${args.workId} not found in this conversation.`);
|
|
266
|
+
let changed = false;
|
|
267
|
+
if (args.workName !== undefined) {
|
|
268
|
+
const name = requiredName(args.workName);
|
|
269
|
+
if (name !== work.workName) {
|
|
270
|
+
work.workName = name;
|
|
271
|
+
changed = true;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (args.workInfo !== undefined) {
|
|
275
|
+
const info = requiredText(args.workInfo);
|
|
276
|
+
if (info !== work.workInfo) {
|
|
277
|
+
work.workInfo = info;
|
|
278
|
+
changed = true;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (!changed)
|
|
282
|
+
throw new Error("WorkUpdate requires at least one changed field.");
|
|
283
|
+
work.updatedAt = Date.now();
|
|
284
|
+
return { ...work };
|
|
285
|
+
}, context);
|
|
286
|
+
return {
|
|
287
|
+
content: [{ type: "text", text: `Updated work ${updated.workId}: ${updated.workName}` }],
|
|
288
|
+
details: { workId: updated.workId, workName: updated.workName },
|
|
289
|
+
};
|
|
290
|
+
},
|
|
291
|
+
});
|
|
292
|
+
const workDelete = defineTool({
|
|
293
|
+
name: "WorkDelete",
|
|
294
|
+
description: "Delete a work and every todo under it. Use only for explicit cancellation or mistaken entries.",
|
|
295
|
+
parameters: Type.Object({ workId: Type.String({ minLength: 1 }) }, { additionalProperties: false }),
|
|
296
|
+
replay: "unsafe",
|
|
297
|
+
executionMode: "sequential",
|
|
298
|
+
async execute(args, api, context) {
|
|
299
|
+
if (context.abortSignal?.aborted)
|
|
300
|
+
throw new Error("WorkDelete aborted before its transaction.");
|
|
301
|
+
const removed = await api.commit(async (tx) => {
|
|
302
|
+
const doc = await tx.doc(tasksDoc, api.conversationId);
|
|
303
|
+
const index = doc.works.findIndex((entry) => entry.workId === args.workId);
|
|
304
|
+
if (index === -1)
|
|
305
|
+
throw new Error(`Work ${args.workId} not found in this conversation.`);
|
|
306
|
+
const removedTodos = doc.todos.filter((todo) => todo.workId === args.workId);
|
|
307
|
+
doc.todos = doc.todos.filter((todo) => todo.workId !== args.workId);
|
|
308
|
+
const [work] = doc.works.splice(index, 1);
|
|
309
|
+
if (!work)
|
|
310
|
+
throw new Error(`Work ${args.workId} is no longer available.`);
|
|
311
|
+
return { workId: work.workId, todoCount: removedTodos.length };
|
|
312
|
+
}, context);
|
|
313
|
+
return {
|
|
314
|
+
content: [{ type: "text", text: `Deleted work ${removed.workId} and ${removed.todoCount} associated todo${removed.todoCount === 1 ? "" : "s"}.` }],
|
|
315
|
+
details: { workId: removed.workId, todoCount: removed.todoCount },
|
|
316
|
+
};
|
|
317
|
+
},
|
|
318
|
+
});
|
|
319
|
+
const todoCreate = defineTool({
|
|
320
|
+
name: "TodoCreate",
|
|
321
|
+
description: `Create one concrete todo under an existing work. A distinct new user request needs its own todo, even under an existing work; reuse an existing todo only when it owns the same outcome. New tasks default to active. taskInfo is hidden coordination metadata; finalThoughts is the only user-visible task text. Supply blockedReason and dependentOn when creating a blocked task. ${DEPENDENCY_GUIDANCE} completionPercent is an optional 0-100 estimate, null for unknown; 100 requires completed status.`,
|
|
322
|
+
parameters: Type.Object({
|
|
323
|
+
workId: Type.String({ minLength: 1 }),
|
|
324
|
+
taskName: NameSchema,
|
|
325
|
+
taskInfo: TaskInfoSchema,
|
|
326
|
+
finalThoughts: Type.Optional(FinalThoughtsSchema),
|
|
327
|
+
status: Type.Optional(StatusSchema),
|
|
328
|
+
completionPercent: Type.Optional(CompletionSchema),
|
|
329
|
+
blockedReason: Type.Optional(BlockedReasonSchema),
|
|
330
|
+
dependentOn: Type.Optional(DependencySchema),
|
|
331
|
+
decisionQuestionId: Type.Optional(DecisionQuestionSchema),
|
|
332
|
+
}, { additionalProperties: false }),
|
|
333
|
+
replay: "unsafe",
|
|
334
|
+
executionMode: "sequential",
|
|
335
|
+
async execute(args, api, context) {
|
|
336
|
+
if (context.abortSignal?.aborted)
|
|
337
|
+
throw new Error("TodoCreate aborted before its transaction.");
|
|
338
|
+
const created = await api.commit(async (tx) => {
|
|
339
|
+
const doc = await tx.doc(tasksDoc, api.conversationId);
|
|
340
|
+
if (!doc.works.some((work) => work.workId === args.workId)) {
|
|
341
|
+
throw new Error(`Work ${args.workId} not found in this conversation.`);
|
|
342
|
+
}
|
|
343
|
+
if (doc.todos.length >= maxTodos)
|
|
344
|
+
throw new Error(`Maximum of ${maxTodos} todos reached.`);
|
|
345
|
+
const status = (args.status ?? "active");
|
|
346
|
+
if (status === "closed")
|
|
347
|
+
throw new Error("Create the task first; close it after its verified completion.");
|
|
348
|
+
checkCompletion(status, args.completionPercent ?? null);
|
|
349
|
+
const now = Date.now();
|
|
350
|
+
// Chord rejects an own undefined property as non-JSON. Normalize once and
|
|
351
|
+
// omit the field entirely when the caller supplied nothing or blank text.
|
|
352
|
+
const finalThoughts = optionalThoughts(args.finalThoughts);
|
|
353
|
+
const dependency = normalizeDependency(status, args.dependentOn, undefined);
|
|
354
|
+
const decisionQuestionId = normalizeDecisionQuestionId(status, dependency, args.decisionQuestionId, undefined);
|
|
355
|
+
const todo = {
|
|
356
|
+
taskId: `T${doc.nextTaskId}`,
|
|
357
|
+
workId: args.workId,
|
|
358
|
+
taskName: requiredName(args.taskName),
|
|
359
|
+
taskInfo: requiredText(args.taskInfo),
|
|
360
|
+
...(finalThoughts === undefined ? {} : { finalThoughts }),
|
|
361
|
+
status,
|
|
362
|
+
blockedReason: normalizeBlockedReason(status, args.blockedReason ?? undefined, undefined),
|
|
363
|
+
dependentOn: dependency,
|
|
364
|
+
...(status === "blocked" ? { blockedAt: now } : {}),
|
|
365
|
+
...(decisionQuestionId === undefined ? {} : { decisionQuestionId }),
|
|
366
|
+
completionPercent: status === "completed" ? 100 : (args.completionPercent ?? null),
|
|
367
|
+
createdAt: now,
|
|
368
|
+
updatedAt: now,
|
|
369
|
+
};
|
|
370
|
+
doc.todos.push(todo);
|
|
371
|
+
doc.nextTaskId += 1;
|
|
372
|
+
return { ...todo };
|
|
373
|
+
}, context);
|
|
374
|
+
return {
|
|
375
|
+
content: [{ type: "text", text: `Created todo ${created.taskId} under ${created.workId}: ${created.taskName} [${created.status}]` }],
|
|
376
|
+
details: { taskId: created.taskId, workId: created.workId, status: created.status },
|
|
377
|
+
};
|
|
378
|
+
},
|
|
379
|
+
});
|
|
380
|
+
const todoList = defineTool({
|
|
381
|
+
name: "TodoList",
|
|
382
|
+
description: "List todos for this conversation, with progress and status. Effort timing is unsupported natively. Optional taskId, workId, status, and limit filters. Read-only.",
|
|
383
|
+
parameters: Type.Object({
|
|
384
|
+
taskId: Type.Optional(Type.String()),
|
|
385
|
+
workId: Type.Optional(Type.String()),
|
|
386
|
+
status: Type.Optional(StatusSchema),
|
|
387
|
+
limit: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
388
|
+
}, { additionalProperties: false }),
|
|
389
|
+
replay: "safe",
|
|
390
|
+
executionMode: "sequential",
|
|
391
|
+
async execute(args, api, context) {
|
|
392
|
+
const snapshot = await api.snapshot(tasksDoc, api.conversationId, context);
|
|
393
|
+
const matches = (snapshot?.todos ?? [])
|
|
394
|
+
.filter((todo) => args.taskId === undefined || todo.taskId === args.taskId)
|
|
395
|
+
.filter((todo) => args.workId === undefined || todo.workId === args.workId)
|
|
396
|
+
.filter((todo) => args.status === undefined || todo.status === args.status)
|
|
397
|
+
.sort((left, right) => left.createdAt - right.createdAt);
|
|
398
|
+
const todos = args.limit === undefined ? matches : matches.slice(-args.limit);
|
|
399
|
+
const text = todos.length === 0
|
|
400
|
+
? "No todos found."
|
|
401
|
+
: todos.map((todo) => formatTodo(todo)).join("\n\n");
|
|
402
|
+
return {
|
|
403
|
+
content: [{ type: "text", text: bounded(`Showing ${todos.length} of ${matches.length} matching todos\n\n${text}`) }],
|
|
404
|
+
details: { count: todos.length, total: matches.length },
|
|
405
|
+
};
|
|
406
|
+
},
|
|
407
|
+
});
|
|
408
|
+
const todoUpdate = defineTool({
|
|
409
|
+
name: "TodoUpdate",
|
|
410
|
+
description: `Update a todo's name, hidden coordination metadata, visible final thoughts, status, progress, blocked reason, or dependency. Requires at least one changed field. A status change clears an unsupplied thought; supply the new completed result or blocked dependency. ${DEPENDENCY_GUIDANCE} Completion follows: 100 only with completed status; reopening a completed task without a fresh estimate resets progress to unknown. Do not rename or broaden a todo to absorb a distinct new request; create a new todo. Effort timing is unsupported natively: there is no working field.`,
|
|
411
|
+
parameters: Type.Object({
|
|
412
|
+
taskId: Type.String({ minLength: 1 }),
|
|
413
|
+
taskName: Type.Optional(NameSchema),
|
|
414
|
+
taskInfo: Type.Optional(TaskInfoSchema),
|
|
415
|
+
finalThoughts: Type.Optional(FinalThoughtsSchema),
|
|
416
|
+
status: Type.Optional(StatusSchema),
|
|
417
|
+
completionPercent: Type.Optional(CompletionSchema),
|
|
418
|
+
blockedReason: Type.Optional(BlockedReasonSchema),
|
|
419
|
+
dependentOn: Type.Optional(DependencySchema),
|
|
420
|
+
decisionQuestionId: Type.Optional(DecisionQuestionSchema),
|
|
421
|
+
}, { additionalProperties: false }),
|
|
422
|
+
replay: "unsafe",
|
|
423
|
+
executionMode: "sequential",
|
|
424
|
+
async execute(args, api, context) {
|
|
425
|
+
if (context.abortSignal?.aborted)
|
|
426
|
+
throw new Error("TodoUpdate aborted before its transaction.");
|
|
427
|
+
const updated = await api.commit(async (tx) => {
|
|
428
|
+
const doc = await tx.doc(tasksDoc, api.conversationId);
|
|
429
|
+
const todo = doc.todos.find((entry) => entry.taskId === args.taskId);
|
|
430
|
+
if (!todo)
|
|
431
|
+
throw new Error(`Todo ${args.taskId} not found in this conversation.`);
|
|
432
|
+
const oldStatus = todo.status;
|
|
433
|
+
const oldDependency = todo.dependentOn;
|
|
434
|
+
const oldQuestion = todo.decisionQuestionId;
|
|
435
|
+
const status = (args.status ?? oldStatus);
|
|
436
|
+
if (status === "closed" && oldStatus !== "completed")
|
|
437
|
+
throw new Error("Close a task after its verified completion.");
|
|
438
|
+
if (oldStatus === "closed" && status !== "closed")
|
|
439
|
+
throw new Error("Reopen a closed task through an explicit human decision.");
|
|
440
|
+
if (oldStatus === "closed")
|
|
441
|
+
throw new Error("Reopen this closed task through an explicit human decision before editing it.");
|
|
442
|
+
checkCompletion(status, args.completionPercent);
|
|
443
|
+
// Validate the reason transition before mutating anything: entering blocked
|
|
444
|
+
// without a reason is rejected, and leaving blocked always clears the reason.
|
|
445
|
+
const transitioned = args.status !== undefined && args.status !== oldStatus;
|
|
446
|
+
const reason = (args.blockedReason !== undefined || transitioned)
|
|
447
|
+
? normalizeBlockedReason(status, args.blockedReason ?? undefined, transitioned ? undefined : todo)
|
|
448
|
+
: todo.blockedReason;
|
|
449
|
+
const dependency = (args.dependentOn !== undefined || transitioned)
|
|
450
|
+
? normalizeDependency(status, args.dependentOn, transitioned ? undefined : todo)
|
|
451
|
+
: todo.dependentOn;
|
|
452
|
+
const decisionQuestionId = normalizeDecisionQuestionId(status, dependency, args.decisionQuestionId, todo);
|
|
453
|
+
const blockedClassChanged = status === "blocked" && (oldStatus !== "blocked" || oldDependency !== dependency);
|
|
454
|
+
let changed = false;
|
|
455
|
+
if (args.taskName !== undefined) {
|
|
456
|
+
const name = requiredName(args.taskName);
|
|
457
|
+
if (name !== todo.taskName) {
|
|
458
|
+
todo.taskName = name;
|
|
459
|
+
changed = true;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
if (args.taskInfo !== undefined) {
|
|
463
|
+
const info = requiredText(args.taskInfo);
|
|
464
|
+
if (info !== todo.taskInfo) {
|
|
465
|
+
todo.taskInfo = info;
|
|
466
|
+
changed = true;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
if (args.finalThoughts !== undefined) {
|
|
470
|
+
const thoughts = optionalThoughts(args.finalThoughts);
|
|
471
|
+
if (thoughts !== todo.finalThoughts) {
|
|
472
|
+
if (thoughts === undefined)
|
|
473
|
+
delete todo.finalThoughts;
|
|
474
|
+
else
|
|
475
|
+
todo.finalThoughts = thoughts;
|
|
476
|
+
changed = true;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
else if (transitioned && todo.finalThoughts !== undefined) {
|
|
480
|
+
// Do not carry a stale active or blocked thought into the new state.
|
|
481
|
+
delete todo.finalThoughts;
|
|
482
|
+
changed = true;
|
|
483
|
+
}
|
|
484
|
+
if (transitioned) {
|
|
485
|
+
todo.status = status;
|
|
486
|
+
changed = true;
|
|
487
|
+
}
|
|
488
|
+
if (reason !== todo.blockedReason) {
|
|
489
|
+
todo.blockedReason = reason;
|
|
490
|
+
changed = true;
|
|
491
|
+
}
|
|
492
|
+
if (dependency !== todo.dependentOn) {
|
|
493
|
+
todo.dependentOn = dependency;
|
|
494
|
+
changed = true;
|
|
495
|
+
}
|
|
496
|
+
if (decisionQuestionId !== oldQuestion) {
|
|
497
|
+
if (decisionQuestionId === undefined)
|
|
498
|
+
delete todo.decisionQuestionId;
|
|
499
|
+
else
|
|
500
|
+
todo.decisionQuestionId = decisionQuestionId;
|
|
501
|
+
changed = true;
|
|
502
|
+
}
|
|
503
|
+
if (status === "blocked") {
|
|
504
|
+
if (blockedClassChanged) {
|
|
505
|
+
todo.blockedAt = Date.now();
|
|
506
|
+
changed = true;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
else if (todo.blockedAt !== undefined) {
|
|
510
|
+
delete todo.blockedAt;
|
|
511
|
+
changed = true;
|
|
512
|
+
}
|
|
513
|
+
if (args.completionPercent !== undefined && args.completionPercent !== todo.completionPercent) {
|
|
514
|
+
todo.completionPercent = args.completionPercent;
|
|
515
|
+
changed = true;
|
|
516
|
+
}
|
|
517
|
+
// Reopening a completed task without a fresh estimate resets progress to unknown.
|
|
518
|
+
if (oldStatus === "completed" && status !== "completed" && args.completionPercent === undefined && todo.completionPercent !== null) {
|
|
519
|
+
todo.completionPercent = null;
|
|
520
|
+
changed = true;
|
|
521
|
+
}
|
|
522
|
+
if (status === "completed" && todo.completionPercent !== 100) {
|
|
523
|
+
todo.completionPercent = 100;
|
|
524
|
+
changed = true;
|
|
525
|
+
}
|
|
526
|
+
if (!changed) {
|
|
527
|
+
throw new Error("TodoUpdate requires at least one changed field.");
|
|
528
|
+
}
|
|
529
|
+
todo.updatedAt = Date.now();
|
|
530
|
+
const transition = todoTransition({ status: oldStatus, dependentOn: oldDependency ?? undefined }, { status, dependentOn: dependency ?? undefined });
|
|
531
|
+
return {
|
|
532
|
+
taskId: todo.taskId,
|
|
533
|
+
workId: todo.workId,
|
|
534
|
+
status: todo.status,
|
|
535
|
+
completionPercent: taskCompletion(todo.status, todo.completionPercent),
|
|
536
|
+
transition: transition ?? null,
|
|
537
|
+
};
|
|
538
|
+
}, context);
|
|
539
|
+
return {
|
|
540
|
+
content: [{ type: "text", text: `Updated todo ${updated.taskId}: [${updated.status}] · ${formatCompletion(updated.completionPercent)}` }],
|
|
541
|
+
details: {
|
|
542
|
+
...updated,
|
|
543
|
+
data: updated.transition === null ? null : { transition: updated.transition },
|
|
544
|
+
},
|
|
545
|
+
};
|
|
546
|
+
},
|
|
547
|
+
});
|
|
548
|
+
const todoDelete = defineTool({
|
|
549
|
+
name: "TodoDelete",
|
|
550
|
+
description: "Delete a todo from its work. Use only for explicit cancellation, scope removal, or mistaken entries.",
|
|
551
|
+
parameters: Type.Object({ taskId: Type.String({ minLength: 1 }) }, { additionalProperties: false }),
|
|
552
|
+
replay: "unsafe",
|
|
553
|
+
executionMode: "sequential",
|
|
554
|
+
async execute(args, api, context) {
|
|
555
|
+
if (context.abortSignal?.aborted)
|
|
556
|
+
throw new Error("TodoDelete aborted before its transaction.");
|
|
557
|
+
const removed = await api.commit(async (tx) => {
|
|
558
|
+
const doc = await tx.doc(tasksDoc, api.conversationId);
|
|
559
|
+
const index = doc.todos.findIndex((entry) => entry.taskId === args.taskId);
|
|
560
|
+
if (index === -1)
|
|
561
|
+
throw new Error(`Todo ${args.taskId} not found in this conversation.`);
|
|
562
|
+
const [todo] = doc.todos.splice(index, 1);
|
|
563
|
+
if (!todo)
|
|
564
|
+
throw new Error(`Todo ${args.taskId} is no longer available.`);
|
|
565
|
+
return { taskId: todo.taskId, taskName: todo.taskName };
|
|
566
|
+
}, context);
|
|
567
|
+
return {
|
|
568
|
+
content: [{ type: "text", text: `Deleted todo ${removed.taskId}: ${removed.taskName}` }],
|
|
569
|
+
details: { taskId: removed.taskId },
|
|
570
|
+
};
|
|
571
|
+
},
|
|
572
|
+
});
|
|
573
|
+
return defineExtension({
|
|
574
|
+
name: "tasks",
|
|
575
|
+
tools: [workCreate, workList, workUpdate, workDelete, todoCreate, todoList, todoUpdate, todoDelete],
|
|
576
|
+
});
|
|
577
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
/** The native header belongs to the layout, not the content mod. Preserve originals. */
|
|
3
|
+
export declare function ensureHerdrTasksHeader(ctx: Pick<ExtensionContext, "cwd" | "signal">, home: string): Promise<void>;
|