@abhishek944/pi-tasks 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +59 -12
  2. package/dist/agents/delegation.d.ts +4 -0
  3. package/dist/agents/delegation.js +59 -0
  4. package/dist/agents/herdr.d.ts +10 -3
  5. package/dist/agents/herdr.js +39 -12
  6. package/dist/agents/links.d.ts +3 -3
  7. package/dist/agents/links.js +42 -19
  8. package/dist/auto-continue.js +160 -27
  9. package/dist/command.d.ts +2 -2
  10. package/dist/command.js +8 -4
  11. package/dist/delegated-time.d.ts +11 -0
  12. package/dist/delegated-time.js +51 -2
  13. package/dist/dependency.d.ts +7 -0
  14. package/dist/dependency.js +13 -0
  15. package/dist/durable.d.ts +38 -0
  16. package/dist/durable.js +515 -0
  17. package/dist/herdr-header.d.ts +3 -0
  18. package/dist/herdr-header.js +100 -0
  19. package/dist/herdr-panel.d.ts +7 -0
  20. package/dist/herdr-panel.js +182 -0
  21. package/dist/index.js +98 -56
  22. package/dist/markdown.js +3 -1
  23. package/dist/open-repository.d.ts +5 -3
  24. package/dist/open-repository.js +19 -5
  25. package/dist/panel-settings.d.ts +11 -0
  26. package/dist/panel-settings.js +30 -0
  27. package/dist/snapshot.d.ts +23 -0
  28. package/dist/snapshot.js +123 -0
  29. package/dist/state.d.ts +21 -18
  30. package/dist/state.js +357 -286
  31. package/dist/thoughts.d.ts +11 -0
  32. package/dist/thoughts.js +14 -0
  33. package/dist/timing.js +2 -1
  34. package/dist/tools.js +48 -29
  35. package/dist/tracking.js +18 -11
  36. package/dist/types.d.ts +9 -2
  37. package/dist/ui/panel.d.ts +2 -1
  38. package/dist/ui/panel.js +33 -21
  39. package/dist/ui/task-view.d.ts +7 -0
  40. package/dist/ui/task-view.js +10 -0
  41. package/dist/ui/works-dashboard.d.ts +3 -2
  42. package/dist/ui/works-dashboard.js +33 -24
  43. package/docs/REFERENCE.md +58 -30
  44. package/docs/USAGE_GUIDE.md +129 -51
  45. package/herdr/pi-tasks/README.md +45 -0
  46. package/herdr/pi-tasks/header.js +192 -0
  47. package/herdr/pi-tasks/main.js +413 -0
  48. package/herdr/pi-tasks/mod.json +3 -0
  49. package/herdr/pi-tasks/spinner.svg +1 -0
  50. package/package.json +26 -1
  51. package/dist/agents/tools.d.ts +0 -3
  52. package/dist/agents/tools.js +0 -143
