@howaboua/pi-shepherdr 0.1.2 → 0.1.4

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/CHANGELOG.md ADDED
@@ -0,0 +1,52 @@
1
+ # @howaboua/pi-shepherdr
2
+
3
+ ## 0.1.4
4
+
5
+ - Preserve extension-owned messages while delivering true developer-role policy through compatible Pi Codex Responses adapters.
6
+
7
+ - Add an optional custom-message API that retains caller rendering and restoration fields.
8
+ - Route Shepherdr's unclaimed worker events and orchestration toggles through it, preserving ordinary Pi delivery when unavailable.
9
+ - Send review preface/triage policy and realtime voice start/end guidance as developer messages without elevating raw reviewer findings, spoken delegations, or transcript tails.
10
+ - Keep persisted developer messages in context across model switches, using ordinary Pi conversion on incompatible models.
11
+
12
+ - Fix worker settlement, custom model preservation, and prompt-only image generation.
13
+
14
+ - Settle Shepherdr workers after Pi expands skill or prompt-template invocations.
15
+ - Preserve custom Codex models and `models.json` overrides, including after refresh.
16
+ - Keep optional tool arguments optional in Codex Responses requests while preserving explicit strict sampling.
17
+ - Treat null image selectors as absent, so prompt-only requests generate rather than edit.
18
+ - Honor the details toggle in Notebook Mode to hide duplicate output previews.
19
+ - Show submitted messages without waiting for cached WebSocket warmup, while keeping generation serialized behind it.
20
+
21
+ ## 0.1.3
22
+
23
+ - Replaced Shepherdr's fire-and-forget tool with persistent blocking and asynchronous agents in normal Pi, Code Mode, and Notebook Mode.
24
+
25
+ - Start, steer, inspect, and answer multiple agents through the `agents` tool.
26
+ - Customize the bundled general, explorer, and reviewer profiles or add your own.
27
+ - Activate orchestration mode with `/herdr` when the main session should coordinate agent work.
28
+
29
+ ## 0.1.2
30
+
31
+ ### Changes
32
+
33
+ - [#298](https://github.com/IgorWarzocha/howaboua-pi-stuff/pull/298) [`b20e7de`](https://github.com/IgorWarzocha/howaboua-pi-stuff/commit/b20e7de137fe89344bc15b06c7e7e0bf02a896b3) Thanks [@IgorWarzocha](https://github.com/IgorWarzocha)! - Orchestrate Pi agents across named remote Herdr machines with automatic SSH bridge deployment and explicit reconnect controls.
34
+
35
+ ## 0.1.1
36
+
37
+ ### Changes
38
+
39
+ - [#269](https://github.com/IgorWarzocha/howaboua-pi-stuff/pull/269) [`6138ffd`](https://github.com/IgorWarzocha/howaboua-pi-stuff/commit/6138ffd735bb4f7f80e451320dbfd0933a4acaa7) Thanks [@howaclawa](https://github.com/howaclawa)!:
40
+ - Add shared realtime voice prompts for ask prompts, Auto Trees, Shepherdr settlements, and review progress.
41
+ - Announce compaction and stream conversational Pi updates after two sentences.
42
+ - Keep silent tool-step summaries compatible without exposing Chat Completions thinking content.
43
+ - Configure delegation acknowledgements and deliver V3 delegations immediately.
44
+ - Preserve late delegations, calls after data-channel closure, prepared Code Mode prompts, and Codex cache continuity.
45
+ - Reduce LAN playback dropouts with one more jitter-buffer frame.
46
+
47
+ ## 0.1.0
48
+
49
+ ### Changes
50
+
51
+ - [#256](https://github.com/IgorWarzocha/howaboua-pi-stuff/pull/256) [`4d306ed`](https://github.com/IgorWarzocha/howaboua-pi-stuff/commit/4d306eded0057c82868a1628bd2131a7eedfd7a6) Thanks [@IgorWarzocha](https://github.com/IgorWarzocha)!:
52
+ - Add Shepherdr, a Herdr-native Pi agent orchestrator with event-driven monitoring and a live fleet widget.
package/README.md CHANGED
@@ -1,16 +1,12 @@
1
1
  # pi-shepherdr
2
2
 
3
- Talk to one Pi. Let it run the others.
3
+ One persistent agent system for ordinary Pi, Code Mode and Notebook Mode.
4
4
 
5
- Shepherdr turns one Pi session into an orchestrator for Pi agents running across [Herdr](https://herdr.dev). Give work to the master; it can find existing agents, start new ones in explicit locations, send follow-ups and bring their full replies back into the same conversation.
5
+ Shepherdr combines a monitored [Herdr](https://herdr.dev) fleet with blocking and asynchronous agent calls. It registers one routed `agents` tool in normal Pi. When Pi Codex is installed, the same definition, renderer and implementation become `tools.agents` inside Code and Notebook Mode.
6
6
 
7
- The master gets one small JSON-schema tool with the actions and arguments it needs. Its complete active surface measures 290 `o200k` tokens: 247 for the OpenAI Responses tool declaration and 43 for the master guideline. Workers load none of it.
7
+ Asynchronous calls return after dispatch, then push completion, failure or blockage into the controller with a steer message. The model never has to poll. Blocking calls hold the tool call and return the worker's reply directly.
8
8
 
9
- Enable master mode and Pi already knows its job. You do not have to explain Herdr, ask it to load an orchestration skill or remind it to delegate. The schema handles ordinary delegation without `--help` or improvised CLI commands. Herdr and Shepherdr should be enough on their own; any other Pi extensions and skills continue to work alongside them.
10
-
11
- This is particularly handy with realtime voice. You keep talking to one agent while the workers operate in their panes and project directories. Finished work comes back automatically. If a worker needs approval or an answer, the master is steered at the next opportunity instead of leaving you to hunt through panes.
12
-
13
- Herdr still owns the terminals, layout and restored sessions. Shepherdr connects them to one Pi conversation.
9
+ With Pi Codex's compatible custom developer-message API active, asynchronous worker reports and orchestration toggles use the Responses developer role while retaining their normal display and session restoration. Without that API or adapter, delivery remains ordinary Pi custom messages. Blocking results stay in the tool response.
14
10
 
15
11
  ## Install
16
12
 
@@ -18,79 +14,88 @@ Herdr still owns the terminals, layout and restored sessions. Shepherdr connects
18
14
  pi install npm:@howaboua/pi-shepherdr
19
15
  ```
20
16
 
21
- Requires Pi 0.84.1 or newer and the Herdr Pi integration:
17
+ Requires Pi 0.84.3 or newer, Herdr 0.8.x and the Herdr Pi integration:
22
18
 
23
19
  ```bash
24
20
  herdr integration install pi
25
21
  ```
26
22
 
27
- Shepherdr supports Herdr 0.8.x. It was developed and validated with 0.8.0; Herdr 0.7.x and older are unsupported. The controlling Pi session must run inside Herdr.
23
+ Do not load Pi Codex's example `agents.toml` custom tool alongside Shepherdr; they own the same agent surface.
28
24
 
29
- ## Set up the master
25
+ Pi Codex 3.0.25 or newer is optional. Without it, Shepherdr remains a normal Pi extension.
30
26
 
31
- Pi sessions remain ordinary workers by default. They receive no orchestration tool or master instructions.
27
+ ## Enable orchestration
32
28
 
33
- To try master mode in the current session:
29
+ Pi sessions remain ordinary workers until explicitly promoted. Run Pi inside Herdr, then activate the agent tool and orchestration guidance for the current session:
34
30
 
35
31
  ```text
36
- /herdr master
32
+ /herdr
37
33
  ```
38
34
 
39
- For a lasting setup, open Pi in a dedicated control directory and run:
35
+ The command records one visible mode message without triggering a turn. Run `/herdr` again to return to normal guidance while keeping the agent tool available. Resumed controller sessions restore their last mode; new worker sessions in the same directory remain dormant.
40
36
 
41
- ```text
42
- /herdr json
43
- ```
37
+ `/herdr machines` opens the Add/Remove Machine interface. Settings live at `<pi-agent-directory>/shepherdr.json`, where the directory defaults to `~/.pi/agent` and `PI_CODING_AGENT_DIR` overrides it. `/herdr connect [machine]` retries configured remotes after activation.
44
38
 
45
- That command atomically merges the following setting into `.pi/shepherdr.json`:
39
+ Remote machines connect over noninteractive SSH. The target needs Node, Herdr 0.8.x, the Herdr Pi integration and a running Herdr session. Shepherdr installs one helper at `~/.pi/agent/shepherdr.mjs` on each remote, runs it only for the connection lifetime and leaves no remote daemon behind.
46
40
 
47
- ```json
48
- {
49
- "master": true
50
- }
51
- ```
41
+ ## Agent calls
52
42
 
53
- Future Pi sessions in that directory start as masters. `/herdr master` affects only the current session.
43
+ Call the `agents` tool with `action: "help"` before first use, then send flat request objects. Code and Notebook Mode expose the same router as `await tools.agents({ action: "help" })`; every call requires `action`.
54
44
 
55
- While master mode is active, Pi is guided to delegate project implementation and synthesize the results. It works directly when you explicitly ask, and for configuration, documentation and routine operations in its current directory.
45
+ | Action | Result |
46
+ | --- | --- |
47
+ | `help` | Live profiles, request shapes, coordination rules and the advanced Herdr escape hatch |
48
+ | `list` | Profiles, machines and matching Pi agents |
49
+ | `find` | Agents matching a query or status |
50
+ | `spawn` | Spawn a profiled Pi agent and send its initial task |
51
+ | `send` | Send work or a follow-up to an existing agent |
52
+ | `read` | Read the latest assistant reply or bounded terminal output |
53
+ | `answer` | Answer a worker blocked on Pi Ask |
54
+ | `watch` | Push future settlement from an existing Pi agent |
55
+ | `unwatch` | Stop reporting an agent |
56
56
 
57
- ## Connect more machines
57
+ `spawn`, `send` and `answer` block by default. Set `blocking: false` only when the controller should continue other work immediately. Completion and blockage are then delivered automatically.
58
58
 
59
- Run `/herdr` and choose **Add machine**. Give the machine a name and an SSH target that already connects noninteractively; the remote machine needs Node, Herdr and the Pi integration. Machine settings live in `~/.pi/agent/shepherdr.json`.
59
+ Every `spawn` needs an `agent_type` and a concise two- or three-word `label`. The label names both the Herdr tab and Pi session; the routing `name` remains optional and is derived from it when omitted.
60
60
 
61
- Master mode connects every configured machine once in parallel. A failed or dropped connection remains unavailable without retrying automatically; use `/herdr connect` or `/herdr connect <machine>` to try again.
61
+ Cancelling a blocking call does not kill its worker. The waiter detaches and the eventual result returns through normal asynchronous delivery.
62
62
 
63
- Shepherdr maintains one remote helper at `~/.pi/agent/shepherdr.mjs`. It updates that file atomically when needed, runs it only for the lifetime of the SSH connection and leaves no remote daemon behind. Agent lists, workspaces, monitored state and full replies retain their machine identity. Ask the master naturally—for example, “run this on desktop”—and it routes the existing `herdr_agents` tool with the configured machine name.
63
+ ## Profiles
64
64
 
65
- ## What the master can do
65
+ On first load, Shepherdr installs three editable profiles:
66
66
 
67
- Shepherdr adds one compact `herdr_agents` tool. Its schema is the complete model-facing control surface:
67
+ - `general` uses `openai-codex/gpt-5.6-sol` with `high` thinking for implementation
68
+ - `explorer` uses `openai-codex/gpt-5.6-terra` with `high` thinking for read-only discovery
69
+ - `reviewer` uses `openai-codex/gpt-5.6-luna` with `xhigh` thinking for generic read-only review
68
70
 
69
- | Action | What it does |
70
- | --- | --- |
71
- | `list` | Find Pi agents and Herdr workspaces. |
72
- | `start` | Launch a named Pi agent in an explicitly selected new workspace, new tab or existing pane. An optional prompt starts work immediately. |
73
- | `watch` | Subscribe to an existing Pi agent. |
74
- | `send` | Send a follow-up to any Pi agent and monitor it automatically. |
75
- | `unwatch` | Stop reporting an agent without stopping or moving it. |
71
+ Use `general` sparingly, mainly when requested or while orchestration is active. For work in the controller's repository, create and prepare a dedicated worktree, then pass it as `cwd`.
76
72
 
77
- Delegation is fire-and-forget. A `start` with an initial prompt, plus every `watch` and `send`, tells the master not to poll. Completion or blockage arrives automatically.
73
+ Profiles live under:
78
74
 
79
- Shepherdr does not invent another workspace model or resume mechanism. It never silently moves, focuses, releases or closes existing panes. Herdr remains responsible for detach, reattach, layout restoration and native Pi session restoration.
75
+ ```text
76
+ <pi-agent-directory>/shepherdr/profiles/<name>/profile.json
77
+ ```
80
78
 
81
- ## Results and blocked workers
79
+ That directory is authoritative after initialization. Edit a profile to change it, add a directory to create an agent type, or delete its directory to remove it; deleted defaults are not recreated. Profiles never inherit the controller's model or thinking level.
82
80
 
83
- A live widget shows the watched agents and their state. When work settles, the master receives a labelled purple message containing the original task and the full, untruncated worker response.
81
+ ```json
82
+ {
83
+ "description": "Read-only dependency review",
84
+ "model": "provider/model",
85
+ "thinking": "high",
86
+ "prompt": "prompt.md",
87
+ "accepts": ["base"],
88
+ "pi_args": []
89
+ }
90
+ ```
84
91
 
85
- Finished, failed and blocked events all steer the master. During an active turn, the event arrives after the current tool calls and before the next model response. While idle, it starts a response immediately.
92
+ `prompt` is read as system-prompt text. An optional `prepare` module may export `prepare({ cwd, message, base, local })` and return the worker message. Preparation runs on the controlling machine before dispatch; `local` says whether that machine also hosts the worker.
86
93
 
87
- A blocked event includes the pane ID and concrete Herdr commands for inspecting and operating it:
94
+ ## Advanced Herdr control
88
95
 
89
- ```bash
90
- herdr agent read <pane> --source visible
91
- herdr agent prompt <pane> "<text>"
92
- herdr agent send-keys <pane> <keys>
93
- ```
96
+ Ordinary delegation stays inside `agents`. For workspace, tab, pane, process, focus, layout or raw-terminal operations, run `herdr --skill` and follow the installed Herdr skill. Shepherdr does not duplicate those controls.
97
+
98
+ Herdr still owns terminals, layout, agent processes and restored sessions. Shepherdr owns event subscriptions, remote routing, the fleet widget and purple settlement messages.
94
99
 
95
100
  ## License
96
101
 
package/biome.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://biomejs.dev/schemas/2.4.16/schema.json",
2
+ "$schema": "https://biomejs.dev/schemas/2.5.10/schema.json",
3
3
  "vcs": {
4
4
  "enabled": true,
5
5
  "clientKind": "git",
package/changelog.ts ADDED
@@ -0,0 +1,337 @@
1
+ // Generated extension packages copy this file during changelog:extensions.
2
+
3
+ import { randomUUID } from "node:crypto";
4
+ import { readFileSync } from "node:fs";
5
+ import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
6
+ import { dirname, join } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import {
9
+ DynamicBorder,
10
+ type ExtensionAPI,
11
+ getAgentDir,
12
+ getMarkdownTheme,
13
+ } from "@earendil-works/pi-coding-agent";
14
+ import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
15
+
16
+ const ENTRY_TYPE = "@howaboua/pi-stuff/changelog";
17
+ const REGISTRATION_CHANNEL = "@howaboua/pi-stuff/changelog/register/v1";
18
+ const STATE_FILENAME = "howaboua-pi-stuff-changelog.json";
19
+ const SUPPRESS_KEY = "suppress";
20
+ const LOCK_STALE_MS = 30_000;
21
+ const LOCK_TIMEOUT_MS = 2_000;
22
+
23
+ interface PackageMetadata {
24
+ name: string;
25
+ version: string;
26
+ }
27
+
28
+ interface PackageRegistration extends PackageMetadata {
29
+ changelogPath: string;
30
+ }
31
+
32
+ interface RegistrationEvent {
33
+ accept: () => void;
34
+ registration: PackageRegistration;
35
+ }
36
+
37
+ interface ChangelogEntry {
38
+ content: string;
39
+ version: string;
40
+ }
41
+
42
+ interface ChangelogEntryData {
43
+ markdown: string;
44
+ }
45
+
46
+ type ChangelogState = Record<string, boolean | string>;
47
+
48
+ function packageRegistration(): PackageRegistration {
49
+ const packageDirectory = fileURLToPath(new URL(".", import.meta.url));
50
+ const metadata = JSON.parse(
51
+ readFileSync(join(packageDirectory, "package.json"), "utf8"),
52
+ ) as Partial<PackageMetadata>;
53
+ if (typeof metadata.name !== "string" || typeof metadata.version !== "string")
54
+ throw new Error(`Invalid package metadata in ${packageDirectory}`);
55
+ return {
56
+ name: metadata.name,
57
+ version: metadata.version,
58
+ changelogPath: join(packageDirectory, "CHANGELOG.md"),
59
+ };
60
+ }
61
+
62
+ function isRegistrationEvent(value: unknown): value is RegistrationEvent {
63
+ if (!value || typeof value !== "object") return false;
64
+ const event = value as Partial<RegistrationEvent>;
65
+ return (
66
+ typeof event.accept === "function" &&
67
+ typeof event.registration?.name === "string" &&
68
+ typeof event.registration.version === "string" &&
69
+ typeof event.registration.changelogPath === "string"
70
+ );
71
+ }
72
+
73
+ function parseChangelog(markdown: string): ChangelogEntry[] {
74
+ const entries: ChangelogEntry[] = [];
75
+ let currentLines: string[] = [];
76
+ let currentVersion: string | undefined;
77
+
78
+ for (const line of markdown.split("\n")) {
79
+ const version = line.match(/^##\s+\[?(\d+\.\d+\.\d+)\]?(?:\s.*)?$/)?.[1];
80
+ if (version) {
81
+ if (currentVersion)
82
+ entries.push({
83
+ content: currentLines.join("\n").trim(),
84
+ version: currentVersion,
85
+ });
86
+ currentVersion = version;
87
+ currentLines = [line];
88
+ } else if (currentVersion) {
89
+ currentLines.push(line);
90
+ }
91
+ }
92
+
93
+ if (currentVersion)
94
+ entries.push({
95
+ content: currentLines.join("\n").trim(),
96
+ version: currentVersion,
97
+ });
98
+ return entries;
99
+ }
100
+
101
+ function compareVersions(left: string, right: string): number {
102
+ const leftParts = left.split(".").map(Number);
103
+ const rightParts = right.split(".").map(Number);
104
+ for (let index = 0; index < 3; index++) {
105
+ const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
106
+ if (difference !== 0) return difference;
107
+ }
108
+ return 0;
109
+ }
110
+
111
+ function isStableVersion(version: string): boolean {
112
+ return /^\d+\.\d+\.\d+$/.test(version);
113
+ }
114
+
115
+ function statePath(): string {
116
+ return join(getAgentDir(), STATE_FILENAME);
117
+ }
118
+
119
+ async function readState(path: string): Promise<ChangelogState> {
120
+ let text: string;
121
+ try {
122
+ text = await readFile(path, "utf8");
123
+ } catch (error) {
124
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
125
+ throw error;
126
+ }
127
+ const parsed = JSON.parse(text) as unknown;
128
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
129
+ throw new Error(`${path} must contain a JSON object`);
130
+ for (const [name, value] of Object.entries(parsed)) {
131
+ if (name === SUPPRESS_KEY) {
132
+ if (typeof value !== "boolean")
133
+ throw new Error(`${path} ${SUPPRESS_KEY} must be a boolean`);
134
+ } else if (typeof value !== "string") {
135
+ throw new Error(`${path} version for ${name} must be a string`);
136
+ }
137
+ }
138
+ return parsed as ChangelogState;
139
+ }
140
+
141
+ async function acquireLock(path: string): Promise<() => Promise<void>> {
142
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
143
+ while (true) {
144
+ try {
145
+ await mkdir(path);
146
+ return () => rm(path, { force: true, recursive: true });
147
+ } catch (error) {
148
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
149
+ const info = await stat(path).catch(() => undefined);
150
+ if (info && Date.now() - info.mtimeMs > LOCK_STALE_MS) {
151
+ await rm(path, { force: true, recursive: true });
152
+ continue;
153
+ }
154
+ if (Date.now() >= deadline)
155
+ throw new Error(`Timed out waiting for ${path}`);
156
+ await new Promise((resolve) => setTimeout(resolve, 20));
157
+ }
158
+ }
159
+ }
160
+
161
+ async function writeState(path: string, state: ChangelogState): Promise<void> {
162
+ await mkdir(dirname(path), { mode: 0o700, recursive: true });
163
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
164
+ try {
165
+ const ordered = Object.fromEntries(
166
+ Object.entries(state).sort(([left], [right]) =>
167
+ left.localeCompare(right),
168
+ ),
169
+ );
170
+ await writeFile(temporaryPath, `${JSON.stringify(ordered, null, 2)}\n`, {
171
+ encoding: "utf8",
172
+ mode: 0o600,
173
+ });
174
+ await rename(temporaryPath, path);
175
+ } catch (error) {
176
+ await rm(temporaryPath, { force: true });
177
+ throw error;
178
+ }
179
+ }
180
+
181
+ function packageMarkdown(
182
+ registration: PackageRegistration,
183
+ entries: ChangelogEntry[],
184
+ ): string {
185
+ const body = (entry: ChangelogEntry) =>
186
+ entry.content
187
+ .replace(/^##[^\n]*\n*/, "")
188
+ .replace(/^###\s+(?:Changes|Minor Changes|Patch Changes)\s*\n*/gim, "")
189
+ .replace(/^###\s+(.+)$/gm, "**$1**");
190
+ if (entries.length === 1) {
191
+ const [entry] = entries;
192
+ if (!entry) return "";
193
+ return `## ${registration.name} ${entry.version}\n\n${body(entry)}`;
194
+ }
195
+ return [
196
+ `## ${registration.name}`,
197
+ ...entries.map((entry) => `**${entry.version}**\n\n${body(entry)}`),
198
+ ].join("\n\n");
199
+ }
200
+
201
+ async function claimUpdates(
202
+ registrations: Iterable<PackageRegistration>,
203
+ ): Promise<{ errors: string[]; markdown?: string }> {
204
+ const stableRegistrations = [...registrations]
205
+ .filter((registration) => isStableVersion(registration.version))
206
+ .sort((left, right) => left.name.localeCompare(right.name));
207
+ if (stableRegistrations.length === 0) return { errors: [] };
208
+ const path = statePath();
209
+ await mkdir(dirname(path), { mode: 0o700, recursive: true });
210
+ const release = await acquireLock(`${path}.lock`);
211
+ try {
212
+ const state = await readState(path);
213
+ const errors: string[] = [];
214
+ const sections: string[] = [];
215
+ let changed = false;
216
+ if (state[SUPPRESS_KEY] === true) {
217
+ for (const registration of stableRegistrations) {
218
+ const seenVersion = state[registration.name];
219
+ if (
220
+ typeof seenVersion !== "string" ||
221
+ compareVersions(registration.version, seenVersion) > 0
222
+ ) {
223
+ state[registration.name] = registration.version;
224
+ changed = true;
225
+ }
226
+ }
227
+ if (changed) await writeState(path, state);
228
+ return { errors };
229
+ }
230
+ for (const registration of stableRegistrations) {
231
+ const seenVersion = state[registration.name];
232
+ if (
233
+ typeof seenVersion === "string" &&
234
+ compareVersions(registration.version, seenVersion) <= 0
235
+ )
236
+ continue;
237
+ try {
238
+ const entries = parseChangelog(
239
+ await readFile(registration.changelogPath, "utf8"),
240
+ ).filter(
241
+ (entry) =>
242
+ compareVersions(entry.version, registration.version) <= 0 &&
243
+ (typeof seenVersion === "string"
244
+ ? compareVersions(entry.version, seenVersion) > 0
245
+ : entry.version === registration.version),
246
+ );
247
+ if (entries.length === 0) {
248
+ errors.push(
249
+ `No ${registration.version} changelog entry found for ${registration.name}`,
250
+ );
251
+ continue;
252
+ }
253
+ sections.push(packageMarkdown(registration, entries));
254
+ state[registration.name] = registration.version;
255
+ changed = true;
256
+ } catch (error) {
257
+ errors.push(
258
+ `Could not read the ${registration.name} changelog: ${error instanceof Error ? error.message : String(error)}`,
259
+ );
260
+ }
261
+ }
262
+ if (changed) await writeState(path, state);
263
+ return {
264
+ errors,
265
+ ...(sections.length > 0 ? { markdown: sections.join("\n\n") } : {}),
266
+ };
267
+ } finally {
268
+ await release();
269
+ }
270
+ }
271
+
272
+ function registerCoordinator(
273
+ pi: ExtensionAPI,
274
+ registration: PackageRegistration,
275
+ ): void {
276
+ let accepted = false;
277
+ pi.events.emit(REGISTRATION_CHANNEL, {
278
+ registration,
279
+ accept: () => {
280
+ accepted = true;
281
+ },
282
+ } satisfies RegistrationEvent);
283
+ if (accepted) return;
284
+
285
+ const registrations = new Map([[registration.name, registration]]);
286
+ pi.events.on(REGISTRATION_CHANNEL, (value) => {
287
+ if (!isRegistrationEvent(value)) return;
288
+ registrations.set(value.registration.name, value.registration);
289
+ value.accept();
290
+ });
291
+ pi.registerEntryRenderer<ChangelogEntryData>(
292
+ ENTRY_TYPE,
293
+ (entry, _options, theme) => {
294
+ if (!entry.data) return undefined;
295
+ const container = new Container();
296
+ container.addChild(new DynamicBorder());
297
+ container.addChild(
298
+ new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0),
299
+ );
300
+ container.addChild(new Spacer(1));
301
+ container.addChild(
302
+ new Markdown(entry.data.markdown.trim(), 1, 0, getMarkdownTheme()),
303
+ );
304
+ container.addChild(new Spacer(1));
305
+ container.addChild(new DynamicBorder());
306
+ return container;
307
+ },
308
+ );
309
+ pi.on("session_start", async (event, ctx) => {
310
+ if (event.reason === "reload" || ctx.mode !== "tui") return;
311
+ if (
312
+ ctx.sessionManager
313
+ .getEntries()
314
+ .some((entry) =>
315
+ ["branch_summary", "compaction", "message"].includes(entry.type),
316
+ )
317
+ )
318
+ return;
319
+ try {
320
+ const update = await claimUpdates(registrations.values());
321
+ if (update.markdown)
322
+ pi.appendEntry<ChangelogEntryData>(ENTRY_TYPE, {
323
+ markdown: update.markdown,
324
+ });
325
+ for (const error of update.errors) ctx.ui.notify(error, "warning");
326
+ } catch (error) {
327
+ ctx.ui.notify(
328
+ `Could not update Howaboua changelog state: ${error instanceof Error ? error.message : String(error)}`,
329
+ "warning",
330
+ );
331
+ }
332
+ });
333
+ }
334
+
335
+ export default function howabouaPackageChangelog(pi: ExtensionAPI): void {
336
+ registerCoordinator(pi, packageRegistration());
337
+ }
package/index.ts CHANGED
@@ -1,13 +1,103 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import registerPackageChangelog from "./changelog.js";
3
+ import { isBlockingAgentsCall } from "./src/agents-contract.js";
4
+ import { createAgentsTool } from "./src/agents-tool.js";
5
+ import { registerAgentController } from "./src/controller.js";
6
+ import { registerDeveloperDelivery } from "./src/delivery.js";
2
7
  import { AgentFleet } from "./src/fleet.js";
3
- import { registerMasterMode } from "./src/master-mode.js";
4
8
  import { registerAgentEventRenderer } from "./src/messages.js";
5
- import { registerHerdrAgentsTool } from "./src/tool.js";
9
+ import { installAgentProfiles } from "./src/profiles.js";
6
10
 
7
- export default function shepherdrExtension(pi: ExtensionAPI): void {
11
+ const CODE_MODE_PACKAGE = "@howaboua/pi-codex-conversion";
12
+ const CODE_MODE_MODULE = `${CODE_MODE_PACKAGE}/code-mode`;
13
+
14
+ export default async function shepherdrExtension(
15
+ pi: ExtensionAPI,
16
+ ): Promise<void> {
17
+ registerPackageChangelog(pi);
18
+ await installAgentProfiles();
19
+ await registerDeveloperDelivery(pi);
8
20
  const fleet = new AgentFleet(pi);
21
+ const tool = createAgentsTool(fleet);
9
22
 
10
23
  registerAgentEventRenderer(pi);
11
- registerHerdrAgentsTool(pi, fleet);
12
- registerMasterMode(pi, fleet);
24
+ pi.registerTool(tool);
25
+ const registration = await registerAgentsInCodeMode(pi, tool, fleet);
26
+ registerAgentController(pi, fleet, {
27
+ onActiveChange: () => registration?.refresh(),
28
+ });
29
+ }
30
+
31
+ async function registerAgentsInCodeMode(
32
+ pi: ExtensionAPI,
33
+ tool: ReturnType<typeof createAgentsTool>,
34
+ fleet: AgentFleet,
35
+ ) {
36
+ try {
37
+ const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
38
+ await import("@howaboua/pi-codex-conversion/code-mode");
39
+ const registration = registerCodeModeExtensionTools(
40
+ pi,
41
+ () => [
42
+ adaptToolForCodeMode(tool, {
43
+ blocking: isBlockingAgentsCall,
44
+ usage: 'await tools.agents({ action: "help" }) // first call alone',
45
+ }),
46
+ ],
47
+ { isActive: () => fleet.isActive() },
48
+ );
49
+ pi.on("session_shutdown", () => registration.unregister());
50
+ return registration;
51
+ } catch (error) {
52
+ if (isMissingCodeModeExtension(error)) return undefined;
53
+ if (isOutdatedCodeModeExtension(error)) {
54
+ throw new Error(
55
+ "Update " +
56
+ CODE_MODE_PACKAGE +
57
+ " to 3.0.24 or newer to use Shepherdr with it",
58
+ { cause: error },
59
+ );
60
+ }
61
+ throw error;
62
+ }
63
+ }
64
+
65
+ function isMissingCodeModeExtension(error: unknown): boolean {
66
+ if (
67
+ !error ||
68
+ typeof error !== "object" ||
69
+ !("code" in error) ||
70
+ !("message" in error) ||
71
+ typeof error.message !== "string"
72
+ ) {
73
+ return false;
74
+ }
75
+ if (
76
+ error.code !== "ERR_MODULE_NOT_FOUND" &&
77
+ error.code !== "MODULE_NOT_FOUND"
78
+ ) {
79
+ return false;
80
+ }
81
+ const missing = error.message.match(
82
+ /Cannot find (?:package|module) ['"]([^'"]+)['"]/,
83
+ )?.[1];
84
+ return missing === CODE_MODE_PACKAGE || missing === CODE_MODE_MODULE;
85
+ }
86
+
87
+ function isOutdatedCodeModeExtension(error: unknown): boolean {
88
+ if (
89
+ !error ||
90
+ typeof error !== "object" ||
91
+ !("code" in error) ||
92
+ !("message" in error) ||
93
+ typeof error.message !== "string"
94
+ )
95
+ return false;
96
+ return (
97
+ (error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" ||
98
+ error.code === "ERR_UNSUPPORTED_DIR_IMPORT") &&
99
+ (error.message.includes(CODE_MODE_MODULE) ||
100
+ (error.message.includes("Package subpath './code-mode'") &&
101
+ error.message.includes(CODE_MODE_PACKAGE)))
102
+ );
13
103
  }