@abhishek944/pi-tasks 0.13.0 → 0.14.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 CHANGED
@@ -6,6 +6,7 @@ It adds:
6
6
 
7
7
  - `WorkCreate`, `WorkList`, `WorkUpdate`, and `WorkDelete`
8
8
  - `TodoCreate`, `TodoList`, `TodoUpdate`, and `TodoDelete`
9
+ - `TaskTimeExport` and `TaskTimeImport` for measured delegated effort
9
10
  - `/works`, a detailed floating dashboard modeled after `pi-loop-monitor`'s `/monitors`
10
11
  - a compact floating top-right panel with work and todo names, completion percentages, and measured active time
11
12
  - main-conversation guidance that keeps normal requested work current across every Pi skill and requires each delegated agent to establish its own Work and Todo IDs before assigned work
@@ -49,7 +50,7 @@ The panel and `/works` reserve **Done** and **Time** columns. Select the task yo
49
50
 
50
51
  The extension uses `Date.now()` to add working intervals, including thinking and foreground tools. Idle time, native retry delays between agent loops, and blocking user prompts do not count. Completion, blocking, cancellation, ownership changes, abort, and shutdown stop the timer automatically. Saved totals survive reload and branch navigation; restored tasks are paused and offline time never counts. A running time has a `▶` marker. Totals are saved on interval boundaries, not every display tick. A forced process kill can lose the current unsaved interval. Blocking prompt exclusion needs a Pi host that emits `ui_prompt_start`/`ui_prompt_end`; older hosts still pause at agent-loop boundaries.
51
52
 
52
- New tasks start at `0s`; historical tasks without timing show `—` until measured, with no attempt to reconstruct earlier time. Work time sums every task's measured effort, including cancelled tasks; any unknown task makes the total unknown. It is not wall-clock duration or an estimate of remaining time. Every delegated agent times its own local tasks; the parent delegate record shows `—` because remote time is unmeasured, and makes the Work total unknown. It never treats waiting as work. Listings and copied Markdown include the same totals.
53
+ New tasks start at `0s`; historical tasks without timing show `—` until measured, with no attempt to reconstruct earlier time. Work time sums every task's measured effort, including cancelled tasks; any unknown task makes the total unknown. It is not wall-clock duration or an estimate of remaining time. Every delegated agent times its own local tasks. AgentCreate supplies a timing report path; the worker calls `TaskTimeExport` with its assignment task IDs after pausing or completing them. The parent then calls `TaskTimeImport` with its delegated task ID. The parent task and Work include that measured effort, without counting waiting or changing status. Until exported and imported, delegated effort shows `—`. Repeated imports replace the cumulative snapshot rather than adding it again. See [delegated timing](docs/USAGE_GUIDE.md#delegated-timing). Listings and copied Markdown include the same totals.
53
54
 