@@ -0,0 +1,182 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, isAbsolute, join } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { app, hc, object, TERMINAL_ID } from "./agents/herdr.js";
7
+ import { ensureHerdrTasksHeader } from "./herdr-header.js";
8
+ import { readSnapshot } from "./snapshot.js";
9
+ /** Install missing shipped assets only. Never overwrite a personal/customized mod. */
10
+ async function installBundledMod(appHome) {
11
+ const assets = await Promise.all(["README.md", "main.js", "mod.json", "spinner.svg"].map(async (name) => ({
12
+ name, contents: await readFile(new URL(`../herdr/pi-tasks/${name}`, import.meta.url)),
13
+ })));
14
+ const directory = join(appHome, "mods", "pi-tasks");
15
+ await mkdir(directory, { recursive: true });
16
+ for (const asset of assets) {
17
+ try {
18
+ await writeFile(join(directory, asset.name), asset.contents, { flag: "wx" });
19
+ }
20
+ catch (error) {
21
+ if (error.code !== "EEXIST")
22
+ throw error;
23
+ }
24
+ }
25
+ }
26
+ /** Public Core document read only. One connection per deliberate opener, no service. */
27
+ async function readAppDocument(ctx) {
28
+ return new Promise((resolve, reject) => {
29
+ const child = spawn("hc", ["connect"], { cwd: ctx.cwd, signal: ctx.signal, stdio: ["pipe", "pipe", "pipe"] });
30
+ let output = "";
31
+ const timer = setTimeout(() => finish(new Error("Core pane inventory timed out.")), 10_000);
32
+ let settled = false;
33
+ function finish(error, value) {
34
+ if (settled)
35
+ return;
36
+ settled = true;
37
+ clearTimeout(timer);
38
+ child.kill();
39
+ if (error)
40
+ reject(error);
41
+ else
42
+ resolve(value);
43
+ }
44
+ child.on("error", (error) => finish(error));
45
+ child.on("close", () => { if (!settled)
46
+ finish(new Error("Core closed before returning its pane inventory.")); });
47
+ child.stdin.on("error", (error) => finish(error));
48
+ child.stderr.resume();
49
+ child.stdout.setEncoding("utf8");
50
+ child.stdout.on("data", (chunk) => {
51
+ output += chunk;
52
+ if (output.length > 2 * 1024 * 1024) {
53
+ finish(new Error("Core pane inventory is too large."));
54
+ return;
55
+ }
56
+ const end = output.indexOf("\n");
57
+ if (end < 0)
58
+ return;
59
+ try {
60
+ const reply = object(JSON.parse(output.slice(0, end)));
61
+ const value = object(object(reply?.result)?.value);
62
+ if (reply?.id !== "activity-pane-read" || !value || reply.error)
63
+ throw new Error("Core returned no usable pane inventory.");
64
+ finish(undefined, value);
65
+ }
66
+ catch (error) {
67
+ finish(error instanceof Error ? error : new Error(String(error)));
68
+ }
69
+ });
70
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: "activity-pane-read", method: "doc.get", params: { name: "herdr-app" } })}\n`);
71
+ });
72
+ }
73
+ function blocks(value) {
74
+ const node = object(value);
75
+ if (!node)
76
+ return [];
77
+ return [...(node.type === "block" ? [node] : []), ...(Array.isArray(node.children) ? node.children.flatMap(blocks) : [])];
78
+ }
79
+ /**
80
+ * A pane's content copy cannot name its own pane: Herdr passes a pane header `{pane, terminal}`
81
+ * but a content mod only the props it was created with. The Tasks status filter is view state
82
+ * keyed by that pane id, so this opener, which knows both ids, publishes the hosting pane beside
83
+ * the session task file. The view reads it and stays unfiltered while it is absent.
84
+ */
85
+ function tasksPaneFile(snapshot) {
86
+ return snapshot.endsWith(".json") ? `${snapshot.slice(0, -5)}.pane` : `${snapshot}.pane`;
87
+ }
88
+ async function publishTasksPane(snapshot, pane) {
89
+ const path = tasksPaneFile(snapshot);
90
+ await mkdir(dirname(path), { recursive: true });
91
+ await writeFile(path, `${pane}\n`);
92
+ }
93
+ /** Show beside this terminal, or hide only its same-session Tasks mod panes. */
94
+ export async function setHerdrTasksPaneVisible(ctx, visible, snapshot, openCommand = ["cursor"], options = {}) {
95
+ if (visible && (typeof snapshot !== "string" || !isAbsolute(snapshot))) {
96
+ throw new Error("This Pi instance has no session task snapshot binding. Restart Pi, resume this session, then run /works herdr-on again.");
97
+ }
98
+ if (visible && !readSnapshot(snapshot, ctx.sessionManager.getSessionId())) {
99
+ throw new Error("This session's task snapshot is missing. Restart/resume Pi to initialize session task storage, or restore the missing task file, before opening Herdr Tasks.");
100
+ }
101
+ const terminal = process.env.HC_TERMINAL_ID;
102
+ if (!terminal || !TERMINAL_ID.test(terminal))
103
+ throw new Error("Open this Pi session in Herdr Core before opening its Tasks pane.");
104
+ const current = await hc(["get", terminal], ctx.cwd, ctx.signal);
105
+ if (current.address !== terminal || current.state !== "live")
106
+ throw new Error("The originating Core terminal is not live.");
107
+ const appHome = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "herdr-app");
108
+ const inventory = await app(["ls"], ctx.cwd, ctx.signal);
109
+ const document = await readAppDocument(ctx);
110
+ const sessionId = ctx.sessionManager.getSessionId();
111
+ for (const rawSpace of Array.isArray(inventory.spaces) ? inventory.spaces : []) {
112
+ const space = object(rawSpace);
113
+ for (const rawTab of Array.isArray(space?.tabs) ? space.tabs : []) {
114
+ const tab = object(rawTab);
115
+ for (const rawTerminal of Array.isArray(tab?.terminals) ? tab.terminals : []) {
116
+ const item = object(rawTerminal);
117
+ if (item?.terminal !== terminal || typeof item.pane !== "string")
118
+ continue;
119
+ if (space?.machine)
120
+ throw new Error("The file-backed Tasks pane currently supports local Herdr sessions only.");
121
+ const documentSpace = (Array.isArray(document.spaces) ? document.spaces : []).map(object).find((entry) => entry?.id === space?.id);
122
+ const documentTab = (Array.isArray(documentSpace?.tabs) ? documentSpace.tabs : []).map(object).find((entry) => entry?.id === tab?.id);
123
+ const panes = blocks(documentTab?.root);
124
+ if (!panes.some((pane) => pane.id === item.pane && object(pane.content)?.terminal === terminal)) {
125
+ throw new Error("The source terminal pane changed. Retry opening Tasks from this session.");
126
+ }
127
+ const matches = (pane, mod) => {
128
+ const content = object(pane.content);
129
+ const binding = object(content?.props);
130
+ return typeof pane.id === "string" && content?.terminal == null && content?.mod === mod && binding?.sessionId === sessionId && binding.terminal === terminal;
131
+ };
132
+ const existing = panes.filter((pane) => matches(pane, "pi-tasks"));
133
+ if (!visible) {
134
+ for (const pane of existing)
135
+ await app(["do", "pane.close", JSON.stringify({ pane: pane.id })], ctx.cwd, ctx.signal);
136
+ return;
137
+ }
138
+ if (existing.length) {
139
+ const pane = existing[0];
140
+ if (typeof pane.id !== "string")
141
+ throw new Error("The existing Tasks pane has no pane ID.");
142
+ await app(["do", "pane.focus", JSON.stringify({ pane: pane.id })], ctx.cwd, ctx.signal);
143
+ await publishTasksPane(snapshot, pane.id);
144
+ return;
145
+ }
146
+ if (options.replaceStale) {
147
+ for (const pane of panes) {
148
+ const content = object(pane.content);
149
+ const binding = object(content?.props);
150
+ if (typeof pane.id === "string" && content?.terminal == null && content?.mod === "pi-tasks"
151
+ && binding?.terminal === terminal && binding.sessionId !== sessionId) {
152
+ await app(["do", "pane.close", JSON.stringify({ pane: pane.id })], ctx.cwd, ctx.signal);
153
+ }
154
+ }
155
+ }
156
+ const activity = panes.find((pane) => matches(pane, "pi-loop-monitor"));
157
+ await installBundledMod(appHome);
158
+ await ensureHerdrTasksHeader(ctx, appHome);
159
+ const args = ["do", "pane.split", JSON.stringify({ pane: activity?.id ?? item.pane, direction: activity ? "down" : "right", mod: "pi-tasks", props: { sessionId: ctx.sessionManager.getSessionId(), snapshot, terminal, openCommand, paneFile: tasksPaneFile(snapshot) } })];
160
+ let result;
161
+ try {
162
+ result = await app(args, ctx.cwd, ctx.signal);
163
+ }
164
+ catch (error) {
165
+ const failure = object(error);
166
+ const message = [error instanceof Error ? error.message : "", failure?.stdout, failure?.stderr].filter((part) => typeof part === "string").join("\n");
167
+ // Herdr discovers new folders asynchronously. This exact rejection
168
+ // happens before pane creation, so one discovery retry cannot duplicate it.
169
+ if (!message.includes('no mod "pi-tasks" in mods/') && !message.includes('no mod \\"pi-tasks\\" in mods/'))
170
+ throw error;
171
+ await delay(1_000, undefined, { signal: ctx.signal });
172
+ result = await app(args, ctx.cwd, ctx.signal);
173
+ }
174
+ if (typeof result.pane !== "string")
175
+ throw new Error("Herdr did not return a Tasks pane ID.");
176
+ await publishTasksPane(snapshot, result.pane);
177
+ return;
178
+ }
179
+ }
180
+ }
181
+ throw new Error("This Pi terminal has no pane in the running Herdr app. Open its terminal tab first.");
182
+ }
package/dist/index.js CHANGED
@@ -1,10 +1,12 @@
1
- import { delegateLink, focusPane } from "./agents/links.js";
2
- import { registerAgentTools } from "./agents/tools.js";
1
+ import { registerDelegationBridge } from "./agents/delegation.js";
2
+ import { delegateLink, focusTerminal } from "./agents/links.js";
3
3
  import { registerTaskAutoContinue } from "./auto-continue.js";
4
4
  import { registerWorksCommand } from "./command.js";
5
5
  import { registerDelegatedTimeTools } from "./delegated-time.js";
6
6
  import { GitStatusCache } from "./git-status.js";
7
- import { openRepository, openSession } from "./open-repository.js";
7
+ import { setHerdrTasksPaneVisible } from "./herdr-panel.js";
8
+ import { openRepository, openSession, readOpenCommand } from "./open-repository.js";
9
+ import { readHerdrPanelSettings, readPanelSettings } from "./panel-settings.js";
8
10
  import { TaskState } from "./state.js";
9
11
  import { safeSingleLine } from "./text.js";
10
12
  import { registerTaskTiming } from "./timing.js";
@@ -15,72 +17,112 @@ export default function tasksExtension(pi) {
15
17
  let panel;
16
18
  const state = new TaskState(pi, () => panel?.update());
17
19
  const git = new GitStatusCache();
18
- panel = new TasksPanelHost(state, git);
20
+ const getSettings = () => pi.getSettings?.();
21
+ const getOpenCommand = () => readOpenCommand(getSettings());
22
+ let visibleMode = "floating";
23
+ panel = new TasksPanelHost(state, git, getOpenCommand);
24
+ async function openHerdrTasksPaneOnStart(ctx) {
25
+ if (!process.env.HC_TERMINAL_ID)
26
+ return;
27
+ let enabled;
28
+ try {
29
+ enabled = readHerdrPanelSettings(getSettings()).enabled;
30
+ }
31
+ catch (error) {
32
+ ctx.ui.notify(error instanceof Error ? error.message : "Invalid Herdr panel settings.", "error");
33
+ return;
34
+ }
35
+ if (!enabled)
36
+ return;
37
+ try {
38
+ await setHerdrTasksPaneVisible(ctx, true, state.snapshotPath, getOpenCommand(), { replaceStale: true });
39
+ }
40
+ catch {
41
+ // The native pane is an optional display; /works herdr-on reports the reason.
42
+ }
43
+ }
19
44
  registerTaskTools(pi, state);
20
45
  registerDelegatedTimeTools(pi, state);
21
46
  registerTaskTiming(pi, state);
22
- registerAgentTools(pi, state);
47
+ registerDelegationBridge(pi, state);
23
48
  registerTrackingGuidance(pi);
24
49
  registerTaskAutoContinue(pi, state);
25
- registerWorksCommand(pi, state, git);
26
- pi.registerCommand("works-panel", {
27
- description: "Set the works panel display mode",
28
- handler: async (args, ctx) => {
29
- const requested = args.trim();
30
- const delegateTask = /^delegate\s+(T\d+)$/.exec(requested)?.[1];
31
- if (delegateTask) {
32
- const todo = state.getTodo(delegateTask);
33
- const link = todo ? delegateLink(todo.taskInfo) : undefined;
34
- if (!link) {
35
- ctx.ui.notify("This task has no Herdr delegate link, or Pi is not running inside Herdr.", "warning");
36
- return;
37
- }
38
- try {
39
- await focusPane(link.paneId, ctx.cwd);
40
- ctx.ui.notify("Opened delegated agent in Herdr.", "info");
41
- }
42
- catch (error) {
43
- const reason = error instanceof Error ? safeSingleLine(error.message) : "Unknown error.";
44
- ctx.ui.notify(`Could not open delegate. ${reason}`, "error");
45
- }
46
- return;
50
+ registerWorksCommand(pi, state, git, getOpenCommand, async (requested, ctx) => {
51
+ if (requested === "herdr-on" || requested === "herdr-off") {
52
+ try {
53
+ const visible = requested === "herdr-on";
54
+ await setHerdrTasksPaneVisible(ctx, visible, visible ? state.snapshotPath : "", visible ? getOpenCommand() : undefined);
55
+ ctx.ui.notify(visible ? "Opened the Herdr Tasks pane." : "Closed this session’s Herdr Tasks pane.", "info");
47
56
  }
48
- if (requested === "open" || requested === "open-session") {
49
- try {
50
- if (requested === "open-session")
51
- await openSession(ctx.cwd, ctx.sessionManager.getSessionId());
52
- else
53
- await openRepository(ctx.cwd);
54
- ctx.ui.notify(requested === "open-session" ? "Opened session artifacts in Cursor." : "Opened repository in Cursor.", "info");
55
- }
56
- catch (error) {
57
- const reason = error instanceof Error ? ` ${safeSingleLine(error.message)}` : "";
58
- ctx.ui.notify(`Could not open Cursor. Check cursor is on PATH.${reason}`, "error");
59
- }
60
- return;
57
+ catch (error) {
58
+ ctx.ui.notify(error instanceof Error ? safeSingleLine(error.message) : "Could not change the Herdr Tasks pane visibility.", "error");
61
59
  }
62
- if (requested === "minimize" || requested === "maximize") {
63
- panel?.setMinimized(requested === "minimize");
64
- ctx.ui.notify(`Works panel: ${requested}d`, "info");
60
+ return;
61
+ }
62
+ const delegateTask = /^delegate\s+(T\d+)$/.exec(requested)?.[1];
63
+ if (delegateTask) {
64
+ const todo = state.getTodo(delegateTask);
65
+ const link = todo ? delegateLink(todo.taskInfo) : undefined;
66
+ if (!link) {
67
+ ctx.ui.notify("This task has no valid Core delegate terminal link.", "warning");
65
68
  return;
66
69
  }
67
- const mode = requested === "floating" || requested === "widget" || requested === "off" ? requested : undefined;
68
- if (!mode) {
69
- ctx.ui.notify("Usage: /works-panel floating|widget|off|minimize|maximize|open|open-session or /works-panel delegate T<number>", "info");
70
- return;
70
+ try {
71
+ await focusTerminal(link.terminalId, ctx.cwd);
72
+ ctx.ui.notify("Opened delegated agent in Herdr.", "info");
73
+ }
74
+ catch (error) {
75
+ const reason = error instanceof Error ? safeSingleLine(error.message) : "Unknown error.";
76
+ ctx.ui.notify(`Could not open delegate. ${reason}`, "error");
71
77
  }
72
- panel?.setMode(mode);
73
- ctx.ui.notify(`Works panel: ${mode}`, "info");
74
- },
78
+ return;
79
+ }
80
+ if (requested === "open" || requested === "open-session") {
81
+ try {
82
+ const command = getOpenCommand();
83
+ if (requested === "open-session")
84
+ await openSession(ctx.cwd, ctx.sessionManager.getSessionId(), command);
85
+ else
86
+ await openRepository(ctx.cwd, command);
87
+ ctx.ui.notify(requested === "open-session" ? "Opened session artifacts." : "Opened repository.", "info");
88
+ }
89
+ catch (error) {
90
+ const reason = error instanceof Error ? ` ${safeSingleLine(error.message)}` : "";
91
+ ctx.ui.notify(`Could not open directory. Check pi-tasks.openCommand and that its executable is installed on PATH.${reason}`, "error");
92
+ }
93
+ return;
94
+ }
95
+ if (requested === "minimize" || requested === "maximize") {
96
+ panel?.setMinimized(requested === "minimize");
97
+ ctx.ui.notify(`Works panel: ${requested}d`, "info");
98
+ return;
99
+ }
100
+ const mode = requested === "compact-on" ? visibleMode : requested === "compact-off" ? "off" : requested === "floating" || requested === "widget" ? requested : undefined;
101
+ if (!mode) {
102
+ ctx.ui.notify("Usage: /works [compact-on|compact-off|herdr-on|herdr-off|floating|widget|minimize|maximize|open|open-session] or /works delegate T<number>", "info");
103
+ return;
104
+ }
105
+ if (mode !== "off")
106
+ visibleMode = mode;
107
+ panel?.setMode(mode);
108
+ ctx.ui.notify(`Works compact display: ${mode}`, "info");
75
109
  });
76
- pi.on("session_start", (_event, ctx) => {
77
- state.restore(ctx);
110
+ pi.on("session_start", async (event, ctx) => {
111
+ state.restore(ctx, event.reason === "fork");
78
112
  git.setCwd(ctx.cwd);
79
- if (ctx.mode === "tui")
113
+ try {
114
+ const settings = readPanelSettings(getSettings());
115
+ visibleMode = settings.mode;
116
+ panel?.setMode(settings.enabled ? visibleMode : "off");
117
+ }
118
+ catch (error) {
119
+ panel?.setMode("off");
120
+ ctx.ui.notify(error instanceof Error ? error.message : "Invalid task panel settings.", "error");
121
+ }
122
+ if (ctx.mode === "tui") {
80
123
  panel?.attach(ctx.ui, ctx.cwd, ctx.sessionManager.getSessionId());
81
- });
82
- pi.on("session_tree", (_event, ctx) => {
83
- state.restore(ctx);
124
+ await openHerdrTasksPaneOnStart(ctx);
125
+ }
84
126
  });
85
127
  pi.on("tool_result", (event) => {
86
128
  if (event.toolName === "write" || event.toolName === "edit" || event.toolName === "bash")
package/dist/markdown.js CHANGED
@@ -1,5 +1,7 @@
1
+ import { dependentOnLabel } from "./dependency.js";
1
2
  import { formatCompletion, taskCompletion, workCompletion } from "./progress.js";
2
3
  import { safeMultiline, safeSingleLine } from "./text.js";
4
+ import { finalThoughtsFor } from "./thoughts.js";
3
5
  import { formatTime, taskTime, workTime } from "./time.js";
4
6
  export function formatWorksMarkdown(works) {
5
7
  const lines = ["# Works and Todos", ""];
@@ -12,7 +14,7 @@ export function formatWorksMarkdown(works) {
12
14
  continue;
13
15
  }
14
16
  for (const todo of work.tasks) {
15
- lines.push(`#### ${todo.taskId} — ${escapeMarkdownInline(safeSingleLine(todo.taskName))}`, "", `**Status:** ${todo.status}`, ...(todo.status === "blocked" ? ["", "**Blocked reason:**", "", markdownBody(todo.blockedReason ?? "No reason recorded."), ""] : []), `**Completion:** ${formatCompletion(taskCompletion(todo))}`, `**Time:** ${formatTime(taskTime(todo))}${todo.workingSince === undefined ? "" : " (running)"}`, "", markdownBody(todo.taskInfo), "");
17
+ lines.push(`#### ${todo.taskId} — ${escapeMarkdownInline(safeSingleLine(todo.taskName))}`, "", `**Status:** ${todo.status}`, `**Completion:** ${formatCompletion(taskCompletion(todo))}`, `**Time:** ${formatTime(taskTime(todo))}${todo.workingSince === undefined ? "" : " (running)"}`, "", `**Final thoughts${dependentOnLabel(todo.dependentOn) === undefined ? "" : ` (Dependent on: ${dependentOnLabel(todo.dependentOn)})`}:**`, "", markdownBody(finalThoughtsFor(todo) ?? "No final thoughts recorded."), "");
16
18
  }
