@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.
Files changed (54) hide show
  1. package/README.md +63 -14
  2. package/dist/agents/delegation.d.ts +4 -0
  3. package/dist/agents/delegation.js +130 -0
  4. package/dist/agents/herdr.d.ts +10 -3
  5. package/dist/agents/herdr.js +39 -12
  6. package/dist/agents/links.d.ts +3 -3
  7. package/dist/agents/links.js +42 -19
  8. package/dist/auto-continue.js +409 -33
  9. package/dist/blocked.d.ts +29 -0
  10. package/dist/blocked.js +100 -0
  11. package/dist/command.d.ts +2 -2
  12. package/dist/command.js +7 -3
  13. package/dist/delegated-time.d.ts +12 -1
  14. package/dist/delegated-time.js +96 -15
  15. package/dist/dependency.d.ts +7 -0
  16. package/dist/dependency.js +13 -0
  17. package/dist/durable.d.ts +42 -0
  18. package/dist/durable.js +577 -0
  19. package/dist/herdr-header.d.ts +3 -0
  20. package/dist/herdr-header.js +100 -0
  21. package/dist/herdr-panel.d.ts +15 -0
  22. package/dist/herdr-panel.js +219 -0
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +125 -56
  25. package/dist/markdown.js +3 -1
  26. package/dist/panel-settings.d.ts +11 -0
  27. package/dist/panel-settings.js +30 -0
  28. package/dist/progress.js +1 -1
  29. package/dist/snapshot.d.ts +23 -0
  30. package/dist/snapshot.js +166 -0
  31. package/dist/state.d.ts +43 -18
  32. package/dist/state.js +581 -289
  33. package/dist/thoughts.d.ts +11 -0
  34. package/dist/thoughts.js +14 -0
  35. package/dist/timing.js +9 -2
  36. package/dist/tools.js +295 -34
  37. package/dist/tracking.js +25 -13
  38. package/dist/transition.d.ts +9 -0
  39. package/dist/transition.js +26 -0
  40. package/dist/types.d.ts +76 -3
  41. package/dist/ui/panel.js +38 -19
  42. package/dist/ui/task-view.d.ts +7 -0
  43. package/dist/ui/task-view.js +10 -0
  44. package/dist/ui/works-dashboard.js +37 -19
  45. package/docs/REFERENCE.md +85 -31
  46. package/docs/USAGE_GUIDE.md +129 -55
  47. package/herdr/pi-tasks/README.md +46 -0
  48. package/herdr/pi-tasks/header.js +212 -0
  49. package/herdr/pi-tasks/main.js +488 -0
  50. package/herdr/pi-tasks/mod.json +3 -0
  51. package/herdr/pi-tasks/spinner.svg +1 -0
  52. package/package.json +26 -1
  53. package/dist/agents/tools.d.ts +0 -3
  54. package/dist/agents/tools.js +0 -143
