@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
package/README.md CHANGED
@@ -11,11 +11,11 @@ It adds:
11
11
  - a compact floating top-right panel with work and todo names, completion percentages, and measured active time
12
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
13
13
 
14
- 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
+ Works and todos belong only to the Pi session ID. Their authoritative JSON file is `<agent-directory>/tasks/<sessionId>.json` (normally `~/.pi/agent/tasks/`). Navigating the conversation tree never rolls tasks back. Resume/reload retains the same records; a fork with a new session ID starts empty. Existing sessions import their selected legacy task view once when no JSON store exists; original history is left untouched. `/ask` and `/btw` conversations do not update works, todos, loops, or monitors.
15
15
 
16
16
  The coordination model is intentionally small: a work is a collection of tasks with shared context and no status, a todo is one concrete step with its own status, 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`.
17
17
 
18
- 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
+ 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 the hidden `taskInfo`; the only visible task text is `finalThoughts`. 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.
19
19
 
20
20
  ## Install
21
21
 
@@ -31,19 +31,38 @@ The extension guides Pi to manage work automatically for normal requests that st
31
31
 
32
32
  ```text
33
33
  WorkCreate workName="Add task tracking" workInfo="Detailed goal, scope, constraints, and expected outcome"
34
- TodoCreate workId="W1" taskName="Implement state" taskInfo="Detailed task context and expected result" status="active"
34
+ TodoCreate workId="W1" taskName="Implement state" taskInfo="owner: self — records and state changes." finalThoughts="State schema and storage are being implemented." status="active"
35
35
  TodoUpdate taskId="T1" working=true
36
- TodoUpdate taskId="T1" completionPercent=40 taskInfo="The state changes are implemented; rendering and verification remain."
37
- TodoUpdate taskId="T1" status="completed" taskInfo="Implementation is complete; typecheck and build passed."
36
+ TodoUpdate taskId="T1" completionPercent=40 finalThoughts="State changes are implemented; rendering and verification remain."
37
+ TodoUpdate taskId="T1" status="completed" finalThoughts="State, rendering, typecheck, and build passed. Live native behavior is unverified."
38
+ TodoUpdate taskId="T2" status="blocked" dependentOn="another-agent" blockedReason="Waiting for review. Resume when it returns."
38
39
  WorkUpdate workId="W1" workInfo="Task tracking is implemented; state and UI checks passed."
