@abhishek944/pi-tasks 0.9.0 → 0.10.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
@@ -8,16 +8,18 @@ It adds:
8
8
  - `TodoCreate`, `TodoList`, `TodoUpdate`, and `TodoDelete`
9
9
  - `/works`, a detailed floating dashboard modeled after `pi-loop-monitor`'s `/monitors`
10
10
  - a compact floating top-right panel with work and todo names and completion percentages
11
- - main-conversation guidance that keeps normal requested work current across every Pi skill
11
+ - 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
12
12
 
13
13
  Works and todos follow the active Pi session branch. Forking or navigating the session tree restores the state for that branch. `/ask` and `/btw` conversations do not update works, todos, loops, or monitors.
14
14
 
15
15
  The coordination model is intentionally small: a work is the overall outcome, a todo is one concrete step under it, a monitor runs one long-lived background command, and a loop schedules a future or repeated wake. Loops and monitors remain owned by `pi-loop-monitor`.
16
16
 
17
+ Tracking guidance requires the globally installed `implement` skill as the coordination workflow for every tracked Work, including worker-local Works, while preserving specialized skill permissions. Pi-tasks owns records/progress, `implement` owns task ownership decisions and artifact paths, and `herdr` owns delegated-agent lifecycle. Root artifacts use repository-relative `var/<sessionId>/<workId>/<taskId>/`; children nest their own session/Work/Task path below the parent task directory. Each task records `self` or `delegate` with a reason in `taskInfo`. These are instructions, not runtime enforcement, shared cross-session records, or an automatic skill installer. Missing required skills, tools, or IDs blocks execution; plain conversation and `/ask`/`/btw` remain outside this workflow. See [the usage guide](docs/USAGE_GUIDE.md#shared-workflow-and-artifacts) for setup and the full contract.
18
+
17
19
  ## Install
18
20
 
19
21
  ```bash
20
- pi install npm:@abhishek944/pi-tasks@0.9.0
22
+ pi install npm:@abhishek944/pi-tasks@0.9.1
21
23
  ```
22
24
 
23
25
  Restart Pi or run `/reload`.
@@ -40,7 +42,13 @@ Works and todos use four statuses: `active` (the default), `blocked`, `completed
40
42
 
41
43
  Pi reports approximate task progress through the existing `TodoCreate`/`TodoUpdate` tools using optional `completionPercent` (an integer from 0 to 100, or `null` for unknown). Work progress is the equal average of non-cancelled tasks, rounded down—not the fraction of finished tasks. For example, task values 100, 40, 0, 0 give work progress 35%. A missing estimate makes work progress unknown (`—`); blocked tasks retain their estimate. Completed tasks are 100%; reporting 100 without completed status is rejected. For longer tasks, the guidance asks Pi to include interim estimates after roughly 5–10 meaningful working steps or a milestone, rather than waiting until completion. Estimates remain optional and must be supported by evidence; this is guidance, not an enforced schedule. These percentages are estimates, not time predictions. The floating panel keeps percentages in a reserved right-hand column so long names cannot hide them. Existing keyboard controls are unchanged.
42
44
 
43
- The panel defaults to the floating top-right layout. Its top border centers the current repository's Git branch and staged/unstaged/untracked file counts, refreshed asynchronously with a one-second cache. Clean repositories show `clean`. In fullscreen TUI mode, its title bar has clickable Copy, Open, and Minimize/Maximize actions, and you can scroll overflowing rows directly with the mouse wheel. Open runs `cursor .` in the current session directory (the Cursor CLI must be on PATH). Open `/works` to inspect every row or copy from the keyboard. Use `/works-panel minimize`, `/works-panel maximize`, or `/works-panel open` when mouse input is unavailable. In `/works`, press `o` to open Cursor. Switch layouts with `/works-panel floating`, `/works-panel widget`, or `/works-panel off`.
45
+ 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.
46
+
47
+ The panel defaults to the floating top-right layout. The compact header no longer displays the session ID. An underlined Open session action beside Copy opens this agent's artifact folder in Cursor, including existing nested delegated paths; if none exists, it creates `var/<sessionId>/`. The existing Open still opens the repository. Use `/works-panel open-session` without mouse input. Narrow headers shorten Minimize/Maximize to `[-]`/`[+]`. The `/works` dashboard title stays unchanged. Its top border centers the current repository's Git branch and staged/unstaged/untracked file counts, refreshed asynchronously with a one-second cache. Clean repositories show `clean`. In fullscreen TUI mode, its title bar has clickable Copy, Open, and Minimize/Maximize actions, and you can scroll overflowing rows directly with the mouse wheel. Open runs `cursor .` in the current session directory (the Cursor CLI must be on PATH). Open `/works` to inspect every row or copy from the keyboard. Use `/works-panel minimize`, `/works-panel maximize`, or `/works-panel open` when mouse input is unavailable. In `/works`, press `o` to open Cursor. Switch layouts with `/works-panel floating`, `/works-panel widget`, or `/works-panel off`.
48
+
49
+ ## Task-owned agents
50
+
51
+ `AgentCreate`, `AgentList`, `AgentStatus`, `AgentOutput`, `AgentSend`, `AgentInterrupt`, `AgentClose`, and `AgentFocus` are simple Herdr CLI wrappers using paneId directly. AgentCreate also registers pi-loop-monitor and returns IDs plus a prepared assignment; confirm MonitorList shows subscription ready, then AgentSend it. `onSignal` wakes the parent for worker state changes; optional `onDone` handles monitor termination, not task completion. No registry, startup receipts, process checks or automatic recovery. Creation/closure need modern Pi nested calls and updated pi-loop-monitor metadata; no pi-herdr-agents dependency. See [agent tools](docs/USAGE_GUIDE.md#agent-tools).
44
52
 
45
53
  ## Optional auto-continuation
46
54
 
@@ -54,9 +62,9 @@ On Pi 1.2.0 or newer, enable unfinished-work continuation in your global or trus
54
62
  }
55
63
  ```
56
64
 
57
- It defaults off. Omit `maxContinuations` for no continuation limit, or add a positive integer such as `"maxContinuations": 10` to cap it. Unlimited continuation can consume tokens indefinitely while unfinished records remain; manual abort and the other stopping conditions still apply. After a normal user-requested run finishes, Pi continues while active works or todos remain. Completed, blocked, and cancelled records are settled. Escape/abort stops the flow; only a fresh accepted main interactive or RPC run rearms it. Extension wakes do not rearm it or reset the limit. The limit counts requested continuations per fresh main user run, not dollars or tool calls. Queued steering/follow-up input does not reset it. Reload after editing settings.
65
+ It defaults off. Omit `maxContinuations` for no continuation limit, or add a positive integer such as `"maxContinuations": 10` to cap it. Unlimited continuation can consume tokens indefinitely while unfinished records remain; manual abort and the other stopping conditions still apply. After a normal user-requested run succeeds or fails, Pi continues while any work or todo is not blocked, completed, or cancelled. Children count independently of their parent; legacy planned/pending records restore as active. Completed, blocked, and cancelled records are settled. Escape/abort stops the flow; only a fresh accepted main interactive or RPC run rearms it. Extension wakes do not rearm it or reset the limit. The limit counts requested continuations per fresh main user run, not dollars or tool calls. Queued steering/follow-up input does not reset it. Reload after editing settings.
58
66
 
59
- Auto-continuation uses Pi's native pre-settlement boundary, after queued work, retries, and compaction. It does not retry failed runs, run with unavailable tracking tools, or start work just because a session was restored. It never changes task statuses itself, and cannot independently prove completion. Older hosts retain ordinary tracking without this feature.
67
+ Auto-continuation uses Pi's native pre-settlement boundary, after queued work, retries, and compaction. Failed runs do not disarm it: after Pi's native retries finish, unfinished records request another continuation. It does not run with unavailable tracking tools or start work just because a session was restored. It never changes task statuses itself, and cannot independently prove completion. Older hosts retain ordinary tracking without this feature.
60
68
 
61
69
  See [the usage guide](docs/USAGE_GUIDE.md) and [reference](docs/REFERENCE.md).
62
70
 
@@ -0,0 +1,4 @@
1
+ export declare const PANE_ID: RegExp;
2
+ export declare function object(value: unknown): Record<string, unknown> | undefined;
3
+ export declare function herdrText(args: string[], cwd: string, signal?: AbortSignal, timeout?: number): Promise<string>;
4
+ export declare function herdr(args: string[], cwd: string, signal?: AbortSignal, timeout?: number): Promise<Record<string, unknown>>;
@@ -0,0 +1,23 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ const execFileAsync = promisify(execFile);
4
+ export const PANE_ID = /^w[A-Za-z0-9]+:p[A-Za-z0-9]+$/;
5
+ export function object(value) {
6
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
7
+ }
8
+ export async function herdrText(args, cwd, signal, timeout = 15_000) {
9
+ if (process.env.HERDR_ENV !== "1")
10
+ throw new Error("Agent tools require Herdr (HERDR_ENV=1).");
11
+ const { stdout } = await execFileAsync("herdr", args, { cwd, signal, timeout, maxBuffer: 256 * 1024, windowsHide: true });
12
+ return stdout;
13
+ }
14
+ export async function herdr(args, cwd, signal, timeout) {
15
+ const response = object(JSON.parse(await herdrText(args, cwd, signal, timeout)));
16
+ const error = object(response?.error);
17
+ if (error)
18
+ throw new Error(typeof error.message === "string" ? error.message : "Herdr command failed.");
19
+ const result = object(response?.result);
20
+ if (!result)
21
+ throw new Error("Herdr returned no result.");
22
+ return result;
23
+ }
@@ -0,0 +1,7 @@
1
+ export interface DelegateLink {
2
+ paneId: string;
3
+ }
4
+ export declare function delegateLink(taskInfo: string): DelegateLink | undefined;
5
+ export declare function focusPane(paneId: string, cwd: string, signal?: AbortSignal): Promise<void>;
6
+ export declare function preservePaneLink(current: string, next: string): string;
7
+ export declare function withPaneLink(taskInfo: string, paneId?: string, monitorId?: string): string;
@@ -0,0 +1,30 @@
1
+ import { taskOwner } from "../ownership.js";
2
+ import { herdr, object, PANE_ID } from "./herdr.js";
3
+ export function delegateLink(taskInfo) {
4
+ if (process.env.HERDR_ENV !== "1" || taskOwner(taskInfo) !== "delegate")
5
+ return undefined;
6
+ const panes = [...taskInfo.matchAll(/^[ \t]*herdr-pane:[ \t]*([^\r\n]*)$/gim)].map((match) => match[1].trim());
7
+ if (panes.length === 0 || panes.some((pane) => !PANE_ID.test(pane)) || new Set(panes).size !== 1)
8
+ return undefined;
9
+ return { paneId: panes[0] };
10
+ }
11
+ export async function focusPane(paneId, cwd, signal) {
12
+ if (!PANE_ID.test(paneId))
13
+ throw new Error("Use the paneId returned by Herdr.");
14
+ const focused = await herdr(["agent", "focus", paneId], cwd, signal);
15
+ const tabId = object(focused.agent)?.tab_id;
16
+ if (typeof tabId !== "string" || !tabId)
17
+ throw new Error("Herdr returned no tab for the delegate.");
18
+ // Pane focus alone can leave the visible client on its previous tab.
19
+ await herdr(["tab", "focus", tabId], cwd, signal);
20
+ }
21
+ export function preservePaneLink(current, next) {
22
+ if (taskOwner(current) !== "delegate" || taskOwner(next) !== "delegate" || /^[ \t]*herdr-(?:pane|monitor):/im.test(next))
23
+ return next;
24
+ const metadata = current.split(/\r?\n/).filter((line) => /^[ \t]*herdr-(?:pane|monitor):/i.test(line));
25
+ return metadata.length ? `${next.trim()}\n${metadata.join("\n")}` : next;
26
+ }
27
+ export function withPaneLink(taskInfo, paneId, monitorId) {
28
+ const text = taskInfo.split(/\r?\n/).filter((line) => !/^[ \t]*herdr-(?:pane|monitor):/i.test(line)).join("\n").trim();
29
+ return paneId ? `${text}\nherdr-pane: ${paneId}\nherdr-monitor: ${monitorId}` : text;
30
+ }
@@ -0,0 +1,3 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { TaskState } from "../state.js";
3
+ export declare function registerAgentTools(pi: ExtensionAPI, state: TaskState): void;
@@ -0,0 +1,140 @@
1
+ import { Type } from "typebox";
2
+ import { taskOwner } from "../ownership.js";
3
+ import { renderTaskCall, renderTaskResult, taskResult } from "../tool-result.js";
4
+ import { areTrackingToolsActive } from "../tracking.js";
5
+ import { herdr, herdrText, object, PANE_ID } from "./herdr.js";
6
+ import { delegateLink, focusPane, withPaneLink } from "./links.js";
7
+ const PaneId = Type.String({ pattern: PANE_ID.source, description: "Actual paneId returned by Herdr, not a pane name." });
8
+ const Target = Type.Object({ paneId: PaneId }, { additionalProperties: false });
9
+ const output = { outputSchema: Type.Object({}, { additionalProperties: true }) };
10
+ const nested = { reachesTools: () => ["MonitorCreate", "MonitorStop"] };
11
+ const mutation = { annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true } };
12
+ const readOnly = { annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } };
13
+ function monitorHost(ctx) {
14
+ const host = ctx;
15
+ if (typeof host.executeTool !== "function" || !["MonitorCreate", "MonitorList", "MonitorStop"].every((name) => host.tools?.some((tool) => tool.name === name))) {
16
+ throw new Error("AgentCreate/Close require modern Pi nested calls and callable pi-loop-monitor tools.");
17
+ }
18
+ return host;
19
+ }
20
+ async function monitor(ctx, name, args, signal) {
21
+ const outcome = object(await monitorHost(ctx).executeTool(name, args, { signal }));
22
+ const details = object(object(outcome?.result)?.details);
23
+ if (outcome?.isError !== false || !details || details.tone === "error")
24
+ throw new Error(`${name} failed. Inspect its tool result.`);
25
+ return details;
26
+ }
27
+ function result(name, data) {
28
+ return { ...taskResult(JSON.stringify(data, null, 2), name, data, `${name}${data.paneId ? ` · ${data.paneId}` : ""}`), structuredContent: data };
29
+ }
30
+ export function registerAgentTools(pi, state) {
31
+ const requireMainWork = () => {
32
+ if (!areTrackingToolsActive(pi))
33
+ throw new Error("Use agent tools in tracked main-conversation work, not /ask or /btw.");
34
+ };
35
+ pi.registerTool({
36
+ 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. 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
+ 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
+ parameters: Type.Object({
40
+ 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
+ assignment: Type.String({ minLength: 1, maxLength: 32_000 }), provider: Type.String({ minLength: 1 }), model: Type.String({ minLength: 1 }),
43
+ thinking: Type.String({ minLength: 1, description: "Explicit thinking level supported by the chosen model." }),
44
+ fast: Type.Optional(Type.Boolean({ description: "Forward --fast only when requested and supported." })),
45
+ onSignal: Type.String({ minLength: 1, maxLength: 10_000, description: "Instructions waking the parent on worker state changes. The monitor stays subscribed for follow-ups." }),
46
+ onDone: Type.Optional(Type.String({ minLength: 1, maxLength: 10_000, description: "Instructions if the monitor process ends, not when the worker finishes. Omit for MonitorCreate's default recovery instruction." })),
47
+ }, { additionalProperties: false }),
48
+ ...output, ...nested, ...mutation, executionMode: "sequential",
49
+ async execute(_id, params, signal, _update, ctx) {
50
+ requireMainWork();
51
+ monitorHost(ctx);
52
+ const todo = state.getTodo(params.taskId);
53
+ if (!todo || todo.workId !== params.workId || taskOwner(todo.taskInfo) !== "delegate")
54
+ throw new Error("Use an existing task in this work with owner: delegate.");
55
+ const handles = {};
56
+ try {
57
+ const current = object((await herdr(["pane", "current"], ctx.cwd, signal)).pane);
58
+ if (typeof current?.workspace_id !== "string")
59
+ throw new Error("Herdr returned no current workspace ID.");
60
+ const created = await herdr(["tab", "create", "--workspace", current.workspace_id, "--cwd", ctx.cwd, "--label", params.taskId, "--no-focus"], ctx.cwd, signal);
61
+ const pane = object(created.root_pane);
62
+ if (typeof pane?.pane_id !== "string" || !PANE_ID.test(pane.pane_id))
63
+ throw new Error(`Herdr returned no root pane ID: ${JSON.stringify(created)}`);
64
+ Object.assign(handles, { paneId: pane.pane_id, tabId: pane.tab_id });
65
+ await herdr(["pane", "rename", pane.pane_id, params.taskId], ctx.cwd, signal);
66
+ const args = ["agent", "start", `task-${params.taskId.toLowerCase()}-${pane.pane_id.replace(":", "-").toLowerCase()}`, "--kind", "pi", "--pane", pane.pane_id,
67
+ "--", "--provider", params.provider, "--model", params.model, "--thinking", params.thinking];
68
+ if (params.fast)
69
+ args.push("--fast");
70
+ await herdr(args, ctx.cwd, signal, 45_000);
71
+ 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);
73
+ if (typeof watched.monitorId !== "string")
74
+ throw new Error("Update pi-loop-monitor: MonitorCreate must return details.monitorId.");
75
+ handles.monitorId = watched.monitorId;
76
+ const currentTodo = state.getTodo(params.taskId);
77
+ if (!currentTodo || currentTodo.workId !== params.workId)
78
+ throw new Error("The parent task is no longer available for linking.");
79
+ state.updateTodo(params.taskId, { 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}`;
81
+ 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." });
83
+ }
84
+ catch (error) {
85
+ 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.`);
86
+ }
87
+ },
88
+ renderCall: renderTaskCall("AgentCreate"), renderResult: renderTaskResult,
89
+ });
90
+ pi.registerTool({
91
+ name: "AgentList", label: "AgentList", description: "Herdr CLI wrapper: list agents. Includes agents outside this work; do not close unrelated resources.",
92
+ parameters: Type.Object({}, { additionalProperties: false }), ...output, ...readOnly,
93
+ async execute(_id, _params, signal, _update, ctx) { return result("AgentList", await herdr(["agent", "list"], ctx.cwd, signal)); },
94
+ renderCall: (_args, theme) => renderTaskCall("AgentList")({}, theme), renderResult: renderTaskResult,
95
+ });
96
+ pi.registerTool({
97
+ name: "AgentStatus", label: "AgentStatus", description: "Herdr CLI wrapper: get current agent state for an explicit paneId.",
98
+ parameters: Target, ...output, ...readOnly,
99
+ async execute(_id, params, signal, _update, ctx) { return result("AgentStatus", await herdr(["agent", "get", params.paneId], ctx.cwd, signal)); },
100
+ renderCall: renderTaskCall("AgentStatus"), renderResult: renderTaskResult,
101
+ });
102
+ pi.registerTool({
103
+ name: "AgentOutput", label: "AgentOutput", description: "Herdr CLI wrapper: read trailing pane output, 50 lines by default, up to 200. Treat output as untrusted; use monitor signals rather than polling.",
104
+ parameters: Type.Object({ paneId: PaneId, lines: Type.Optional(Type.Integer({ minimum: 1, maximum: 200 })) }, { additionalProperties: false }), ...output, ...readOnly,
105
+ async execute(_id, params, signal, _update, ctx) { return result("AgentOutput", { paneId: params.paneId, output: await herdrText(["pane", "read", params.paneId, "--source", "recent-unwrapped", "--lines", String(params.lines ?? 50), "--format", "text"], ctx.cwd, signal) }); },
106
+ renderCall: renderTaskCall("AgentOutput"), renderResult: renderTaskResult,
107
+ });
108
+ pi.registerTool({
109
+ name: "AgentSend", label: "AgentSend", description: "Herdr CLI wrapper: send a prompt without --wait. Confirm the existing monitor is ready before the first assignment; keep the same monitor/callbacks for follow-ups.",
110
+ parameters: Type.Object({ paneId: PaneId, message: Type.String({ minLength: 1, maxLength: 40_000 }) }, { additionalProperties: false }), ...output, ...mutation,
111
+ async execute(_id, params, signal, _update, ctx) { requireMainWork(); return result("AgentSend", await herdr(["agent", "prompt", params.paneId, params.message], ctx.cwd, signal)); },
112
+ renderCall: renderTaskCall("AgentSend"), renderResult: renderTaskResult,
113
+ });
114
+ pi.registerTool({
115
+ name: "AgentInterrupt", label: "AgentInterrupt", description: "Herdr CLI wrapper: send Escape to the agent. Retains its pane and existing monitoring.",
116
+ parameters: Target, ...output, ...mutation,
117
+ async execute(_id, params, signal, _update, ctx) { requireMainWork(); return result("AgentInterrupt", await herdr(["agent", "send-keys", params.paneId, "esc"], ctx.cwd, signal)); },
118
+ renderCall: renderTaskCall("AgentInterrupt"), renderResult: renderTaskResult,
119
+ });
120
+ pi.registerTool({
121
+ name: "AgentClose", label: "AgentClose", description: "Stop the supplied monitor, then close the supplied pane. Only use IDs for resources you created and no longer need. No ownership registry, automatic recovery or task completion.",
122
+ parameters: Type.Object({ paneId: PaneId, monitorId: Type.String({ minLength: 1 }) }, { additionalProperties: false }), ...output, ...nested, ...mutation,
123
+ async execute(_id, params, signal, _update, ctx) {
124
+ requireMainWork();
125
+ await monitor(ctx, "MonitorStop", { monitorId: params.monitorId }, signal);
126
+ const closed = await herdr(["pane", "close", params.paneId], ctx.cwd, signal);
127
+ for (const todo of state.listTodos())
128
+ if (delegateLink(todo.taskInfo)?.paneId === params.paneId)
129
+ state.updateTodo(todo.taskId, { taskInfo: withPaneLink(todo.taskInfo) });
130
+ return result("AgentClose", { ...closed, paneId: params.paneId, monitorId: params.monitorId });
131
+ },
132
+ renderCall: renderTaskCall("AgentClose"), renderResult: renderTaskResult,
133
+ });
134
+ pi.registerTool({
135
+ name: "AgentFocus", label: "AgentFocus", description: "Herdr CLI wrapper: focus the agent at an explicit paneId. Also powers underlined delegate badge links.",
136
+ parameters: Target, ...output, ...mutation,
137
+ async execute(_id, params, signal, _update, ctx) { requireMainWork(); await focusPane(params.paneId, ctx.cwd, signal); return result("AgentFocus", { paneId: params.paneId }); },
138
+ renderCall: renderTaskCall("AgentFocus"), renderResult: renderTaskResult,
139
+ });
140
+ }
@@ -68,7 +68,7 @@ export function registerTaskAutoContinue(pi, state) {
68
68
  host.on("agent_before_settle", (event, ctx) => {
69
69
  if (!active)
70
70
  return;
71
- if (event.outcome !== "completed" || ctx.signal?.aborted) {
71
+ if (event.outcome === "aborted" || ctx.signal?.aborted) {
72
72
  armed = false;
73
73
  pendingUserInput = false;
74
74
  pendingMainRun = false;
@@ -90,10 +90,12 @@ export function registerTaskAutoContinue(pi, state) {
90
90
  }
91
91
  if (!settings.enabled || event.continue || event.context.pendingMessages.length > 0 || ctx.hasPendingMessages())
92
92
  return;
93
+ // Errors do not settle work; only explicit record states do. Count children independently.
94
+ const settled = new Set(["blocked", "completed", "cancelled"]);
93
95
  const records = [
94
- ...state.listWorks().filter((work) => work.status === "active")
96
+ ...state.listWorks().filter((work) => !settled.has(work.status))
95
97
  .map((work) => ({ id: work.workId, name: work.workName, status: work.status })),
96
- ...state.listTodos().filter((todo) => todo.status === "active")
98
+ ...state.listTodos().filter((todo) => !settled.has(todo.status))
97
99
  .map((todo) => ({ id: todo.taskId, workId: todo.workId, name: todo.taskName, status: todo.status })),
98
100
  ];
99
101
  if (records.length === 0)
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
+ import { delegateLink, focusPane } from "./agents/links.js";
2
+ import { registerAgentTools } from "./agents/tools.js";
1
3
  import { registerTaskAutoContinue } from "./auto-continue.js";
2
4
  import { registerWorksCommand } from "./command.js";
3
5
  import { GitStatusCache } from "./git-status.js";
4
- import { openRepository } from "./open-repository.js";
6
+ import { openRepository, openSession } from "./open-repository.js";
5
7
  import { TaskState } from "./state.js";
6
8
  import { safeSingleLine } from "./text.js";
7
9
  import { registerTaskTools } from "./tools.js";
@@ -13,6 +15,7 @@ export default function tasksExtension(pi) {
13
15
  const git = new GitStatusCache();
14
16
  panel = new TasksPanelHost(state, git);
15
17
  registerTaskTools(pi, state);
18
+ registerAgentTools(pi, state);
16
19
  registerTrackingGuidance(pi);
17
20
  registerTaskAutoContinue(pi, state);
18
21
  registerWorksCommand(pi, state, git);
@@ -20,10 +23,31 @@ export default function tasksExtension(pi) {
20
23
  description: "Set the works panel display mode",
21
24
  handler: async (args, ctx) => {
22
25
  const requested = args.trim();
23
- if (requested === "open") {
26
+ const delegateTask = /^delegate\s+(T\d+)$/.exec(requested)?.[1];
27
+ if (delegateTask) {
28
+ const todo = state.getTodo(delegateTask);
29
+ const link = todo ? delegateLink(todo.taskInfo) : undefined;
30
+ if (!link) {
31
+ ctx.ui.notify("This task has no Herdr delegate link, or Pi is not running inside Herdr.", "warning");
32
+ return;
33
+ }
34
+ try {
35
+ await focusPane(link.paneId, ctx.cwd);
36
+ ctx.ui.notify("Opened delegated agent in Herdr.", "info");
37
+ }
38
+ catch (error) {
39
+ const reason = error instanceof Error ? safeSingleLine(error.message) : "Unknown error.";
40
+ ctx.ui.notify(`Could not open delegate. ${reason}`, "error");
41
+ }
42
+ return;
43
+ }
44
+ if (requested === "open" || requested === "open-session") {
24
45
  try {
25
- await openRepository(ctx.cwd);
26
- ctx.ui.notify("Opened repository in Cursor.", "info");
46
+ if (requested === "open-session")
47
+ await openSession(ctx.cwd, ctx.sessionManager.getSessionId());
48
+ else
49
+ await openRepository(ctx.cwd);
50
+ ctx.ui.notify(requested === "open-session" ? "Opened session artifacts in Cursor." : "Opened repository in Cursor.", "info");
27
51
  }
28
52
  catch (error) {
29
53
  const reason = error instanceof Error ? ` ${safeSingleLine(error.message)}` : "";
@@ -38,7 +62,7 @@ export default function tasksExtension(pi) {
38
62
  }
39
63
  const mode = requested === "floating" || requested === "widget" || requested === "off" ? requested : undefined;
40
64
  if (!mode) {
41
- ctx.ui.notify("Usage: /works-panel floating|widget|off|minimize|maximize|open", "info");
65
+ ctx.ui.notify("Usage: /works-panel floating|widget|off|minimize|maximize|open|open-session or /works-panel delegate T<number>", "info");
42
66
  return;
43
67
  }
44
68
  panel?.setMode(mode);
@@ -49,7 +73,7 @@ export default function tasksExtension(pi) {
49
73
  state.restore(ctx);
50
74
  git.setCwd(ctx.cwd);
51
75
  if (ctx.mode === "tui")
52
- panel?.attach(ctx.ui, ctx.cwd);
76
+ panel?.attach(ctx.ui, ctx.cwd, ctx.sessionManager.getSessionId());
53
77
  });
54
78
  pi.on("session_tree", (_event, ctx) => {
55
79
  state.restore(ctx);
@@ -1,2 +1,4 @@
1
1
  /** Launch Cursor without a shell, using the active session's working directory. */
2
2
  export declare function openRepository(cwd: string): Promise<void>;
3
+ /** Open the existing direct or nested agent artifact root, creating a new root only if needed. */
4
+ export declare function openSession(cwd: string, sessionId: string): Promise<void>;
@@ -1,7 +1,29 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { glob, mkdir, stat } from "node:fs/promises";
3
+ import { resolve } from "node:path";
2
4
  import { promisify } from "node:util";
3
5
  const execFileAsync = promisify(execFile);
4
6
  /** Launch Cursor without a shell, using the active session's working directory. */
5
7
  export async function openRepository(cwd) {
6
8
  await execFileAsync("cursor", ["."], { cwd, timeout: 10_000, maxBuffer: 64 * 1024, windowsHide: true });
7
9
  }
10
+ /** Open the existing direct or nested agent artifact root, creating a new root only if needed. */
11
+ export async function openSession(cwd, sessionId) {
12
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(sessionId))
13
+ throw new Error("A valid Pi session ID is required to open session artifacts.");
14
+ const repository = await execFileAsync("git", ["rev-parse", "--show-toplevel"], { cwd, timeout: 5_000, maxBuffer: 64 * 1024, windowsHide: true })
15
+ .then(({ stdout }) => stdout.trim(), () => cwd);
16
+ const varRoot = resolve(repository, "var");
17
+ await mkdir(varRoot, { recursive: true });
18
+ const matches = [];
19
+ for await (const path of glob(`**/${sessionId}`, { cwd: varRoot })) {
20
+ const directory = resolve(varRoot, path);
21
+ if ((await stat(directory)).isDirectory())
22
+ matches.push(directory);
23
+ }
24
+ if (matches.length > 1)
25
+ throw new Error("Multiple artifact folders match this session; open the intended folder explicitly.");
26
+ const directory = matches[0] ?? resolve(varRoot, sessionId);
27
+ await mkdir(directory, { recursive: true });
28
+ await openRepository(directory);
29
+ }
@@ -0,0 +1 @@
1
+ export declare function taskOwner(taskInfo: string): "self" | "delegate" | "unassigned";
@@ -0,0 +1,9 @@
1
+ export function taskOwner(taskInfo) {
2
+ const owners = new Set([...taskInfo.matchAll(/^[ \t]*owner:[ \t]*(self|delegate)(?=[ \t.,;:\r]|$)/gim)]
3
+ .map((match) => match[1]?.toLowerCase()));
4
+ if (owners.size !== 1)
5
+ return "unassigned";
6
+ if (owners.has("self"))
7
+ return "self";
8
+ return owners.has("delegate") ? "delegate" : "unassigned";
9
+ }
package/dist/tools.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { StringEnum } from "@earendil-works/pi-ai";
2
2
  import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead } from "@earendil-works/pi-coding-agent";
3
3
  import { Type } from "typebox";
4
+ import { preservePaneLink } from "./agents/links.js";
4
5
  import { formatCompletion, taskCompletion, workCompletion } from "./progress.js";
5
6
  import { renderTaskCall, renderTaskResult, taskResult } from "./tool-result.js";
6
7
  const StatusSchema = StringEnum(["active", "blocked", "completed", "cancelled"]);
@@ -144,7 +145,8 @@ export function registerTaskTools(pi, state) {
144
145
  completionPercent: Type.Optional(CompletionSchema),
145
146
  }, { additionalProperties: false, minProperties: 2 }),
146
147
  execute(_id, params) {
147
- const todo = state.updateTodo(params.taskId, { taskName: params.taskName, taskInfo: params.taskInfo, status: params.status, completionPercent: params.completionPercent });
148
+ const taskInfo = params.taskInfo === undefined ? undefined : preservePaneLink(state.getTodo(params.taskId)?.taskInfo ?? "", params.taskInfo);
149
+ const todo = state.updateTodo(params.taskId, { taskName: params.taskName, taskInfo, status: params.status, completionPercent: params.completionPercent });
148
150
  return Promise.resolve(taskResult(`Updated todo ${todo.taskId}: ${todo.taskName} · ${formatCompletion(taskCompletion(todo))} [${todo.status}]`, "todo-update", { taskId: todo.taskId, workId: todo.workId, completionPercent: taskCompletion(todo) }));
149
151
  },
150
152
  renderCall: renderTaskCall("TodoUpdate"),
package/dist/tracking.js CHANGED
@@ -5,6 +5,17 @@ Work is the overall outcome being pursued. A todo is a concrete step that belong
5
5
  For every normal user request that starts or continues work, keep the session's work and todo records synchronized. Do not skip tracking because the work looks small.
6
6
  Write workInfo and taskInfo in normal prose with full sentences and spaces between words. Conversational brevity modes must not compress stored records or concatenate words.
7
7
 
8
+ Every delegated subagent, at every delegation depth, must use these tools to create or resume its own session-local Work and Todos before assigned work. Do not begin assigned work without a real workId and an active taskId for the current step. Keep these records current and return the IDs with results, checks, and blockers. Parent assignment IDs are context, not shared records: IDs are session-scoped. Record the parent assignment in the worker's details; do not mutate the parent's session records. Include this requirement in every subagent prompt. If tracking tools or IDs are unavailable, report the blocker and do not begin delegated work; a parent-owned Todo or Markdown checklist is not a substitute. Do not invent IDs or backdate tracking. This is an instruction, not a runtime enforcement hook, and does not change the /ask or /btw exceptions.
9
+
10
+ Shared workflow contract:
11
+ - Every tracked Work, including each subagent's local Work, follows the global implement skill for coordination. Read it before execution, or reuse it if already active; do not recursively invoke it. Specialized skills retain their scope and safety limits: research/review stay read-only and planning does not authorize implementation. If the skill is unavailable, report the blocker rather than executing without it.
12
+ - Before execution, read the full current sessionId through the agent's own shell tool using printf '%s\\n' "$PI_SESSION_ID". Require a nonempty safe component matching [A-Za-z0-9][A-Za-z0-9_-]* and real tool-returned Work/Task IDs. Missing tools, identity, or IDs block execution; never substitute the parent's identity or invent IDs. Reading instructions, obtaining identity, and establishing tracking are startup steps.
13
+ - Root task artifacts use repository-relative var/<sessionId>/<workId>/<taskId>/, not system /var/. A delegated worker appends its own <childSessionId>/<childWorkId>/<childTaskId>/ beneath the exact parentTaskDir supplied in its assignment, recursively. Keep resolved paths inside the repository's var/, including through symlinks. Record canonical paths and parent IDs in taskInfo, pass them unchanged in handoffs, and return them with results. Validate ownership before reuse after resume or branch navigation; do not overwrite artifacts just because numeric IDs match. Create artifacts only when useful; feature names are descriptions, not path keys. Do not migrate existing artifacts implicitly. Follow implement for the detailed contract and report incompatible helper paths rather than inventing arguments.
14
+ - For every task, start taskInfo with owner: self or owner: delegate followed by a short reason before execution. Preserve this explicit declaration when updating taskInfo; the panel reads this line to show the ownership badge, with unassigned for missing or conflicting decisions. Delegate only when scope/acceptance criteria are clear, ownership can be isolated, inputs and prerequisites are ready, and useful parallelism or expertise outweighs startup and integration costs. Respect skill-specific delegation restrictions and required tracking/monitor tools. Keep small, tightly coupled, shared-interface, or expensive-to-explain work with one owner. Delegating agents retain responsibility for monitoring, integration, verification, and cleanup; children apply the same rule when allowed to delegate. No arbitrary worker, file-count, or depth thresholds.
15
+ - Herdr subagent root panes are named exactly with the parent's delegated Task ID, such as T34, with no brackets, descriptions, Work IDs, or other prefixes. This is a display label, not the child's session or local Task ID. Use returned resource IDs for lifecycle operations because pane names can repeat across sessions; rename an owned worker pane when assigning it a different parent Todo.
16
+ - Prefer pi-tasks AgentCreate/List/Status/Output/Send/Interrupt/Close/Focus CLI wrappers for supported Herdr operations; use CLI only for unavailable capabilities. AgentCreate takes an existing owner: delegate task, canonical taskDir, explicit model flags and onSignal/optional onDone instructions, creates the pane and monitor, and automatically links the delegate badge. It does not send work: confirm MonitorList shows subscription ready, then AgentSend the returned assignment to the actual paneId. Follow-ups keep that same monitor/callbacks. onSignal handles worker state changes; onDone means the monitor process ended, not the task finished. Do not add duplicate monitors, infer completion from signals or close workers before follow-ups finish. Use AgentClose only with paneId/monitorId values for resources you created. Wrappers assume panes are not repurposed and add no registry, process checks or automatic recovery.
17
+ - Pi-tasks owns task records/progress and task-owned agent tool orchestration; implement owns coordination and artifact paths; Herdr owns panes/processes and pi-loop-monitor owns supervision. The shared skill/path guidance is instruction-only, not automatic cross-session shared records; Agent tools simply wrap the CLI and existing monitor tools. Plain conversation, /ask, and /btw remain outside this workflow.
18
+
8
19
  Before implementation, investigation, or any other requested work:
9
20
  1. Use WorkList and TodoList to find the relevant existing records and avoid duplicates.
10
21
  2. If no suitable work exists, create one with WorkCreate. Otherwise use WorkUpdate to refresh its detailed workInfo and mark it active.
@@ -1,4 +1,5 @@
1
1
  import { type ExtensionUIContext, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import { type DelegateLink } from "../agents/links.js";
2
3
  import type { GitSnapshot, GitStatusCache } from "../git-status.js";
3
4
  import type { TaskState } from "../state.js";
4
5
  import type { TodoStatus, WorkStatus } from "../types.js";
@@ -13,8 +14,9 @@ export declare class TasksPanelHost {
13
14
  private mode;
14
15
  private minimized;
15
16
  private cwd;
17
+ private sessionId;
16
18
  constructor(state: TaskState, git: GitStatusCache);
17
- attach(ui: ExtensionUIContext, cwd: string): void;
19
+ attach(ui: ExtensionUIContext, cwd: string, sessionId: string): void;
18
20
  setMode(mode: TasksPanelMode): void;
19
21
  getMode(): TasksPanelMode;
20
22
  setMinimized(minimized: boolean): void;
@@ -23,7 +25,16 @@ export declare class TasksPanelHost {
23
25
  private applyMode;
24
26
  private hideCurrent;
25
27
  }
26
- export declare function progressName(name: string, completion: number | null, width: number): string;
28
+ export declare function recordId(id: string, theme: Theme): string;
29
+ export declare function ownerBadge(taskInfo: string, theme: Theme, linked?: boolean): string;
30
+ export type DelegateHitRegion = {
31
+ start: number;
32
+ end: number;
33
+ y: number;
34
+ link: DelegateLink;
35
+ };
36
+ export declare function delegateHitRegion(link: DelegateLink | undefined, start: number, line: string, y: number, leftPad?: number): DelegateHitRegion | undefined;
37
+ export declare function progressName(name: string, completion: number | null, width: number, prefix?: string): string;
27
38
  export declare function workIcon(status: WorkStatus, theme: Theme): string;
28
39
  export declare function todoIcon(status: TodoStatus, theme: Theme): string;
29
40
  export declare function frame(content: string, innerWidth: number, theme: Theme): string;