@@ -0,0 +1,166 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, join } from "node:path";
4
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
5
+ import { isTaskDependency } from "./dependency.js";
6
+ import { taskOwner } from "./ownership.js";
7
+ const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
8
+ const TERMINAL_ID = /^(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)?t[0-9a-z]+$/;
9
+ const MAX_SNAPSHOT_BYTES = 16 * 1024 * 1024;
10
+ const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
11
+ const integer = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
12
+ const text = (value) => typeof value === "string" && value.trim().length > 0;
13
+ const id = (value, prefix) => typeof value === "string" && new RegExp(`^${prefix}[1-9][0-9]*$`).test(value) && integer(Number(value.slice(1)));
14
+ export function taskSnapshotPath(sessionId) {
15
+ if (!SESSION_ID.test(sessionId))
16
+ throw new Error("A valid Pi session ID is required for task storage.");
17
+ return join(getAgentDir(), "tasks", `${sessionId}.json`);
18
+ }
19
+ export function emptySnapshot(sessionId, cwd) {
20
+ return { version: 1, sessionId, cwd, updatedAt: Date.now(), nextWorkId: 1, nextTaskId: 1, works: [], todos: [], agentRunning: false };
21
+ }
22
+ /** Reject damaged files rather than silently replacing user task data. */
23
+ export function validateSnapshot(value, sessionId) {
24
+ const invalid = () => { throw new Error("Invalid task snapshot. Restore the file from backup; it has not been overwritten."); };
25
+ if (!object(value) || value.version !== 1 || value.sessionId !== sessionId || !text(value.cwd)
26
+ || !integer(value.updatedAt) || !integer(value.nextWorkId) || value.nextWorkId < 1
27
+ || !integer(value.nextTaskId) || value.nextTaskId < 1 || typeof value.agentRunning !== "boolean"
28
+ || !Array.isArray(value.works) || value.works.length > 100 || !Array.isArray(value.todos) || value.todos.length > 500
29
+ || (value.terminalId !== undefined && (typeof value.terminalId !== "string" || !TERMINAL_ID.test(value.terminalId))))
30
+ return invalid();
31
+ const works = new Set();
32
+ for (const work of value.works) {
33
+ if (!object(work) || !id(work.workId, "W") || works.has(work.workId) || !text(work.workName) || !text(work.workInfo)
34
+ || !integer(work.createdAt) || !integer(work.updatedAt) || Number(work.workId.slice(1)) >= value.nextWorkId)
35
+ return invalid();
36
+ works.add(work.workId);
37
+ }
38
+ const todos = new Set();
39
+ let running = 0;
40
+ for (const todo of value.todos) {
41
+ if (!object(todo) || !id(todo.taskId, "T") || todos.has(todo.taskId) || !text(todo.workId) || !works.has(todo.workId)
42
+ || !text(todo.taskName) || !text(todo.taskInfo) || !integer(todo.createdAt) || !integer(todo.updatedAt)
43
+ || (todo.revision !== undefined && (!integer(todo.revision) || todo.revision < 1))
44
+ || (todo.worktree !== undefined && (typeof todo.worktree !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(todo.worktree)))
45
+ || (todo.finalThoughts !== undefined && !text(todo.finalThoughts))
46
+ || !["active", "blocked", "completed", "closed", "cancelled"].includes(String(todo.status))
47
+ || Number(todo.taskId.slice(1)) >= value.nextTaskId
48
+ || (todo.blockedReason !== undefined && todo.blockedReason !== null && !text(todo.blockedReason))
49
+ || (todo.status !== "blocked" && todo.blockedReason != null)
50
+ || (todo.dependentOn !== undefined && (todo.status !== "blocked" || !isTaskDependency(todo.dependentOn)))
51
+ || (todo.blockedAt !== undefined && (todo.status !== "blocked" || !integer(todo.blockedAt)))
52
+ || (todo.decisionQuestionId !== undefined && (todo.status !== "blocked" || todo.dependentOn !== "user-decision" || typeof todo.decisionQuestionId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]*$/u.test(todo.decisionQuestionId)))
53
+ || (todo.completionPercent != null && (!integer(todo.completionPercent) || todo.completionPercent > 100))
54
+ || ((todo.status === "completed" || todo.status === "closed") && todo.completionPercent !== 100)
55
+ || (todo.status !== "completed" && todo.status !== "closed" && todo.completionPercent === 100)
56
+ || (todo.elapsedMs != null && !integer(todo.elapsedMs)))
57
+ return invalid();
58
+ if (todo.goal !== undefined) {
59
+ if (!object(todo.goal) || !text(todo.goal.goal) || !Array.isArray(todo.goal.criteria) || todo.goal.criteria.length === 0
60
+ || !todo.goal.criteria.every(text) || !integer(todo.goal.revision) || todo.goal.revision < 1)
61
+ return invalid();
62
+ if (todo.goal.confirmation !== undefined && (!object(todo.goal.confirmation) || todo.goal.confirmation.revision !== todo.goal.revision
63
+ || !text(todo.goal.confirmation.questionId) || !text(todo.goal.confirmation.answeredAt)))
64
+ return invalid();
65
+ }
66
+ if (todo.lifecycleDecisions !== undefined && (!Array.isArray(todo.lifecycleDecisions) || todo.lifecycleDecisions.some((decision) => !object(decision) || !["cancel", "reopen"].includes(String(decision.action)) || !text(decision.questionId) || !text(decision.answeredAt) || (decision.reason !== undefined && !text(decision.reason)))))
67
+ return invalid();
68
+ if (todo.workerClose !== undefined) {
69
+ const close = todo.workerClose;
70
+ if (!object(close) || (close.request === undefined && close.outcome === undefined))
71
+ return invalid();
72
+ const request = close.request;
73
+ if (request !== undefined && (!object(request) || typeof request.terminalId !== "string" || !TERMINAL_ID.test(request.terminalId) || !integer(request.turn) || !integer(request.requestedAt)))
74
+ return invalid();
75
+ if (close.outcome !== undefined && close.outcome !== "not-run-absent" && close.outcome !== "unverified-absent" && close.outcome !== "completed")
76
+ return invalid();
77
+ }
78
+ if (todo.closeoutAttempts !== undefined) {
79
+ if (!Array.isArray(todo.closeoutAttempts))
80
+ return invalid();
81
+ for (const attempt of todo.closeoutAttempts) {
82
+ if (!object(attempt) || !text(attempt.questionId) || !Array.isArray(attempt.batchTaskIds) || !attempt.batchTaskIds.length || !attempt.batchTaskIds.every((item) => id(item, "T")) || new Set(attempt.batchTaskIds).size !== attempt.batchTaskIds.length || !attempt.batchTaskIds.includes(todo.taskId) || !integer(attempt.taskRevision) || !text(attempt.taskName) || !text(attempt.limits)
83
+ || !object(attempt.goal) || !text(attempt.goal.goal) || !integer(attempt.goal.revision) || !Array.isArray(attempt.goal.criteria) || !attempt.goal.criteria.length || !attempt.goal.criteria.every(text)
84
+ || !object(attempt.goal.confirmation) || attempt.goal.confirmation.revision !== attempt.goal.revision || !text(attempt.goal.confirmation.questionId) || !text(attempt.goal.confirmation.answeredAt)
85
+ || !Array.isArray(attempt.results) || attempt.results.length !== attempt.goal.criteria.length
86
+ || attempt.results.some((result) => !object(result) || !text(result.criterion) || !text(result.result) || !text(result.evidence))
87
+ || (attempt.decision !== undefined && (!object(attempt.decision) || typeof attempt.decision.approved !== "boolean" || !text(attempt.decision.answeredAt) || typeof attempt.decision.feedback !== "string"))
88
+ || (attempt.workerClose !== undefined && attempt.workerClose !== "not-run-absent" && attempt.workerClose !== "unverified-absent" && attempt.workerClose !== "completed")
89
+ || (attempt.workerCloseRequest !== undefined && (!object(attempt.workerCloseRequest) || typeof attempt.workerCloseRequest.terminalId !== "string" || !TERMINAL_ID.test(attempt.workerCloseRequest.terminalId) || !integer(attempt.workerCloseRequest.turn) || !integer(attempt.workerCloseRequest.requestedAt))))
90
+ return invalid();
91
+ const criteria = attempt.goal.criteria;
92
+ if (attempt.results.some((result, index) => !object(result) || result.criterion !== criteria[index]))
93
+ return invalid();
94
+ }
95
+ }
96
+ if (todo.delegatedTimes !== undefined) {
97
+ if (!Array.isArray(todo.delegatedTimes))
98
+ return invalid();
99
+ const reports = new Set();
100
+ for (const source of todo.delegatedTimes) {
101
+ if (!object(source) || !text(source.reportPath) || reports.has(source.reportPath)
102
+ || (source.reportRoot !== undefined && (!text(source.reportRoot) || !isAbsolute(source.reportRoot)))
103
+ || (source.elapsedMs !== null && !integer(source.elapsedMs))
104
+ || (source.workerSessionId !== undefined && (typeof source.workerSessionId !== "string" || !SESSION_ID.test(source.workerSessionId))))
105
+ return invalid();
106
+ reports.add(source.reportPath);
107
+ }
108
+ }
109
+ if (todo.workingSince !== undefined) {
110
+ if (!integer(todo.workingSince) || !value.agentRunning || value.focusedTaskId !== todo.taskId || todo.status !== "active" || taskOwner(todo.taskInfo) !== "self")
111
+ return invalid();
112
+ running += 1;
113
+ }
114
+ todos.add(todo.taskId);
115
+ }
116
+ if (running > 1 || (value.focusedTaskId !== undefined && (!id(value.focusedTaskId, "T") || !todos.has(value.focusedTaskId))))
117
+ return invalid();
118
+ if (value.focusedTaskId !== undefined) {
119
+ const focused = value.todos.find((todo) => todo.taskId === value.focusedTaskId);
120
+ if (focused?.status !== "active" || taskOwner(focused.taskInfo) !== "self")
121
+ return invalid();
122
+ }
123
+ }
124
+ /** Only ENOENT is an uninitialized store; parse/identity/permission failures propagate. */
125
+ export function readSnapshot(path, sessionId) {
126
+ let contents;
127
+ try {
128
+ const stat = lstatSync(path);
129
+ if (!stat.isFile() || stat.size > MAX_SNAPSHOT_BYTES)
130
+ throw new Error("Task snapshot must be a regular file no larger than 16 MiB.");
131
+ contents = readFileSync(path, "utf8");
132
+ }
133
+ catch (error) {
134
+ if (error.code === "ENOENT")
135
+ return undefined;
136
+ throw error;
137
+ }
138
+ let snapshot;
139
+ try {
140
+ snapshot = JSON.parse(contents);
141
+ }
142
+ catch {
143
+ throw new Error("Task snapshot is not valid JSON. It has not been overwritten.");
144
+ }
145
+ validateSnapshot(snapshot, sessionId);
146
+ return snapshot;
147
+ }
148
+ /** One synchronous Pi writer, atomic replacement; Herdr is a reader only. */
149
+ export function writeSnapshot(path, snapshot) {
150
+ validateSnapshot(snapshot, snapshot.sessionId);
151
+ const data = `${JSON.stringify(snapshot, null, 2)}\n`;
152
+ if (Buffer.byteLength(data) > MAX_SNAPSHOT_BYTES)
153
+ throw new Error("Task snapshot exceeds 16 MiB; no changes were saved.");
154
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
155
+ const temporary = `${path}.${randomUUID()}.tmp`;
156
+ try {
157
+ writeFileSync(temporary, data, { flag: "wx", mode: 0o600 });
158
+ renameSync(temporary, path);
159
+ }
160
+ finally {
161
+ try {
162
+ unlinkSync(temporary);
163
+ }
164
+ catch { /* Preserve the original write error if cleanup also fails. */ }
165
+ }
166
+ }
package/dist/state.d.ts CHANGED
@@ -1,20 +1,20 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { DelegatedTime, Todo, TodoStatus, Work, WorkWithTodos } from "./types.js";
3
+ /** Legacy session entries are read once for migration, never written again. */
3
4
  export declare const TASK_ENTRY_TYPE = "pi-tasks-state";
