@oisin-ee/pi-dogsled 0.24.0 → 0.25.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,13 +13,13 @@ Install the binary on each Herdr host. Use the same release tag in each command.
13
13
  Binary:
14
14
 
15
15
  ```sh
16
- mise use github:oisin-ee/dogsled@v0.24.0
16
+ mise use github:oisin-ee/dogsled@v0.25.3
17
17
  ```
18
18
 
19
19
  Pi (extension, tools, and skill), from npm or as part of `@oisin-ee/oisinpi`:
20
20
 
21
21
  ```sh
22
- pi install npm:@oisin-ee/pi-dogsled@0.24.0
22
+ pi install npm:@oisin-ee/pi-dogsled@0.25.3
23
23
  ```
24
24
 
25
25
  At session start the extension compares its version with `dogsled --version` and warns when they differ.
@@ -27,14 +27,14 @@ At session start the extension compares its version with `dogsled --version` and
27
27
  Claude Code (hooks, tools, and skill):
28
28
 
29
29
  ```sh
30
- claude plugin marketplace add oisin-ee/dogsled#v0.24.0
30
+ claude plugin marketplace add oisin-ee/dogsled#v0.25.3
31
31
  claude plugin install dogsled@dogsled
32
32
  ```
33
33
 
34
34
  Codex (hooks, tools, and skill):
35
35
 
36
36
  ```sh
37
- codex plugin marketplace add oisin-ee/dogsled --ref v0.24.0
37
+ codex plugin marketplace add oisin-ee/dogsled --ref v0.25.3
38
38
  codex plugin add dogsled@dogsled
39
39
  ```
40
40
 
