@oisin-ee/pi-dogsled 0.26.0 → 0.27.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 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.26.0
16
+ mise use github:oisin-ee/dogsled@v0.27.0
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.26.0
22
+ pi install npm:@oisin-ee/pi-dogsled@0.27.0
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.26.0
30
+ claude plugin marketplace add oisin-ee/dogsled#v0.27.0
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.26.0
37
+ codex plugin marketplace add oisin-ee/dogsled --ref v0.27.0
38
38
  codex plugin add dogsled@dogsled
39
39
  ```
40
40
 
@@ -44,7 +44,7 @@ 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.26.0 --yes
47
+ herdr plugin install oisin-ee/dogsled --ref v0.27.0 --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.
@@ -182,7 +182,22 @@ dogsled drop <item-id> --host netcup
182
182
  dogsled done # as a child: my whole task is complete
183
183
  ```
184
184
 
185
- `drop` deletes a closed child's retained local and origin branches, including unmerged commits. Only the item's owner can use it. It refuses a branch checked out in a worktree. Already absent branches count as success. The item and its done mark stay settled and leave the board.
185
+ `drop` deletes a closed child's retained local and origin branches, including unmerged commits. Only the item's owner can use it, except on an orphan: when the origin's evidence proves the owner pane is gone or its session ended, any session can drop it. It refuses a branch checked out in a worktree. Already absent branches count as success. The item and its done mark stay settled and leave the board.
186
+
187
+ ### Claim custody and accept a result
188
+
189
+ ```sh
190
+ dogsled claim <item-id> --revision 0 --json
191
+ dogsled accept <item-id> --result <result-id> --evidence "Reviewed the exact returned result" --json
192
+ ```
193
+
194
+ `claim` takes custody of an orphaned child recorded on this host. Dogsled uses the caller's live pane and harness session. The original owner, task, reply, and result do not change. `--revision` names the expected custody revision. Without it, Dogsled reads the current revision before the atomic claim. A repeated claim by the current custodian returns `held` without another transfer.
195
+
196
+ A claim refuses a wrong host, a live custodian, an unproven orphan, a stale revision, or custody that moved during the claim. Refusals include a typed reason.
197
+
198
+ `accept` records the custodian's review of the exact saved result from a unit request. The caller must hold a custody claim. The receipt names the claim, revision, execution, result, reviewer, and review evidence. The original task stays open. Acceptance does not prove original task completion. An identical acceptance returns the same review without another write. A different review for the same claim is refused.
199
+
200
+ Both commands support `--json`. MCP exposes `claim` and `accept`, named `mcp__dogsled__claim` and `mcp__dogsled__accept` in Pi. Pi stores successful receipts with the custom type `dogsled.custody.v1`. These entries are audit receipts only. They do not call todo or its provider, and they do not change task state.
186
201
 
187
202
  `close` ends a child now, for an owner who does not want to wait for the sweep. `--host` defaults to the host of the pane's open item, else local.
188
203
 
@@ -407,7 +422,7 @@ The report includes start and finish times, removals, failures, repository warni
407
422
  `dogsled status` and `status --json` show the latest pass. Prompt context adds one summary line when that pass has errors or warnings.
408
423
  The service also writes removals, failures, repository warnings, and holds to stderr.
409
424
  Child completion and orphan checks remain independent of requested doctor cleanup.
410
- An orphan that is dirty, unpushed, `working`, `blocked`, or on an unreachable host stays open. Status shows `orphaned:` and the reason on its item line, the brief counts it, and every check-in on the host lists it.
425
+ An orphan that is dirty, unpushed, `working`, `blocked`, or on an unreachable host stays open. `dogsled status` lists each item once as `orphaned (unclaimed)`, `orphaned (claimed)`, or `unknown`. Check-ins no longer repeat orphan notices.
411
426
  Prune also handles ended jobs and `targets`. Disk and process findings are report-only. Repository findings remain report-only except for absent remembered paths.
412
427
 
413
428
  ## Placement
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oisin-ee/pi-dogsled",
3
- "version": "0.26.0",
3
+ "version": "0.27.0",
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/board.ts CHANGED
@@ -20,7 +20,7 @@ export async function herdrAvailable(env: NodeJS.ProcessEnv = process.env): Prom
20
20
  export type Group = "to_land" | "attention" | "running" | "waiting";
21
21
 