4
5
  export declare const MAX_WORKS = 100;
5
6
  export declare const MAX_TODOS = 500;
7
+ /** File-backed session state. Only the binding lives here, never an authoritative record cache. */
6
8
  export declare class TaskState {
7
- private readonly pi;
8
9
  private readonly onChange;
9
- private works;
10
- private todos;
11
- private nextWorkId;
12
- private nextTaskId;
13
- private focusedTaskId;
14
- private workingSince;
15
- private agentRunning;
16
- constructor(pi: ExtensionAPI, onChange: () => void);
17
- restore(ctx: ExtensionContext): void;
10
+ private binding;
11
+ /** An explicit working=false pause lasts until the next run boundary. */
12
+ private autoTimingPaused;
13
+ constructor(_pi: ExtensionAPI, onChange: () => void);
14
+ get snapshotPath(): string;
15
+ restore(ctx: ExtensionContext, freshFork?: boolean): void;
16
+ private read;
17
+ private change;
18
18
  listWorks(filter?: {
19
19
  workId?: string;
20
20
  }): WorkWithTodos[];
@@ -25,22 +25,47 @@ export declare class TaskState {
25
25
  }): Todo[];
26
26
  getWork(workId: string): Work | undefined;
27
27
  getTodo(taskId: string): Todo | undefined;