@@ -44,11 +44,27 @@ The [Codex CLI reference](https://developers.openai.com/codex/cli/reference#code
44
44
  Herdr (left-docked work board):
45
45
 
46
46
  ```sh
47
- herdr plugin install oisin-ee/dogsled --ref v0.24.0 --yes
47
+ herdr plugin install oisin-ee/dogsled --ref v0.25.3 --yes
48
48
  ```
49
49
 
50
50
  The Claude and Codex plugins use the binary on `PATH`. The Herdr plugin's build step (`plugin/fetch.sh`) installs its own binary at `bin/dogsled`: the release archive for the manifest version, checked against its published SHA-256. When that release has no archive for the platform, it runs `cargo build --release --locked` instead, which needs Rust at the crate's `rust-version` or newer. A checksum mismatch stops the install. `DOGSLED_RELEASES` replaces the download base, such as a mirror. `herdr plugin link` skips build steps, so run `sh plugin/fetch.sh` in a linked checkout. No plugin starts host services.
51
51
 
52
+ ## Web portal
53
+
54
+ Run the portal with `dogsled web`, then open `http://127.0.0.1:7465`.
55
+ The server listens only on the loopback address.
56
+ The port defaults to 7465. Set `[web] port` in `dogsled.toml`, or pass `dogsled web --port PORT`.
57
+ If the portal uses another port, set `DOGSLED_WEB_PORT` for the Pi tools so they can find it.
58
+
59
+ The portal creates its token at `~/.local/state/dogsled/web/token`, or `$DOGSLED_STATE/web/token` with a custom state directory.
60
+ Only the owner can read the token file. Agent API requests use it as a Bearer credential.
61
+ Release archives include `dev.dogsled.web.plist` for the macOS login service.
62
+ Dotfiles renders and loads the template. It runs `dogsled web` and restarts it after a failure.
63
+
64
+ Without a persistent portal, `dogsled interview --file questions.json` opens a temporary server and prints the answers as JSON.
65
+ `dogsled review --file plan.md --pane PANE --session SESSION --cwd DIR` opens a temporary server and prints the decision as JSON.
66
+ Both commands close their server after the interaction ends.
67
+
52
68
  ## Commands
53
69
 
54
70
  ```sh
@@ -637,6 +653,15 @@ cargo build --release
637
653
  npm ci
638
654
  ```
639
655
 
656
+ The server embeds the Dioxus portal UI, so the web bundle must exist before the binary builds.
657
+ `moon run :web-build` runs `dx bundle --web --release` and writes the bundle to `web/public`.
658
+ Run it before a plain `cargo build`:
659
+
660
+ ```sh
661
+ moon run :web-build
662
+ cargo build --release
663
+ ```
664
+
640
665
  Proto and moon own the development tooling. `proto install` installs the versions in `.prototools`, and `moon run` runs the checks:
641
666
 
642
667
  ```sh
@@ -644,10 +669,13 @@ proto install
644
669
  moon run :fmt-check :lint :test :typecheck :test-shim
645
670
  ```
646
671
 
672
+ The `lint` and `test` tasks build the web bundle first, so they work in a fresh checkout.
673
+
647
674
  The executable is `target/release/dogsled`.
648
- Release archives include the binary, `dogsled.service`, and `dev.dogsled.plist` from `plugin/services/`.
649
- Harness installers read their manifests and skill from Git, not the binary archive. The skill move does not change the archive contents.
650
- Both run `dogsled serve` through `~/.local/bin/mise`, restart on failure, and log to the dogsled state directory.
675
+ Release archives include the binary and three service templates from `plugin/services/`: `dogsled.service`, `dev.dogsled.plist`, and `dev.dogsled.web.plist`.
676
+ Harness installers read their manifests and skill from Git, not the binary archive.
677
+ The first two templates run `dogsled serve`. The web template runs `dogsled web`.
678
+ All three run through `~/.local/bin/mise`, restart on failure, and log to the dogsled state directory.
651
679
  Dotfiles installs the systemd user unit or renders the launchd template with an absolute, XML-escaped `@HOME@` path.
652
680
  For launchd, dotfiles creates `~/.local/state/dogsled` before loading the agent. Systemd creates it through `StateDirectory`.
653
681
  If mise has a different installation path, dotfiles adjusts the executable path.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oisin-ee/pi-dogsled",
3
- "version": "0.24.0",
3
+ "version": "0.25.3",
4
4
  "description": "Pi extension for dogsled: the board, the /dogsled panel, the inbox reader, and the dogsled tools. Needs the dogsled binary of the same version.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/pi/index.ts CHANGED
@@ -9,6 +9,9 @@ import { type Details, InboxReader, MESSAGE_TYPE } from "./inbox.ts";
9
9
  import { openPanel } from "./panel.ts";
10
10
  import { loadJobHistory, type JobHistory } from "./work-history.ts";
11
11
  import { WorkPanel, WorkDetail, runWorkAction, type WorkAction, type WorkCursor, type WorkData, type WorkTab } from "./work-panel.ts";
12
+ import { registerInterview } from "./interview.ts";
13
+ import { registerPlanMode } from "./plan-mode.ts";
14
+ import { PortalClient } from "./portal-client.ts";
12
15
 
13
16
  const REFRESH_MS = 10_000;
14
17
 
@@ -48,7 +51,16 @@ export default function dogsled(pi: ExtensionAPI) {
48
51
 
49
52
  const inbox = new InboxReader(pi, exec);
50
53
  const units = new UnitBridge(pi, binary);
51
- pi.on("tool_call", (event, ctx) => units.call(event, ctx));
54
+ // The portal owns the interactive parts of Pi: the interview form and the plan review.
55
+ const portal = new PortalClient();
56
+ const planMode = registerPlanMode(pi, portal);
57
+ const interviews = registerInterview(pi, portal);
58
+ // One handler owns the tool call: the unit bridge first, then the plan-mode gate.
59
+ pi.on("tool_call", async (event, ctx) => {
60
+ const result = await units.call(event, ctx);
61
+ if (result) return result;
62
+ return planMode.gate(event, ctx);
63
+ });
52
64
  pi.on("tool_execution_end", (event, ctx) => units.ended(event.toolCallId, ctx));
53
65
 
54
66
  pi.registerMessageRenderer<Details>(MESSAGE_TYPE, (message, { expanded, outputPad }, theme) => {
@@ -272,6 +284,9 @@ export default function dogsled(pi: ExtensionAPI) {
272
284
  });
273
285
  pi.on("session_shutdown", async (_event, ctx) => {
274
286
  units.stop();
287
+ planMode.stop();
288
+ planMode.stopWatching();
289
+ interviews.close();
275
290
  workPanel?.dispose();
276
291
  generation++;
277
292
  workAbort?.abort();
@@ -0,0 +1,382 @@
1
+ // The `interview` tool: the model asks the user a structured form, and the
2
+ // portal's form server carries the questions and the answers. The tool keeps
3
+ // the name, the parameters, and the result shape of pi-interview 0.13.0, so
4
+ // the model asks the way it always did. Only the transport differs: the form
5
+ // lives on the loopback portal server, not in a local window.
6
+ import { randomUUID } from "node:crypto";
7
+ import { readFileSync } from "node:fs";
8
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
9
+ import { tmpdir } from "node:os";
10
+ import { isAbsolute, join } from "node:path";
11
+ import type { AgentToolResult, ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent";
12
+ import { PortalClient, PortalDown, sleep, startOneShot } from "./portal-client.ts";
13
+
14
+ /** How long the tool waits between two polls for the answers. */
15
+ const POLL_MS = 500;
16
+
17
+ /** The parameter schema of pi-interview 0.13.0, so the model calls it the same way. */
18
+ const interviewParameters = {
19
+ type: "object",
20
+ required: ["questions"],
21
+ properties: {
22
+ questions: { type: "string", description: "Inline JSON string with questions, or path to a questions JSON file" },
23
+ timeout: { type: "number", description: "Seconds before auto-timeout", default: 600 },
24
+ verbose: { type: "boolean", description: "Enable debug logging", default: false },
25
+ async: { type: "boolean", description: "Return immediately instead of waiting for the user. The answer arrives later as a message tagged with the returned interview ID; keep working and do not poll.", default: false },
26
+ theme: {
27
+ type: "object",
28
+ properties: {
29
+ mode: { type: "string", enum: ["auto", "light", "dark"] },
30
+ name: { type: "string" },
31
+ lightPath: { type: "string" },
32
+ darkPath: { type: "string" },
33
+ toggleHotkey: { type: "string" },
34
+ },
35
+ additionalProperties: false,
36
+ },
37
+ },
38
+ } as const;
39
+
40
+ /** The tool description of pi-interview 0.13.0, unchanged. */
41
+ const interviewDescription =
42
+ "Present an interactive form to gather user responses. " +
43
+ "Opens in a configured Orca browser tab, a native macOS window (Glimpse), or a standard browser. " +
44
+ "Use proactively when: choosing between multiple approaches, gathering requirements before implementation, " +
45
+ "exploring design tradeoffs, or when decisions have multiple dimensions worth discussing. " +
46
+ "Provides better UX than back-and-forth chat for structured input. " +
47
+ "Image responses and attachments are returned as file paths - use read tool directly to display them. " +
48
+ "Pass questions as inline JSON string directly (preferred) or as a path to a JSON file. " +
49
+ 'Questions JSON format: { "title": "...", "description": "...", "questions": [{ "id": "q1", "type": "single|multi|text|image|info", "question": "...", "options": ["A", "B"], "content": { "source": "...", "lang": "ts" }, "media": { "type": "image|chart|mermaid|table|html", ... } }] }. ' +
50
+ "Options can be strings or objects: { label: string, content?: { source, lang?, file?, lines?, highlights?, title?, showSource? } }. " +
51
+ "Always set recommended with context explaining your reasoning. Recommended options show a 'Recommended' badge and are pre-selected for the user. " +
52
+ 'Use conviction: "slight" when unsure (does NOT pre-select), conviction: "strong" when very confident (shows Recommended badge). ' +
53
+ "Omit conviction for normal recommendations (pre-selects). " +
54
+ 'Use weight: "critical" for key decisions (visually prominent), weight: "minor" for low-stakes questions (compact card). ' +
55
+ "When questions have recommendations, set description to guide review (e.g., 'Review my suggestions and adjust as needed'). " +
56
+ "Questions can have a content field to display code or markdown above options. lang: \"md\" or \"markdown\" defaults to markdown preview unless showSource is true. Types: single (radio), multi (checkbox), text (textarea), image (file upload), info (non-interactive). " +
57
+ 'Media blocks: { type: "image", src, alt, caption }, { type: "table", table: { headers, rows, highlights }, caption }, { type: "chart", chart: { data, options }, caption }, { type: "mermaid", mermaid: "graph LR\\n..." }, { type: "html", html }. ' +
58
+ "Info type is a non-interactive content panel for displaying context with media. Media position: above (default), below, side (two-column).";
59
+
60
+ /** One answer to one question, as the portal returns it. */
61
+ export interface ResponseItem {
62
+ id: string;
63
+ value: string | string[] | { option: string; note?: string } | { option: string; note?: string }[];
64
+ attachments?: string[];
65
+ }
66
+
67
+ /** The result shape of pi-interview 0.13.0. */
68
+ export interface InterviewDetails {
69
+ status: "completed" | "cancelled" | "timeout" | "aborted" | "queued" | "started";
70
+ responses: ResponseItem[];
71
+ url: string;
72
+ }
73
+
74
+ /** One question of a form, as the model wrote it. */
75
+ export interface Question {
76
+ id: string;
77
+ type: "single" | "multi" | "text" | "image" | "info";
78
+ question: string;
79
+ }
80
+
81
+ /** A questions file, parsed. The portal renders it as a form. */
82
+ export type QuestionsFile = Record<string, unknown>;
83
+
84
+ function isChoiceValue(value: unknown): value is { option: string; note?: string } {
85
+ return typeof value === "object" && value !== null && !Array.isArray(value) && typeof (value as { option?: unknown }).option === "string";
86
+ }
87
+
88
+ /** The value of one answer, as the model reads it. */
89
+ function formatResponseValue(value: ResponseItem["value"]): string {
90
+ if (Array.isArray(value)) {
91
+ if (value.every(isChoiceValue)) return value.map(item => item.note ? `${item.option} (${item.note})` : item.option).join(", ");
92
+ return value.join(", ");
93
+ }
94
+ if (isChoiceValue(value)) return value.note ? `${value.option} (${value.note})` : value.option;
95
+ return value;
96
+ }
97
+
98
+ function hasAnswerValue(value: ResponseItem["value"]): boolean {
99
+ if (Array.isArray(value)) {
100
+ if (value.every(isChoiceValue)) return value.some(item => item.option.trim() !== "");
101
+ return value.some(item => typeof item === "string" && item.trim() !== "");
102
+ }
103
+ if (isChoiceValue(value)) return value.option.trim() !== "";
104
+ return typeof value === "string" && value.trim() !== "";
105
+ }
106
+
107
+ function hasAnswer(response: ResponseItem): boolean {
108
+ return hasAnswerValue(response.value) || Boolean(response.attachments?.length);
109
+ }
110
+
111
+ /** The answered questions, in the order the form asked them. */
112
+ function buildAnsweredResponses(responses: ResponseItem[], questions: Question[]): ResponseItem[] {
113
+ const byId = new Map(responses.filter(response => response && typeof response.id === "string").map(response => [response.id, response]));
114
+ return questions.flatMap(question => {
115
+ const response = byId.get(question.id);
116
+ if (!response || !hasAnswer(response)) return [];
117
+ return [response];
118
+ });
119
+ }
120
+
121
+ /** The answered questions as the model reads them: a summary and the structured data. */
122
+ function formatAnsweredResponses(responses: ResponseItem[], questions: Question[]): string {
123
+ const answered = buildAnsweredResponses(responses, questions);
124
+ if (answered.length === 0) return "(none)";
125
+ const questionById = new Map(questions.map(question => [question.id, question]));
126
+ const summary = answered.map(response => {
127
+ const question = questionById.get(response.id);
128
+ if (!question) return `- ${response.id}`;
129
+ let line = `- ${question.question}: ${formatResponseValue(response.value)}`;
130
+ if (response.attachments?.length) line += ` [attachments: ${response.attachments.join(", ")}]`;
131
+ return line;
132
+ }).join("\n");
133
+ return `${summary}\n\nStructured response data:\n\n\`\`\`json\n${JSON.stringify(answered, null, 2)}\n\`\`\``;
134
+ }
135
+
136
+ /**
137
+ * The questions of a form, read from the inline JSON or from a questions file.
138
+ * The model may pass either form, as pi-interview does. The file is read
139
+ * relative to the working directory, and a broken file is an error before any
140
+ * call to the portal.
141
+ */
142
+ export function loadQuestions(input: string, cwd: string): QuestionsFile {
143
+ const trimmed = input.trimStart();
144
+ const inline = trimmed.startsWith("{") || /^`{3,}(?:json|jsonc)?\s*\n?\s*\{/i.test(trimmed);
145
+ const text = inline ? trimmed : readQuestionsFile(input, cwd);
146
+ const data = parseQuestionsJson(text);
147
+ validateQuestionsFile(data);
148
+ return data;
149
+ }
150
+
151
+ /** The questions of a form, in the order the form asks them. */
152
+ function formQuestions(file: QuestionsFile): Question[] {
153
+ const list = file["questions"];
154
+ if (!Array.isArray(list)) return [];
155
+ return list.flatMap(entry => {
156
+ const question = (entry ?? {}) as Partial<Question>;
157
+ if (typeof question.id !== "string" || typeof question.question !== "string") return [];
158
+ return [{ id: question.id, type: questionType(question.type), question: question.question }];
159
+ });
160
+ }
161
+
162
+ /** The type of a question, when it is one the form knows. */
163
+ function questionType(value: unknown): Question["type"] {
164
+ return value === "single" || value === "multi" || value === "text" || value === "image" || value === "info" ? value : "text";
165
+ }
166
+
167
+ /** Read the questions file, or say that it is not there. */
168
+ function readQuestionsFile(input: string, cwd: string): string {
169
+ const path = resolveQuestionPath(input, cwd);
170
+ try { return readFileSync(path, "utf8"); }
171
+ catch (error) {
172
+ const code = (error as { code?: string }).code;
173
+ if (code === "ENOENT") throw new Error(`Questions file not found: ${path}`);
174
+ throw new Error(`Cannot read the questions file ${path}: ${error instanceof Error ? error.message : String(error)}`);
175
+ }
176
+ }
177
+
178
+ /** The JSON text of a questions file, without the code fence a model may wrap it in. */
179
+ function questionsJsonText(text: string): string {
180
+ const json = text.trim();
181
+ const fence = json.match(/^`{3,}(?:json|jsonc)?\s*\n([\s\S]*?)\n\s*`{3,}\s*$/i);
182
+ return (fence ? (fence[1] ?? "") : json).trim();
183
+ }
184
+
185
+ /** The parsed questions, or an error that names the problem. */
186
+ function parseQuestionsJson(text: string): unknown {
187
+ try { return JSON.parse(questionsJsonText(text)); }
188
+ catch (error) { throw new Error(`Invalid questions JSON: ${error instanceof Error ? error.message : String(error)}`); }
189
+ }
190
+
191
+ /** The parsed questions must be a file with a questions array. */
192
+ function validateQuestionsFile(data: unknown): asserts data is QuestionsFile {
193
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("Invalid questions JSON: no questions object");
194
+ const list = (data as { questions?: unknown }).questions;
195
+ if (!Array.isArray(list)) throw new Error("Invalid questions JSON: no questions array");
196
+ list.forEach((entry, index) => {
197
+ const question = (entry ?? {}) as Partial<Question>;
198
+ if (typeof question.id !== "string" || typeof question.question !== "string") throw new Error(`Invalid questions JSON: question ${index} has no id or question`);
199
+ });
200
+ }
201
+
202
+ function resolveQuestionPath(input: string, cwd: string): string {
203
+ const expanded = input.startsWith("~/") ? join(process.env["HOME"] ?? "", input.slice(2)) : input;
204
+ return isAbsolute(expanded) ? expanded : join(cwd, expanded);
205
+ }
206
+
207
+ /**
208
+ * The answers the portal returns. The contract is one body: the id of the
209
+ * form, and the responses of the form. The questions are not part of it, so
210
+ * the tool names the answers from the questions the model sent. Any other
211
+ * body is an error that names the shape it expected.
212
+ */
213
+ function parseAnswers(value: unknown): ResponseItem[] {
214
+ const payload = value as { id?: unknown; responses?: unknown } | null;
215
+ if (!payload || typeof payload !== "object" || Array.isArray(payload) || typeof payload.id !== "string" || !Array.isArray(payload.responses)) {
216
+ throw new Error('dogsled web returned an unexpected answer shape: expected {"id": string, "responses": ResponseItem[]}');
217
+ }
218
+ return payload.responses.filter(isResponseItem);
219
+ }
220
+
221
+ /** One answer of the portal, in the shape the contract names. */
222
+ function isResponseItem(value: unknown): value is ResponseItem {
223
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
224
+ const item = value as { id?: unknown; value?: unknown; attachments?: unknown };
225
+ if (typeof item.id !== "string" || item.value === undefined) return false;
226
+ return item.attachments === undefined || Array.isArray(item.attachments);
227
+ }
228
+
229
+ /** The `interview` tool: ask the user a form through the portal and wait for the answers. */
230
+ export class InterviewTool {
231
+ private readonly client: PortalClient;
232
+ private readonly deliver: (content: string) => void;
233
+ /** The background waits of the async interviews, so the session can close them. */
234
+ private readonly pending = new Set<AbortController>();
235
+ constructor(client: PortalClient = new PortalClient(), deliver: (content: string) => void = () => undefined) {
236
+ this.client = client;
237
+ this.deliver = deliver;
238
+ }
239
+
240
+ /** Run one interview. The tool's `signal` withdraws the form. */
241
+ async run(params: { questions: string; timeout?: number; verbose?: boolean; async?: boolean }, ctx: ExtensionToolContext, signal: AbortSignal | undefined): Promise<AgentToolResult<InterviewDetails>> {
242
+ const cwd = ctx.cwd;
243
+ const session = ctx.sessionManager.getSessionId();
244
+ const pane = process.env["HERDR_PANE_ID"] ?? "";
245
+ // The questions are parsed before the call, so a broken file or bad JSON
246
+ // is a tool error and never reaches the portal.
247
+ const file = loadQuestions(params.questions, cwd);
248
+ let created: { id?: unknown };
249
+ try {
250
+ created = await this.client.json<{ id?: unknown }>("POST", "/api/questions", {
251
+ questions: file, pane, session, cwd,
252
+ }, signal);
253
+ } catch (error) {
254
+ if (!(error instanceof PortalDown)) throw error;
255
+ return this.fallback(file, params, ctx, signal);
256
+ }
257
+ const id = typeof created?.id === "string" ? created.id : "";
258
+ if (!id) throw new Error("dogsled web did not return an interview id");
259
+
260
+ if (params.async) {
261
+ // The form runs on its own: the tool's own signal no longer owns it, and the
262
+ // answers arrive as a message, like pi-interview does.
263
+ const own = new AbortController();
264
+ this.pending.add(own);
265
+ void this.wait(id, file, own.signal, params.timeout)
266
+ .then(answers => { this.deliver(`Interview ${id} finished.\n\n${answers.text}`); })
267
+ .catch(error => { this.deliver(`Interview ${id} did not finish: ${error instanceof Error ? error.message : String(error)}`); })
268
+ .finally(() => { this.pending.delete(own); });
269
+ return {
270
+ content: [{ type: "text", text: `Interview ${id} started. The answer arrives later as a message; keep working and do not poll.` }],
271
+ details: { status: "started", responses: [], url: "" },
272
+ };
273
+ }
274
+
275
+ try {
276
+ const answers = await this.wait(id, file, signal, params.timeout);
277
+ return {
278
+ content: [{ type: "text", text: `User completed the interview form.\n\nAnswered responses:\n${answers.text}` }],
279
+ details: { status: "completed", responses: answers.responses, url: "" },
280
+ };
281
+ } catch (error) {
282
+ // An aborted interview withdraws its form, so the portal does not wait for an answer.
283
+ if (signal?.aborted) {
284
+ await this.client.request("DELETE", `/api/questions/${encodeURIComponent(id)}`).catch(() => undefined);
285
+ return { content: [{ type: "text", text: "Interview was aborted." }], details: { status: "aborted", responses: [], url: "" } };
286
+ }
287
+ throw error;
288
+ }
289
+ }
290
+
291
+ /** Run the same form on a temporary server when the portal cannot be reached. */
292
+ private async fallback(file: QuestionsFile, params: { timeout?: number; async?: boolean }, ctx: ExtensionToolContext, signal: AbortSignal | undefined): Promise<AgentToolResult<InterviewDetails>> {
293
+ const directory = await mkdtemp(join(tmpdir(), "dogsled-interview-"));
294
+ const own = new AbortController();
295
+ const abort = params.async || !signal ? own.signal : AbortSignal.any([own.signal, signal]);
296
+ this.pending.add(own);
297
+ let background = false;
298
+ try {
299
+ const path = join(directory, "questions.json");
300
+ await writeFile(path, JSON.stringify(file), { mode: 0o600 });
301
+ const command = startOneShot([
302
+ "interview", "--file", path, "--pane", process.env["HERDR_PANE_ID"] ?? "",
303
+ "--session", ctx.sessionManager.getSessionId(), "--cwd", ctx.cwd,
304
+ "--timeout", String(Math.max(1, Math.ceil(params.timeout ?? 600))),
305
+ ], this.client.env, abort);
306
+ await command.started;
307
+ const answer = command.result.then(stdout => parseAnswers(JSON.parse(stdout)));
308
+ if (params.async) {
309
+ const id = randomUUID();
310
+ background = true;
311
+ void answer.finally(async () => {
312
+ this.pending.delete(own);
313
+ await rm(directory, { recursive: true, force: true });
314
+ }).then(responses => {
315
+ this.deliver(`Interview ${id} finished.\n\n${formatAnsweredResponses(responses, formQuestions(file))}`);
316
+ }).catch(error => {
317
+ if (!own.signal.aborted) this.deliver(`Interview ${id} did not finish: ${error instanceof Error ? error.message : String(error)}`);
318
+ });
319
+ return {
320
+ content: [{ type: "text", text: `Interview ${id} started. The answer arrives later as a message; keep working and do not poll.` }],
321
+ details: { status: "started", responses: [], url: "" },
322
+ };
323
+ }
324
+ const responses = await answer;
325
+ return {
326
+ content: [{ type: "text", text: `User completed the interview form.\n\nAnswered responses:\n${formatAnsweredResponses(responses, formQuestions(file))}` }],
327
+ details: { status: "completed", responses, url: "" },
328
+ };
329
+ } catch (error) {
330
+ if (abort.aborted) return { content: [{ type: "text", text: "Interview was aborted." }], details: { status: "aborted", responses: [], url: "" } };
331
+ throw error;
332
+ } finally {
333
+ if (!background) {
334
+ this.pending.delete(own);
335
+ await rm(directory, { recursive: true, force: true });
336
+ }
337
+ }
338
+ }
339
+
340
+ /** Close the background waits of the async interviews. */
341
+ close(): void {
342
+ for (const controller of this.pending) controller.abort();
343
+ this.pending.clear();
344
+ }
345
+
346
+ /** Poll the portal until it has the answers, the form is withdrawn, or the wait ends. */
347
+ private async wait(id: string, file: QuestionsFile, signal: AbortSignal | undefined, timeout: number | undefined): Promise<{ text: string; responses: ResponseItem[] }> {
348
+ const seconds = timeout ?? 600;
349
+ const deadline = Date.now() + Math.max(1, seconds) * 1000;
350
+ for (;;) {
351
+ if (signal?.aborted) throw new Error("Interview was aborted.");
352
+ const response = await this.client.request("GET", `/api/questions/${encodeURIComponent(id)}/answer`, { signal });
353
+ if (response.status === 204) {
354
+ if (Date.now() >= deadline) throw new Error(`Interview form timed out after ${seconds} seconds.`);
355
+ await sleep(POLL_MS, signal);
356
+ continue;
357
+ }
358
+ if (response.status === 410) throw new Error("The interview form was withdrawn before it was answered.");
359
+ if (!response.ok) throw new Error(`dogsled web GET /api/questions/${id}/answer failed: ${response.status} ${(await response.text()).trim()}`);
360
+ const responses = parseAnswers(await response.json());
361
+ return { text: formatAnsweredResponses(responses, formQuestions(file)), responses };
362
+ }
363
+ }
364
+ }
365
+
366
+ /** Register the `interview` tool. */
367
+ export function registerInterview(pi: ExtensionAPI, client: PortalClient = new PortalClient()): InterviewTool {
368
+ const tool = new InterviewTool(client, content => { pi.sendUserMessage(content); });
369
+ pi.registerTool({
370
+ name: "interview",
371
+ label: "Interview",
372
+ description: interviewDescription,
373
+ promptSnippet: "Gather structured user input through an interactive form for requirements, tradeoffs, or multi-dimensional decisions.",
374
+ parameters: interviewParameters,
375
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
376
+ const question = params as { questions?: unknown };
377
+ if (typeof question.questions !== "string" || !question.questions) throw new Error("interview needs the questions, as inline JSON or a path to a questions file");
378
+ return await tool.run(question as { questions: string }, ctx, signal);
379
+ },
380
+ });
381
+ return tool;
382
+ }
@@ -0,0 +1,343 @@
1
+ // Plan mode: the model explores read-only, writes one markdown plan, and sends
2
+ // it to the portal for review. The decision comes back later, as a message.
3
+ // While planning, the gate stops the model from changing anything but a
4
+ // markdown file. It is a guard against mistakes, not a sandbox: it can be
5
+ // wrong, and it does not cover every tool that can change a file.
6
+ import { readFile } from "node:fs/promises";
7
+ import { extname, isAbsolute, relative, resolve, sep } from "node:path";
8
+ import type { ExtensionAPI, ExtensionContext, ToolCallEvent, ToolCallEventResult } from "@earendil-works/pi-coding-agent";
9
+ import { Key } from "@earendil-works/pi-tui";
10
+ import { PortalClient, PortalDown, sleep, startOneShot } from "./portal-client.ts";
11
+
12
+ /** The tool that sends a plan to the portal. */
13
+ const SUBMIT_PLAN = "submit_plan";
14
+
15
+ /** The custom message the framing note joins the conversation as. */
16
+ const PLAN_MODE_MESSAGE = "dogsled:plan-mode";
17
+
18
+ /** The file types the gate lets the model write while planning. */
19
+ const PLAN_EXTENSIONS = new Set([".md", ".mdx"]);
20
+
21
+ /** The message the model reads when planning starts. */
22
+ const PLANNING_MESSAGE =
23
+ "Plan mode is on. Explore the repository read-only: read files, search, and run read-only commands. " +
24
+ "Write the plan as one markdown file in the working directory, then call submit_plan with that file. " +
25
+ "Do not change any other file until the plan is approved.";
26
+
27
+ /** The bash commands the gate blocks while planning. */
28
+ const BLOCKED_COMMANDS = ["tee", "rm", "mv", "cp", "mkdir", "touch", "sed -i", "git commit", "git push", "git checkout", "git reset", "npm install"];
29
+
30
+ /** The portal's decision about one plan. */
31
+ export interface Decision {
32
+ review_id: string;
33
+ path: string;
34
+ decision: "approved" | "changes_requested";
35
+ message: string;
36
+ plan_content: string;
37
+ }
38
+
39
+ /** The payload the plan-approved event carries, as pi-todo consumes it. */
40
+ export interface PlanApproved {
41
+ cwd: string;
42
+ planFilePath: string;
43
+ planContent: string;
44
+ feedback?: string;
45
+ }
46
+
47
+ /** The parts of the extension API that plan mode uses. */
48
+ export interface PlanHost {
49
+ events: ExtensionAPI["events"];
50
+ sendUserMessage(content: string, options?: { deliverAs?: "steer" | "followUp" }): void;
51
+ sendMessage(message: { customType: string; content: string; display: boolean }, options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" }): void;
52
+ getActiveTools(): string[];
53
+ setActiveTools(names: string[]): void;
54
+ }
55
+
56
+ /** Whether a path stays inside the working directory and ends in a plan file type. */
57
+ export function planPathAllowed(path: string, cwd: string): boolean {
58
+ if (!path) return false;
59
+ const target = isAbsolute(path) ? resolve(path) : resolve(cwd, path);
60
+ const inside = relative(cwd, target);
61
+ if (inside.startsWith("..") || inside.split(sep).includes("..")) return false;
62
+ return PLAN_EXTENSIONS.has(extname(target).toLowerCase());
63
+ }
64
+
65
+ /** The quoted parts of a command, which are text and not shell syntax. */
66
+ function withoutQuoted(command: string): string {
67
+ return command.replace(/'[^']*'/g, "''").replace(/"[^"]*"/g, '""');
68
+ }
69
+
70
+ /** Why a bash command is blocked while planning, or undefined when it is allowed. */
71
+ export function bashBlocked(command: string): string | undefined {
72
+ const text = withoutQuoted(command);
73
+ // Every write redirect, unless it only throws the output away or duplicates a descriptor.
74
+ for (const match of text.matchAll(/>>?/g)) {
75
+ const rest = text.slice(match.index + match[0].length).trimStart();
76
+ if (rest.startsWith("/dev/null") || rest.startsWith("&")) continue;
77
+ return "a write redirect";
78
+ }
79
+ for (const blocked of BLOCKED_COMMANDS) {
80
+ const pattern = new RegExp(`(?:^|[;&|(\\s])${blocked.replace(/[ -]/g, "\\$&")}(?![\\w-])`, "m");
81
+ if (pattern.test(text)) return blocked;
82
+ }
83
+ return undefined;
84
+ }
85
+
86
+ /** The path a write or edit tool call targets. */
87
+ function targetPath(input: unknown): string {
88
+ if (typeof input !== "object" || input === null) return "";
89
+ const path = (input as { path?: unknown }).path;
90
+ return typeof path === "string" ? path : "";
91
+ }
92
+
93
+ /** The command a bash tool call runs. */
94
+ function bashCommand(input: unknown): string {
95
+ if (typeof input !== "object" || input === null) return "";
96
+ const command = (input as { command?: unknown }).command;
97
+ return typeof command === "string" ? command : "";
98
+ }
99
+
100
+ /** The reason a tool call is blocked while planning, or undefined when it is allowed. */
101
+ function planningBlock(event: ToolCallEvent, cwd: string): string | undefined {
102
+ if (event.toolName === "write" || event.toolName === "edit") {
103
+ const path = targetPath(event.input);
104
+ if (!planPathAllowed(path, cwd)) return `Planning is on: ${event.toolName} may only change a markdown file (.md or .mdx) inside ${cwd}. The target was ${path || "(no path)"}.`;
105
+ return undefined;
106
+ }
107
+ if (event.toolName === "bash") {
108
+ const blocked = bashBlocked(bashCommand(event.input));
109
+ if (blocked) return `Planning is on: this command uses ${blocked}, which changes files. Explore read-only until the plan is approved.`;
110
+ }
111
+ return undefined;
112
+ }
113
+
114
+ interface ReviewCreated { id: string; revision: number }
115
+
116
+ /** The plan-mode state of one Pi session. */
117
+ export class PlanMode {
118
+ private readonly pi: PlanHost;
119
+ private readonly client: PortalClient;
120
+ private planning = false;
121
+ private framed = false;
122
+ private watching: AbortController | undefined;
123
+ private readonly pending = new Set<AbortController>();
124
+ /** The reviews this session already delivered, so a reconnect never delivers one twice. */
125
+ private readonly delivered = new Set<string>();
126
+ /** The reviews the portal acknowledged. A review that was delivered but not acked is acked again, not delivered again. */
127
+ private readonly acked = new Set<string>();
128
+
129
+ constructor(pi: PlanHost, client: PortalClient = new PortalClient()) {
130
+ this.pi = pi;
131
+ this.client = client;
132
+ }
133
+
134
+ /** Whether the model is planning. */
135
+ get active(): boolean { return this.planning; }
136
+
137
+ /** Enter or leave planning. Entering frames the task once and shows the submit tool. */
138
+ toggle(): void {
139
+ if (this.planning) this.stop();
140
+ else this.start();
141
+ }
142
+
143
+ /** Enter planning: frame the task, and make the submit tool the only plan tool. */
144
+ start(): void {
145
+ this.planning = true;
146
+ this.activate();
147
+ if (this.framed) return;
148
+ this.framed = true;
149
+ // A conversation message, not a system prompt change: the plan mode frames the task
150
+ // for this turn only, and the system prompt stays as the session wrote it.
151
+ this.pi.sendMessage({ customType: PLAN_MODE_MESSAGE, content: PLANNING_MESSAGE, display: true }, { triggerTurn: true });
152
+ }
153
+
154
+ /** Leave planning: hide the submit tool. */
155
+ stop(): void {
156
+ this.planning = false;
157
+ this.deactivate();
158
+ }
159
+
160
+ /** The tool call gate. It blocks changes while planning and lets everything else through. */
161
+ gate(event: ToolCallEvent, ctx: ExtensionContext): ToolCallEventResult | undefined {
162
+ if (!this.planning) return undefined;
163
+ const reason = planningBlock(event, ctx.cwd);
164
+ if (!reason) return undefined;
165
+ return { block: true, reason };
166
+ }
167
+
168
+ /** Send a plan to the portal and start waiting for its decision. */
169
+ async submit(filePath: string, ctx: ExtensionContext): Promise<ReviewCreated | { fallback: true }> {
170
+ const path = isAbsolute(filePath) ? filePath : resolve(ctx.cwd, filePath);
171
+ const content = await readFile(path, "utf8");
172
+ let created: ReviewCreated;
173
+ try {
174
+ created = await this.client.json<ReviewCreated>("POST", "/api/reviews", {
175
+ path, content, pane: process.env["HERDR_PANE_ID"] ?? "",
176
+ session: ctx.sessionManager.getSessionId(), cwd: ctx.cwd,
177
+ });
178
+ } catch (error) {
179
+ if (!(error instanceof PortalDown)) throw error;
180
+ await this.fallback(path, ctx);
181
+ return { fallback: true };
182
+ }
183
+ const id = typeof created?.id === "string" ? created.id : "";
184
+ const revision = Number(created?.revision);
185
+ if (!id || !Number.isFinite(revision)) throw new Error("dogsled web did not return a review id and revision");
186
+ this.watch(ctx);
187
+ return { id, revision };
188
+ }
189
+
190
+ /** Start a temporary review server without holding the tool call open. */
191
+ private async fallback(path: string, ctx: ExtensionContext): Promise<void> {
192
+ const controller = new AbortController();
193
+ this.pending.add(controller);
194
+ const command = startOneShot([
195
+ "review", "--file", path, "--pane", process.env["HERDR_PANE_ID"] ?? "",
196
+ "--session", ctx.sessionManager.getSessionId(), "--cwd", ctx.cwd,
197
+ ], this.client.env, controller.signal);
198
+ try { await command.started; }
199
+ catch (error) { this.pending.delete(controller); throw error; }
200
+ void command.result.then(stdout => this.decision(stdout, ctx, false))
201
+ .catch(error => {
202
+ if (!controller.signal.aborted) {
203
+ const message = `Plan review did not finish: ${error instanceof Error ? error.message : String(error)}`;
204
+ this.pi.sendUserMessage(message, ctx.isIdle() ? undefined : { deliverAs: "steer" });
205
+ }
206
+ })
207
+ .finally(() => { this.pending.delete(controller); });
208
+ }
209
+
210
+ /** Hold one decisions stream open until the session ends. */
211
+ private watch(ctx: ExtensionContext): void {
212
+ if (this.watching) return;
213
+ const controller = new AbortController();
214
+ this.watching = controller;
215
+ const session = ctx.sessionManager.getSessionId();
216
+ void this.stream(session, controller.signal, ctx);
217
+ }
218
+
219
+ /** Close the decisions stream. */
220
+ stopWatching(): void {
221
+ this.watching?.abort();
222
+ this.watching = undefined;
223
+ for (const controller of this.pending) controller.abort();
224
+ this.pending.clear();
225
+ }
226
+
227
+ private async stream(session: string, signal: AbortSignal, ctx: ExtensionContext): Promise<void> {
228
+ let backoff = 500;
229
+ while (!signal.aborted) {
230
+ try {
231
+ const events = await this.client.events(`/api/sessions/${encodeURIComponent(session)}/decisions`, signal);
232
+ for await (const event of events) {
233
+ if (signal.aborted) break;
234
+ if (event.event !== "decision") continue;
235
+ await this.decision(event.data, ctx);
236
+ }
237
+ backoff = 500;
238
+ } catch {
239
+ // The portal may be restarting. Reconnect with a longer wait.
240
+ }
241
+ if (signal.aborted) break;
242
+ await sleep(backoff, signal);
243
+ backoff = Math.min(backoff * 2, 30_000);
244
+ }
245
+ }
246
+
247
+ /** Deliver one decision, acknowledge it, and hand the approved plan on. */
248
+ async decision(payload: string, ctx: ExtensionContext, acknowledge = true): Promise<void> {
249
+ let decision: Partial<Decision> | null;
250
+ try { decision = JSON.parse(payload) as Partial<Decision> | null; }
251
+ catch {
252
+ if (!acknowledge) throw new Error("dogsled review returned invalid decision JSON");
253
+ return;
254
+ }
255
+ if (!decision || typeof decision.review_id !== "string" || !decision.review_id
256
+ || (decision.decision !== "approved" && decision.decision !== "changes_requested")
257
+ || typeof decision.path !== "string" || typeof decision.message !== "string" || typeof decision.plan_content !== "string") {
258
+ if (!acknowledge) throw new Error("dogsled review returned an unexpected decision shape");
259
+ return;
260
+ }
261
+ const review = decision.review_id;
262
+ // A review the portal did not acknowledge is acked again, never delivered again.
263
+ if (!this.delivered.has(review)) {
264
+ this.delivered.add(review);
265
+ const message = typeof decision.message === "string" ? decision.message : "";
266
+ if (message) {
267
+ // A running agent is steered, so the message joins the turn that is running.
268
+ if (ctx.isIdle()) this.pi.sendUserMessage(message);
269
+ else this.pi.sendUserMessage(message, { deliverAs: "steer" });
270
+ }
271
+ if (decision.decision === "approved") {
272
+ const approved: PlanApproved = {
273
+ cwd: ctx.cwd,
274
+ planFilePath: typeof decision.path === "string" ? decision.path : "",
275
+ planContent: typeof decision.plan_content === "string" ? decision.plan_content : "",
276
+ ...(message ? { feedback: message } : {}),
277
+ };
278
+ this.pi.events.emit("dogsled:plan-approved", approved);
279
+ this.stop();
280
+ }
281
+ }
282
+ // The one-shot command acknowledges its own decision before exiting.
283
+ if (!acknowledge || this.acked.has(review)) return;
284
+ await this.client.json<unknown>("POST", `/api/decisions/${encodeURIComponent(review)}/ack`).catch(() => undefined);
285
+ this.acked.add(review);
286
+ }
287
+
288
+ /** Show the submit tool while planning. */
289
+ private activate(): void {
290
+ const active = this.pi.getActiveTools();
291
+ if (!active.includes(SUBMIT_PLAN)) this.pi.setActiveTools([...active, SUBMIT_PLAN]);
292
+ }
293
+
294
+ /** Hide the submit tool again. */
295
+ private deactivate(): void {
296
+ const active = this.pi.getActiveTools();
297
+ if (active.includes(SUBMIT_PLAN)) this.pi.setActiveTools(active.filter(name => name !== SUBMIT_PLAN));
298
+ }
299
+ }
300
+
301
+ /** Register the plan mode: the submit tool, the command, and the shortcut. */
302
+ export function registerPlanMode(pi: ExtensionAPI, client: PortalClient = new PortalClient()): PlanMode {
303
+ const host: PlanHost = {
304
+ events: pi.events,
305
+ sendUserMessage: (content, options) => { pi.sendUserMessage(content, options); },
306
+ sendMessage: (message, options) => { pi.sendMessage(message, options); },
307
+ getActiveTools: () => pi.getActiveTools(),
308
+ setActiveTools: names => { pi.setActiveTools(names); },
309
+ };
310
+ const mode = new PlanMode(host, client);
311
+ pi.registerTool({
312
+ name: SUBMIT_PLAN,
313
+ label: "Submit plan",
314
+ description: "Send the plan file to the portal for review. Write the plan as one markdown file in the working directory, then call this with its path. The decision arrives later as a message.",
315
+ promptSnippet: "Send a written plan for review and wait for the decision.",
316
+ parameters: {
317
+ type: "object",
318
+ required: ["filePath"],
319
+ properties: { filePath: { type: "string", description: "Path of the markdown plan file, absolute or relative to the working directory" } },
320
+ } as const,
321
+ // The tool belongs to planning only, so it is declared to the model while planning runs.
322
+ defaultActive: false,
323
+ executionMode: "sequential",
324
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
325
+ const filePath = (params as { filePath?: unknown }).filePath;
326
+ if (typeof filePath !== "string" || !filePath) throw new Error("submit_plan needs the path of the plan file");
327
+ const review = await mode.submit(filePath, ctx);
328
+ return {
329
+ content: [{ type: "text", text: `${"fallback" in review ? "Started a review in a browser tab" : `Pushed as revision ${review.revision}`}; the decision arrives later as a message; end your turn.` }],
330
+ details: review,
331
+ };
332
+ },
333
+ });
334
+ pi.registerCommand("plan", {
335
+ description: "Toggle plan mode (Ctrl+Alt+P)",
336
+ handler: async () => { mode.toggle(); },
337
+ });
338
+ pi.registerShortcut(Key.ctrlAlt("p"), {
339
+ description: "Toggle plan mode",
340
+ handler: async () => { mode.toggle(); },
341
+ });
342
+ return mode;
343
+ }
@@ -0,0 +1,187 @@
1
+ // The client for the loopback portal server, `dogsled web`. The portal owns the
2
+ // interactive parts of Pi: the interview form and the plan review. This module
3
+ // only speaks HTTP to it. Every call carries the portal's bearer token, and the
4
+ // server answers with the board, a form, a review, or a decision.
5
+ import { spawn } from "node:child_process";
6
+ import { readFileSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
9
+
10
+ const DEFAULT_PORT = 7465;
11
+
12
+ /** `dogsled web` could not be reached, or its token file is missing. */
13
+ export class PortalDown extends Error {
14
+ constructor(detail: string) {
15
+ super(`dogsled web is not running (${detail}). Start it with \`dogsled web\`.`);
16
+ this.name = "PortalDown";
17
+ }
18
+ }
19
+
20
+ /** The port `dogsled web` listens on: `DOGSLED_WEB_PORT`, else 7465. */
21
+ function portalPort(env: NodeJS.ProcessEnv): number {
22
+ const port = Number(env["DOGSLED_WEB_PORT"]);
23
+ return Number.isInteger(port) && port > 0 && port < 65536 ? port : DEFAULT_PORT;
24
+ }
25
+
26
+ /** The dogsled state directory: `DOGSLED_STATE`, else `$XDG_STATE_HOME/dogsled`, else `~/.local/state/dogsled`. */
27
+ function stateDirectory(env: NodeJS.ProcessEnv): string {
28
+ const state = env["DOGSLED_STATE"];
29
+ if (state) return state;
30
+ const xdg = env["XDG_STATE_HOME"];
31
+ if (xdg) return join(xdg, "dogsled");
32
+ return join(homedir(), ".local", "state", "dogsled");
33
+ }
34
+
35
+ /** One Server-Sent Event: its name and its data. */
36
+ interface ServerEvent { event: string; data: string }
37
+
38
+ /** Parse a Server-Sent Events stream into events. Comments and unnamed fields are skipped. */
39
+ async function* serverEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<ServerEvent> {
40
+ const reader = body.getReader();
41
+ const decoder = new TextDecoder();
42
+ let buffer = "";
43
+ let event = "message";
44
+ let data: string[] = [];
45
+ const take = (): ServerEvent | undefined => {
46
+ if (!data.length) { event = "message"; return undefined; }
47
+ const out = { event, data: data.join("\n") };
48
+ event = "message";
49
+ data = [];
50
+ return out;
51
+ };
52
+ const line = (text: string): void => {
53
+ if (!text || text.startsWith(":")) return;
54
+ const colon = text.indexOf(":");
55
+ const field = colon < 0 ? text : text.slice(0, colon);
56
+ let value = colon < 0 ? "" : text.slice(colon + 1);
57
+ if (value.startsWith(" ")) value = value.slice(1);
58
+ if (field === "event") event = value;
59
+ else if (field === "data") data.push(value);
60
+ };
61
+ try {
62
+ for (;;) {
63
+ const { done, value } = await reader.read();
64
+ if (done) break;
65
+ buffer += decoder.decode(value, { stream: true });
66
+ for (;;) {
67
+ const index = buffer.search(/\r\n|\r|\n/);
68
+ if (index < 0) break;
69
+ // A trailing "\r" may be the first half of "\r\n"; wait for the next chunk.
70
+ if (buffer[index] === "\r" && index + 1 === buffer.length) break;
71
+ const separator = /^\r\n|^\r|^\n/.exec(buffer.slice(index))?.[0] ?? "\n";
72
+ const text = buffer.slice(0, index);
73
+ buffer = buffer.slice(index + separator.length);
74
+ line(text);
75
+ if (text === "") { const out = take(); if (out) yield out; }
76
+ }
77
+ }
78
+ if (buffer) line(buffer);
79
+ const out = take();
80
+ if (out) yield out;
81
+ } finally {
82
+ await reader.cancel().catch(() => undefined);
83
+ }
84
+ }
85
+
86
+ /** The HTTP client for the loopback portal server. Every call carries the bearer token. */
87
+ export class PortalClient {
88
+ readonly env: NodeJS.ProcessEnv;
89
+ constructor(env: NodeJS.ProcessEnv = process.env) { this.env = env; }
90
+
91
+ /** The port this client talks to. */
92
+ get port(): number { return portalPort(this.env); }
93
+
94
+ /** The portal's bearer token, read from the state directory. */
95
+ token(): string {
96
+ const file = join(stateDirectory(this.env), "web", "token");
97
+ try { return readFileSync(file, "utf8").trim(); }
98
+ catch { throw new PortalDown(`no token at ${file}`); }
99
+ }
100
+
101
+ /** Send a request. A server that cannot be reached is a `PortalDown` error; an aborted `signal` keeps its own error. */
102
+ async request(method: string, path: string, options: { body?: unknown; signal?: AbortSignal | undefined; accept?: string } = {}): Promise<Response> {
103
+ const headers: Record<string, string> = {
104
+ // The bearer token is what the portal checks: a valid token passes a
105
+ // state-changing request without an Origin header.
106
+ authorization: `Bearer ${this.token()}`,
107
+ };
108
+ if (options.accept) headers["accept"] = options.accept;
109
+ const init: RequestInit = { method, headers };
110
+ if (options.body !== undefined) {
111
+ headers["content-type"] = "application/json";
112
+ init.body = JSON.stringify(options.body);
113
+ }
114
+ if (options.signal) init.signal = options.signal;
115
+ try {
116
+ return await fetch(`http://127.0.0.1:${this.port}${path}`, init);
117
+ } catch (error) {
118
+ if (options.signal?.aborted) throw error;
119
+ const cause = error instanceof Error ? error.cause : undefined;
120
+ const detail = cause instanceof Error ? cause.message : error instanceof Error ? error.message : String(error);
121
+ throw new PortalDown(detail);
122
+ }
123
+ }
124
+
125
+ /** Send a request and return its JSON body; any other status is an error. An empty body is `undefined`. */
126
+ async json<T>(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<T> {
127
+ const response = await this.request(method, path, { body, signal });
128
+ if (!response.ok) throw new Error(`dogsled web ${method} ${path} failed: ${response.status} ${(await response.text()).trim()}`);
129
+ const text = await response.text();
130
+ if (!text.trim()) return undefined as T;
131
+ return JSON.parse(text) as T;
132
+ }
133
+
134
+ /** Open a Server-Sent Events stream. */
135
+ async events(path: string, signal: AbortSignal): Promise<AsyncGenerator<ServerEvent>> {
136
+ const response = await this.request("GET", path, { accept: "text/event-stream", signal });
137
+ if (!response.ok || !response.body) throw new Error(`dogsled web GET ${path} failed: ${response.status}`);
138
+ return serverEvents(response.body);
139
+ }
140
+ }
141
+
142
+ /** A one-shot command: startup is separate from its eventual answer. */
143
+ export function startOneShot(args: string[], env: NodeJS.ProcessEnv, signal: AbortSignal): { started: Promise<void>; result: Promise<string> } {
144
+ const child = spawn("dogsled", args, { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "inherit"] });
145
+ const started = new Promise<void>((resolve, reject) => {
146
+ child.once("spawn", resolve);
147
+ child.once("error", reject);
148
+ });
149
+ const result = new Promise<string>((resolve, reject) => {
150
+ const chunks: Buffer[] = [];
151
+ let size = 0;
152
+ let failure: Error | undefined;
153
+ const abort = () => { child.kill("SIGTERM"); };
154
+ child.stdout.on("data", (chunk: Buffer) => {
155
+ size += chunk.length;
156
+ if (size > 10 * 1024 * 1024) {
157
+ failure = new Error("dogsled returned more than 10 MiB of output");
158
+ child.kill("SIGTERM");
159
+ } else chunks.push(chunk);
160
+ });
161
+ child.once("error", error => { failure = error; });
162
+ child.once("close", (code, killed) => {
163
+ signal.removeEventListener("abort", abort);
164
+ if (signal.aborted) reject(new Error("dogsled command was aborted"));
165
+ else if (failure) reject(failure);
166
+ else if (code !== 0) reject(new Error(`dogsled ${args[0]} exited with ${code ?? killed}`));
167
+ else resolve(Buffer.concat(chunks).toString("utf8"));
168
+ });
169
+ signal.addEventListener("abort", abort, { once: true });
170
+ if (signal.aborted) abort();
171
+ });
172
+ // Startup can fail before the caller reaches either await. The caller still
173
+ // observes both rejections; neither is an unhandled background promise.
174
+ void started.catch(() => undefined);
175
+ void result.catch(() => undefined);
176
+ return { started, result };
177
+ }
178
+
179
+ /** Resolve after `ms`, or early when `signal` aborts. */
180
+ export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
181
+ return new Promise(resolve => {
182
+ if (signal?.aborted) { resolve(); return; }
183
+ const done = () => { clearTimeout(timer); signal?.removeEventListener("abort", done); resolve(); };
184
+ const timer = setTimeout(done, ms);
185
+ signal?.addEventListener("abort", done, { once: true });
186
+ });
187
+ }