39
40
  ```
40
41
 
41
- Run `/works` to inspect full `workInfo` and `taskInfo` in an interactive overlay.
42
+ `taskInfo` is hidden coordination metadata: keep the `owner:` declaration, canonical artifact paths, parent IDs, and necessary execution constraints there. It is never shown in the task panel. `finalThoughts` is the only user-visible task text. A blocked task also stores `dependentOn="user-decision"` or `dependentOn="another-agent"`, which task details show beside Final thoughts. Use final thoughts for a short significant active update, a completed result with verification and remaining limits, or rely on `blockedReason` for the authoritative blocked dependency. Do not repeat the goal, ownership rationale, or history there; see [Final thoughts](docs/USAGE_GUIDE.md#final-thoughts).
42
43
 
43
- Works are collections with no status. Tasks use four statuses: `active` (the default), `blocked`, `completed`, and `cancelled`. Use `blocked` as soon as the next step must wait for agent output, review, an external response, user input, permission, or another obstacle. Supply `blockedReason` when creating a blocked task or entering blocked status, explaining the dependency and resume condition; retain progress. The reason is preserved during other blocked edits and cleared when leaving blocked. Older records without a reason remain readable. Parent delegated tasks stay blocked while awaiting worker output; the worker's own local tasks may be active. AgentCreate automatically blocks the parent task after successful creation, retaining its progress. For manual delegation, mark the parent task blocked explicitly. Return blocked tasks to active when the dependency resolves and work resumes. Status does not itself schedule a wake. Legacy saved task statuses `planned` and `pending` restore as active; old Work statuses are ignored. Work tools no longer accept status or a status filter. To cancel an entire Work, cancel its remaining tasks; WorkDelete still deletes the collection and its tasks.
44
+ Run `/works` to inspect full `workInfo` and each task's Final thoughts in an interactive overlay. Hidden task metadata stays available to tools for resumption but is not rendered. Display controls now live under this one command; `/works-panel` has been removed.
45
+
46
+ | Command | Display |
47
+ | --- | --- |
48
+ | `/works` | Open the on-demand overlay dashboard |
49
+ | `/works compact-on` / `/works compact-off` | Show/hide the compact Pi display |
50
+ | `/works herdr-on` / `/works herdr-off` | Open/focus or close only this session’s native Tasks pane |
51
+
52
+ These displays are independent. Hiding either display never stops tracking. Auxiliary actions such as `/works open`, `/works open-session`, and `/works delegate T<number>` remain available.
53
+
54
+ Works are collections with no status. Tasks use four statuses: `active` (the default), `blocked`, `completed`, and `cancelled`. Use `blocked` only when the next step waits for a user decision (a response, approval, or permission) or for another agent's output or review. Supply both `blockedReason` and `dependentOn` when creating a blocked task or entering blocked status: `dependentOn` is exactly `"user-decision"` or `"another-agent"`. Explain the dependency and what will unblock it; retain progress. The blocked reason is that task's visible Final thoughts, so do not duplicate it. Both fields are preserved during other blocked edits and cleared when leaving blocked. Older blocked records without either field remain readable without an invented dependency. Do not mark a task blocked for an external service, tool failure, or other obstacle that fits neither category; keep it active, preserve safety, and report the unavailable dependency truthfully. A status change clears an unsupplied thought, so an old active note cannot hide a new blocker. Completed tasks should state the short verified result and remaining limits in `finalThoughts`; historical completed records without one remain honestly empty rather than showing old narrative. Parent delegated tasks stay blocked while awaiting worker output; the worker's own local tasks may be active. AgentCreate automatically blocks the parent task after successful creation, retaining its progress. For manual delegation, mark the parent task blocked explicitly. Return blocked tasks to active when the dependency resolves and work resumes. Status does not itself schedule a wake. Legacy saved task statuses `planned` and `pending` restore as active; old Work statuses are ignored. Work tools no longer accept status or a status filter. To cancel an entire Work, cancel its remaining tasks; WorkDelete still deletes the collection and its tasks.
44
55
 
45
56
  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.
46
57
 
58
+ ### Native Herdr view
59
+
60
+ Run `/works herdr-on` from the intended local Pi session to open its compact native Work → Task tree. Task names toggle inline Final thoughts; `taskInfo` is never shown. A blocked task shows its authoritative blocked reason and, when stored, `Dependent on: User decision` or `Dependent on: Another agent` beside the Final thoughts label; a task with no thought shows an honest empty label. Legacy blocked records without a dependency show no invented label. Linked task-only `Agent ↗` buttons open existing delegates: a pane owner gets normal focus, while a pane-less Core child opens its own screen overlay over the current tab without navigating to its parent. The pane header carries a compact status dropdown (All statuses, Active, Blocked, Completed, Cancelled) that narrows the tree to matching tasks while Work progress and effort stay totals for every task; its selection is per-pane view state and is never written to records or settings. Numeric progress/time stay on the right; the native header × closes only the view. No extra session/status bar or Read-only footer.
61
+
62
+ Set `pi-tasks.herdrPanel.enabled` to `true` to open or focus the pane automatically at each session start in a local Herdr Core TUI session. The package fallback is off when the key is omitted; a malformed value reports a diagnostic and stays off. Automatic startup also replaces this terminal’s Tasks pane from an earlier session and keeps setup failures silent. `/works herdr-off` still closes the running session’s pane, and commands never rewrite settings.
63
+
64
+ First setup installs missing content assets and creates/selects personal copies of the current pane header/layout for the persistent native-header close; originals and customized files are preserved. See [native setup, compatibility and rollback](herdr/pi-tasks/README.md). `/works compact-off` hides only the compact TUI, not tracking or the native view.
65
+
47
66
  ### Active task time
48
67
 
49
68
  The panel and `/works` reserve **Done** and **Time** columns. Select the task you are actually working on with `TodoUpdate taskId="T1" working=true`; it must be active and have `owner: self` in its details. Selecting another task pauses the previous one. Use `working=false` to pause without changing status. Select again at the beginning of each fresh run; merely creating or marking a task active never starts its timer.
@@ -52,13 +71,15 @@ The extension uses `Date.now()` to add working intervals, including thinking and
52
71
 
53
72
  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.
54
73
 
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.
74
+ 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 the hidden `taskInfo`; preserve it on updates. Missing or conflicting decisions show `[unassigned]`, without rewriting stored names or old records. Final thoughts never carry ownership, links, or paths. Inside Herdr, `AgentCreate` automatically links its task to an underlined, clickable `[delegate]` badge; Open actions are also underlined. See [delegate terminal links](docs/USAGE_GUIDE.md#delegate-terminal-links) for linking and keyboard access.
56
75
 
57
- 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`.
76
+ The compact TUI panel is off by default. Enable it with `/works compact-on` or `pi-tasks.panel.enabled:true`; its default visible layout is floating at the top-right. The compact header no longer displays the session ID. An underlined Open session action beside Copy opens this agent's artifact folder using the configured command, including existing nested delegated paths; if none exists, it creates `var/<sessionId>/`. The existing Open still opens the repository. Use `/works 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 defaults to `cursor .`; configure `pi-tasks.openCommand` to use another tool (see [configuration](docs/USAGE_GUIDE.md#configure-open-and-open-session)). Open `/works` to inspect every row or copy from the keyboard. Use `/works minimize`, `/works maximize`, or `/works open` when mouse input is unavailable. In `/works`, press `o` to run the configured command. Switch layouts with `/works floating` or `/works widget`; `/works compact-off` hides the compact TUI and `/works compact-on` restores the last visible layout. Set `pi-tasks.panel.enabled` to `false` for a hidden default; `panel.mode` selects `floating` (default) or `widget`. The separate native Herdr pane follows `pi-tasks.herdrPanel.enabled` (default `false`). Commands override only the running instance, not settings. `/works` remains available on demand. See [visibility and Herdr pane setup](docs/USAGE_GUIDE.md#panel-visibility-and-herdr-tasks-pane).
58
77
 