17
19
  }
18
20
  return `${lines.join("\n").trimEnd()}\n`;
@@ -1,4 +1,6 @@
1
- /** Launch Cursor without a shell, using the active session's working directory. */
2
- export declare function openRepository(cwd: string): Promise<void>;
1
+ /** Read the executable and fixed arguments from Pi's merged settings. */
2
+ export declare function readOpenCommand(settings: unknown): string[];
3
+ /** Launch the configured command without a shell, appending the target directory. */
4
+ export declare function openRepository(cwd: string, command?: string[]): Promise<void>;
3
5
  /** 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>;
6
+ export declare function openSession(cwd: string, sessionId: string, command?: string[]): Promise<void>;
@@ -3,12 +3,26 @@ import { glob, mkdir, stat } from "node:fs/promises";
3
3
  import { resolve } from "node:path";
4
4
  import { promisify } from "node:util";
5
5
  const execFileAsync = promisify(execFile);
6
- /** Launch Cursor without a shell, using the active session's working directory. */
7
- export async function openRepository(cwd) {
8
- await execFileAsync("cursor", ["."], { cwd, timeout: 10_000, maxBuffer: 64 * 1024, windowsHide: true });
6
+ /** Read the executable and fixed arguments from Pi's merged settings. */
7
+ export function readOpenCommand(settings) {
8
+ const config = settings !== null && typeof settings === "object" ? settings["pi-tasks"] : undefined;
9
+ const command = config !== null && typeof config === "object" ? config.openCommand : undefined;
10
+ if (command === undefined)
11
+ return ["cursor"];
12
+ if (!Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== "string" || part.includes("\0")) || !command[0].trim()) {
13
+ throw new Error("pi-tasks.openCommand must be a nonempty array of strings starting with an executable, for example [\"code\", \"--new-window\"].");
14
+ }
15
+ return [...command];
16
+ }
17
+ /** Launch the configured command without a shell, appending the target directory. */
18
+ export async function openRepository(cwd, command = ["cursor"]) {
19
+ const [executable, ...args] = command;
20
+ if (!executable)
21
+ throw new Error("An open command executable is required.");
22
+ await execFileAsync(executable, [...args, "."], { cwd, timeout: 10_000, maxBuffer: 64 * 1024, windowsHide: true });
9
23
  }