28
- private snapshot;
29
- /** Gate the selected task on actual agent execution, not task status. */
28
+ getFocusedTodo(): Todo | undefined;
30
29
  setAgentRunning(running: boolean): void;
31
30
  setWorking(taskId: string, working: boolean): void;
32
31
  clearWorking(): void;
33
- private saveInterval;
32
+ /**
33
+ * Select the only eligible task when execution begins, so routine work needs
34
+ * no separate working=true call. Explicit choices and pauses always win, and
35
+ * timing starts only while the agent is actually running.
36
+ */
37
+ autoSelectWorking(): void;
34
38
  createWork(workName: string, workInfo: string): Work;
35
39
  updateWork(workId: string, patch: Partial<Pick<Work, "workName" | "workInfo">>): Work;
36
40
  deleteWork(workId: string): boolean;
37
- createTodo(workId: string, taskName: string, taskInfo: string, status?: TodoStatus, completionPercent?: number | null, blockedReason?: string | null): Todo;
38
- updateTodo(taskId: string, patch: Partial<Pick<Todo, "taskName" | "taskInfo" | "status" | "blockedReason" | "completionPercent">> & {
41
+ createTodo(input: {
42
+ workId: string;
43
+ taskName: string;
44
+ taskInfo: string;
45
+ goal: {
46
+ goal: string;
47
+ criteria: string[];
48
+ };
49
+ finalThoughts?: string;
50
+ completionPercent?: number | null;
51
+ }): Todo;
52
+ setGoal(taskId: string, input: {
53
+ goal: string;
54
+ criteria: string[];
55
+ }): Todo;
56
+ updateTodo(taskId: string, patch: Partial<Pick<Todo, "taskName" | "taskInfo" | "finalThoughts" | "status" | "blockedReason" | "dependentOn" | "decisionQuestionId" | "completionPercent">> & {
39
57
  working?: boolean;
40
58
  }): Todo;
41
- /** Replace a cumulative assignment snapshot, never add it again on retry. */
59
+ /** Record the one worker /close request for a completed delegated task. */
60
+ beginWorkerClose(taskId: string, terminalId: string, turn: number): Todo;
61
+ /** Close a completed task after its worker /close was verified. */
62
+ closeWorker(taskId: string, terminalId: string): Todo;
63
+ /** Close a completed task whose worker is confirmed absent. */
64
+ closeAbsent(taskId: string): Todo;
65
+ applyHumanLifecycleDecision(taskId: string, expectedRevision: number, action: "cancel" | "reopen", questionId: string, answeredAt: string, reason?: string): Todo;
66
+ /** Bind an assignment to one worktree; rebinding an existing task is forbidden. */
67
+ setWorktree(taskId: string, worktree: string): void;
68
+ removeUnstartedDelegatedTime(taskId: string, reportPath: string): void;
42
69
  setDelegatedTime(taskId: string, source: DelegatedTime): void;
43
70
  deleteTodo(taskId: string): boolean;
44
- private record;
45
- private apply;
46
71
  }