59
- ## Task-owned agents
78
+ ## Agents through pi-herdr
60
79
 
61
- `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).
80
+ The separate [pi-herdr](https://github.com/abhishek944/pi-herdr) package owns `AgentCreate`, `AgentResume`, `AgentList`, `AgentStatus`, `AgentOutput`, `AgentSend`, `AgentInterrupt`, `AgentClose`, and `AgentFocus`. This package does not register Agent tools. They wrap hc/Core operations using returned terminalId addresses. Creation derives and creates the canonical delegated-task directory, verifies the real Core parent and native Pi readiness, then registers pi-loop-monitor. A post-launch failure returns structured partial handles; AgentResume finishes that same worker after validating the timing descriptor and Core ownership. Workers are Core-only by default; `present: true` also adopts the worker into a dedicated visible task-named Herdr app tab and verifies that mapping. Confirm its subscription ready receipt before AgentSend. Focus uses herdr-app and reports when no app is available; a pane-less child is presented through the existing `terminal.peek` overlay instead of an `agent.focus` no-op. Process lifecycle uses hc. No HERDR_ENV prerequisite, legacy TUI fallback, registry or recovery runtime. Creation/resume/closure require modern Pi nested calls and updated pi-loop-monitor. Completing a delegate task whose worker record is still linked returns a one-shot cleanup advisory after pi-herdr verifies session/task ownership; it never closes or interrupts the worker. See [agent tools](docs/USAGE_GUIDE.md#agent-tools).
81
+
82
+ pi-herdr 0.1.0 requires this working source's version-1 delegation bridge; published pi-tasks 0.15.0 does not provide it. Install the compatible local pi-tasks source alongside pi-herdr and reload/restart Pi. Do not load the legacy npm source in parallel. pi-tasks retains records, timing, delegate metadata and display helpers; pi-herdr discovers those operations through Pi's event bus without importing pi-tasks internals.
62
83
 
63
84
  ## Optional auto-continuation
64
85
 
@@ -72,12 +93,38 @@ On Pi 1.2.0 or newer, enable unfinished-work continuation in your global or trus
72
93
  }
73
94
  ```