54
55
  The panel and `/works` prefix work names with IDs and task names with IDs plus ownership, such as `[W1] Locate subagent restrictions` and `[T1] [self] Inspect the implement skill`. Task ownership comes from an explicit `owner: self` or `owner: delegate` declaration at the start of a line in `taskInfo`; preserve it on updates. Missing or conflicting decisions show `[unassigned]`, without rewriting stored names or old records. Inside Herdr, `AgentCreate` automatically links its task to an underlined, clickable `[delegate]` badge; Open actions are also underlined. See [delegate pane links](docs/USAGE_GUIDE.md#delegate-pane-links) for linking and keyboard access.
55
56
 
@@ -1,4 +1,5 @@
1
1
  import { Type } from "typebox";
2
+ import { createTimingReport } from "../delegated-time.js";
2
3
  import { taskOwner } from "../ownership.js";
3
4
  import { renderTaskCall, renderTaskResult, taskResult } from "../tool-result.js";
4
5
  import { areTrackingToolsActive } from "../tracking.js";
@@ -34,11 +35,11 @@ export function registerAgentTools(pi, state) {
34
35
  };
35
36
  pi.registerTool({
36
37
  name: "AgentCreate", label: "AgentCreate",
37
- description: "Wrap Herdr tab creation, Pi startup and MonitorCreate. Returns actual paneId/tabId/monitorId and a prepared assignment; automatically links the task's delegate badge and marks the parent task blocked while awaiting the worker. Does NOT send work: confirm MonitorList shows subscription ready, then AgentSend the returned assignment. onSignal wakes the parent for worker state changes; optional onDone handles monitor termination, not task completion. No private agent registry, automatic recovery or process checks.",
38
+ description: "Wrap a timing descriptor, Herdr tab creation, Pi startup and MonitorCreate. Requires an existing canonical taskDir inside repository var/. Returns reportPath, actual paneId/tabId/monitorId and a prepared assignment with timing-export instructions; automatically links the task's delegate badge and marks the parent task blocked while awaiting the worker. Does NOT send work: confirm MonitorList shows subscription ready, then AgentSend the returned assignment. onSignal wakes the parent for worker state changes; optional onDone handles monitor termination, not task completion. No private agent registry, automatic recovery or process checks.",
38
39
  promptGuidelines: ["Prefer these agent tools over CLI for supported operations; use Herdr CLI only for missing capabilities.", "Choose explicit provider/model/thinking/Fast through model-routing-policy. Create only authorized agents, never in /ask or /btw.", "After AgentCreate, confirm MonitorList shows the pane subscription ready before AgentSend. Do not add a duplicate monitor. Read actual output/files before completing tasks."],
39
40
  parameters: Type.Object({
40
41
  workId: Type.String({ pattern: "^W[1-9][0-9]*$" }), taskId: Type.String({ pattern: "^T[1-9][0-9]*$" }),
41
- taskDir: Type.String({ minLength: 1, description: "Existing canonical parent task artifact directory from implement. Passed to the worker; no directory is created by this wrapper." }),
42
+ taskDir: Type.String({ minLength: 1, description: "Existing canonical parent task artifact directory from implement, inside repository var/. A unique timing descriptor is written here and passed to the worker; no directory is created by this wrapper." }),
42
43
  assignment: Type.String({ minLength: 1, maxLength: 32_000 }), provider: Type.String({ minLength: 1 }), model: Type.String({ minLength: 1 }),
43
44
  thinking: Type.String({ minLength: 1, description: "Explicit thinking level supported by the chosen model." }),
44
45
  fast: Type.Optional(Type.Boolean({ description: "Forward --fast only when requested and supported." })),
@@ -52,7 +53,8 @@ export function registerAgentTools(pi, state) {
52
53
  const todo = state.getTodo(params.taskId);
53
54
  if (!todo || todo.workId !== params.workId || taskOwner(todo.taskInfo) !== "delegate")
54
55
  throw new Error("Use an existing task in this work with owner: delegate.");
55
- const handles = {};
56
+ const reportPath = await createTimingReport(ctx, params.taskDir, params.workId, params.taskId);
57
+ const handles = { reportPath };
56
58
  try {
57
59
  const current = object((await herdr(["pane", "current"], ctx.cwd, signal)).pane);
58
60
  if (typeof current?.workspace_id !== "string")
@@ -69,17 +71,18 @@ export function registerAgentTools(pi, state) {
69
71
  args.push("--fast");
70
72
  await herdr(args, ctx.cwd, signal, 45_000);
71
73
  const watched = await monitor(ctx, "MonitorCreate", { herdrPaneId: pane.pane_id, description: `Agent ${params.taskId} (${pane.pane_id})`, timeout: 0,
72
- onSignal: params.onSignal, ...(params.onDone === undefined ? {} : { onDone: params.onDone }) }, signal);
74
+ onSignal: `${params.onSignal}\nWhen worker output is available, call TaskTimeImport for taskId ${params.taskId} to import measured effort from its timing report. Timing import does not verify or complete the task.`, ...(params.onDone === undefined ? {} : { onDone: params.onDone }) }, signal);
73
75
  if (typeof watched.monitorId !== "string")
74
76
  throw new Error("Update pi-loop-monitor: MonitorCreate must return details.monitorId.");
75
77
  handles.monitorId = watched.monitorId;
76
78
  const currentTodo = state.getTodo(params.taskId);
77
79
  if (!currentTodo || currentTodo.workId !== params.workId)
78
80
  throw new Error("The parent task is no longer available for linking.");
81
+ state.setDelegatedTime(params.taskId, { reportPath, elapsedMs: null });
79
82
  state.updateTodo(params.taskId, { status: "blocked", blockedReason: "Waiting for the delegated agent. Resume when its output is available for inspection and verification.", taskInfo: withPaneLink(currentTodo.taskInfo, pane.pane_id, watched.monitorId) });
80
- const assignment = `Parent session ${ctx.sessionManager.getSessionId()}, work ${params.workId}, task ${params.taskId}. Exact parentTaskDir: ${params.taskDir}. Read global implement and applicable skills. Obtain your own PI_SESSION_ID through your shell, establish your own Work and active Todo using WorkList/TodoList and create/update tools before executing, keep them current, and return your IDs, nested task artifact path, changed files, checks and blockers. Parent IDs are context, not shared records. This handoff grants no additional permissions.\n\n${params.assignment}`;
83
+ const assignment = `Parent session ${ctx.sessionManager.getSessionId()}, work ${params.workId}, task ${params.taskId}. Exact parentTaskDir: ${params.taskDir}. Read global implement and applicable skills. Obtain your own PI_SESSION_ID through your shell, establish your own Work and active Todo using WorkList/TodoList and create/update tools before executing, keep them current, and return your IDs, nested task artifact path, changed files, checks and blockers. Parent IDs are context, not shared records. This handoff grants no additional permissions. Timing reportPath: ${JSON.stringify(reportPath)}. Before returning results, pause or complete every assignment task, import any nested delegates with TaskTimeImport, then call TaskTimeExport with this exact reportPath and all assignment-local taskIds (including cancelled tasks, excluding unrelated work). Never calculate or type durations yourself. After follow-ups, export the cumulative set again to the same reportPath. If export is unavailable or fails, report that limitation; do not hand-write the timing file.\n\n${params.assignment}`;
81
84
  return result("AgentCreate", { ...handles, taskDir: params.taskDir, assignment, assignmentSent: false,
82
- next: "Confirm MonitorList shows subscription ready, then AgentSend this assignment to the returned paneId." });
85
+ next: "Confirm MonitorList shows subscription ready, then AgentSend this assignment to the returned paneId. After worker output is available, call TaskTimeImport for this task before closing its agent; verify completion separately." });
83
86
  }
84
87
  catch (error) {
85
88
  throw new Error(`${error instanceof Error ? error.message : String(error)}. The command may have partially completed. Handles returned so far: ${JSON.stringify(handles)}. Inspect these resources; no automatic retry or cleanup was performed.`);
@@ -0,0 +1,4 @@
1
+ import { type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { TaskState } from "./state.js";
3
+ export declare function createTimingReport(ctx: ExtensionContext, taskDir: string, workId: string, taskId: string): Promise<string>;
4
+ export declare function registerDelegatedTimeTools(pi: ExtensionAPI, state: TaskState): void;
@@ -0,0 +1,164 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readFile, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
4
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
5
+ import { Type } from "typebox";
6
+ import { formatTime, taskTime } from "./time.js";
7
+ import { renderTaskCall, renderTaskResult, taskResult } from "./tool-result.js";
8
+ import { areTrackingToolsActive } from "./tracking.js";
9
+ const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
10
+ const TASK_ID = /^T[1-9][0-9]*$/;
11
+ const WORK_ID = /^W[1-9][0-9]*$/;
12
+ const ElapsedSchema = Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]);
13
+ const execution = { executionMode: "sequential", annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false } };
14
+ function inside(root, path) {
15
+ const suffix = relative(root, path);
16
+ return !!suffix && suffix !== ".." && !suffix.startsWith(`..${sep}`) && !isAbsolute(suffix);
17
+ }
18
+ /** All reports are regular files within the repository's real var/ tree. */
19
+ async function reportDirectory(cwd, path) {
20
+ const root = resolve(await realpath(cwd), "var");
21
+ const directory = await realpath(path);
22
+ if (!inside(root, directory))
23
+ throw new Error("Timing reports must be below the repository's var/ directory.");
24
+ return directory;
25
+ }
26
+ async function reportFile(cwd, path) {
27
+ const requested = resolve(cwd, path);
28
+ const directory = await reportDirectory(cwd, dirname(requested));
29
+ const actual = await realpath(requested);
30
+ if (actual !== resolve(directory, basename(requested)) || !(await stat(actual)).isFile()) {
31
+ throw new Error("Timing reports must be regular files, not symlinks.");
32
+ }
33
+ return actual;
34
+ }
35
+ function object(value) {
36
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
37
+ }
38
+ function validElapsed(value) {
39
+ return value === null || (typeof value === "number" && Number.isSafeInteger(value) && value >= 0);
40
+ }
41
+ async function readReport(path) {
42
+ if ((await stat(path)).size > 128_000)
43
+ throw new Error("Timing report exceeds 128 KB.");
44
+ const data = object(JSON.parse(await readFile(path, "utf8")));
45
+ if (data?.version !== 1 || typeof data.parentSessionId !== "string" || !SESSION_ID.test(data.parentSessionId)
46
+ || typeof data.parentWorkId !== "string" || !WORK_ID.test(data.parentWorkId)
47
+ || typeof data.parentTaskId !== "string" || !TASK_ID.test(data.parentTaskId)
48
+ || !(data.workerSessionId === null || (typeof data.workerSessionId === "string" && SESSION_ID.test(data.workerSessionId)))
49
+ || !Array.isArray(data.tasks) || data.tasks.length > 500)
50
+ throw new Error("Malformed timing report.");
51
+ const ids = new Set();
52
+ for (const raw of data.tasks) {
53
+ const task = object(raw);
54
+ if (!task || typeof task.taskId !== "string" || !TASK_ID.test(task.taskId) || ids.has(task.taskId) || !validElapsed(task.elapsedMs)) {
55
+ throw new Error("Malformed or duplicate timing report task.");
56
+ }
57
+ ids.add(task.taskId);
58
+ }
59
+ if ((data.workerSessionId === null) !== (data.tasks.length === 0))
60
+ throw new Error("Timing report has no worker measurement.");
61
+ return data;
62
+ }
63
+ export async function createTimingReport(ctx, taskDir, workId, taskId) {
64
+ const sessionId = ctx.sessionManager.getSessionId();
65
+ if (!SESSION_ID.test(sessionId))
66
+ throw new Error("Invalid parent session ID for timing handoff.");
67
+ const directory = await reportDirectory(ctx.cwd, resolve(ctx.cwd, taskDir));
68
+ const path = resolve(directory, `delegated-time-${randomUUID()}.json`);
69
+ const report = { version: 1, parentSessionId: sessionId, parentWorkId: workId, parentTaskId: taskId, workerSessionId: null, tasks: [] };
70
+ await withFileMutationQueue(path, () => writeFile(path, `${JSON.stringify(report, null, 2)}\n`, { flag: "wx", mode: 0o600 }));
71
+ return path;
72
+ }
73
+ function measuredTotal(report) {
74
+ if (!report.tasks.length || report.tasks.some((task) => task.elapsedMs === null))
75
+ return null;
76
+ const total = report.tasks.reduce((sum, task) => sum + (task.elapsedMs ?? 0), 0);
77
+ if (!Number.isSafeInteger(total))
78
+ throw new Error("Timing report total is too large.");
79
+ return total;
80
+ }
81
+ export function registerDelegatedTimeTools(pi, state) {
82
+ const requireMainWork = () => {
83
+ if (!areTrackingToolsActive(pi))
84
+ throw new Error("Timing handoffs are available only in tracked main-conversation work, not /ask or /btw.");
85
+ };
86
+ pi.registerTool({
87
+ name: "TaskTimeExport", label: "TaskTimeExport",
88
+ description: "Export measured effort for this worker's assignment to the exact reportPath supplied by AgentCreate. Pause or complete every included task first. Supply all assignment task IDs, including cancelled tasks and imported nested delegates; exclude unrelated tasks. Re-export the cumulative set after follow-ups. Durations come from pi-tasks, never from the model. Does not complete the parent task.",
89
+ parameters: Type.Object({
90
+ reportPath: Type.String({ minLength: 1 }),
91
+ taskIds: Type.Array(Type.String({ pattern: TASK_ID.source }), { minItems: 1, maxItems: 500, uniqueItems: true }),
92
+ }, { additionalProperties: false }),
93
+ ...{ outputSchema: Type.Object({ reportPath: Type.String(), workerSessionId: Type.String(), elapsedMs: ElapsedSchema, taskIds: Type.Array(Type.String()) }) },
94
+ ...execution,
95
+ async execute(_id, params, _signal, _update, ctx) {
96
+ requireMainWork();
97
+ const path = await reportFile(ctx.cwd, params.reportPath);
98
+ return withFileMutationQueue(path, async () => {
99
+ const previous = await readReport(path);
100
+ const workerSessionId = ctx.sessionManager.getSessionId();
101
+ if (!SESSION_ID.test(workerSessionId) || workerSessionId === previous.parentSessionId)
102
+ throw new Error("Timing export requires a distinct worker session.");
103
+ if (previous.workerSessionId !== null && previous.workerSessionId !== workerSessionId)
104
+ throw new Error("Timing report belongs to another worker session.");
105
+ const ids = new Set(params.taskIds);
106
+ if (ids.size !== params.taskIds.length || previous.tasks.some((task) => !ids.has(task.taskId)))
107
+ throw new Error("Re-export all previously reported tasks plus any new assignment tasks.");
108
+ const now = Date.now();
109
+ const tasks = params.taskIds.map((taskId) => {
110
+ const todo = state.getTodo(taskId);
111
+ if (!todo)
112
+ throw new Error(`Todo ${taskId} not found in this worker session.`);
113
+ if (todo.workingSince !== undefined)
114
+ throw new Error(`Pause or complete ${taskId} before exporting timing.`);
115
+ return { taskId, elapsedMs: taskTime(todo, now) };
116
+ });
117
+ const report = { ...previous, workerSessionId, tasks };
118
+ const elapsedMs = measuredTotal(report);
119
+ const temporary = `${path}.${randomUUID()}.tmp`;
120
+ try {
121
+ await writeFile(temporary, `${JSON.stringify(report, null, 2)}\n`, { flag: "wx", mode: 0o600 });
122
+ await rename(temporary, path);
123
+ }
124
+ finally {
125
+ await unlink(temporary).catch((error) => { if (error.code !== "ENOENT")
126
+ throw error; });
127
+ }
128
+ const data = { reportPath: path, workerSessionId, elapsedMs, taskIds: params.taskIds };
129
+ return { ...taskResult(`Exported ${tasks.length} task timings: ${formatTime(elapsedMs)}. Parent must call TaskTimeImport for ${report.parentTaskId}.`, "task-time-export", data), structuredContent: data };
130
+ });
131
+ },
132
+ renderCall: renderTaskCall("TaskTimeExport"), renderResult: renderTaskResult,
133
+ });
134
+ pi.registerTool({
135
+ name: "TaskTimeImport", label: "TaskTimeImport",
136
+ description: "Import this delegated task's registered worker timing files after worker output is available. Repeated imports replace cumulative snapshots, never double-count. Parent status and completion are unchanged. Missing worker measurements stay unknown. Import nested delegate time before exporting to your own caller.",
137
+ parameters: Type.Object({ taskId: Type.String({ pattern: TASK_ID.source }) }, { additionalProperties: false }),
138
+ ...{ outputSchema: Type.Object({ taskId: Type.String(), elapsedMs: ElapsedSchema }) },
139
+ ...execution,
140
+ async execute(_id, params, _signal, _update, ctx) {
141
+ requireMainWork();
142
+ const todo = state.getTodo(params.taskId);
143
+ if (!todo?.delegatedTimes?.length)
144
+ throw new Error("This task has no timing handoff registered by AgentCreate.");
145
+ const updates = [];
146
+ for (const source of todo.delegatedTimes) {
147
+ const path = await reportFile(ctx.cwd, source.reportPath);
148
+ const report = await readReport(path);
149
+ if (report.parentSessionId !== ctx.sessionManager.getSessionId() || report.parentWorkId !== todo.workId || report.parentTaskId !== todo.taskId) {
150
+ throw new Error("Timing report belongs to another parent assignment.");
151
+ }
152
+ if (source.workerSessionId && source.workerSessionId !== report.workerSessionId)
153
+ throw new Error("Timing report belongs to another worker session.");
154
+ updates.push({ reportPath: source.reportPath, workerSessionId: report.workerSessionId ?? undefined, elapsedMs: measuredTotal(report) });
155
+ }
156
+ for (const source of updates)
157
+ state.setDelegatedTime(todo.taskId, source);
158
+ const elapsedMs = taskTime(state.getTodo(todo.taskId));
159
+ const data = { taskId: todo.taskId, elapsedMs };
160
+ return { ...taskResult(`Imported timing for ${todo.taskId}: ${formatTime(elapsedMs)}. Status remains ${todo.status}.${updates.some((source) => !source.workerSessionId) ? " A worker has not exported its measurement yet." : ""}`, "task-time-import", data), structuredContent: data };
161
+ },
162
+ renderCall: renderTaskCall("TaskTimeImport"), renderResult: renderTaskResult,
163
+ });
164
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /** Session-scoped work and todo tracking for Pi. */
2
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
3
  export default function tasksExtension(pi: ExtensionAPI): void;
4
- export type { Todo, TodoStatus, Work, WorkWithTodos } from "./types.js";
4
+ export type { DelegatedTime, Todo, TodoStatus, Work, WorkWithTodos } from "./types.js";
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@ import { delegateLink, focusPane } from "./agents/links.js";
2
2
  import { registerAgentTools } from "./agents/tools.js";
3
3
  import { registerTaskAutoContinue } from "./auto-continue.js";
4
4
  import { registerWorksCommand } from "./command.js";
5
+ import { registerDelegatedTimeTools } from "./delegated-time.js";
5
6
  import { GitStatusCache } from "./git-status.js";
6
7
  import { openRepository, openSession } from "./open-repository.js";
7
8
  import { TaskState } from "./state.js";
@@ -16,6 +17,7 @@ export default function tasksExtension(pi) {
16
17
  const git = new GitStatusCache();
17
18
  panel = new TasksPanelHost(state, git);
18
19
  registerTaskTools(pi, state);
20
+ registerDelegatedTimeTools(pi, state);
19
21
  registerTaskTiming(pi, state);
20
22
  registerAgentTools(pi, state);
21
23
  registerTrackingGuidance(pi);
package/dist/state.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import type { Todo, TodoStatus, Work, WorkWithTodos } from "./types.js";
2
+ import type { DelegatedTime, Todo, TodoStatus, Work, WorkWithTodos } from "./types.js";
3
3
  export declare const TASK_ENTRY_TYPE = "pi-tasks-state";
4
4
  export declare const MAX_WORKS = 100;
5
5
  export declare const MAX_TODOS = 500;
@@ -38,6 +38,8 @@ export declare class TaskState {
38
38
  updateTodo(taskId: string, patch: Partial<Pick<Todo, "taskName" | "taskInfo" | "status" | "blockedReason" | "completionPercent">> & {
39
39
  working?: boolean;
40
40
  }): Todo;
41
+ /** Replace a cumulative assignment snapshot, never add it again on retry. */
42
+ setDelegatedTime(taskId: string, source: DelegatedTime): void;
41
43
  deleteTodo(taskId: string): boolean;
42
44
  private record;
43
45
  private apply;
package/dist/state.js CHANGED
@@ -63,7 +63,7 @@ export class TaskState {
63
63
  return todo ? this.snapshot(todo) : undefined;
64
64
  }
65
65
  snapshot(todo) {
66
- return { ...todo, workingSince: todo.taskId === this.focusedTaskId ? this.workingSince : undefined };
66
+ return { ...todo, delegatedTimes: todo.delegatedTimes?.map((source) => ({ ...source })), workingSince: todo.taskId === this.focusedTaskId ? this.workingSince : undefined };
67
67
  }
68
68
  /** Gate the selected task on actual agent execution, not task status. */
69
69
  setAgentRunning(running) {
@@ -200,6 +200,20 @@ export class TaskState {
200
200
  this.setWorking(taskId, patch.working);
201
201
  return this.getTodo(taskId);
202
202
  }
203
+ /** Replace a cumulative assignment snapshot, never add it again on retry. */
204
+ setDelegatedTime(taskId, source) {
205
+ const todo = this.todos.get(taskId);
206
+ if (!todo || taskOwner(todo.taskInfo) !== "delegate")
207
+ throw new Error("Delegated timing requires an existing owner: delegate task.");
208
+ if (!validDelegatedTime(source))
209
+ throw new Error("Invalid delegated timing source.");
210
+ const previous = todo.delegatedTimes?.find((entry) => entry.reportPath === source.reportPath);
211
+ if (previous?.workerSessionId && previous.workerSessionId !== source.workerSessionId)
212
+ throw new Error("Timing report belongs to another worker session.");
213
+ if (previous?.elapsedMs === source.elapsedMs && previous?.workerSessionId === source.workerSessionId)
214
+ return;
215
+ this.record({ version: 1, type: "todo-delegated-time", at: Date.now(), taskId, source });
216
+ }
203
217
  deleteTodo(taskId) {
204
218
  if (!this.todos.has(taskId))
205
219
  return false;
@@ -260,6 +274,7 @@ export class TaskState {
260
274
  taskName: safeSingleLine(event.todo.taskName),
261
275
  completionPercent: taskCompletion(event.todo),
262
276
  elapsedMs: validElapsed(event.todo.elapsedMs) ? event.todo.elapsedMs : null,
277
+ delegatedTimes: undefined,
263
278
  workingSince: undefined,
264
279
  });
265
280
  this.nextTaskId = Math.max(this.nextTaskId, numericId(event.todo.taskId) + 1);
@@ -293,6 +308,14 @@ export class TaskState {
293
308
  this.todos.set(event.taskId, { ...todo, elapsedMs: event.elapsedMs });
294
309
  break;
295
310
  }
311
+ case "todo-delegated-time": {
312
+ const todo = this.todos.get(event.taskId);
313
+ if (todo && validDelegatedTime(event.source)) {
314
+ const sources = (todo.delegatedTimes ?? []).filter((source) => source.reportPath !== event.source.reportPath);
315
+ this.todos.set(event.taskId, { ...todo, delegatedTimes: [...sources, { ...event.source }] });
316
+ }
317
+ break;
318
+ }
296
319
  case "todo-deleted":
297
320
  this.todos.delete(event.taskId);
298
321
  break;
@@ -317,6 +340,11 @@ function normalizeBlockedReason(status, supplied, current) {
317
340
  throw new Error("blockedReason must not exceed 10000 characters.");
318
341
  return reason;
319
342
  }
343
+ function validDelegatedTime(value) {
344
+ return !!value && typeof value.reportPath === "string" && value.reportPath.length > 0
345
+ && (value.elapsedMs === null || validElapsed(value.elapsedMs))
346
+ && (value.workerSessionId === undefined || (typeof value.workerSessionId === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value.workerSessionId)));
347
+ }
320
348
  function validElapsed(value) {
321
349
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
322
350
  }
@@ -368,7 +396,7 @@ function parseEvent(value) {
368
396
  const candidate = value;
369
397
  if (candidate.version !== 1 || typeof candidate.type !== "string")
370
398
  return undefined;
371
- if (!["work-created", "work-updated", "work-deleted", "todo-created", "todo-updated", "todo-deleted", "todo-time"].includes(candidate.type))
399
+ if (!["work-created", "work-updated", "work-deleted", "todo-created", "todo-updated", "todo-deleted", "todo-time", "todo-delegated-time"].includes(candidate.type))
372
400
  return undefined;
373
401
  return value;
374
402
  }
package/dist/time.js CHANGED
@@ -1,11 +1,18 @@
1
1
  import { taskOwner } from "./ownership.js";
2
2
  /** Measured task effort, not time since task creation. */
3
3
  export function taskTime(todo, now = Date.now()) {
4
- // Parent delegate records have no remote timing source. Keep local intervals
5
- // stored, but never present a local subtotal as the full delegated effort.
6
- if (taskOwner(todo.taskInfo) === "delegate" || todo.elapsedMs === undefined || todo.elapsedMs === null)
4
+ // A delegate without a report is unmeasured, not a zero-length assignment.
5
+ if (taskOwner(todo.taskInfo) === "delegate" && !todo.delegatedTimes?.length)
7
6
  return null;
8
- return todo.elapsedMs + (todo.workingSince === undefined ? 0 : Math.max(0, now - todo.workingSince));
7
+ if (todo.elapsedMs === undefined || todo.elapsedMs === null)
8
+ return null;
9
+ let total = todo.elapsedMs + (todo.workingSince === undefined ? 0 : Math.max(0, now - todo.workingSince));
10
+ for (const source of todo.delegatedTimes ?? []) {
11
+ if (source.elapsedMs === null)
12
+ return null;
13
+ total += source.elapsedMs;
14
+ }
15
+ return Number.isSafeInteger(total) ? total : null;
9
16
  }
10
17
  /** Cancelled tasks still consumed effort. Unknown historical time stays unknown. */
11
18
  export function workTime(work, now = Date.now()) {
@@ -15,6 +22,8 @@ export function workTime(work, now = Date.now()) {
15
22
  if (elapsed === null)
16
23
  return null;
17
24
  total += elapsed;
25
+ if (!Number.isSafeInteger(total))
26
+ return null;
18
27
  }
19
28
  return work.tasks.length ? total : null;
20
29
  }
package/dist/tracking.js CHANGED
@@ -20,7 +20,7 @@ Before implementation, investigation, or any other requested work:
20
20
  1. Use WorkList and TodoList to find the relevant existing records and avoid duplicates.
21
21
  2. If no suitable work exists, create one with WorkCreate. Otherwise use WorkUpdate when its scope or shared context needs refreshing.
22
22
  3. Create or update the work's todos so they match the requested scope. Works have no status. New todos default to active; task statuses are active, blocked, completed, and cancelled. Keep taskInfo detailed and self-contained.
23
- 4. Mark the todo being attempted active with TodoUpdate before doing that work. For an owner: self task, include working=true to select it for automatic time measurement on every fresh run. Only one local task can be timed; selecting another pauses the previous one. Use working=false when pausing without changing status. Idle, blocking user prompts, and terminal statuses pause automatically. Delegated agents time their own local tasks; a parent delegate record is not a running local task. Never estimate or submit durations.
23
+ 4. Mark the todo being attempted active with TodoUpdate before doing that work. For an owner: self task, include working=true to select it for automatic time measurement on every fresh run. Only one local task can be timed; selecting another pauses the previous one. Use working=false when pausing without changing status. Idle, blocking user prompts, and terminal statuses pause automatically. Delegated agents time their own local tasks; a parent delegate record is not a running local task. AgentCreate provides a timing reportPath: workers pause or complete assignment tasks and call TaskTimeExport with that path and all assignment-local taskIds before returning. The parent calls TaskTimeImport for its delegated task after worker output is available, before closing the agent. Follow-ups re-export the cumulative assignment task set and re-import. Import nested delegate time before exporting to your own caller. These tools read measured values; never hand-write timing reports or estimate or submit durations.
24
24
  5. completionPercent on TodoCreate/TodoUpdate is optional. When estimating, use an approximate integer from 0 to 100 based on actual work and verification, not elapsed time or a fixed mapping from status. Use 0 for genuinely unstarted tasks and null when unknown. Never invent progress to make a work look further along.
25
25
 
26
26
  During and after the attempt:
package/dist/types.d.ts CHANGED
@@ -6,6 +6,12 @@ export interface Work {
6
6
  createdAt: number;
7
7
  updatedAt: number;
8
8
  }
9
+ /** One assignment's cumulative imported effort; absent measurement stays unknown. */
10
+ export interface DelegatedTime {
11
+ reportPath: string;
12
+ elapsedMs: number | null;
13
+ workerSessionId?: string;
14
+ }
9
15
  export interface Todo {
10
16
  taskId: string;
11
17
  workId: string;
@@ -17,6 +23,7 @@ export interface Todo {
17
23
  completionPercent?: number | null;
18
24
  /** Accumulated measured time; missing/null means historical time is unknown. */
19
25
  elapsedMs?: number | null;
26
+ delegatedTimes?: DelegatedTime[];
20
27
  /** Current interval start, exposed only in live snapshots, never restored. */
21
28
  workingSince?: number;
22
29
  createdAt: number;
@@ -58,6 +65,12 @@ export type TaskEvent = {
58
65
  at: number;
59
66
  taskId: string;
60
67
  elapsedMs: number;
68
+ } | {
69
+ version: 1;
70
+ type: "todo-delegated-time";
71
+ at: number;
72
+ taskId: string;
73
+ source: DelegatedTime;
61
74
  } | {
62
75
  version: 1;
63
76
  type: "todo-deleted";
package/docs/REFERENCE.md CHANGED
@@ -20,7 +20,7 @@ Limits:
20
20
 
21
21
  A work contains `workId`, `workName`, `workInfo`, `createdAt`, and `updatedAt`. It is a collection with no stored or derived lifecycle status. Work tools do not accept status, and WorkList has no status filter. The public WorkStatus type is removed; consumers should use TodoStatus for task lifecycle.
22
22
 
23
- A todo contains `taskId`, `workId`, `taskName`, `taskInfo`, `status`, optional `blockedReason`, optional `completionPercent`, optional `elapsedMs`, runtime-only optional `workingSince`, `createdAt`, and `updatedAt`. Todo status is `active`, `blocked`, `completed`, or `cancelled`; new todos default to `active`.
23
+ A todo contains `taskId`, `workId`, `taskName`, `taskInfo`, `status`, optional `blockedReason`, optional `completionPercent`, optional `elapsedMs`, optional `delegatedTimes`, runtime-only optional `workingSince`, `createdAt`, and `updatedAt`. Todo status is `active`, `blocked`, `completed`, or `cancelled`; new todos default to `active`.
24
24
 
25
25
  The public list shape assembles each work with `tasks: Todo[]`; tasks are stored separately to avoid duplicate state. Work progress is derived, not independently stored or editable.
26
26
 
@@ -48,7 +48,13 @@ TaskState owns focus, an agent-running gate, and an in-memory interval timestamp
48
48
 
49
49
  `registerTaskTiming` gates focus with agent start/end and nested blocking user-prompt events. Every new `before_agent_start` clears prior selection; native loop continuations can retain selection until final settlement. Abort signals close the interval immediately. Settlement, shutdown, and pre-navigation boundaries close and clear selection. Tool execution and model thinking within an agent loop count; idle and native retry waits between loops do not. Hosts without blocking-prompt events cannot exclude an in-loop extension dialog, but retain loop-boundary pauses. There is no per-second persistence, heartbeat, or crash-recovery registry: forced termination may lose the uncommitted interval.
50
50
 
51
- `taskTime`, `workTime`, and `formatTime` supply shared display calculations. Work time sums all tasks, including cancelled tasks, because already-spent effort is real; an empty Work or any unknown task yields unknown. This differs deliberately from completion, which excludes cancelled tasks and averages rather than sums. Delegated workers measure their own session-local self tasks. Parent delegate task records display unknown and propagate unknown to Work totals; they do not import child timing or use prompt-to-completion duration as a substitute. Stored local intervals survive ownership changes but are not displayed as the full delegated duration. No cross-session task registry or parent monitor timing bridge is added.
51
+ `taskTime`, `workTime`, and `formatTime` supply shared display calculations. Work time sums all tasks, including cancelled tasks, because already-spent effort is real; an empty Work or any unknown task yields unknown. This differs deliberately from completion, which excludes cancelled tasks and averages rather than sums. Delegated workers measure their own session-local tasks. Parent delegate records remain unknown until their registered assignment snapshots have been exported and imported. Known task effort is the stored local interval total plus imported assignment totals; prompt-to-completion duration is never used as a substitute. Imported sources remain attached across ownership changes so already-consumed effort is not lost. Unknown local history or any unknown source keeps the aggregate unknown. Unsafe aggregate totals also display unknown. No cross-session task registry or live monitor timing bridge is added.
52
+
53
+ `TaskTimeExport({ reportPath, taskIds })` reads the descriptor created by AgentCreate and writes a paused cumulative snapshot for the explicitly selected worker tasks. The schema contains version 1, parent session/Work/Task IDs, worker session identity and an array of `{ taskId, elapsedMs }` values. The worker cannot supply durations. Export rejects running tasks, missing or duplicate IDs, another worker session, and dropping previously exported tasks. Cancelled tasks belong in the assignment set; unrelated tasks do not. Nested delegate imports must happen before export. Unknown values propagate rather than becoming zero.
54
+
55
+ `TaskTimeImport({ taskId })` reads only the paths already registered on that parent task, validates parent and worker identities, and persists the latest snapshot per source. Missing exports remain unknown; missing files and malformed reports produce errors. Validation finishes before state updates begin. A version-1 `todo-delegated-time` event stores `{ reportPath, elapsedMs, workerSessionId? }` per assignment. Re-import replaces the source instead of adding it again, so follow-up cumulative exports and repeated imports do not double-count. Additional AgentCreate assignments add separate sources. Neither export nor import changes status, completion or task descriptive timestamps. Totals remain available after report files or panes are removed, until another explicit import is attempted. Imported events follow the parent branch; files hold the latest worker snapshot and are not branch-versioned, so an explicit import after navigation intentionally reads the latest exported value. Forked parent sessions cannot import reports addressed to the original parent session.
56
+
57
+ Report files are bounded to 128 KB and 500 unique task IDs, contain no task prose, and must be regular files below the repository's canonical var/ tree. Exports use the host file-mutation queue and atomic replacement. Descriptor names are unique per assignment. Existing legacy/manual delegations without a registered report remain unknown. Both worker and parent need the new tools loaded; older readers ignore the new timing event. No migration of historical durations is attempted.
52
58
 
53
59
  Compact floating/widget views refresh running durations once per second while visible and dispose the render timer on hide. `/works` reuses its existing refresh interval. Neither timer writes session entries. Both views reserve Done and Time columns with name clipping, a running marker, and explicit unknown duration. The compact box minimum is 48 columns so the task prefix does not consume the entire name area; widget views hide below that width. Lists, dashboard details, and copied Markdown show the same measured totals.
54
60
 
@@ -98,9 +104,9 @@ Open appears between Copy and Minimize/Maximize. It executes `cursor` with the s
98
104
 
99
105
  Agent tools are thin, bounded, shell-free Herdr CLI wrappers using actual paneId values. No separate agent handle, private registry, process/session validation, startup receipt, recovery/reconnection or acquisition framework is implemented. Panes are assumed not to be repurposed. Structured CLI errors are reported even with exit code zero, and partial creation failures report the handles already obtained without automatic retry/cleanup.
100
106
 
101
- AgentCreate creates a dedicated unfocused tab, starts Pi with the supplied model flags and calls the existing MonitorCreate through ctx.executeTool with onSignal and optional onDone unchanged. It returns paneId/tabId/monitorId, assignmentSent:false and the prepared assignment. The AI must confirm MonitorList shows subscription ready before explicit AgentSend. Follow-up sends do not replace the monitor. AgentClose calls MonitorStop with the supplied monitorId, then closes the supplied pane; callers must use only resources they created. AgentList returns the CLI inventory, including unrelated agents. No subprocess runs during rendering.
107
+ AgentCreate creates a timing descriptor in the existing canonical taskDir, then creates a dedicated unfocused tab, starts Pi with the supplied model flags and calls the existing MonitorCreate through ctx.executeTool. It appends a TaskTimeImport reminder to onSignal; optional onDone remains unchanged. It returns paneId/tabId/monitorId/reportPath, assignmentSent:false and the prepared assignment with TaskTimeExport instructions. The AI must confirm MonitorList shows subscription ready before explicit AgentSend. Follow-up sends do not replace the monitor. AgentClose calls MonitorStop with the supplied monitorId, then closes the supplied pane; callers must use only resources they created. AgentList returns the CLI inventory, including unrelated agents. No subprocess runs during rendering.
102
108
 
103
- AgentCreate marks the parent task blocked and stores herdr-pane and herdr-monitor lines in existing taskInfo after successful agent startup and monitor creation; task tools persist and restore these details. TodoUpdate preserves existing link lines for delegate-to-delegate detail edits unless explicit replacement metadata is supplied, so ordinary progress/status descriptions do not silently disable navigation. Changing ownership, explicit `herdr-pane: none`, or AgentClose can unlink. delegateLink interprets an unambiguous valid pane ID for owner:delegate inside Herdr. AgentClose removes matching delegate links. No task schema change or automatic task completion is introduced. The onSignal/onDone callbacks remain entirely owned by pi-loop-monitor; onDone means its process ended, not that worker work is complete.
109
+ AgentCreate marks the parent task blocked and stores herdr-pane and herdr-monitor lines in existing taskInfo after successful agent startup and monitor creation; task tools persist and restore these details. TodoUpdate preserves existing link lines for delegate-to-delegate detail edits unless explicit replacement metadata is supplied, so ordinary progress/status descriptions do not silently disable navigation. Changing ownership, explicit `herdr-pane: none`, or AgentClose can unlink. delegateLink interprets an unambiguous valid pane ID for owner:delegate inside Herdr. AgentClose removes matching delegate links. Pane links do not change task schema or complete tasks automatically; separate delegatedTimes fields hold timing snapshots. Execution of onSignal/onDone remains owned by pi-loop-monitor; onDone means its process ended, not that worker work is complete.
104
110
 
105
111
  Delegate navigation and AgentFocus first focus the pane, then explicitly activate the tab returned by Herdr; pane-focus success alone does not guarantee that the visible client switched tabs.
106
112
 
@@ -120,7 +120,30 @@ The first call selects T1; the second pauses T1 and selects T2; the third pauses
120
120
 
121
121
  Time is saved total milliseconds plus `Date.now() - workingSince` while running. The extension saves each interval when paused, switched, or finished, not on every one-second display refresh. Thinking and foreground tool execution count. Idle periods, retry delays between agent loops, and blocking extension UI prompts pause timing. Blocking, completion, cancellation, changing away from self ownership, abort, and shutdown close the interval. Select again at the beginning of each new run. A restored session or branch always starts paused and excludes offline time. Abrupt process termination can lose the unsaved current interval; there is no background checkpoint writer. Blocking prompt exclusion requires a Pi host emitting `ui_prompt_start` and `ui_prompt_end`; older hosts retain loop-boundary timing.
122
122
 
123
- The compact panel and `/works` show reserved Done and Time columns; `▶` beside a duration means it is running. New tasks show `0s`. Legacy tasks without timing show `—`; selecting one begins measurement from now, not from its creation date. Work time sums task effort, including cancelled tasks; any unknown duration makes its total unknown. This is not elapsed wall-clock time and does not predict completion. Each delegated agent times its own local self tasks; parent delegate records show `—` because remote time is unmeasured, making the Work total unknown rather than a misleading local-only subtotal. List tools and copied Markdown include durations too.
123
+ The compact panel and `/works` show reserved Done and Time columns; `▶` beside a duration means it is running. New tasks show `0s`. Legacy tasks without timing show `—`; selecting one begins measurement from now, not from its creation date. Work time sums task effort, including cancelled tasks; any unknown duration makes its total unknown. This is not elapsed wall-clock time and does not predict completion. Each delegated agent times its own local tasks. Parent delegate records show `—` until the worker exports measured time and the parent imports it. Imported effort contributes to both the parent task and its Work, even while the parent task remains blocked. List tools and copied Markdown include durations too.
124
+
125
+ ### Delegated timing
126
+
127
+ AgentCreate creates a unique `delegated-time-<id>.json` descriptor below the existing canonical parent task directory and returns its `reportPath`. Its prepared worker assignment includes export instructions; its monitor callback includes import instructions. Herdr still runs the worker and pi-loop-monitor still reports state changes. The timing file, not the notification or chat response, carries the measured values. Both agents need this version of pi-tasks loaded.
128
+
129
+ Before returning, the worker pauses or completes its assignment tasks and exports their timing:
130
+
131
+ ```text
132
+ TodoUpdate taskId="T1" working=false
133
+ TaskTimeExport reportPath="<exact path from AgentCreate>" taskIds=["T1", "T2"]
134
+ ```
135
+
136
+ Use worker-local IDs for every task in this assignment, including cancelled tasks. Exclude unrelated work. Durations are read by the extension; the model never supplies milliseconds. Import any nested delegates before exporting their containing task. Unknown nested or historical effort stays unknown. An export is a paused snapshot, not a live timer; work performed after export needs a new export.
137
+
138
+ After inspecting the worker output, the parent imports timing using its own task ID:
139
+
140
+ ```text
141
+ TaskTimeImport taskId="T5"
142
+ ```
143
+
144
+ Import leaves status and completion unchanged. The parent can remain blocked and still display measured worker effort. Import before closing the worker, so export failures can be corrected. Repeated imports replace the previous cumulative value. After follow-ups, the worker re-exports all previously included task IDs plus any new assignment tasks to the same file, and the parent imports again. A new AgentCreate on the same parent task registers an additional assignment source; its effort is added once, and unreported sources make the total unknown.
145
+
146
+ Report files contain parent IDs, worker session identity and task timing values, not task text or transcripts. They must remain under repository `var/`. A report binds to its first exporting worker session. Missing files, identity mismatches and malformed data produce tool errors; missing worker exports remain unknown rather than zero. Legacy/manual delegations without an AgentCreate report remain unknown. Existing imported totals survive reload and pane closure; newer worker exports only affect the parent after another explicit import. Older extension versions cannot show these imported totals. No polling, background timing registry, or changes to Herdr/pi-loop-monitor are involved.
124
147
 
125
148
  ### Completion percentages
126
149
 
@@ -149,7 +172,7 @@ These are simple Herdr CLI wrappers in pi-tasks, with no pi-herdr-agents depende
149
172
 
150
173
  | Tool | Purpose |
151
174
  | --- | --- |
152
- | `AgentCreate` | Create an unfocused tab, start Pi and register monitoring; return paneId/tabId/monitorId plus a prepared assignment. No prompt is sent. |
175
+ | `AgentCreate` | Create a timing descriptor, an unfocused tab, start Pi and register monitoring; return paneId/tabId/monitorId/reportPath plus a prepared assignment. No prompt is sent. |
153
176
  | `AgentList` | `herdr agent list` (includes unrelated agents). |
154
177
  | `AgentStatus` | `herdr agent get <paneId>`. |
155
178
  | `AgentOutput` | `herdr pane read`; 50 trailing lines by default, up to 200. |
@@ -174,7 +197,7 @@ AgentCreate({
174
197
  })
175
198
  ```
176
199
 
177
- Replace placeholders using the existing implement path convention and model-routing-policy. The wrapper passes taskDir to the prepared worker assignment; it does not create folders or verify the running model. It adds parent context and worker-local tracking instructions without granting extra permissions.
200
+ Replace placeholders using the existing implement path convention and model-routing-policy. The wrapper requires taskDir to exist inside the repository's canonical var/ tree. It creates a timing descriptor there but does not create folders or verify the running model. It adds parent context, worker-local tracking and timing-export instructions without granting extra permissions.
178
201
 
179
202
  AgentCreate returns `assignmentSent: false`. Confirm MonitorList shows `Herdr signal subscription ready for <paneId>`, then call `AgentSend({ paneId, message: assignment })` using the returned assignment. Do not add a second monitor. Follow-up messages use that same paneId and existing subscription.
180
203
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abhishek944/pi-tasks",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Session-scoped work and todo tracking for Pi.",
5
5
  "license": "MIT",
6
6
  "type": "module",