22
22
  export interface Row {
23
- group: Group;
23
+ group: string;
24
24
  kind: string;
25
25
  id: string;
26
26
  name: string;
@@ -57,11 +57,16 @@ export interface Paint {
57
57
  bold(text: string): string;
58
58
  }
59
59
 
60
- const TITLES: Record<Group, string> = { to_land: "TO LAND", attention: "ATTENTION", running: "RUNNING", waiting: "WAITING" };
60
+ const TITLES: Record<Group, string> = { to_land: "READY TO MERGE", attention: "NEEDS YOU", running: "WORKING", waiting: "QUEUED" };
61
61
  /** Groups in action order: what the owner must do first comes first. */
62
62
  export const GROUPS: readonly Group[] = ["to_land", "attention", "running", "waiting"];
63
63
  const ORDER = GROUPS;
64
- const COUNTS: Record<Group, string> = { to_land: "to land", attention: "need attention", running: "running", waiting: "waiting" };
64
+ const COUNTS: Record<Group, string> = { to_land: "ready to merge", attention: "needs you", running: "working", waiting: "queued" };
65
+
66
+ /** Unknown evidence stays visible in the group that needs the owner. */
67
+ export function boardGroup(group: string): Group {
68
+ return GROUPS.find(known => known === group) ?? "attention";
69
+ }
65
70
 
66
71
  export function parseBoard(value: unknown): Board {
67
72
  const data = value as Partial<Board> | null;
@@ -84,9 +89,10 @@ export function clean(text: string): string {
84
89
  }
85
90
 
86
91
  function icon(row: Row): [string, ThemeColor] {
87
- if (row.group === "to_land") return ["●", "success"];
88
- if (row.group === "attention") return ["!", "warning"];
89
- if (row.group === "waiting") return ["⋯", "muted"];
92
+ const group = boardGroup(row.group);
93
+ if (group === "to_land") return ["●", "success"];
94
+ if (group === "attention") return ["!", "warning"];
95
+ if (group === "waiting") return ["⋯", "muted"];
90
96
  if (row.kind === "job") return ["▸", "accent"];
91
97
  return row.state === "working" ? ["◐", "accent"] : ["○", "muted"];
92
98
  }
@@ -108,7 +114,7 @@ function pad(text: string, width: number): string {
108
114
 
109
115
  /** A row whose transcript text is safe to draw. */
110
116
  export function cleanRow(row: Row): Row {
111
- return { ...row, name: clean(row.name), what: clean(row.what), host: clean(row.host), state: clean(row.state), activity: clean(row.activity || row.state) };
117
+ return { ...row, group: boardGroup(row.group), name: clean(row.name), what: clean(row.what), host: clean(row.host), state: clean(row.state), activity: clean(row.activity || row.state) };
112
118
  }
113
119
 
114
120
  /** Column widths shared by every row drawn together, so the columns line up. */
@@ -141,7 +147,7 @@ export function boardColumns(rows: Row[], width: number): Columns {
141
147
 
142
148
  /** `dogsled <counts>` on the left and one load meter per host on the right. */
143
149
  export function boardHeader(board: Board, width: number, paint: Paint): string {
144
- const counts = ORDER.map(g => [g, board.rows.filter(r => r.group === g).length] as const)
150
+ const counts = ORDER.map(g => [g, board.rows.filter(r => boardGroup(r.group) === g).length] as const)
145
151
  .filter(([, n]) => n > 0)
146
152
  .map(([g, n]) => `${n} ${COUNTS[g]}`)
147
153
  .join(" · ");
@@ -151,8 +157,9 @@ export function boardHeader(board: Board, width: number, paint: Paint): string {
151
157
  return truncateToWidth(gap >= 2 ? `${left}${" ".repeat(gap)}${meters}` : left, width);
152
158
  }
153
159
 
154
- export function groupTitle(group: Group, paint: Paint): string {
155
- return ` ${paint.fg(group === "attention" ? "warning" : "muted", TITLES[group])}`;
160
+ export function groupTitle(group: string, paint: Paint): string {
161
+ const known = boardGroup(group);
162
+ return ` ${paint.fg(known === "attention" ? "warning" : "muted", TITLES[known])}`;
156
163
  }
157
164
 
158
165
  /** One cleaned row. `prefix` is two columns wide: blank, or a selection marker. */
package/pi/index.ts CHANGED
@@ -63,6 +63,28 @@ export default function dogsled(pi: ExtensionAPI) {
63
63
  });
64
64
  pi.on("tool_execution_end", (event, ctx) => units.ended(event.toolCallId, ctx));
65
65
 
66
+ // Custody receipts are audit facts only. They never call todo or its provider.
67
+ pi.on("tool_result", event => {
68
+ const kind = event.toolName === "mcp__dogsled__claim" ? "claim"
69
+ : event.toolName === "mcp__dogsled__accept" ? "accept" : undefined;
70
+ if (!kind || event.isError) return;
71
+ for (const block of event.content) {
72
+ if (block.type !== "text") continue;
73
+ let receipt: unknown;
74
+ try { receipt = JSON.parse(block.text); } catch { continue; }
75
+ if (!receipt || typeof receipt !== "object"
76
+ || !("kind" in receipt) || receipt.kind !== kind
77
+ || !("item" in receipt) || typeof receipt.item !== "string"
78
+ || !("revision" in receipt) || typeof receipt.revision !== "number") continue;
79
+ if (kind === "claim") {
80
+ if (!("outcome" in receipt) || !["claimed", "held"].includes(String(receipt.outcome))
81
+ || !("custodianPane" in receipt) || typeof receipt.custodianPane !== "string") continue;
82
+ } else if (!("resultId" in receipt) || typeof receipt.resultId !== "string"
83
+ || !("reviewId" in receipt) || typeof receipt.reviewId !== "string") continue;
84
+ pi.appendEntry("dogsled.custody.v1", receipt);
85
+ }
86
+ });
87
+
66
88
  pi.registerMessageRenderer<Details>(MESSAGE_TYPE, (message, { expanded, outputPad }, theme) => {
67
89
  const records = message.details?.records ?? [];
68
90
  const box = new Box(outputPad, 1, text => theme.bg("customMessageBg", text));
@@ -286,7 +308,8 @@ export default function dogsled(pi: ExtensionAPI) {
286
308
  units.stop();
287
309
  planMode.stop();
288
310
  planMode.stopWatching();
289
- interviews.close();
311
+ try { await interviews.close(); }
312
+ catch (error) { ctx.ui.notify(`Interview cleanup failed: ${String(error)}`, "error"); }
290
313
  workPanel?.dispose();
291
314
  generation++;
292
315
  workAbort?.abort();
package/pi/interview.ts CHANGED
@@ -1,15 +1,9 @@
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";
1
+ // Interviews live in the portal inbox. The owner opens the portal; asking a
2
+ // question never opens a browser or starts a temporary form server.
7
3
  import { readFileSync } from "node:fs";
8
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
9
- import { tmpdir } from "node:os";
10
4
  import { isAbsolute, join } from "node:path";
11
5
  import type { AgentToolResult, AgentToolUpdateCallback, ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent";
12
- import { openInBrowser, PortalClient, PortalDown, portalUrl, sleep, startOneShot } from "./portal-client.ts";
6
+ import { PortalClient, PortalDown, portalUrl, sleep } from "./portal-client.ts";
13
7
 
14
8
  /** How long the tool waits between two polls for the answers. */
15
9
  const POLL_MS = 500;
@@ -20,7 +14,7 @@ const interviewParameters = {
20
14
  required: ["questions"],
21
15
  properties: {
22
16
  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 },
17
+ timeout: { type: "number", description: "Optional timeout in seconds. Without it, wait until the user answers or rejects the interview.", minimum: 1 },
24
18
  verbose: { type: "boolean", description: "Enable debug logging", default: false },
25
19
  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
20
  theme: {
@@ -40,7 +34,8 @@ const interviewParameters = {
40
34
  /** The interview description with the portal's browser transport. */
41
35
  const interviewDescription =
42
36
  "Present an interactive form to gather user responses. " +
43
- "Opens the Dogsled portal, or a fallback browser tab when the portal is not running. " +
37
+ "Adds the form to the Dogsled portal inbox without opening a browser tab. Assume the user can open the portal. " +
38
+ "The user can answer or reject the interview with a reason. No timeout applies unless you explicitly set one. " +
44
39
  "Use proactively when: choosing between multiple approaches, gathering requirements before implementation, " +
45
40
  "exploring design tradeoffs, or when decisions have multiple dimensions worth discussing. " +
46
41
  "Provides better UX than back-and-forth chat for structured input. " +
@@ -48,6 +43,7 @@ const interviewDescription =
48
43
  "Pass questions as inline JSON string directly (preferred) or as a path to a JSON file. " +
49
44
  '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
45
  "Options can be strings or objects: { label: string, content?: { source, lang?, file?, lines?, highlights?, title?, showSource? } }. " +
46
+ "Every single and multi question automatically offers Other with a free-text answer; selected options also accept extra context. " +
51
47
  "Always set recommended with context explaining your reasoning. Recommended options show a 'Recommended' badge and are pre-selected for the user. " +
52
48
  'Use conviction: "slight" when unsure (does NOT pre-select), conviction: "strong" when very confident (shows Recommended badge). ' +
53
49
  "Omit conviction for normal recommendations (pre-selects). " +
@@ -60,14 +56,15 @@ const interviewDescription =
60
56
  /** One answer to one question, as the portal returns it. */
61
57
  export interface ResponseItem {
62
58
  id: string;
63
- value: string | string[] | { option: string; note?: string } | { option: string; note?: string }[];
59
+ value: string | { option: string; note?: string } | (string | { option: string; note?: string })[];
64
60
  attachments?: string[];
65
61
  }
66
62
 
67
63
  /** The result shape of pi-interview 0.13.0. */
68
64
  export interface InterviewDetails {
69
- status: "completed" | "cancelled" | "timeout" | "aborted" | "queued" | "started";
65
+ status: "completed" | "rejected" | "cancelled" | "timeout" | "aborted" | "queued" | "started";
70
66
  responses: ResponseItem[];
67
+ reason?: string;
71
68
  url: string;
72
69
  }
73
70
 
@@ -87,19 +84,13 @@ function isChoiceValue(value: unknown): value is { option: string; note?: string
87
84
 
88
85
  /** The value of one answer, as the model reads it. */
89
86
  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
- }
87
+ if (Array.isArray(value)) return value.map(formatResponseValue).join(", ");
94
88
  if (isChoiceValue(value)) return value.note ? `${value.option} (${value.note})` : value.option;
95
89
  return value;
96
90
  }
97
91
 
98
92
  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
- }
93
+ if (Array.isArray(value)) return value.some(hasAnswerValue);
103
94
  if (isChoiceValue(value)) return value.option.trim() !== "";
104
95
  return typeof value === "string" && value.trim() !== "";
105
96
  }
@@ -240,12 +231,20 @@ function attachmentUrl(path: string): string {
240
231
  * the tool names the answers from the questions the model sent. Any other
241
232
  * body is an error that names the shape it expected.
242
233
  */
243
- function parseAnswers(value: unknown): ResponseItem[] {
244
- const payload = value as { id?: unknown; responses?: unknown } | null;
234
+ function parseAnswers(value: unknown): { responses: ResponseItem[]; rejection?: { reason: string } } {
235
+ const payload = value as { id?: unknown; responses?: unknown; rejection?: unknown } | null;
245
236
  if (!payload || typeof payload !== "object" || Array.isArray(payload) || typeof payload.id !== "string" || !Array.isArray(payload.responses)) {
246
237
  throw new Error('dogsled web returned an unexpected answer shape: expected {"id": string, "responses": ResponseItem[]}');
247
238
  }
248
- return payload.responses.filter(isResponseItem);
239
+ if (!payload.responses.every(isResponseItem)) throw new Error("dogsled web returned an invalid response item");
240
+ if (payload.rejection !== undefined) {
241
+ const rejection = payload.rejection as { reason?: unknown } | null;
242
+ if (!rejection || typeof rejection !== "object" || typeof rejection.reason !== "string" || payload.responses.length !== 0) {
243
+ throw new Error("dogsled web returned an invalid rejection");
244
+ }
245
+ return { responses: [], rejection: { reason: rejection.reason } };
246
+ }
247
+ return { responses: payload.responses };
249
248
  }
250
249
 
251
250
  /** One answer of the portal, in the shape the contract names. */
@@ -256,17 +255,22 @@ function isResponseItem(value: unknown): value is ResponseItem {
256
255
  return item.attachments === undefined || Array.isArray(item.attachments);
257
256
  }
258
257
 
258
+ interface Outcome {
259
+ status: "completed" | "rejected" | "cancelled" | "timeout" | "aborted";
260
+ text: string;
261
+ responses: ResponseItem[];
262
+ reason?: string;
263
+ }
264
+
259
265
  /** The `interview` tool: ask the user a form through the portal and wait for the answers. */
260
266
  export class InterviewTool {
261
267
  private readonly client: PortalClient;
262
268
  private readonly deliver: (content: string) => void;
263
- private readonly open: (url: string) => void;
264
269
  /** The background waits of the async interviews, so the session can close them. */
265
- private readonly pending = new Set<AbortController>();
266
- constructor(client: PortalClient = new PortalClient(), deliver: (content: string) => void = () => undefined, open: (url: string) => void = openInBrowser) {
270
+ private readonly pending = new Map<AbortController, Promise<Outcome>>();
271
+ constructor(client: PortalClient = new PortalClient(), deliver: (content: string) => void = () => undefined) {
267
272
  this.client = client;
268
273
  this.deliver = deliver;
269
- this.open = open;
270
274
  }
271
275
 
272
276
  /** Run one interview. The tool's `signal` withdraws the form. */
@@ -277,113 +281,50 @@ export class InterviewTool {
277
281
  // The questions are parsed before the call, so a broken file or bad JSON
278
282
  // is a tool error and never reaches the portal.
279
283
  const file = loadQuestions(params.questions, cwd);
280
- let created: { id?: unknown };
281
- try {
282
- // The images of the form are uploaded first, so the browser loads
283
- // them from the portal instead of from the agent's own disk.
284
- const questions = await this.uploadMedia(file, cwd, signal);
285
- created = await this.client.json<{ id?: unknown }>("POST", "/api/questions", {
286
- questions, pane, session, cwd,
287
- }, signal);
288
- } catch (error) {
289
- if (!(error instanceof PortalDown)) throw error;
290
- // The portal is down, so the form goes to the one-shot interview
291
- // with the questions as the model wrote them.
292
- return this.fallback(file, params, ctx, signal);
284
+ if (params.timeout !== undefined && (!Number.isFinite(params.timeout) || params.timeout < 1 || params.timeout > 2_147_483)) {
285
+ throw new Error("Interview timeout must be between 1 and 2147483 seconds.");
293
286
  }
287
+ const uploaded = await this.uploadMedia(file, cwd, signal);
288
+ const created = await this.client.json<{ id?: unknown }>("POST", "/api/questions", {
289
+ questions: uploaded, pane, session, cwd,
290
+ }, signal);
294
291
  const id = typeof created?.id === "string" ? created.id : "";
295
292
  if (!id) throw new Error("dogsled web did not return an interview id");
296
293
  const url = portalUrl(`/?question=${encodeURIComponent(id)}&pane=${encodeURIComponent(pane)}`, this.client.env);
297
- this.open(url);
298
294
  onUpdate?.({
299
- content: [{ type: "text", text: `Interview ${id} started: ${url}. Waiting for your answers.` }],
295
+ content: [{ type: "text", text: `Interview ${id} is in the Dogsled inbox: ${url}. Waiting for answers or rejection.` }],
300
296
  details: { status: "started", responses: [], url },
301
297
  });
302
298
 
299
+ const own = new AbortController();
300
+ const operation = params.async || !signal ? own.signal : AbortSignal.any([own.signal, signal]);
301
+ if (signal?.aborted) own.abort();
302
+ const answer = this.wait(id, file, operation, params.timeout)
303
+ .finally(() => { this.pending.delete(own); });
304
+ this.pending.set(own, answer);
303
305
  if (params.async) {
304
- // The form runs on its own: the tool's own signal no longer owns it, and the
305
- // answers arrive as a message, like pi-interview does.
306
- const own = new AbortController();
307
- this.pending.add(own);
308
- void this.wait(id, file, own.signal, params.timeout)
309
- .then(answers => { this.deliver(`Interview ${id} finished.\n\n${answers.text}`); })
310
- .catch(error => { this.deliver(`Interview ${id} did not finish: ${error instanceof Error ? error.message : String(error)}`); })
311
- .finally(() => { this.pending.delete(own); });
306
+ void answer.then(outcome => {
307
+ if (!own.signal.aborted) this.deliver(`Interview ${id} ${outcome.status}.\n\n${outcome.text}`);
308
+ }).catch(error => {
309
+ if (!own.signal.aborted) this.deliver(`Interview ${id} did not finish: ${error instanceof Error ? error.message : String(error)}`);
310
+ });
312
311
  return {
313
- content: [{ type: "text", text: `Interview ${id} started: ${url}. The answer arrives later as a message; keep working and do not poll.` }],
312
+ content: [{ type: "text", text: `Interview ${id} is in the Dogsled inbox: ${url}. The outcome arrives later as a message; keep working and do not poll.` }],
314
313
  details: { status: "started", responses: [], url },
315
314
  };
316
315
  }
317
-
318
- try {
319
- const answers = await this.wait(id, file, signal, params.timeout);
320
- return {
321
- content: [{ type: "text", text: `User completed the interview form: ${url}\n\nAnswered responses:\n${answers.text}` }],
322
- details: { status: "completed", responses: answers.responses, url },
323
- };
324
- } catch (error) {
325
- // An aborted interview withdraws its form, so the portal does not wait for an answer.
326
- if (signal?.aborted) {
327
- await this.client.request("DELETE", `/api/questions/${encodeURIComponent(id)}`).catch(() => undefined);
328
- return { content: [{ type: "text", text: "Interview was aborted." }], details: { status: "aborted", responses: [], url } };
329
- }
330
- throw error;
331
- }
332
- }
333
-
334
- /** Run the same form on a temporary server when the portal cannot be reached. */
335
- private async fallback(file: QuestionsFile, params: { timeout?: number; async?: boolean }, ctx: ExtensionToolContext, signal: AbortSignal | undefined): Promise<AgentToolResult<InterviewDetails>> {
336
- const directory = await mkdtemp(join(tmpdir(), "dogsled-interview-"));
337
- const own = new AbortController();
338
- const abort = params.async || !signal ? own.signal : AbortSignal.any([own.signal, signal]);
339
- this.pending.add(own);
340
- let background = false;
341
- try {
342
- const path = join(directory, "questions.json");
343
- await writeFile(path, JSON.stringify(file), { mode: 0o600 });
344
- const command = startOneShot([
345
- "interview", "--file", path, "--pane", process.env["HERDR_PANE_ID"] ?? "",
346
- "--session", ctx.sessionManager.getSessionId(), "--cwd", ctx.cwd,
347
- "--timeout", String(Math.max(1, Math.ceil(params.timeout ?? 600))),
348
- ], this.client.env, abort);
349
- await command.started;
350
- const answer = command.result.then(stdout => parseAnswers(JSON.parse(stdout)));
351
- if (params.async) {
352
- const id = randomUUID();
353
- background = true;
354
- void answer.finally(async () => {
355
- this.pending.delete(own);
356
- await rm(directory, { recursive: true, force: true });
357
- }).then(responses => {
358
- this.deliver(`Interview ${id} finished.\n\n${formatAnsweredResponses(responses, formQuestions(file))}`);
359
- }).catch(error => {
360
- if (!own.signal.aborted) this.deliver(`Interview ${id} did not finish: ${error instanceof Error ? error.message : String(error)}`);
361
- });
362
- return {
363
- content: [{ type: "text", text: `Interview ${id} started. The answer arrives later as a message; keep working and do not poll.` }],
364
- details: { status: "started", responses: [], url: "" },
365
- };
366
- }
367
- const responses = await answer;
368
- return {
369
- content: [{ type: "text", text: `User completed the interview form.\n\nAnswered responses:\n${formatAnsweredResponses(responses, formQuestions(file))}` }],
370
- details: { status: "completed", responses, url: "" },
371
- };
372
- } catch (error) {
373
- if (abort.aborted) return { content: [{ type: "text", text: "Interview was aborted." }], details: { status: "aborted", responses: [], url: "" } };
374
- throw error;
375
- } finally {
376
- if (!background) {
377
- this.pending.delete(own);
378
- await rm(directory, { recursive: true, force: true });
379
- }
380
- }
316
+ const { text, ...details } = await answer;
317
+ return { content: [{ type: "text", text: `${text}\n\n${url}` }], details: { ...details, url } };
381
318
  }
382
319
 
383
- /** Close the background waits of the async interviews. */
384
- close(): void {
385
- for (const controller of this.pending) controller.abort();
320
+ /** Finish withdrawal before the extension runtime exits or is replaced. */
321
+ async close(): Promise<void> {
322
+ for (const controller of this.pending.keys()) controller.abort();
323
+ const results = await Promise.allSettled(this.pending.values());
386
324
  this.pending.clear();
325
+ for (const result of results) {
326
+ if (result.status === "rejected") throw result.reason;
327
+ }
387
328
  }
388
329
 
389
330
  /**
@@ -395,9 +336,7 @@ export class InterviewTool {
395
336
  * attachment, and the `src` becomes the URL the portal serves.
396
337
  *
397
338
  * The portal is asked whether it is there before the first local file is
398
- * read, so a portal that is down falls back to the one-shot interview
399
- * with the questions as the model wrote them, and a missing file stays a
400
- * tool error only when there is a portal to upload it to.
339
+ * read. If it is down, report that directly without starting another server.
401
340
  */
402
341
  private async uploadMedia(file: QuestionsFile, cwd: string, signal: AbortSignal | undefined): Promise<QuestionsFile> {
403
342
  const list = file["questions"];
@@ -451,9 +390,8 @@ export class InterviewTool {
451
390
  /**
452
391
  * The bytes of an image, as an attachment of the portal.
453
392
  *
454
- * A portal that cannot be reached is a `PortalDown` error, so the form
455
- * falls back to the one-shot interview. A portal that refuses the image
456
- * is an error that names the file.
393
+ * A portal that cannot be reached is a `PortalDown` error.
394
+ * A portal that refuses the image is an error that names the file.
457
395
  */
458
396
  private async uploadAttachment(bytes: Buffer, path: string, signal: AbortSignal | undefined): Promise<string> {
459
397
  let response: Response;
@@ -484,29 +422,62 @@ export class InterviewTool {
484
422
  return attachmentUrl(payload.path);
485
423
  }
486
424
 
487
- /** Poll the portal until it has the answers, the form is withdrawn, or the wait ends. */
488
- private async wait(id: string, file: QuestionsFile, signal: AbortSignal | undefined, timeout: number | undefined): Promise<{ text: string; responses: ResponseItem[] }> {
489
- const seconds = timeout ?? 600;
490
- const deadline = Date.now() + Math.max(1, seconds) * 1000;
491
- for (;;) {
492
- if (signal?.aborted) throw new Error("Interview was aborted.");
493
- const response = await this.client.request("GET", `/api/questions/${encodeURIComponent(id)}/answer`, { signal });
494
- if (response.status === 204) {
495
- if (Date.now() >= deadline) throw new Error(`Interview form timed out after ${seconds} seconds.`);
496
- await sleep(POLL_MS, signal);
497
- continue;
425
+ /** Resolve saved outcomes consistently in sync, async, and cancellation races. */
426
+ private outcome(payload: unknown, file: QuestionsFile): Outcome {
427
+ const { responses, rejection } = parseAnswers(payload);
428
+ if (rejection) return {
429
+ status: "rejected", responses: [], reason: rejection.reason,
430
+ text: `User rejected the interview. Do not treat this as approval.\n\nReason: ${rejection.reason || "No reason given."}`,
431
+ };
432
+ return { status: "completed", responses, text: `User completed the interview form.\n\nAnswered responses:\n${formatAnsweredResponses(responses, formQuestions(file))}` };
433
+ }
434
+
435
+ /** Cancel abandoned forms, but recover a terminal outcome that won the race. */
436
+ private async withdraw(id: string, file: QuestionsFile): Promise<Outcome | undefined> {
437
+ const signal = AbortSignal.timeout(5_000);
438
+ const path = `/api/questions/${encodeURIComponent(id)}`;
439
+ const response = await this.client.request("DELETE", path, { signal });
440
+ if (response.status === 409) {
441
+ const saved = await this.client.json<unknown>("GET", `${path}/answer?wait=0`, undefined, signal);
442
+ return this.outcome(saved, file);
443
+ }
444
+ if (!response.ok && response.status !== 410) throw new Error(`Could not withdraw interview ${id}: HTTP ${response.status}`);
445
+ return undefined;
446
+ }
447
+
448
+ /** No implicit deadline: the owner can leave the form in the inbox until ready. */
449
+ private async wait(id: string, file: QuestionsFile, signal: AbortSignal, timeout: number | undefined): Promise<Outcome> {
450
+ const deadline = new AbortController();
451
+ const timer = timeout === undefined ? undefined : setTimeout(() => deadline.abort(), timeout * 1000);
452
+ timer?.unref();
453
+ const operation = AbortSignal.any([signal, deadline.signal]);
454
+ try {
455
+ for (;;) {
456
+ operation.throwIfAborted();
457
+ const response = await this.client.request("GET", `/api/questions/${encodeURIComponent(id)}/answer`, { signal: operation });
458
+ if (response.status === 204) {
459
+ await sleep(POLL_MS, operation);
460
+ continue;
461
+ }
462
+ if (response.status === 410) return { status: "cancelled", responses: [], text: "The interview was withdrawn." };
463
+ if (!response.ok) throw new Error(`dogsled web GET /api/questions/${id}/answer failed: ${response.status} ${(await response.text()).trim()}`);
464
+ return this.outcome(await response.json(), file);
498
465
  }
499
- if (response.status === 410) throw new Error("The interview form was withdrawn before it was answered.");
500
- if (!response.ok) throw new Error(`dogsled web GET /api/questions/${id}/answer failed: ${response.status} ${(await response.text()).trim()}`);
501
- const responses = parseAnswers(await response.json());
502
- return { text: formatAnsweredResponses(responses, formQuestions(file)), responses };
466
+ } catch (error) {
467
+ const saved = await this.withdraw(id, file);
468
+ if (saved) return saved;
469
+ if (signal.aborted) return { status: "aborted", responses: [], text: "Interview was aborted." };
470
+ if (deadline.signal.aborted) return { status: "timeout", responses: [], text: `Interview timed out after ${timeout} seconds and was removed from the inbox.` };
471
+ throw error;
472
+ } finally {
473
+ if (timer) clearTimeout(timer);
503
474
  }
504
475
  }
505
476
  }
506
477
 
507
478
  /** Register the `interview` tool. */
508
479
  export function registerInterview(pi: ExtensionAPI, client: PortalClient = new PortalClient()): InterviewTool {
509
- const tool = new InterviewTool(client, content => { pi.sendUserMessage(content); });
480
+ const tool = new InterviewTool(client, content => { pi.sendUserMessage(content, { deliverAs: "steer" }); });
510
481
  pi.registerTool({
511
482
  name: "interview",
512
483
  label: "Interview",
package/pi/unit-bridge.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionAPI, ExtensionContext, ToolCallEvent, ToolCallEventResult, SessionStartEvent } from "@earendil-works/pi-coding-agent";
2
- import { acquire, execution, prepared, record, reference, repositoryIdentity, sameExecution, sameRef, unitInput, unwrap, type Execution, type Prepared, type UnitRef } from "./unit-protocol.ts";
2
+ import { acquire, acknowledgement, decodeDelivery, execution, prepared, record, reference, repositoryIdentity, sameExecution, sameRef, settlementExecution, settlementOrigin, unitInput, unwrap, type Execution, type Prepared, type UnitRef } from "./unit-protocol.ts";
3
3
  import { UnitWorker, type UnitExec } from "./unit-worker.ts";
4
4
 
5
5
  interface Invocation { origin: UnitRef; execution?: Execution; cwd: string; prepared?: Prepared; ended: boolean }
@@ -144,22 +144,33 @@ export class UnitBridge {
144
144
  /** Provider settlement acknowledgements are independent of inbox text acknowledgements. */
145
145
  drain(ctx: ExtensionContext): Promise<void> {
146
146
  if (this.draining) return this.draining;
147
- const epoch = this.epoch;
147
+ const epoch = this.epoch, session = ctx.sessionManager.getSessionId();
148
148
  this.draining = (async () => {
149
149
  if (!acquire(this.pi.events)) return;
150
150
  const pending = await this.exec(["unit", "settlements"], ctx.cwd);
151
151
  if (!Array.isArray(pending)) throw new Error("LAUNCH_UNRESOLVED: settlements returned no list");
152
152
  for (const event of pending) {
153
153
  if (epoch !== this.epoch) return;
154
- if (!record(event) || typeof event.eventId !== "string") throw new Error("LAUNCH_UNRESOLVED: invalid settlement identity");
155
- const owner = record(event.binding) ? event.binding.execution : event.execution;
156
- if (!execution(owner)) throw new Error("LAUNCH_UNRESOLVED: missing settlement execution");
154
+ // The envelope and its custody reference are validated apart from the provider event.
155
+ const delivery = decodeDelivery(event), settlement = delivery.settlement;
156
+ if (typeof settlement.eventId !== "string") throw new Error("LAUNCH_UNRESOLVED: invalid settlement identity");
157
+ const owner = settlementExecution(settlement);
158
+ if (!owner) throw new Error("LAUNCH_UNRESOLVED: missing settlement execution");
159
+ const origin = settlementOrigin(settlement);
160
+ if (!origin) throw new Error("LAUNCH_UNRESOLVED: missing settlement origin");
161
+ if (origin.sessionId !== session) continue; // Another session owns this result.
157
162
  const provider = acquire(this.pi.events);
158
163
  if (!provider) return;
159
- const result = provider.settle(event);
164
+ const inspected = provider.inspect(origin.unitId);
165
+ if (!inspected.ok) continue;
166
+ const contract = inspected.value;
167
+ if (!record(contract) || !reference(contract.ref) || !sameRef(contract.ref, origin)) continue; // Wrong branch or revision.
168
+ this.current(epoch, session, ctx);
169
+ const result = provider.settle(settlement);
160
170
  if (!result.ok) continue; // Wrong branch or revision stays pending in Dogsled.
161
171
  if (!record(result.value) || typeof result.value.applied !== "boolean") throw new Error("PROVIDER_UNAVAILABLE: invalid settlement acknowledgement");
162
- await this.exec(["unit", "ack-settlement", "--input", JSON.stringify({ execution: owner, eventId: event.eventId })], ctx.cwd);
172
+ this.current(epoch, session, ctx);
173
+ await this.exec(["unit", "ack-settlement", "--input", JSON.stringify(acknowledgement(owner, settlement.eventId, delivery.custody))], ctx.cwd);
163
174
  }
164
175
  })().finally(() => { this.draining = undefined; });
165
176
  return this.draining;
@@ -28,6 +28,39 @@ export function sameRef(a: UnitRef, b: UnitRef): boolean {
28
28
  export function sameExecution(a: Execution, b: Execution): boolean {
29
29
  return a.executor === b.executor && a.ownerId === b.ownerId && a.requestId === b.requestId;
30
30
  }
31
+ export interface Custody { itemId: string; claimId: string; revision: number; recipient: string }
32
+ /** A settlement as the server delivers it: the unchanged provider event, and the custody it was delivered under. */
33
+ export interface Delivery { custody?: Custody; settlement: Record<string, unknown> }
34
+ export function custody(value: unknown): value is Custody {
35
+ return record(value) && text(value.itemId) && text(value.claimId) && Number.isSafeInteger(value.revision) && Number(value.revision) > 0 && text(value.recipient);
36
+ }
37
+ /** Decode a settlement delivery. The envelope and its custody reference are validated apart from the provider event.
38
+ * A settlement without an envelope is the older, un-enveloped form. */
39
+ export function decodeDelivery(value: unknown): Delivery {
40
+ if (!record(value)) throw new Error("LAUNCH_UNRESOLVED: invalid settlement identity");
41
+ if (!("custody" in value) && !("settlement" in value)) return { settlement: value };
42
+ if (value.version !== 1) throw new Error("LAUNCH_UNRESOLVED: unknown delivery version");
43
+ if (!custody(value.custody)) throw new Error("LAUNCH_UNRESOLVED: malformed delivery custody");
44
+ if (!record(value.settlement)) throw new Error("LAUNCH_UNRESOLVED: malformed delivery settlement");
45
+ return { custody: value.custody, settlement: value.settlement };
46
+ }
47
+ /** The settlement acknowledgement: the original execution, the event, and the custody it was delivered under. */
48
+ export interface Acknowledgement { execution: Execution; eventId: string; custody?: Custody }
49
+ export function acknowledgement(owner: Execution, eventId: string, custody?: Custody): Acknowledgement {
50
+ return custody ? { execution: owner, eventId, custody } : { execution: owner, eventId };
51
+ }
52
+ /** The origin reference of one settlement event: the bound contract, or the refused origin. */
53
+ export function settlementOrigin(value: Record<string, unknown>): UnitRef | undefined {
54
+ if (record(value.binding) && reference(value.binding.contract)) return value.binding.contract;
55
+ if (reference(value.origin)) return value.origin;
56
+ return undefined;
57
+ }
58
+ /** The execution that owns one settlement event: the bound execution, or the refused execution. */
59
+ export function settlementExecution(value: Record<string, unknown>): Execution | undefined {
60
+ if (record(value.binding) && execution(value.binding.execution)) return value.binding.execution;
61
+ if (execution(value.execution)) return value.execution;
62
+ return undefined;
63
+ }
31
64
  export function binding(value: unknown): value is Binding {
32
65
  return record(value) && reference(value.contract) && execution(value.execution) && typeof value.exportDigest === "string" && /^[a-f0-9]{64}$/.test(value.exportDigest);
33
66
  }
package/pi/work-panel.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { getKeybindings, Key, matchesKey, Text, ScrollView, truncateToWidth } from "@earendil-works/pi-tui";
3
- import { boardColumns, boardHeader, boardRow, clean, cleanRow, groupTitle, GROUPS, type Group, type Row } from "./board.ts";
3
+ import { boardColumns, boardGroup, boardHeader, boardRow, clean, cleanRow, groupTitle, GROUPS, type Group, type Row } from "./board.ts";
4
4
  import { taskLines, type WorkState } from "./work.ts";
5
5
  import type { TodoView, WorkTodo } from "./work-todo.ts";
6
6
  import type { JobHistory, WorkExec } from "./work-history.ts";
@@ -23,9 +23,9 @@ export function workEntries(data: WorkData, tab: WorkTab, history: boolean): Wor
23
23
  const todos: WorkEntry[] = data.todo && !data.todo.display.empty ? [{ value: "todos", label: clean(data.todo.display.summary), description: clean(data.todo.display.current), kind: "todo" }] : [];
24
24
  const canonicalHost = (label: string) => data.history.hosts?.find(host => host.label === label)?.id ?? label;
25
25
  // Board order: the task, then the groups in action order, as the collapsed board draws them.
26
- const rows: WorkEntry[] = GROUPS.flatMap(group => data.board.rows.filter(row => row.group === group)).map(raw => {
26
+ const rows: WorkEntry[] = GROUPS.flatMap(group => data.board.rows.filter(row => boardGroup(row.group) === group)).map(raw => {
27
27
  const row = cleanRow(raw);
28
- return { value: `${raw.kind}:${canonicalHost(raw.host)}:${raw.id}`, id: raw.id, host: canonicalHost(raw.host), ...(raw.pane ? { pane: raw.pane } : {}), kind: raw.group === "waiting" ? "queued" : raw.kind === "job" ? "job" : "agent", label: `${raw.group === "attention" || raw.group === "to_land" ? "!" : "●"} ${row.name} · ${row.state}`, description: row.host, running: raw.group === "running", row };
28
+ return { value: `${raw.kind}:${canonicalHost(raw.host)}:${raw.id}`, id: raw.id, host: canonicalHost(raw.host), ...(raw.pane ? { pane: raw.pane } : {}), kind: row.group === "waiting" ? "queued" : raw.kind === "job" ? "job" : "agent", label: `${row.group === "attention" || row.group === "to_land" ? "!" : "●"} ${row.name} · ${row.state}`, description: row.host, running: row.group === "running", row };
29
29
  });
30
30
  const visible = tab === "todos" ? todos : tab === "agents" ? rows.filter(row => row.value.startsWith("agent:")) : tab === "jobs" ? rows.filter(row => row.value.startsWith("job:")) : [...todos, ...rows];
31
31
  if (tab === "all" || tab === "jobs") {
@@ -129,7 +129,8 @@ export class WorkPanel {
129
129
  this.entries.forEach((entry, index) => {
130
130
  const mark = index === this.selected ? this.theme.fg("accent", "→ ") : " ";
131
131
  if (entry.row) {
132
- if (entry.row.group !== group) { group = entry.row.group; lines.push({ text: groupTitle(group, this.theme) }); }
132
+ const nextGroup = boardGroup(entry.row.group);
133
+ if (nextGroup !== group) { group = nextGroup; lines.push({ text: groupTitle(group, this.theme) }); }
133
134
  lines.push({ text: boardRow(entry.row, columns, width, this.theme, mark), entry: index });
134
135
  return;
135
136
  }
@@ -16,7 +16,7 @@ You may edit plans, briefs, and docs that you own.
16
16
 
17
17
  Make the code or config edit in this session, with no worker, in these cases:
18
18
 
19
- - The cause and every edit are known, and the whole change is under about 100 changed lines.
19
+ - You can name every edit before you start, and there are at most 3. An edit is one change to one place in one file. Tests you add count as edits.
20
20
  - No host can start a worker, and the change fits in one session. A failed spawn alone is not a blocker.
21
21
  - The user tells you to make the change. Never cite this skill to refuse.
22
22
 
@@ -7,5 +7,5 @@ A reply that ends with `done` comes from a closed worker. Its pane and worktree
7
7
  2. Compare the diff with the brief. Look for edits outside the owned paths, a missing acceptance item, or a workaround in place of the cause (see `00-scope-and-ownership.md`).
8
8
  3. Run the acceptance command once, at the reported head SHA. Skip it if the reply or a reviewer already shows it passing at that same SHA. Do not run the repository's heavy gate yet. A docs-only unit needs no build or test run.
9
9
  4. If the unit is not trivial, start a `reviewer` unit. Name the branch, the head SHA, and the base in its brief.
10
- 5. If something is wrong, add a follow-up `writer` unit with the specific defect. Start it on the same branch, so it continues from the kept commits: `spawn {unit: {id}, branch: <same branch>}`. Do not fix it yourself.
10
+ 5. If something is wrong and its cause and fix are known, apply step 0 of `SKILL.md`: a small fix is yours to make on the same branch. Otherwise, add a follow-up `writer` unit with the specific defect. Start it on the same branch, so it continues from the kept commits: `spawn {unit: {id}, branch: <same branch>}`.
11
11
  6. When the unit is accepted, mark its todo done with the evidence: the SHA, the command, and the result.