@abhishek944/pi-tasks 0.15.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -14
- package/dist/agents/delegation.d.ts +4 -0
- package/dist/agents/delegation.js +130 -0
- package/dist/agents/herdr.d.ts +10 -3
- package/dist/agents/herdr.js +39 -12
- package/dist/agents/links.d.ts +3 -3
- package/dist/agents/links.js +42 -19
- package/dist/auto-continue.js +409 -33
- package/dist/blocked.d.ts +29 -0
- package/dist/blocked.js +100 -0
- package/dist/command.d.ts +2 -2
- package/dist/command.js +7 -3
- package/dist/delegated-time.d.ts +12 -1
- package/dist/delegated-time.js +96 -15
- package/dist/dependency.d.ts +7 -0
- package/dist/dependency.js +13 -0
- package/dist/durable.d.ts +42 -0
- package/dist/durable.js +577 -0
- package/dist/herdr-header.d.ts +3 -0
- package/dist/herdr-header.js +100 -0
- package/dist/herdr-panel.d.ts +15 -0
- package/dist/herdr-panel.js +219 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +125 -56
- package/dist/markdown.js +3 -1
- package/dist/panel-settings.d.ts +11 -0
- package/dist/panel-settings.js +30 -0
- package/dist/progress.js +1 -1
- package/dist/snapshot.d.ts +23 -0
- package/dist/snapshot.js +166 -0
- package/dist/state.d.ts +43 -18
- package/dist/state.js +581 -289
- package/dist/thoughts.d.ts +11 -0
- package/dist/thoughts.js +14 -0
- package/dist/timing.js +9 -2
- package/dist/tools.js +295 -34
- package/dist/tracking.js +25 -13
- package/dist/transition.d.ts +9 -0
- package/dist/transition.js +26 -0
- package/dist/types.d.ts +76 -3
- package/dist/ui/panel.js +38 -19
- package/dist/ui/task-view.d.ts +7 -0
- package/dist/ui/task-view.js +10 -0
- package/dist/ui/works-dashboard.js +37 -19
- package/docs/REFERENCE.md +85 -31
- package/docs/USAGE_GUIDE.md +129 -55
- package/herdr/pi-tasks/README.md +46 -0
- package/herdr/pi-tasks/header.js +212 -0
- package/herdr/pi-tasks/main.js +488 -0
- package/herdr/pi-tasks/mod.json +3 -0
- package/herdr/pi-tasks/spinner.svg +1 -0
- package/package.json +26 -1
- package/dist/agents/tools.d.ts +0 -3
- 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
|
|
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,34 +31,55 @@ 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="
|
|
35
|
-
TodoUpdate taskId="T1"
|
|
36
|
-
TodoUpdate taskId="T1"
|
|
37
|
-
TodoUpdate taskId="T1" status="
|
|
34
|
+
TodoCreate workId="W1" taskName="Implement state" taskInfo="owner: self — records and state changes." goal={ goal: "State schema and storage are implemented", criteria: ["Schema and storage are implemented", "Typecheck and build pass"] }
|
|
35
|
+
TodoUpdate taskId="T1" completionPercent=40 finalThoughts="State changes are implemented; rendering and verification remain."
|
|
36
|
+
TodoUpdate taskId="T1" status="completed" finalThoughts="State, rendering, typecheck, and build passed. Live native behavior is unverified."
|
|
37
|
+
TodoUpdate taskId="T1" status="closed"
|
|
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
|
-
|
|
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 together with the blocked age when the record stores one. A user-decision blocker can store the pi-decisions `decisionQuestionId` that it waits on. 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
|
-
|
|
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. Every task starts `active` with its own visible goal and acceptance criteria; no separate goal approval is required to work, delegate, complete, or close it. `TaskGoalUpdate` records a material goal change. Verified work is `completed` at 100% and can be closed without a closeout approval step; closing is an agent action after verified completion, and a delegated worker's `/close` is requested and verified with `TaskWorkerClose` or `TaskCloseoutFinalize`. Tasks use `active`, `blocked`, `completed`, `closed`, and `cancelled`. Cancelling a task or reopening a closed or cancelled task requires an explicit human decision through `TaskLifecycleDecision`; `closed` and `cancelled` records stay stored. A cancellation requested from an active task is recorded as blocked on `user-decision` with its `decisionQuestionId` while the page is pending; rejection restores it to active. The tool accepts an optional cancellation `reason`, shown on the page and recorded with the decision. 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 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; a new blocked state records `blockedAt`, while a legacy record without it omits the age entirely. Older blocked records without either field remain readable without an invented dependency. When several tasks link the same `decisionQuestionId`, one answer must reconcile all of them, and a superseded page is retired with pi-decisions `WithdrawQuestion` while its tasks are updated in the same turn. If a conversation concludes that a blocker no longer exists, the task record must change in that same turn; saying no input is needed without updating it is a lifecycle defect. 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 through the human decision path; WorkDelete removes only tasks with no recorded work, so a Work containing retained tasks cannot be deleted.
|
|
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 (all), Blocked on you, Waiting on agents, Completed, Cancelled) that narrows the tree to matching tasks; Completed lists every finished task, including records closed after verified completion, so finished work does not disappear from the view used to find it, while All statuses stays the live view; the split entries use dependency counts, labels show how many tasks each entry lists, and blocked rows show their blocked age when the record stores one 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. A Work with nothing to list is not drawn, and no Work or task record is deleted. 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 refreshes a differing `mods/pi-tasks` asset from this package version, keeping the replaced file as a timestamped backup, then creates/selects personal copies of the current pane header/layout for the persistent native-header close; header and layout originals stay untouched. 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
|
-
The panel and `/works` reserve **Done** and **Time** columns.
|
|
68
|
+
The panel and `/works` reserve **Done** and **Time** columns. An active task whose details declare `owner: self` starts timing automatically when a run begins, or when it becomes the only eligible task during a run; routine work needs no extra call. Use `TodoUpdate taskId="T1" working=true` only to switch between tasks when more than one is eligible; switching pauses the previous task. Use `working=false` to pause without changing status for the rest of that run. Blocked, delegated, completed and closed tasks are never timed automatically, and explicit choices always win.
|
|
50
69
|
|
|
51
70
|
The extension uses `Date.now()` to add working intervals, including thinking and foreground tools. Idle time, native retry delays between agent loops, and blocking user prompts do not count. Completion, blocking, cancellation, ownership changes, abort, and shutdown stop the timer automatically. Saved totals survive reload and branch navigation; restored tasks are paused and offline time never counts. A running time has a `▶` marker. Totals are saved on interval boundaries, not every display tick. A forced process kill can lose the current unsaved interval. Blocking prompt exclusion needs a Pi host that emits `ui_prompt_start`/`ui_prompt_end`; older hosts still pause at agent-loop boundaries.
|
|
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
|
|
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.
|
|
75
|
+
|
|
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).
|
|
56
77
|
|
|
57
|
-
|
|
78
|
+
## Agents through pi-herdr
|
|
58
79
|
|
|
59
|
-
|
|
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).
|
|
60
81
|
|
|
61
|
-
|
|
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,40 @@ 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.
|
|
96
|
+
It defaults off. Auto-continuation defaults to 10 extra runs per fresh accepted main user run when `maxContinuations` is omitted. Set a positive integer such as `"maxContinuations": 20` to change the limit; 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. Record correctness is not budgeted progress: a pending completed/blocked transition still produces one record-only review when auto-continuation is disabled or its limit is reached; it names active tasks as unresolved, says not to continue unrelated active work, and does not count against the progress budget. If active tasks remain when progress is disabled or its limit is reached, one explicit unresolved warning names them and states the actionable continuation (enable the setting, reload, then send a new main prompt; reload alone does not arm continuation, or drive the work in a new prompt); it changes no record and never claims completion. 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
|
|
|
100
|
+
Independently of auto-continuation, a `TodoUpdate` that marks a task completed or blocked, or changes a blocked task's dependency class, emits one reflective prompt at Pi's turn boundary. Every delivered review also includes a read-only blocked-task audit with dependency class, blocked age, linked question, and reason, and the same audit is delivered once for a restored start (`startup`, `/reload`, or `resume`) so a stale blocker cannot survive a restart or reload silently; a fresh fork stays isolated. The audit asks the agent to confirm the dependency, return the task to active, retire an obsolete task through the human cancellation decision, or keep the block with its exact unblock condition and a live question or monitor; it never changes a record itself. Completion prompts ask the agent to re-sweep authorized in-scope work and verification without expanding into optional work. A `user-decision` blocker must first be challenged; if a human choice is genuinely needed, use pi-decisions `SubmitQuestion` and `WaitForAnswer` in the browser rather than asking again in chat, and keep an honest blocked reason when those tools or browser access are unavailable. An `another-agent` blocker stays distinct with one continuous monitor. Prompts are deduplicated per task and transition kind for each fresh main user run and never change task records themselves.
|
|
101
|
+
|
|
79
102
|
See [the usage guide](docs/USAGE_GUIDE.md) and [reference](docs/REFERENCE.md).
|
|
80
103
|
|
|
104
|
+
## Native Durable entrypoint
|
|
105
|
+
|
|
106
|
+
For hosts running on `@earendil-works/pi-durable` 1.1.0, this package also ships a
|
|
107
|
+
settings-only native extension with no desktop dependency:
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
import { createTasksDurableExtension } from "@abhishek944/pi-tasks/durable";
|
|
111
|
+
import { createRegistry } from "@earendil-works/pi-durable";
|
|
112
|
+
|
|
113
|
+
const registry = createRegistry();
|
|
114
|
+
registry.install(createTasksDurableExtension({ maxWorks: 100, maxTodos: 500 }));
|
|
115
|
+
// The host opens its own Harness with models/storage/env and selects `tasks`.
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Settings are plain JSON copied and frozen at factory creation. Records live in one
|
|
119
|
+
conversation-scoped document (`pi-tasks.state`, latest history, initial fork), so each
|
|
120
|
+
conversation has isolated tracking and a fork starts empty. The eight tools are real
|
|
121
|
+
document transactions with the same validation as the desktop extension: `WorkCreate`,
|
|
122
|
+
`WorkList`, `WorkUpdate`, `WorkDelete`, `TodoCreate`, `TodoList`, `TodoUpdate`, and
|
|
123
|
+
`TodoDelete`, including completion rules, hidden `taskInfo` metadata, visible `finalThoughts`, `blockedReason`, and `dependentOn` handling. Effort timing is
|
|
124
|
+
unsupported natively: the native schema has no `working` field and reports no times,
|
|
125
|
+
rather than fabricated zeros. Desktop timing is unchanged. Desktop-only surfaces have no
|
|
126
|
+
native equivalent and are documented in `src/durable.ts` rather than stubbed: Herdr agent
|
|
127
|
+
tools, `TaskTimeExport`/`Import` file handoffs, auto-continuation, the `/works` command,
|
|
128
|
+
and the TUI panel.
|
|
129
|
+
|
|
81
130
|
## Development
|
|
82
131
|
|
|
83
132
|
```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,130 @@
|
|
|
1
|
+
import { lstat, realpath } from "node:fs/promises";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { createTimingReport, inspectTimingReport } from "../delegated-time.js";
|
|
4
|
+
import { taskOwner } from "../ownership.js";
|
|
5
|
+
import { areTrackingToolsActive } from "../tracking.js";
|
|
6
|
+
import { TERMINAL_ID } from "./herdr.js";
|
|
7
|
+
import { delegateLink, withTerminalLink } from "./links.js";
|
|
8
|
+
/** Task-owned state changes used by pi-herdr's lifecycle tools. */
|
|
9
|
+
export function registerDelegationBridge(pi, state) {
|
|
10
|
+
let current;
|
|
11
|
+
pi.on("session_start", (_event, ctx) => { current = { sessionId: ctx.sessionManager.getSessionId() }; });
|
|
12
|
+
pi.on("session_shutdown", () => { current = undefined; });
|
|
13
|
+
pi.events.on("pi-tasks:delegation-api", (data) => {
|
|
14
|
+
const request = data;
|
|
15
|
+
if (request?.version !== 1 || typeof request.respond !== "function" || !current)
|
|
16
|
+
return;
|
|
17
|
+
const binding = current;
|
|
18
|
+
const requireCurrent = (ctx) => {
|
|
19
|
+
if (current !== binding || ctx.sessionManager.getSessionId() !== binding.sessionId)
|
|
20
|
+
throw new Error("The pi-tasks delegation bridge belongs to a replaced session. Discover it again from the current session.");
|
|
21
|
+
if (!areTrackingToolsActive(pi))
|
|
22
|
+
throw new Error("Use agent tools in tracked main-conversation work, not /ask or /btw.");
|
|
23
|
+
};
|
|
24
|
+
const assignment = (ctx, input) => {
|
|
25
|
+
requireCurrent(ctx);
|
|
26
|
+
const todo = state.getTodo(input.taskId);
|
|
27
|
+
if (!todo || todo.workId !== input.workId || !state.listWorks({ workId: input.workId }).length || taskOwner(todo.taskInfo) !== "delegate")
|
|
28
|
+
throw new Error("Use an existing task in this work with owner: delegate.");
|
|
29
|
+
return todo;
|
|
30
|
+
};
|
|
31
|
+
request.respond({
|
|
32
|
+
authorizeWorker(ctx, input) {
|
|
33
|
+
requireCurrent(ctx);
|
|
34
|
+
const todo = input.taskId ? state.getTodo(input.taskId) : undefined;
|
|
35
|
+
const linked = todo ? delegateLink(todo.taskInfo)?.terminalId === input.terminalId : false;
|
|
36
|
+
if (input.action === "cleanup") {
|
|
37
|
+
if (todo?.status === "closed")
|
|
38
|
+
return;
|
|
39
|
+
if (!linked && input.turn === 0 && (!todo || todo.status === "active" || todo.status === "blocked" || todo.status === "cancelled"))
|
|
40
|
+
return;
|
|
41
|
+
throw new Error("Worker cleanup requires a closed task; only an unstarted, unattached partial worker can be cleaned earlier.");
|
|
42
|
+
}
|
|
43
|
+
if (!todo || !linked)
|
|
44
|
+
throw new Error("The worker is not attached to this task.");
|
|
45
|
+
if (input.action === "close-request") {
|
|
46
|
+
if (todo.status !== "completed" || todo.workerClose?.request?.terminalId !== input.terminalId)
|
|
47
|
+
throw new Error("Worker /close requires a completed task and a recorded TaskWorkerClose request.");
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (todo.status !== "active" && todo.status !== "blocked")
|
|
51
|
+
throw new Error("Worker messages require an active or blocked task.");
|
|
52
|
+
},
|
|
53
|
+
getWorktree(ctx, input) {
|
|
54
|
+
const todo = assignment(ctx, input);
|
|
55
|
+
if (todo.status !== "active")
|
|
56
|
+
throw new Error("Delegation requires an active task.");
|
|
57
|
+
return todo.worktree;
|
|
58
|
+
},
|
|
59
|
+
bindWorktree(ctx, input) {
|
|
60
|
+
const todo = assignment(ctx, input);
|
|
61
|
+
if (todo.status !== "active")
|
|
62
|
+
throw new Error("Delegation requires an active task.");
|
|
63
|
+
state.setWorktree(input.taskId, input.worktree);
|
|
64
|
+
},
|
|
65
|
+
async discardUnstarted(ctx, input) {
|
|
66
|
+
const todo = assignment(ctx, input);
|
|
67
|
+
if (!todo.delegatedTimes?.some((item) => item.reportPath === input.reportPath))
|
|
68
|
+
throw new Error("Timing registration not found for this assignment.");
|
|
69
|
+
try {
|
|
70
|
+
await lstat(input.reportPath);
|
|
71
|
+
throw new Error("Cannot discard a timing registration whose report exists.");
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (error.code !== "ENOENT")
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
assignment(ctx, input);
|
|
78
|
+
state.removeUnstartedDelegatedTime(input.taskId, input.reportPath);
|
|
79
|
+
},
|
|
80
|
+
async prepare(ctx, input) {
|
|
81
|
+
const todo = assignment(ctx, input);
|
|
82
|
+
if (todo.status !== "active")
|
|
83
|
+
throw new Error("Delegation requires an active task; explicitly reopen a closed or cancelled task first.");
|
|
84
|
+
const reportRoot = await realpath(input.reportRoot ?? ctx.cwd);
|
|
85
|
+
const reportPath = await createTimingReport(ctx, input.taskDir, input.workId, input.taskId, reportRoot);
|
|
86
|
+
assignment(ctx, input);
|
|
87
|
+
state.setDelegatedTime(input.taskId, { reportPath, reportRoot, elapsedMs: null });
|
|
88
|
+
return { reportPath };
|
|
89
|
+
},
|
|
90
|
+
async inspect(ctx, input) {
|
|
91
|
+
const todo = assignment(ctx, input);
|
|
92
|
+
const source = todo.delegatedTimes?.find((item) => item.reportPath === input.reportPath);
|
|
93
|
+
if (!source) {
|
|
94
|
+
// A partial worker launched by an older version has a parent-created
|
|
95
|
+
// placeholder but no registration until attach. Validate that file.
|
|
96
|
+
return inspectTimingReport(ctx, input.taskDir, input.workId, input.taskId, input.reportPath);
|
|
97
|
+
}
|
|
98
|
+
if (dirname(source.reportPath) !== resolve(input.taskDir))
|
|
99
|
+
throw new Error("Timing report was not registered for this task directory.");
|
|
100
|
+
try {
|
|
101
|
+
const inspected = await inspectTimingReport(ctx, input.taskDir, input.workId, input.taskId, input.reportPath, source.reportRoot);
|
|
102
|
+
assignment(ctx, input);
|
|
103
|
+
return inspected;
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (error.code !== "ENOENT" || source.workerSessionId !== undefined)
|
|
107
|
+
throw error;
|
|
108
|
+
return { reportPath: source.reportPath, timing: "placeholder", workerSessionId: null };
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
attach(ctx, input) {
|
|
112
|
+
const todo = assignment(ctx, input);
|
|
113
|
+
if (todo.status !== "active" && !(todo.status === "blocked" && todo.dependentOn === "another-agent" && delegateLink(todo.taskInfo)?.terminalId === input.terminalId))
|
|
114
|
+
throw new Error("Worker attachment requires an active task or the same already-attached worker.");
|
|
115
|
+
if (!TERMINAL_ID.test(input.terminalId))
|
|
116
|
+
throw new Error("Use the terminalId returned by hc.");
|
|
117
|
+
state.setDelegatedTime(input.taskId, { reportPath: input.reportPath, elapsedMs: null });
|
|
118
|
+
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) });
|
|
119
|
+
},
|
|
120
|
+
detach(ctx, input) {
|
|
121
|
+
requireCurrent(ctx);
|
|
122
|
+
if (!TERMINAL_ID.test(input.terminalId))
|
|
123
|
+
throw new Error("Use the terminalId returned by hc.");
|
|
124
|
+
for (const todo of state.listTodos())
|
|
125
|
+
if (delegateLink(todo.taskInfo)?.terminalId === input.terminalId)
|
|
126
|
+
state.updateTodo(todo.taskId, { taskInfo: withTerminalLink(todo.taskInfo) });
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
}
|
package/dist/agents/herdr.d.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
export declare const
|
|
1
|
+
export declare const TERMINAL_ID: RegExp;
|
|
2
2
|
export declare function object(value: unknown): Record<string, unknown> | undefined;
|
|
3
|
-
export declare function
|
|
4
|
-
export declare function
|
|
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;
|
package/dist/agents/herdr.js
CHANGED
|
@@ -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
|
|
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
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
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
|
|
15
|
-
const
|
|
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 :
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
|
}
|
package/dist/agents/links.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export interface DelegateLink {
|
|
2
|
-
|
|
2
|
+
terminalId: string;
|
|
3
3
|
}
|
|
4
4
|
export declare function delegateLink(taskInfo: string): DelegateLink | undefined;
|
|
5
|
-
export declare function
|
|
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
|
|
7
|
+
export declare function withTerminalLink(taskInfo: string, terminalId?: string, monitorId?: string): string;
|
package/dist/agents/links.js
CHANGED
|
@@ -1,30 +1,53 @@
|
|
|
1
1
|
import { taskOwner } from "../ownership.js";
|
|
2
|
-
import {
|
|
2
|
+
import { app, hc, object, TERMINAL_ID } from "./herdr.js";
|
|
3
3
|
export function delegateLink(taskInfo) {
|
|
4
|
-
if (
|
|
4
|
+
if (taskOwner(taskInfo) !== "delegate")
|
|
5
5
|
return undefined;
|
|
6
|
-
const
|
|
7
|
-
if (
|
|
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 {
|
|
9
|
+
return { terminalId: terminals[0] };
|
|
10
10
|
}
|
|
11
|
-
export async function
|
|
12
|
-
if (!
|
|
13
|
-
throw new Error("Use the
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
-
|
|
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
|
|
28
|
-
const text = taskInfo.split(/\r?\n/).filter((line) => !/^[ \t]*herdr-(?:pane|monitor):/i.test(line)).join("\n").trim();
|
|
29
|
-
return
|
|
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
|
}
|