10
24
  /** Open the existing direct or nested agent artifact root, creating a new root only if needed. */
11
- export async function openSession(cwd, sessionId) {
25
+ export async function openSession(cwd, sessionId, command = ["cursor"]) {
12
26
  if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(sessionId))
13
27
  throw new Error("A valid Pi session ID is required to open session artifacts.");
14
28
  const repository = await execFileAsync("git", ["rev-parse", "--show-toplevel"], { cwd, timeout: 5_000, maxBuffer: 64 * 1024, windowsHide: true })
@@ -25,5 +39,5 @@ export async function openSession(cwd, sessionId) {
25
39
  throw new Error("Multiple artifact folders match this session; open the intended folder explicitly.");
26
40
  const directory = matches[0] ?? resolve(varRoot, sessionId);
27
41
  await mkdir(directory, { recursive: true });
28
- await openRepository(directory);
42
+ await openRepository(directory, command);
29
43
  }
@@ -0,0 +1,11 @@
1
+ export interface PanelSettings {
2
+ enabled: boolean;
3
+ mode: "floating" | "widget";
4
+ }
5
+ export interface HerdrPanelSettings {
6
+ enabled: boolean;
7
+ }
8
+ /** Startup default for the native Herdr Tasks pane; commands still override this running instance. */
9
+ export declare function readHerdrPanelSettings(settings: unknown): HerdrPanelSettings;
10
+ /** Defaults apply on startup/reload; slash commands only override this running instance. */
11
+ export declare function readPanelSettings(settings: unknown): PanelSettings;
@@ -0,0 +1,30 @@
1
+ /** Startup default for the native Herdr Tasks pane; commands still override this running instance. */
2
+ export function readHerdrPanelSettings(settings) {
3
+ const root = object(settings);
4
+ const config = object(root?.["pi-tasks"]);
5
+ const raw = config?.herdrPanel;
6
+ if (raw === undefined)
7
+ return { enabled: false };
8
+ const panel = object(raw);
9
+ if (!panel || (panel.enabled !== undefined && typeof panel.enabled !== "boolean")) {
10
+ throw new Error("pi-tasks.herdrPanel must contain an optional boolean enabled field.");
11
+ }
12
+ return { enabled: panel.enabled === true };
13
+ }
14
+ /** Defaults apply on startup/reload; slash commands only override this running instance. */
15
+ export function readPanelSettings(settings) {
16
+ const root = object(settings);
17
+ const config = object(root?.["pi-tasks"]);
18
+ const raw = config?.panel;
19
+ if (raw === undefined)
20
+ return { enabled: false, mode: "floating" };
21
+ const panel = object(raw);
22
+ if (!panel || (panel.enabled !== undefined && typeof panel.enabled !== "boolean")
23
+ || (panel.mode !== undefined && panel.mode !== "floating" && panel.mode !== "widget")) {
24
+ throw new Error("pi-tasks.panel must contain an optional boolean enabled and mode floating|widget.");
25
+ }
26
+ return { enabled: panel.enabled === true, mode: panel.mode === "widget" ? "widget" : "floating" };
27
+ }
28
+ function object(value) {
29
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
30
+ }
@@ -0,0 +1,23 @@
1
+ import type { Todo, Work } from "./types.js";
2
+ /** Shared on-disk contract for Pi and the read-only Herdr mod. */
3
+ export interface TaskSnapshot {
4
+ version: 1;
5
+ sessionId: string;
6
+ cwd: string;
7
+ terminalId?: string;
8
+ updatedAt: number;
9
+ nextWorkId: number;
10
+ nextTaskId: number;
11
+ works: Work[];
12
+ todos: Todo[];
13
+ agentRunning: boolean;
14
+ focusedTaskId?: string;
15
+ }
16
+ export declare function taskSnapshotPath(sessionId: string): string;
17
+ export declare function emptySnapshot(sessionId: string, cwd: string): TaskSnapshot;
18
+ /** Reject damaged files rather than silently replacing user task data. */
19
+ export declare function validateSnapshot(value: unknown, sessionId: string): asserts value is TaskSnapshot;
20
+ /** Only ENOENT is an uninitialized store; parse/identity/permission failures propagate. */
21
+ export declare function readSnapshot(path: string, sessionId: string): TaskSnapshot | undefined;
22
+ /** One synchronous Pi writer, atomic replacement; Herdr is a reader only. */
23
+ export declare function writeSnapshot(path: string, snapshot: TaskSnapshot): void;
@@ -0,0 +1,123 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
5
+ import { isTaskDependency } from "./dependency.js";
6
+ import { taskOwner } from "./ownership.js";
7
+ const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
8
+ const TERMINAL_ID = /^(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)?t[0-9a-z]+$/;
9
+ const MAX_SNAPSHOT_BYTES = 16 * 1024 * 1024;
10
+ const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
11
+ const integer = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
12
+ const text = (value) => typeof value === "string" && value.trim().length > 0;
13
+ const id = (value, prefix) => typeof value === "string" && new RegExp(`^${prefix}[1-9][0-9]*$`).test(value) && integer(Number(value.slice(1)));
14
+ export function taskSnapshotPath(sessionId) {
15
+ if (!SESSION_ID.test(sessionId))
16
+ throw new Error("A valid Pi session ID is required for task storage.");
17
+ return join(getAgentDir(), "tasks", `${sessionId}.json`);
18
+ }
19
+ export function emptySnapshot(sessionId, cwd) {
20
+ return { version: 1, sessionId, cwd, updatedAt: Date.now(), nextWorkId: 1, nextTaskId: 1, works: [], todos: [], agentRunning: false };
21
+ }
22
+ /** Reject damaged files rather than silently replacing user task data. */
23
+ export function validateSnapshot(value, sessionId) {
24
+ const invalid = () => { throw new Error("Invalid task snapshot. Restore the file from backup; it has not been overwritten."); };
25
+ if (!object(value) || value.version !== 1 || value.sessionId !== sessionId || !text(value.cwd)
26
+ || !integer(value.updatedAt) || !integer(value.nextWorkId) || value.nextWorkId < 1
27
+ || !integer(value.nextTaskId) || value.nextTaskId < 1 || typeof value.agentRunning !== "boolean"
28
+ || !Array.isArray(value.works) || value.works.length > 100 || !Array.isArray(value.todos) || value.todos.length > 500
29
+ || (value.terminalId !== undefined && (typeof value.terminalId !== "string" || !TERMINAL_ID.test(value.terminalId))))
30
+ return invalid();
31
+ const works = new Set();
32
+ for (const work of value.works) {
33
+ if (!object(work) || !id(work.workId, "W") || works.has(work.workId) || !text(work.workName) || !text(work.workInfo)
34
+ || !integer(work.createdAt) || !integer(work.updatedAt) || Number(work.workId.slice(1)) >= value.nextWorkId)
35
+ return invalid();
36
+ works.add(work.workId);
37
+ }
38
+ const todos = new Set();
39
+ let running = 0;
40
+ for (const todo of value.todos) {
41
+ if (!object(todo) || !id(todo.taskId, "T") || todos.has(todo.taskId) || !text(todo.workId) || !works.has(todo.workId)
42
+ || !text(todo.taskName) || !text(todo.taskInfo) || !integer(todo.createdAt) || !integer(todo.updatedAt)
43
+ || (todo.finalThoughts !== undefined && !text(todo.finalThoughts))
44
+ || !["active", "blocked", "completed", "cancelled"].includes(String(todo.status))
45
+ || Number(todo.taskId.slice(1)) >= value.nextTaskId
46
+ || (todo.blockedReason !== undefined && todo.blockedReason !== null && !text(todo.blockedReason))
47
+ || (todo.status !== "blocked" && todo.blockedReason != null)
48
+ || (todo.dependentOn !== undefined && (todo.status !== "blocked" || !isTaskDependency(todo.dependentOn)))
49
+ || (todo.completionPercent != null && (!integer(todo.completionPercent) || todo.completionPercent > 100))
50
+ || (todo.status === "completed" && todo.completionPercent !== 100)
51
+ || (todo.status !== "completed" && todo.completionPercent === 100)
52
+ || (todo.elapsedMs != null && !integer(todo.elapsedMs)))
53
+ return invalid();
54
+ if (todo.delegatedTimes !== undefined) {
55
+ if (!Array.isArray(todo.delegatedTimes))
56
+ return invalid();
57
+ const reports = new Set();
58
+ for (const source of todo.delegatedTimes) {
59
+ if (!object(source) || !text(source.reportPath) || reports.has(source.reportPath)
60
+ || (source.elapsedMs !== null && !integer(source.elapsedMs))
61
+ || (source.workerSessionId !== undefined && (typeof source.workerSessionId !== "string" || !SESSION_ID.test(source.workerSessionId))))
62
+ return invalid();
63
+ reports.add(source.reportPath);
64
+ }
65
+ }
66
+ if (todo.workingSince !== undefined) {
67
+ if (!integer(todo.workingSince) || !value.agentRunning || value.focusedTaskId !== todo.taskId || todo.status !== "active" || taskOwner(todo.taskInfo) !== "self")
68
+ return invalid();
69
+ running += 1;
70
+ }
71
+ todos.add(todo.taskId);
72
+ }
73
+ if (running > 1 || (value.focusedTaskId !== undefined && (!id(value.focusedTaskId, "T") || !todos.has(value.focusedTaskId))))
74
+ return invalid();
75
+ if (value.focusedTaskId !== undefined) {
76
+ const focused = value.todos.find((todo) => todo.taskId === value.focusedTaskId);
77
+ if (focused?.status !== "active" || taskOwner(focused.taskInfo) !== "self")
78
+ return invalid();
79
+ }
80
+ }
81
+ /** Only ENOENT is an uninitialized store; parse/identity/permission failures propagate. */
82
+ export function readSnapshot(path, sessionId) {
83
+ let contents;
84
+ try {
85
+ const stat = lstatSync(path);
86
+ if (!stat.isFile() || stat.size > MAX_SNAPSHOT_BYTES)
87
+ throw new Error("Task snapshot must be a regular file no larger than 16 MiB.");
88
+ contents = readFileSync(path, "utf8");
89
+ }
90
+ catch (error) {
91
+ if (error.code === "ENOENT")
92
+ return undefined;
93
+ throw error;
94
+ }
95
+ let snapshot;
96
+ try {
97
+ snapshot = JSON.parse(contents);
98
+ }
99
+ catch {
100
+ throw new Error("Task snapshot is not valid JSON. It has not been overwritten.");
101
+ }
102
+ validateSnapshot(snapshot, sessionId);
103
+ return snapshot;
104
+ }
105
+ /** One synchronous Pi writer, atomic replacement; Herdr is a reader only. */
106
+ export function writeSnapshot(path, snapshot) {
107
+ validateSnapshot(snapshot, snapshot.sessionId);
108
+ const data = `${JSON.stringify(snapshot, null, 2)}\n`;
109
+ if (Buffer.byteLength(data) > MAX_SNAPSHOT_BYTES)
110
+ throw new Error("Task snapshot exceeds 16 MiB; no changes were saved.");
111
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
112
+ const temporary = `${path}.${randomUUID()}.tmp`;
113
+ try {
114
+ writeFileSync(temporary, data, { flag: "wx", mode: 0o600 });
115
+ renameSync(temporary, path);
116
+ }
117
+ finally {
118
+ try {
119
+ unlinkSync(temporary);
120
+ }
121
+ catch { /* Preserve the original write error if cleanup also fails. */ }
122
+ }
123
+ }