74
95
 
75
- 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 task across all Works on the current session branch is active. Empty Works and blocked, completed, or cancelled tasks do not trigger continuation; legacy planned/pending task statuses restore as active. 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.
96
+ It defaults off. Auto-continuation requests at most 50 extra runs per fresh accepted main user run, even when `maxContinuations` is omitted. Add a positive integer such as `"maxContinuations": 10` to lower the cap; values above 50 are clamped to 50 with one visible warning. After a normal user-requested run succeeds or fails, Pi continues while any task across all Works in the current Pi session is active. Empty Works and blocked, completed, or cancelled tasks do not trigger continuation; legacy planned/pending task statuses restore as active. An active task that launched a command `MonitorCreate` with an `onDone` wake is excluded from continuation until that wake is delivered or dismissed, including while its notification is queued for idle. The exact task is captured at launch. Core `hcTerminalId` subscriptions and unrelated tasks still continue. No task status is changed for that wait. The final requested continuation is labeled final, and the next unfinished boundary warns with the count and hands control back without changing records. Escape/abort stops the flow; only a fresh accepted main interactive or RPC run rearms it and resets the count. Extension wakes, session-tree changes, and queued steering/follow-up input do not reset it. The limit counts requested continuations per fresh main user run, not dollars or tool calls. Reload after editing settings.
76
97
 
77
98
  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.
78
99
 
79
100
  See [the usage guide](docs/USAGE_GUIDE.md) and [reference](docs/REFERENCE.md).
80
101
 
102
+ ## Native Durable entrypoint
103
+
104
+ For hosts running on `@earendil-works/pi-durable` 1.1.0, this package also ships a
105
+ settings-only native extension with no desktop dependency:
106
+
107
+ ```ts
108
+ import { createTasksDurableExtension } from "@abhishek944/pi-tasks/durable";
109
+ import { createRegistry } from "@earendil-works/pi-durable";
110
+
111
+ const registry = createRegistry();
112
+ registry.install(createTasksDurableExtension({ maxWorks: 100, maxTodos: 500 }));
113
+ // The host opens its own Harness with models/storage/env and selects `tasks`.
114
+ ```
115
+
116
+ Settings are plain JSON copied and frozen at factory creation. Records live in one
117
+ conversation-scoped document (`pi-tasks.state`, latest history, initial fork), so each
118
+ conversation has isolated tracking and a fork starts empty. The eight tools are real
119
+ document transactions with the same validation as the desktop extension: `WorkCreate`,
120
+ `WorkList`, `WorkUpdate`, `WorkDelete`, `TodoCreate`, `TodoList`, `TodoUpdate`, and
121
+ `TodoDelete`, including completion rules, hidden `taskInfo` metadata, visible `finalThoughts`, `blockedReason`, and `dependentOn` handling. Effort timing is
122
+ unsupported natively: the native schema has no `working` field and reports no times,
123
+ rather than fabricated zeros. Desktop timing is unchanged. Desktop-only surfaces have no
124
+ native equivalent and are documented in `src/durable.ts` rather than stubbed: Herdr agent
125
+ tools, `TaskTimeExport`/`Import` file handoffs, auto-continuation, the `/works` command,
126
+ and the TUI panel.
127
+
81
128
  ## Development
82
129
 
83
130
  ```bash
@@ -0,0 +1,4 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { TaskState } from "../state.js";
3
+ /** Task-owned state changes used by pi-herdr's lifecycle tools. */
4
+ export declare function registerDelegationBridge(pi: ExtensionAPI, state: TaskState): void;
@@ -0,0 +1,59 @@
1
+ import { createTimingReport, inspectTimingReport } from "../delegated-time.js";
2
+ import { taskOwner } from "../ownership.js";
3
+ import { areTrackingToolsActive } from "../tracking.js";
4
+ import { TERMINAL_ID } from "./herdr.js";
5
+ import { delegateLink, withTerminalLink } from "./links.js";
6
+ /** Task-owned state changes used by pi-herdr's lifecycle tools. */
7
+ export function registerDelegationBridge(pi, state) {
8
+ let current;
9
+ pi.on("session_start", (_event, ctx) => { current = { sessionId: ctx.sessionManager.getSessionId() }; });
10
+ pi.on("session_shutdown", () => { current = undefined; });
11
+ pi.events.on("pi-tasks:delegation-api", (data) => {
12
+ const request = data;
13
+ if (request?.version !== 1 || typeof request.respond !== "function" || !current)
14
+ return;
15
+ const binding = current;
16
+ const requireCurrent = (ctx) => {
17
+ if (current !== binding || ctx.sessionManager.getSessionId() !== binding.sessionId)
18
+ throw new Error("The pi-tasks delegation bridge belongs to a replaced session. Discover it again from the current session.");
19
+ if (!areTrackingToolsActive(pi))
20
+ throw new Error("Use agent tools in tracked main-conversation work, not /ask or /btw.");
21
+ };
22
+ const assignment = (ctx, input) => {
23
+ requireCurrent(ctx);
24
+ const todo = state.getTodo(input.taskId);
25
+ if (!todo || todo.workId !== input.workId || !state.listWorks({ workId: input.workId }).length || taskOwner(todo.taskInfo) !== "delegate")
26
+ throw new Error("Use an existing task in this work with owner: delegate.");
27
+ return todo;
28
+ };
29
+ request.respond({
30
+ async prepare(ctx, input) {
31
+ assignment(ctx, input);
32
+ const reportPath = await createTimingReport(ctx, input.taskDir, input.workId, input.taskId);
33
+ assignment(ctx, input);
34
+ return { reportPath };
35
+ },
36
+ async inspect(ctx, input) {
37
+ assignment(ctx, input);
38
+ const inspected = await inspectTimingReport(ctx, input.taskDir, input.workId, input.taskId, input.reportPath);
39
+ assignment(ctx, input);
40
+ return inspected;
41
+ },
42
+ attach(ctx, input) {
43
+ const todo = assignment(ctx, input);
44
+ if (!TERMINAL_ID.test(input.terminalId))
45
+ throw new Error("Use the terminalId returned by hc.");
46
+ state.setDelegatedTime(input.taskId, { reportPath: input.reportPath, elapsedMs: null });
47
+ state.updateTodo(input.taskId, { status: "blocked", blockedReason: "Waiting for the delegated agent. Resume when its output is available for inspection and verification.", dependentOn: "another-agent", taskInfo: withTerminalLink(todo.taskInfo, input.terminalId, input.monitorId) });
48
+ },
49
+ detach(ctx, input) {
50
+ requireCurrent(ctx);
51
+ if (!TERMINAL_ID.test(input.terminalId))
52
+ throw new Error("Use the terminalId returned by hc.");
53
+ for (const todo of state.listTodos())
54
+ if (delegateLink(todo.taskInfo)?.terminalId === input.terminalId)
55
+ state.updateTodo(todo.taskId, { taskInfo: withTerminalLink(todo.taskInfo) });
56
+ },
57
+ });
58
+ });
59
+ }
@@ -1,4 +1,11 @@
1
- export declare const PANE_ID: RegExp;
1
+ export declare const TERMINAL_ID: RegExp;
2
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>>;
3
+ export declare function cliText(command: "hc" | "herdr-app", args: string[], cwd: string, signal?: AbortSignal, timeout?: number): Promise<string>;
4
+ export declare function hc(args: string[], cwd: string, signal?: AbortSignal, timeout?: number): Promise<Record<string, unknown>>;
5
+ export declare function app(args: string[], cwd: string, signal?: AbortSignal): Promise<Record<string, unknown>>;
6
+ export declare function terminalTab(inventory: Record<string, unknown>, terminalId: string): {
7
+ spaceId: string;
8
+ tabId: string;
9
+ name: string;
10
+ terminalCount: number;
11
+ } | undefined;
@@ -1,23 +1,50 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  const execFileAsync = promisify(execFile);
4
- export const PANE_ID = /^w[A-Za-z0-9]+:p[A-Za-z0-9]+$/;
4
+ export const TERMINAL_ID = /^(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)?t[0-9a-z]+$/;
5
5
  export function object(value) {
6
6
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
7
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 });
8
+ export async function cliText(command, args, cwd, signal, timeout = 15_000) {
9
+ // App commands target the normal desktop instance, not an inherited test fixture.
10
+ const env = command === "herdr-app" ? { ...process.env } : undefined;
11
+ if (env)
12
+ delete env.HERDR_APP_HOME;
13
+ const { stdout } = await execFileAsync(command, args, { cwd, env, signal, timeout, maxBuffer: 1024 * 1024, windowsHide: true });
12
14
  return stdout;
13
15
  }
14
- export async function herdr(args, cwd, signal, timeout) {
15
- const response = object(JSON.parse(await herdrText(args, cwd, signal, timeout)));
16
+ export async function hc(args, cwd, signal, timeout) {
17
+ const [command, ...rest] = args;
18
+ if (!command)
19
+ throw new Error("An hc command is required.");
20
+ return cliJson("hc", [command, "--json", ...rest], cwd, signal, timeout);
21
+ }
22
+ export async function app(args, cwd, signal) {
23
+ return cliJson("herdr-app", args, cwd, signal);
24
+ }
25
+ async function cliJson(command, args, cwd, signal, timeout) {
26
+ const response = object(JSON.parse(await cliText(command, args, cwd, signal, timeout)));
27
+ if (typeof response?.error === "string")
28
+ throw new Error(response.error);
16
29
  const error = object(response?.error);
17
30
  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;
31
+ throw new Error(typeof error.message === "string" ? error.message : `${command} command failed.`);
32
+ if (!response)
33
+ throw new Error(`${command} returned no object.`);
34
+ return response;
35
+ }
36
+ export function terminalTab(inventory, terminalId) {
37
+ for (const rawSpace of Array.isArray(inventory.spaces) ? inventory.spaces : []) {
38
+ const space = object(rawSpace);
39
+ if (typeof space?.id !== "string")
40
+ continue;
41
+ for (const rawTab of Array.isArray(space.tabs) ? space.tabs : []) {
42
+ const tab = object(rawTab);
43
+ const terminals = Array.isArray(tab?.terminals) ? tab.terminals : [];
44
+ if (typeof tab?.id === "string" && terminals.some((value) => object(value)?.terminal === terminalId)) {
45
+ return { spaceId: space.id, tabId: tab.id, name: typeof tab.name === "string" ? tab.name : "", terminalCount: terminals.length };
46
+ }
47
+ }
48
+ }
49
+ return undefined;
23
50
  }
@@ -1,7 +1,7 @@
1
1
  export interface DelegateLink {
2
- paneId: string;
2
+ terminalId: string;
3
3
  }
4
4
  export declare function delegateLink(taskInfo: string): DelegateLink | undefined;
5
- export declare function focusPane(paneId: string, cwd: string, signal?: AbortSignal): Promise<void>;
5
+ export declare function focusTerminal(terminalId: string, cwd: string, signal?: AbortSignal): Promise<void>;
6
6
  export declare function preservePaneLink(current: string, next: string): string;
7
- export declare function withPaneLink(taskInfo: string, paneId?: string, monitorId?: string): string;
7
+ export declare function withTerminalLink(taskInfo: string, terminalId?: string, monitorId?: string): string;
@@ -1,30 +1,53 @@
1
1
  import { taskOwner } from "../ownership.js";
2
- import { herdr, object, PANE_ID } from "./herdr.js";
2
+ import { app, hc, object, TERMINAL_ID } from "./herdr.js";
3
3
  export function delegateLink(taskInfo) {
4
- if (process.env.HERDR_ENV !== "1" || taskOwner(taskInfo) !== "delegate")
4
+ if (taskOwner(taskInfo) !== "delegate")
5
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)
6
+ const terminals = [...taskInfo.matchAll(/^[ \t]*hc-terminal:[ \t]*([^\r\n]*)$/gim)].map((match) => match[1].trim());
7
+ if (terminals.length === 0 || terminals.some((terminal) => !TERMINAL_ID.test(terminal)) || new Set(terminals).size !== 1)
8
8
  return undefined;
9
- return { paneId: panes[0] };
9
+ return { terminalId: terminals[0] };
10
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);
11
+ export async function focusTerminal(terminalId, cwd, signal) {
12
+ if (!TERMINAL_ID.test(terminalId))
13
+ throw new Error("Use the terminalId returned by hc.");
14
+ const presentation = await presentationRoute(terminalId, cwd, signal);
15
+ await app(["do", presentation === "peek" ? "terminal.peek" : "agent.focus", JSON.stringify({ terminal: terminalId })], cwd, signal);
16
+ }
17
+ /** The same small routing contract as pi-herdr's AgentFocus and the native panel. */
18
+ async function presentationRoute(terminalId, cwd, signal) {
19
+ if (terminalId.includes("/"))
20
+ return "focus";
21
+ const inventory = await app(["ls"], cwd, signal);
22
+ let listedChild = false;
23
+ for (const rawSpace of Array.isArray(inventory.spaces) ? inventory.spaces : []) {
24
+ const space = object(rawSpace);
25
+ for (const rawTab of Array.isArray(space?.tabs) ? space.tabs : []) {
26
+ const tab = object(rawTab);
27
+ for (const rawTerminal of Array.isArray(tab?.terminals) ? tab.terminals : []) {
28
+ const terminal = object(rawTerminal);
29
+ if (terminal?.terminal === terminalId)
30
+ return "focus";
31
+ if (Array.isArray(terminal?.sub_agents) && terminal.sub_agents.includes(terminalId))
32
+ listedChild = true;
33
+ }
34
+ }
35
+ }
36
+ if (listedChild)
37
+ return "peek";
38
+ const record = await hc(["get", terminalId], cwd, signal);
39
+ if (typeof record.parent === "string" && record.parent.trim())
40
+ return "peek";
41
+ throw new Error("Herdr is not showing this agent. Open its space, then retry.");
20
42
  }
21
43
  export function preservePaneLink(current, next) {
22
- if (taskOwner(current) !== "delegate" || taskOwner(next) !== "delegate" || /^[ \t]*herdr-(?:pane|monitor):/im.test(next))
44
+ if (taskOwner(current) !== "delegate" || taskOwner(next) !== "delegate" || /^[ \t]*(?:hc-(?:terminal|monitor)|herdr-(?:pane|monitor)):/im.test(next))
23
45
  return next;
24
- const metadata = current.split(/\r?\n/).filter((line) => /^[ \t]*herdr-(?:pane|monitor):/i.test(line));
46
+ // Preserve historical links as text, but never interpret a TUI pane as a Core terminal.
47
+ const metadata = current.split(/\r?\n/).filter((line) => /^[ \t]*(?:hc-(?:terminal|monitor)|herdr-(?:pane|monitor)):/i.test(line));
25
48
  return metadata.length ? `${next.trim()}\n${metadata.join("\n")}` : next;
26
49
  }
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;
50
+ export function withTerminalLink(taskInfo, terminalId, monitorId) {
51
+ const text = taskInfo.split(/\r?\n/).filter((line) => !/^[ \t]*(?:hc-(?:terminal|monitor)|herdr-(?:pane|monitor)):/i.test(line)).join("\n").trim();
52
+ return terminalId ? `${text}\nhc-terminal: ${terminalId}\nhc-monitor: ${monitorId}` : text;
30
53
  }