pi-straw-boss 0.89.0 → 0.91.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.
@@ -6410,7 +6410,13 @@ var GATE_PREFIX = "straw-link:gate";
6410
6410
  var linkGate = contract("straw-link-gate", GATE_PREFIX, void 0, true, SELECT_SHAPE, void 0, true);
6411
6411
  var REQUEST_PREFIX = "straw-link:request";
6412
6412
  var linkRequest = contract("straw-link-request", REQUEST_PREFIX, "link_request", void 0, SELECT_SHAPE, void 0, true);
6413
- var OWNERS = [robotHand, secretDrop, rpiv, mcpAdapter, piCode, uiPrompt, linkGate, linkRequest];
6413
+ var BOSS_PREFIX = "straw-boss:boss";
6414
+ var QUESTIONS_SHAPE = { parse: (owner, raw) => {
6415
+ const p = raw;
6416
+ return p?.version === 1 && str6(p.id) && p.id.length <= 64 && str6(p.digest) && str6(p.toolCallId) && Array.isArray(p.questions) && p.questions.every((q2) => str6(q2?.question) && Array.isArray(q2.options) && q2.options.every((o) => str6(o?.title))) ? { owner, id: p.id, toolCallId: p.toolCallId, digest: p.digest, questions: p.questions.map((q2) => ({ question: q2.question, multiple: false, options: q2.options.map((o) => ({ title: o.title })) })) } : void 0;
6417
+ }, body: (a) => a.cancel ? { cancel: true } : { answers: a.answers } };
6418
+ var bossQuestion = contract("sb-boss", BOSS_PREFIX, "call_tower", void 0, QUESTIONS_SHAPE, void 0, true);
6419
+ var OWNERS = [robotHand, secretDrop, rpiv, mcpAdapter, piCode, uiPrompt, linkGate, linkRequest, bossQuestion];
6414
6420
 
6415
6421
  // src/commands.ts
6416
6422
  var MAX_COMMANDS = 30;
@@ -24060,7 +24066,7 @@ function parkedRows(slot, now, targets) {
24060
24066
  }
24061
24067
  var rowOf = (t, e, returned) => ({ workspace: t.workspace, ...t.head ? { head: true } : {}, tower: t.label, id: e.id, text: e.text.slice(0, 160), type: e.card?.type ?? "legacy", ...e.card?.from ? { from: e.card.from.name } : {}, at: e.at, ...returned ? { returned } : {} });
24062
24068
  function returnedText(id2, what, at, role) {
24063
- const again = role === "tower" ? "record it again with tower_memory as a wait for the boss, or ask as you asked before" : "ask them again yourself now with ask_user_question (or call_tower again if this session cannot ask them)";
24069
+ const again = role === "tower" ? "record it again with tower_memory as a wait for the boss, or ask as you asked before" : "ask them again now with call_tower why: blocked and boss";
24064
24070
  return `Wait ${id2} (${what}) comes back to you: auto mode ended at ${hhmm(at)} and the boss is back. sb closed the card instead of keeping it for them, so no wait_card answer will come for it. If you still need it, ${again}.`;
24065
24071
  }
24066
24072
  var ownReturnedText = (id2, what, at) => `Your wait ${id2} (${what}) was parked while the boss was away. Auto mode ended at ${hhmm(at)} and the boss is back; sb closed the card instead of keeping it for them. If it still needs the boss, record it again with tower_memory (add kind wait): it reaches them now as a new card.`;
@@ -28947,7 +28953,7 @@ import { randomUUID as randomUUID14 } from "node:crypto";
28947
28953
 
28948
28954
  // src/autotext.ts
28949
28955
  var KIND2 = {
28950
- main: "Decide yourself only where the boss's words in your brief or this session cover it, quoting them; else park it: call_tower why: blocked with the decision and what you need, then go on with work that does not need it, or stop this line and say so on your board.",
28956
+ main: "Decide yourself only where the boss's words in your brief or this session cover it, quoting them; else park it: call_tower why: blocked with the decision in boss and what you need, then go on with work that does not need it, or stop this line and say so on your board.",
28951
28957
  subagent: "Decide within your brief; else caller_ping your dispatcher with the decision and stop.",
28952
28958
  train: "call_tower blocked with reply: false naming what needs the boss, then end.",
28953
28959
  run: "Record a wait for the boss with tower_memory; it is parked."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.89.0",
3
+ "version": "0.91.0",
4
4
  "description": "Straw Boss coordination for pi in Herdr: sessions join a tab's net by choice, the first joiner is its main agent, a workspace tower opens on demand with a live monitoring dashboard, and boss_broadcast reaches the rest",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/prompts/main.md CHANGED
@@ -14,7 +14,7 @@ You are the main agent of Herdr tab {{tab}}, of kind {{duty}}: the boss works wi
14
14
  - When your work turns to another task, `boss_rename` yourself; `boss_duty` when your kind changes (watching, not finishing tasks, is `standing`).
15
15
  - Your work board fills itself from your todos and name: keep them current. `board_set` overrides it until your todos move. Keep secrets, credentials, customer data, and paths outside the project off it: allies' towers read it. Not a report: the done report still goes to whoever asked.
16
16
  - Call `call_tower` at three points only, with `why`: `milestone` when a task landed or a tower request is done (reply: false unless needed); `shared` before you change anything outside your tab (port, database, shared branch, deploy target, another app's checkout, running service), what, how long, reply: false: a heads-up, not a request for go; go ahead at once; stop on a named clash<!-- integration --> (a car slip waits for sb's car notice)<!-- /integration -->; `blocked` when you wait on someone outside your tab or on a decision your authorizations do not cover, or need a work's owner and do not know who (say what; the tower finds them; `waitsOn` names a teammate device). Progress and incidents go on your board: never call the tower to report them.
17
- - A `wait_card` message is the boss's answer to your wait: act on it; it says when to call `secret_drop`. Re-ask a wait you raised only with `boss_wait_ask`; a `wait_returned` one with `ask_user_question`.
17
+ - A `wait_card` message is the boss's answer to your wait: act on it; it says when to call `secret_drop`. Re-ask a wait you raised only with `boss_wait_ask`; a `wait_returned` one with `call_tower` `boss`.
18
18
  - If a tower opened your tab, report the outcome to the sender, and to that tower with `call_tower` (`why: milestone`, reply: false), when done, then wait to be closed.
19
19
  - Done when every task has landed<!-- integration --> (integration app: sb's car notice says landed)<!-- /integration --> or is reported blocked, its worktree is removed, and your board is cleared.
20
20
  <!-- integration -->
package/src/auto.ts CHANGED
@@ -7,6 +7,7 @@ import { type AgentKind, CALL_TOWER_LINE, cancelledText, offNotice, onNotice, re
7
7
  import type { Bridge, Ended } from "./bridge.ts";
8
8
  import type { Declined } from "./declined.ts";
9
9
  import type { Ask } from "./host.ts";
10
+ import { bossQuestion } from "./owners.ts";
10
11
  import type { Kit } from "./state.ts";
11
12
  import { secretShaped } from "./server/waitcard.ts";
12
13
 
@@ -80,10 +81,10 @@ export function createAuto({ pi, cfg, s, guiDir, me }: Kit, d: AutoDeps = {}) {
80
81
  }
81
82
  });
82
83
  pi.on("tool_result", (event) => {
83
- // A call sb cancelled never reads as the boss's Esc: the result is replaced, by the call's id.
84
- const cancelledTool = cancelledIds.get(event.toolCallId);
85
- if (cancelledTool !== undefined) return (cancelledIds.delete(event.toolCallId), { content: [{ type: "text" as const, text: cancelledText(current?.since, cancelledTool, kind()) }] });
86
- const dialog = escaped.get(event.toolCallId);
84
+ // A call sb cancelled never reads as the boss's Esc: the result is replaced, by the call's id. A `call_tower` boss question that went to the tower keeps its own result, which says so (bossask.ts).
85
+ const cancelledTool = cancelledIds.get(event.toolCallId), sentBoss = event.toolName === "call_tower" && (event.details as { boss?: unknown } | undefined)?.boss === "tower";
86
+ if (cancelledTool !== undefined && (cancelledIds.delete(event.toolCallId), !sentBoss)) return { content: [{ type: "text" as const, text: cancelledText(current?.since, cancelledTool, kind()) }] };
87
+ const dialog = sentBoss ? undefined : escaped.get(event.toolCallId);
87
88
  escaped.delete(event.toolCallId);
88
89
  let line: string | undefined;
89
90
  if (dialog) line = refusedText(current?.since, dialog, kind());
@@ -112,11 +113,13 @@ export function createAuto({ pi, cfg, s, guiDir, me }: Kit, d: AutoDeps = {}) {
112
113
  /** A confirmed `on`: the open waits end (an owner that takes a cancel gets it; for the rest the turn is aborted), each with sb's text; a first `on` also tells the session once. */
113
114
  function cancelOpen(st: AutoState, first: boolean) {
114
115
  const unrelayed = tracker?.unrelayed() ?? 0, ended = d.bridge?.cancelWaits?.((dlg) => bossDialogs.has(dlg.id)) ?? { cancelled: [], stuck: [] };
115
- for (const e of [...ended.cancelled, ...ended.stuck]) {
116
+ // `call_tower`'s boss question (bossask.ts) is cancelled too, but says nothing here: it sends itself to the tower and its result says so.
117
+ const own = (e: Ended) => e.dialog.owner !== bossQuestion.name;
118
+ for (const e of [...ended.cancelled, ...ended.stuck].filter(own)) {
116
119
  if (e.toolCallId) (cancelledIds.set(e.toolCallId, e.tool), d.declined?.sbCancelled(e.toolCallId));
117
120
  note({ tool: e.tool, kind: "cancelled", gist: gistOfDialog(e) });
118
121
  }
119
- const texts = [...new Set([...ended.cancelled, ...ended.stuck].map((e) => cancelledText(st.since, e.tool, kind())))];
122
+ const texts = [...new Set([...ended.cancelled, ...ended.stuck].filter(own).map((e) => cancelledText(st.since, e.tool, kind())))];
120
123
  if (first && !d.silent?.()) texts.push(onNotice(st.since));
121
124
  // An owner that took the cancel closes the ui.custom it drew (rpiv, robot_hand 0.8.0), which the wrap counts as a dialog nobody relays: those do not need the turn aborted (AMC-F001).
122
125
  const open = Math.max(0, unrelayed - ended.cancelled.length);
package/src/autotext.ts CHANGED
@@ -4,7 +4,7 @@ import { clock } from "./autostate.ts";
4
4
 
5
5
  export type AgentKind = "main" | "subagent" | "train" | "run";
6
6
  const KIND: Record<AgentKind, string> = {
7
- main: "Decide yourself only where the boss's words in your brief or this session cover it, quoting them; else park it: call_tower why: blocked with the decision and what you need, then go on with work that does not need it, or stop this line and say so on your board.",
7
+ main: "Decide yourself only where the boss's words in your brief or this session cover it, quoting them; else park it: call_tower why: blocked with the decision in boss and what you need, then go on with work that does not need it, or stop this line and say so on your board.",
8
8
  subagent: "Decide within your brief; else caller_ping your dispatcher with the decision and stop.",
9
9
  train: "call_tower blocked with reply: false naming what needs the boss, then end.",
10
10
  run: "Record a wait for the boss with tower_memory; it is parked.",
@@ -17,7 +17,7 @@ export const cancelledText = (since: string | undefined, tool: string, kind: Age
17
17
  export const onNotice = (since: string | undefined) => `sb: auto mode is on since ${clock(since)}: the boss is away until they end it. Nothing that waits for them runs; decide only where the boss's words cover it, or park it; never wait for the boss.`;
18
18
  /** How each kind asks again for a parked wait that came back when auto mode ended (docs/specs/2026-11-21-auto-return.md, AR-D3). */
19
19
  const AGAIN: Record<AgentKind, string> = {
20
- main: "Ask them again yourself then, with ask_user_question.",
20
+ main: "Ask them again then, with call_tower why: blocked and boss.",
21
21
  subagent: "Ask again then as your brief allows (caller_ping your dispatcher).",
22
22
  train: "Ask again with call_tower then.",
23
23
  run: "Record it again with tower_memory if it still needs them.",
package/src/bossask.ts ADDED
@@ -0,0 +1,71 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { Type } from "typebox";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { every } from "./lanface.ts";
5
+ import { BOSS_PREFIX, type Bus, type Question, questionsDigest } from "./owners.ts";
6
+ import type { Kit } from "./state.ts";
7
+
8
+ // A decision only the boss can make, asked by code (docs/specs/2026-11-25-idle-wrap-up.md part 2; boss 2026-11-25: 「「自己問我」應該做成程式碼,直接從程式碼發出」). `call_tower` with `why: blocked` and `boss` draws
9
+ // the question in this main's own pane with pi's dialog (a select with the options and a typed answer, or an input), so Herdr shows the pane waiting and the GUI relays the select as any dialog; the answer is the tool's
10
+ // result and nothing goes to the tower. Under auto mode, in a teammate's turn, on an unattended device, without a terminal, and for any session that is no tab's main (a member, a train, a tower), nothing is drawn:
11
+ // the question goes to the tower as `blocked`, as before 0.91.0. A dialog open when auto mode starts is ended here, and the question goes to the tower: the watch looks at auto.json more often than auto mode's
12
+ // own transition does, so the dialog is usually gone before that transition would cancel it (auto.ts leaves a cancelled `call_tower` its own result).
13
+
14
+ export interface BossQuestion { question: string; options?: string[] }
15
+ const QUESTION_MAX = 500, OPTION_MAX = 120, OPTIONS_MAX = 8, WATCH_MS = 500;
16
+ /** The select's last row: the boss types his own answer instead. */
17
+ export const OWN_ANSWER = "Type another answer…";
18
+ /** No descriptions: `call_tower`'s own clause names it, and the limits are checked here (a tool's size is paid on every turn: tests/tools-budget.test.ts). */
19
+ export const bossParameter = () => Type.Optional(Type.Object({ question: Type.String(), options: Type.Optional(Type.Array(Type.String())) }));
20
+
21
+ /** The question checked and folded: one line each, the options without blanks or repeats. */
22
+ export function bossOf(raw: BossQuestion): BossQuestion {
23
+ const line = (v: unknown) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim() : "");
24
+ const question = line(raw.question);
25
+ if (!question || question.length > QUESTION_MAX) throw new Error(`boss.question is required: one question of 1 to ${QUESTION_MAX} characters`);
26
+ const options = [...new Set((raw.options ?? []).map(line).filter((o) => o && o !== OWN_ANSWER))];
27
+ if (options.length > OPTIONS_MAX || options.some((o) => o.length > OPTION_MAX)) throw new Error(`boss.options: at most ${OPTIONS_MAX}, each at most ${OPTION_MAX} characters`);
28
+ return { question, ...(options.length ? { options } : {}) };
29
+ }
30
+ /** What the tower gets when the boss is not asked here: the message, then the question and its options. */
31
+ export const withBoss = (message: string, q: BossQuestion) => `${message}\nFor the boss: ${q.question}${q.options ? `\nOptions: ${q.options.join(" | ")}` : ""}`;
32
+
33
+ export type Asked = { kind: "answered"; text: string } | { kind: "none"; text: string } | { kind: "tower"; note?: string };
34
+ export type BossAsk = (q: BossQuestion, signal: AbortSignal | undefined, ctx: Pick<ExtensionContext, "hasUI" | "ui"> | undefined, callId?: string) => Promise<Asked>;
35
+ const AUTO_NOTE = "Auto mode is on (the boss is away): the tower parks it, and it comes back to you as a wait_returned message when he is back. Ask him again then, with call_tower boss.";
36
+ type Got = { answer: string; typed: boolean; by: "remote" | "local"; note?: string } | { cancel: true };
37
+
38
+ export function createBossAsk({ pi, cfg, s, role }: Kit, d: { attended(): boolean; remote(): boolean }): BossAsk {
39
+ const watch = cfg.face?.every ?? every, bus = pi.events as unknown as Bus;
40
+ return async (q, signal, ctx, callId) => {
41
+ if (role() !== "main" || s.isTrain || s.isTower || s.remoteOrigin || d.remote() || !d.attended() || !ctx?.hasUI) return { kind: "tower" };
42
+ if (s.autoOn()) return { kind: "tower", note: AUTO_NOTE };
43
+ const title = `The boss decides: ${q.question}`, ac = new AbortController(), stop = watch(() => void (s.autoOn() && ac.abort()), WATCH_MS);
44
+ const opts = { signal: signal ? AbortSignal.any([signal, ac.signal]) : ac.signal };
45
+ // The same question relayed as sb's own questionnaire (owners.ts `bossQuestion`): the page or a paired device picks an option or types an answer, or cancels; the first answer, here or there, wins.
46
+ const id = randomUUID(), questions: Question[] = [{ question: title, multiple: false, options: (q.options ?? []).map((title) => ({ title })) }], digest = questionsDigest(questions);
47
+ let got: Got | undefined;
48
+ const off = bus.on(`${BOSS_PREFIX}:answer`, (raw) => {
49
+ const a = raw as { version?: unknown; id?: unknown; answerId?: unknown; digest?: unknown; answers?: { choices?: unknown; text?: unknown; note?: unknown }[]; cancel?: unknown };
50
+ if (a?.version !== 1 || a.id !== id) return;
51
+ const r = Array.isArray(a.answers) && a.answers.length === 1 ? a.answers[0] : undefined, pick = Array.isArray(r?.choices) && r.choices.length === 1 ? q.options?.[Number(r.choices[0])] : undefined, text = typeof r?.text === "string" ? r.text.trim() : "", note = typeof r?.note === "string" ? r.note.trim() : ""; // the page's note on a pick: a condition the boss adds
52
+ const reason = got ? "closed" : a.digest !== digest ? "digest" : a.cancel === true || pick || text ? undefined : "malformed";
53
+ if (!reason) (got = a.cancel === true ? { cancel: true } : { answer: pick ?? text, typed: !pick, by: "remote", ...(note ? { note } : {}) }), ac.abort();
54
+ bus.emit(`${BOSS_PREFIX}:answer-result`, { version: 1, id, answerId: a.answerId, accepted: !reason, ...(reason ? { reason } : {}) });
55
+ });
56
+ if (callId) bus.emit(`${BOSS_PREFIX}:pending`, { version: 1, id, toolCallId: callId, digest, questions });
57
+ try {
58
+ const pick = q.options ? await ctx.ui.select(title, [...q.options, OWN_ANSWER], opts) : OWN_ANSWER;
59
+ // Auto mode starting between the pick and the typed answer opens no input (it would be answered as Escape and marked refused).
60
+ const typed = pick === OWN_ANSWER, answer = typed && !opts.signal.aborted && !s.autoOn() ? await ctx.ui.input(title, "Your answer", opts) : typed ? undefined : pick;
61
+ if (!got && answer?.trim()) got = { answer: answer.trim(), typed, by: "local" };
62
+ } finally {
63
+ stop();
64
+ off();
65
+ if (callId) bus.emit(`${BOSS_PREFIX}:closed`, { version: 1, id, by: got && "by" in got ? got.by : got ? "cancel" : signal?.aborted ? "abort" : s.autoOn() ? "auto" : "local" });
66
+ }
67
+ if (got && "answer" in got) return { kind: "answered", text: `The boss ${got.typed ? "answered" : "chose"}: ${JSON.stringify(got.answer)}${got.note ? `. His note: ${JSON.stringify(got.note)}` : ""}. This is the boss's answer, asked in this pane; nothing was sent to the tower.` };
68
+ if (s.autoOn()) return { kind: "tower", note: `Auto mode started while the boss was asked, so the dialog closed. ${AUTO_NOTE}` };
69
+ return { kind: "none", text: `The boss did not answer (${signal?.aborted ? "the turn was stopped" : "Esc"}): nothing was sent to the tower. Go on with work that does not need it; ask again only if it still blocks you.` };
70
+ };
71
+ }
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ import { createBoardFill } from "./boardfill.ts";
12
12
  import { createCapFill } from "./capfill.ts";
13
13
  import { createBriefing } from "./briefing.ts";
14
14
  import { createBossWatch } from "./bosswatch.ts";
15
+ import { createBossAsk } from "./bossask.ts";
15
16
  import { createBossPair } from "./bosspair.ts";
16
17
  import { createCloseMain } from "./closemain.ts";
17
18
  import { createDigest } from "./digest.ts";
@@ -47,6 +48,7 @@ import { hasIntegrationApp } from "./train/appsconfig.ts";
47
48
  import { registerTrust } from "./trust/ask.ts";
48
49
  import { registerRunTrust } from "./trust/runtrust.ts";
49
50
  import { registerThreadTools } from "./threadtools.ts";
51
+ import { createWrapUp } from "./wrapup.ts";
50
52
 
51
53
  export type { Deps } from "./state.ts";
52
54
 
@@ -57,10 +59,10 @@ const INTEGRATION_MS = 20_000;
57
59
  const JOIN_RETRY_MS = [1_000, 2_000, 5_000, 15_000];
58
60
 
59
61
  // The composition root: the concerns live in their own modules (state.ts says what they share), and this wires them for one pi session.
60
- export function createStrawBoss({ run: given, world: reading, api = herdrApi(), call = herdrCall(), copy = copyText, env = process.env, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), promptDir = fileURLToPath(new URL("../prompts", import.meta.url)), openUrl = openBrowser, watch = herdrWatch(), stateDir, autoTower = true, nudgeMs = NUDGE_MS, version = VERSION, guardMs = GUARD_MS, couple = true, events = herdrEvents(), detectMs = DETECT_MS, now = Date.now, later = afterExit, adoptMs = ADOPT_MS, restoreMs = RESTORE_WAIT_MS, integrationMs = INTEGRATION_MS, joinRetryMs = JOIN_RETRY_MS, link, server = given ? null : {}, ask, startRead, runSide, face, cwd = () => process.cwd() }: Deps = {}) {
62
+ export function createStrawBoss({ run: given, world: reading, api = herdrApi(), call = herdrCall(), copy = copyText, env = process.env, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), promptDir = fileURLToPath(new URL("../prompts", import.meta.url)), openUrl = openBrowser, watch = herdrWatch(), stateDir, autoTower = true, nudgeMs = NUDGE_MS, version = VERSION, guardMs = GUARD_MS, couple = true, events = herdrEvents(), detectMs = DETECT_MS, now = Date.now, later = afterExit, adoptMs = ADOPT_MS, restoreMs = RESTORE_WAIT_MS, integrationMs = INTEGRATION_MS, joinRetryMs = JOIN_RETRY_MS, link, server = given ? null : {}, ask, startRead, runSide, face, cwd = () => process.cwd(), idleLook }: Deps = {}) {
61
63
  // A run that is not injected is the real CLI, with its listings over the socket; an injected one answers everything itself, listings included.
62
64
  const run = given ?? socketRun(herdrRun, call), world = reading ?? (given ? worldOf(given) : herdrWorld(call));
63
- const cfg: Config = { run, world, api, call, copy, env, sleep, promptDir, openUrl, watch, stateDir, autoTower, nudgeMs, version, guardMs, couple, events, detectMs, now, later, adoptMs, restoreMs, integrationMs, joinRetryMs, link, server, ask, startRead, runSide, face, cwd };
65
+ const cfg: Config = { run, world, api, call, copy, env, sleep, promptDir, openUrl, watch, stateDir, autoTower, nudgeMs, version, guardMs, couple, events, detectMs, now, later, adoptMs, restoreMs, integrationMs, joinRetryMs, link, server, ask, startRead, runSide, face, cwd, idleLook };
64
66
  return function strawBoss(pi: ExtensionAPI): void {
65
67
  // Outside Herdr there is no tab to coordinate. Every session in Herdr relays its dialogs to the GUI (bridge.ts), subagents too: they ask
66
68
  // questions as well. A pi-herdr-agents worker never joins: its parent represents it.
@@ -99,14 +101,16 @@ export function createStrawBoss({ run: given, world: reading, api = herdrApi(),
99
101
  pi.on("session_start", () => void (kit.s.toolSet ??= { link: link.inUse() && link.attended(), cars: cars.enabled(), carApp: hasIntegrationApp(cfg.cwd()) }));
100
102
  let trainGuard: TrainGuard | undefined;
101
103
  const addTrainCar = trainCarTool(kit, () => trainGuard, cars, (text) => reach.callTower(text, undefined, false, "blocked"));
102
- const membership = createMembership(kit, { presence, election, guard, briefing, roles, openTower: reach.openTower, register: () => (tools.addNetTools(), s.isTower || (watch.addTool(), pair.addTool()), tools.addPromote(), tools.addDuty(), tools.addHandover(), addTrainCar()), onMain: link.look, control: () => control });
104
+ const membership = createMembership(kit, { presence, election, guard, briefing, roles, openTower: reach.openTower, register: () => (tools.addNetTools(), s.isTower || (watch.addTool(), pair.addTool(), wrap.addTool()), tools.addPromote(), tools.addDuty(), tools.addHandover(), addTrainCar()), onMain: link.look, control: () => control });
103
105
  // `look` (above) starts and upgrades the sb server (src/server/) and is the way to it; a session that is no part of that has none.
104
106
  const pair = createBossPair(kit, { ask: cfg.ask ?? look?.ask, remote: () => Boolean(link.remoteScope()) }); // boss_pair and board_read's review threads (bosspair.ts)
105
107
  createCapFill(kit); // a main's capacity facts for the board (capfill.ts)
106
- const tools = createTools(kit, { ...reach, mainDuty, promote: membership.promote, digest, closeMain: (query) => control.closeMain(query), closePane: (pane) => control.closePane(pane), deadPanes: () => control.deadPanes(), listen: () => control.register(), link, server: look, boardFill: createBoardFill(kit), pair, waitAsk: () => mainWaitAsk(kit, { ask: cfg.ask ?? look?.ask, here: (fn) => host.here(fn), auto }) });
108
+ const boardFill = createBoardFill(kit);
109
+ const tools = createTools(kit, { ...reach, mainDuty, promote: membership.promote, digest, closeMain: (query) => control.closeMain(query), closePane: (pane) => control.closePane(pane), deadPanes: () => control.deadPanes(), listen: () => control.register(), link, server: look, boardFill, pair, waitAsk: () => mainWaitAsk(kit, { ask: cfg.ask ?? look?.ask, here: (fn) => host.here(fn), auto }), bossAsk: createBossAsk(kit, { attended: () => link.attended(), remote: () => Boolean(link.remoteScope()) }) });
107
110
  const host = createHost(kit, { connected: membership.connected, ask: cfg.ask ?? look?.ask });
108
111
  closeSelf = createClosing(kit);
109
112
  const control = createCloseMain(kit, { closeSelf, check: bridge.stashCheck, turn: bridge.turn });
113
+ const wrap = createWrapUp(kit, { reach, boardFill, closeSelf, blockers: () => bridge.turn?.blockers(), duty: () => mainDuty.now(), remote: () => Boolean(link.remoteScope()), ask: cfg.ask ?? look?.ask }); // idle wrap-up and boss_wrap (wrapup.ts)
110
114
  const watch = createBossWatch(kit, { ask: cfg.ask ?? look?.ask, control, openTower: reach.openTower, remote: () => Boolean(link.remoteScope()) });
111
115
  registerSession(kit, { mainDuty, attended: () => link.attended(), integration: createIntegrationWatch(kit), runMode, briefing, roles, presence, membership, guard, host, reach, digest, control, startTower: createTower(kit, { membership, presence, tools, control, digest, roles, reach }) });
112
116
  trainGuard = registerTrainGuard(kit, cars.client, mainDuty);
package/src/link/hooks.ts CHANGED
@@ -107,6 +107,7 @@ export function createRemoteTurns({ pi, now, config, policy: policyDeps, home, a
107
107
  if (e.toolName === "boss_server") return { block: true, reason: "a remote turn cannot see or restart this computer's sb server, whatever its sender's level" };
108
108
  if (e.toolName === "boss_handover") return { block: true, reason: "a remote turn cannot open a successor of this main, whatever its sender's level" };
109
109
  if (e.toolName === "boss_pair") return { block: true, reason: "a remote turn cannot open a review thread, whatever its sender's level" };
110
+ if (e.toolName === "boss_wrap") return { block: true, reason: "a remote turn cannot wrap up this main, whatever its sender's level" };
110
111
  // As an ally run (server/runtools.ts): dead panes and their list are the local tower's, whatever the sender's level; a main is checked by the tool against its `sb_opened_by` (tools.ts).
111
112
  if (e.toolName === "boss_close_main" && (input.pane !== undefined || input.main === undefined)) return { block: true, reason: REMOTE_CLOSE };
112
113
  if (level === "dispatch") return;
@@ -1,4 +1,6 @@
1
1
  import { Type, type Static, type TSchema } from "typebox";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { type Asked, type BossAsk, bossOf, bossParameter, withBoss } from "../bossask.ts";
2
4
  import type { Reach } from "../reach.ts";
3
5
  import { waitOwner, waitWhat } from "./kinds.ts";
4
6
  import type { Link } from "./runtime.ts";
@@ -6,10 +8,13 @@ import type { Link } from "./runtime.ts";
6
8
  // `call_tower`, a joined session's call to its tower, with the two parts of a link wait (docs/specs/2026-11-21-box-mac-waits.md): `waitsOn` says the task ends at a step only a teammate device can take, and the tower forwards it as a
7
9
  // wait the other end must route (§2.1); `linkWait` answers a wait a teammate device has on this workspace (§2.4). The router in the sb server acts first, so a refusal sends nothing. Kept out of tools.ts, which carries a line budget.
8
10
 
9
- type Tool = <P extends TSchema>(name: string, description: string, parameters: P, body: (params: Static<P>) => Promise<{ text: string; details?: unknown }>) => void;
10
- export const CALL_TOWER_DESCRIPTION = "Send one message to your workspace's tower, or another by workspace, at three points only: why milestone (something landed; reply false unless needed), shared (a heads-up before you change something outside your tab; reply false; go ahead, the tower answers only on a clash), blocked (you wait on someone outside your tab, or on a decision your authorizations do not cover). Opens the tower when none runs; the code writes the header; it answers through intercom unless reply is false. Progress goes on your board, not here.";
11
+ /** What a tool body gets besides its parameters: the call's signal and pi's context, for a dialog in the pane. */
12
+ export type ToolCtx = Pick<ExtensionContext, "hasUI" | "ui">;
13
+ type Tool = <P extends TSchema>(name: string, description: string, parameters: P, body: (params: Static<P>, signal?: AbortSignal, ctx?: ToolCtx, id?: string) => Promise<{ text: string; details?: unknown }>) => void;
14
+ export const CALL_TOWER_DESCRIPTION = "Send one message to your workspace's tower, or another by workspace, at three points only: why milestone (something landed; reply false unless needed), shared (a heads-up before you change something outside your tab; reply false; go ahead, the tower answers only on a clash), blocked (you wait on someone outside your tab, or on a decision your authorizations do not cover; the boss's own decision: boss, asked in your pane). Opens the tower when none runs; the code writes the header; it answers through intercom unless reply is false. Progress goes on your board, not here.";
11
15
 
12
- export function callTowerTool(tool: Tool, towerCall: boolean, callTower: Reach["callTower"], link: Pick<Link, "waitOp">): void {
16
+ /** `bossAsk` (bossask.ts) draws a `boss` question in a local main's pane; without it (a tower run) the question goes to the tower in the message. */
17
+ export function callTowerTool(tool: Tool, towerCall: boolean, callTower: Reach["callTower"], link: Pick<Link, "waitOp">, bossAsk?: BossAsk): void {
13
18
  // A main says why it calls (required); a tower's call is a blocked one, so it may leave it out and the header says unspecified.
14
19
  const whyType = Type.Union([Type.Literal("milestone"), Type.Literal("shared"), Type.Literal("blocked")], { description: "milestone, shared, or blocked." });
15
20
  const whyField = towerCall ? Type.Optional(whyType) : whyType;
@@ -33,9 +38,18 @@ export function callTowerTool(tool: Tool, towerCall: boolean, callTower: Reach["
33
38
  device: Type.String({ description: "Label, short id, or id." }),
34
39
  what: Type.Optional(Type.String({ description: "One line of at most 200 bytes; default the message's first line." })),
35
40
  }, { description: "Instead of your tower: that device's standing main, a question (why blocked) or a notice (why milestone)." })),
41
+ boss: bossParameter(),
36
42
  }),
37
- async ({ message, why, workspace, reply, waitsOn, linkWait, standing }) => {
38
- if ([waitsOn, linkWait, standing].filter(Boolean).length > 1) throw new Error("waitsOn, linkWait, and standing do not go together");
43
+ async ({ message, why, workspace, reply, waitsOn, linkWait, standing, boss }, signal, ctx, id) => {
44
+ if ([waitsOn, linkWait, standing, boss].filter(Boolean).length > 1) throw new Error("waitsOn, linkWait, standing, and boss do not go together");
45
+ if (boss) {
46
+ // A decision only the boss can make (bossask.ts): drawn in this pane, its answer the result and nothing sent; else the tower gets it as blocked.
47
+ if (why !== "blocked") throw new Error("boss goes with why blocked: a decision only the boss can make");
48
+ const q = bossOf(boss), asked: Asked = bossAsk ? await bossAsk(q, signal, ctx, id) : { kind: "tower" };
49
+ if (asked.kind !== "tower") return { text: asked.text, details: { boss: asked.kind } };
50
+ const sent = await callTower(withBoss(message, q), workspace, reply ?? true, why);
51
+ return { text: asked.note ? `${sent.text} ${asked.note}` : sent.text, details: { ...sent.details, boss: "tower" } };
52
+ }
39
53
  if (standing) {
40
54
  // D13: the code sends it as the workspace's tower identity; the tower gets no call for it.
41
55
  if (why !== "blocked" && why !== "milestone") throw new Error("standing goes with why blocked (a question) or milestone (a notice)");
package/src/owners.ts CHANGED
@@ -165,4 +165,8 @@ export const linkGate = contract("straw-link-gate", GATE_PREFIX, undefined, true
165
165
  /** The approval dialog of a `link_request` (src/link/approval.ts): owned by the tool whose call it asks about, so only that call in flight can open it. */
166
166
  export const REQUEST_PREFIX = "straw-link:request";
167
167
  export const linkRequest = contract("straw-link-request", REQUEST_PREFIX, "link_request", undefined, SELECT_SHAPE, undefined, true);
168
- export const OWNERS: OwnerAdapter[] = [robotHand, secretDrop, rpiv, mcpAdapter, piCode, uiPrompt, linkGate, linkRequest];
168
+ /** `call_tower`'s boss question (bossask.ts): sb's own questionnaire of one question, its options and the boss's own words, so the page and a paired device answer it as rpiv's; it takes a cancel. Its tool's twin select is dropped. */
169
+ export const BOSS_PREFIX = "straw-boss:boss";
170
+ const QUESTIONS_SHAPE: Shape = { parse: (owner, raw) => { const p = raw as { version?: unknown; id?: unknown; toolCallId?: unknown; digest?: unknown; questions?: Question[] }; return p?.version === 1 && str(p.id) && p.id.length <= 64 && str(p.digest) && str(p.toolCallId) && Array.isArray(p.questions) && p.questions.every((q) => str(q?.question) && Array.isArray(q.options) && q.options.every((o) => str(o?.title))) ? { owner, id: p.id, toolCallId: p.toolCallId, digest: p.digest, questions: p.questions.map((q) => ({ question: q.question, multiple: false, options: q.options.map((o) => ({ title: o.title })) })) } : undefined; }, body: (a) => (a.cancel ? { cancel: true } : { answers: a.answers }) };
171
+ export const bossQuestion = contract("sb-boss", BOSS_PREFIX, "call_tower", undefined, QUESTIONS_SHAPE, undefined, true);
172
+ export const OWNERS: OwnerAdapter[] = [robotHand, secretDrop, rpiv, mcpAdapter, piCode, uiPrompt, linkGate, linkRequest, bossQuestion];
@@ -49,7 +49,7 @@ const rowOf = (t: Target, e: Entry, returned?: Returned): ParkedRow => ({ worksp
49
49
 
50
50
  /** What the raiser of a parked card is told when auto mode ends, under the `wait_returned` header: the boss is back, so it asks them again itself; sb closed the card, and no `wait_card` answer comes. */
51
51
  export function returnedText(id: string, what: string, at: string, role: string | undefined): string {
52
- const again = role === "tower" ? "record it again with tower_memory as a wait for the boss, or ask as you asked before" : "ask them again yourself now with ask_user_question (or call_tower again if this session cannot ask them)";
52
+ const again = role === "tower" ? "record it again with tower_memory as a wait for the boss, or ask as you asked before" : "ask them again now with call_tower why: blocked and boss";
53
53
  return `Wait ${id} (${what}) comes back to you: auto mode ended at ${hhmm(at)} and the boss is back. sb closed the card instead of keeping it for them, so no wait_card answer will come for it. If you still need it, ${again}.`;
54
54
  }
55
55
  /** The event of a tower (the head included) whose own parked card comes back: it records the wait again if it still needs the boss. */
package/src/state.ts CHANGED
@@ -38,9 +38,9 @@ export type Scope = "tab" | "workspace" | "towers" | "all";
38
38
  * `run` is the CLI for every command; left out, Herdr's listings, `pane current`, and `report-metadata` go over the socket instead (`socketRun`) and `world` is one `session.snapshot`. `world` is the dashboard's and the GUI's reading of panes and workspaces.
39
39
  * `integrationMs` is how long after its start a session checks that Herdr's pi integration is in place (integration.ts); `joinRetryMs` is the waits between a session's asks when its start could not place it or join the net (the last one repeats; session.ts); `adoptMs` is how often a session looks after the sb server; `ask` is how it reaches the server's GUI (host.ts; the control socket by default, through the look); `startRead` is where the recorded server's start time is read from (handover.ts; the process's own cache by default).
40
40
  */
41
- export interface Deps { run?: HerdrRun; world?: HerdrWorld; api?: HerdrApi; call?: HerdrCall; copy?: (text: string) => Promise<void>; env?: NodeJS.ProcessEnv; sleep?: Sleep; promptDir?: string; openUrl?: (url: string) => Promise<void>; watch?: HerdrWatch; stateDir?: string; autoTower?: boolean; nudgeMs?: number; version?: string; guardMs?: number; couple?: boolean; events?: HerdrEvents; detectMs?: number; now?: () => number; later?: (pid: number, args: string[]) => void; adoptMs?: number; restoreMs?: number; integrationMs?: number; joinRetryMs?: number[]; link?: LinkDeps; server?: ServerLookDeps | null; ask?: Ask; startRead?: StartRead; runSide?: RunSideDeps; face?: FaceSeams; /** The session's working folder, where its project's apps.json is read (`process.cwd()`). */ cwd?: () => string }
41
+ export interface Deps { run?: HerdrRun; world?: HerdrWorld; api?: HerdrApi; call?: HerdrCall; copy?: (text: string) => Promise<void>; env?: NodeJS.ProcessEnv; sleep?: Sleep; promptDir?: string; openUrl?: (url: string) => Promise<void>; watch?: HerdrWatch; stateDir?: string; autoTower?: boolean; nudgeMs?: number; version?: string; guardMs?: number; couple?: boolean; events?: HerdrEvents; detectMs?: number; now?: () => number; later?: (pid: number, args: string[]) => void; adoptMs?: number; restoreMs?: number; integrationMs?: number; joinRetryMs?: number[]; link?: LinkDeps; server?: ServerLookDeps | null; ask?: Ask; startRead?: StartRead; runSide?: RunSideDeps; face?: FaceSeams; /** The session's working folder, where its project's apps.json is read (`process.cwd()`). */ cwd?: () => string; /** Runs the idle wrap-up's look (wrapup.ts) on its schedule, once a minute by default, and returns its stop; a test calls the look itself. */ idleLook?: (look: () => Promise<void>) => () => void }
42
42
  /** The dependencies with their defaults filled in; `server` (how a session looks after the sb server, server-look.ts) is null in a session that does not: a test world. */
43
- export type Config = Required<Omit<Deps, "stateDir" | "link" | "server" | "ask" | "startRead" | "runSide" | "face">> & Pick<Deps, "stateDir" | "link" | "server" | "ask" | "startRead" | "runSide" | "face">;
43
+ export type Config = Required<Omit<Deps, "stateDir" | "link" | "server" | "ask" | "startRead" | "runSide" | "face" | "idleLook">> & Pick<Deps, "stateDir" | "link" | "server" | "ask" | "startRead" | "runSide" | "face" | "idleLook">;
44
44
 
45
45
  export interface State {
46
46
  // What this session is.
package/src/tools.ts CHANGED
@@ -13,7 +13,7 @@ import type { Membership } from "./membership.ts";
13
13
  import { type CloseMain, type Control, handedNotice, refuseStanding, remoteCloseTarget } from "./closemain.ts";
14
14
  import { deadList } from "./deadpane.ts";
15
15
  import type { Link } from "./link/runtime.ts";
16
- import { callTowerTool } from "./link/waitcall.ts";
16
+ import { callTowerTool, type ToolCtx } from "./link/waitcall.ts";
17
17
  import { INTEGRATOR } from "./integrator.ts";
18
18
  import { foldName } from "./namefold.ts";
19
19
  import { openSuccessor, opener } from "./opener.ts";
@@ -44,7 +44,7 @@ export const linkRequestParameters = () => Type.Object({
44
44
  reason: Type.String({ description: "One line: why you ask. The boss reads it in the dialog." }),
45
45
  });
46
46
  /** Every tool sb registers, all of them after the child return (index.ts): a role that lists one fails `/boss roles-check` (rolescheck.ts). tests/roles-check.test.ts pins it to the recorded registry. */
47
- export const PARENT_ONLY: readonly string[] = ["board_read", "board_set", "boss_auto", "boss_broadcast", "boss_close_main", "boss_duty", "boss_handover", "boss_open_main", "boss_pair", "boss_promote", "boss_rename", "boss_revive_main", "boss_server", "boss_wait_ask", "boss_watch", "call_tower", "ledger_sweep", "link_request", "tower_done", "tower_list", "tower_memory", "tower_reply", "tower_send", "train_car"];
47
+ export const PARENT_ONLY: readonly string[] = ["board_read", "board_set", "boss_auto", "boss_broadcast", "boss_close_main", "boss_duty", "boss_handover", "boss_open_main", "boss_pair", "boss_promote", "boss_rename", "boss_revive_main", "boss_server", "boss_wait_ask", "boss_watch", "boss_wrap", "call_tower", "ledger_sweep", "link_request", "tower_done", "tower_list", "tower_memory", "tower_reply", "tower_send", "train_car"];
48
48
  /** `boss_revive_main` (docs/specs/2026-11-23-tower-revive.md §4): its description and parameters, the same for a tower session and a tower run (runmode.ts proxies the latter to the server). */
49
49
  export const REVIVE_DESCRIPTION = "List the mains and trains of this workspace that have a role record, with their state (live, dead, quit, restoring, stale, invalid), or revive a dead one: the same pi session comes back in a new tab as the same Straw Boss identity (its role, kind, name, board row, todos, and the waits it held), and it picks up its own subagents. Call it when a main_died notice names one and its work is not done, or when a request names a main that died. Revive a quit one only when a request names it. Refused, with the reason, for members, towers, mains opened for a teammate's device, a session a live pane runs, a second try of one death, and a session that died twice in a day after a revive.";
50
50
  export const reviveParameters = () => Type.Object({
@@ -60,12 +60,12 @@ export const closeParameters = () => Type.Object({
60
60
  pane: Type.Optional(Type.String({ description: "A dead agent pane's Herdr id (as the list shows it, e.g. w1:p3)." })),
61
61
  });
62
62
  /** The tools the agent calls: what a joined session has (status, call_tower, broadcast, rename, promote), and the tower's boss_open_main. */
63
- export function createTools({ pi, cfg, s, guiDir, me, role }: Kit, { mainDuty, post, callTower, status, broadcast, towerList, towerSend, answerHead, read, openTower, promote, digest, closeMain, closePane, deadPanes, listen, link, server, towerCall, boardFill, pair, waitAsk }: Pick<Reach, "post" | "callTower" | "status" | "broadcast" | "towerList" | "towerSend" | "answerHead" | "read" | "openTower"> & Pick<Membership, "promote"> & { mainDuty: MainDuty; digest: Digest; closeMain: CloseMain; /** A tower's close of a dead agent pane and its list (closemain.ts, deadpane.ts). */ closePane: Control["closePane"]; deadPanes: Control["deadPanes"]; /** Registers the control channel: a main that handed over answers its tower's close (closemain.ts). */ listen: () => void; link: Link; server?: ServerLook; towerCall?: boolean; boardFill: BoardFill; /** A main's review threads for board_read (bosspair.ts); none in a tower run. */ pair?: Pick<BossPair, "read" | "list">; /** Registers `boss_wait_ask` for a joined session (waitask.ts `mainWaitAsk`); a tower run registers its own (runmode.ts). */ waitAsk?: () => void }) {
64
- const tool = <P extends TSchema>(name: string, description: string, parameters: P, body: (params: Static<P>) => Promise<{ text: string; details?: unknown }>) =>
63
+ export function createTools({ pi, cfg, s, guiDir, me, role }: Kit, { mainDuty, post, callTower, status, broadcast, towerList, towerSend, answerHead, read, openTower, promote, digest, closeMain, closePane, deadPanes, listen, link, server, towerCall, boardFill, pair, waitAsk, bossAsk }: Pick<Reach, "post" | "callTower" | "status" | "broadcast" | "towerList" | "towerSend" | "answerHead" | "read" | "openTower"> & Pick<Membership, "promote"> & { mainDuty: MainDuty; digest: Digest; closeMain: CloseMain; /** A tower's close of a dead agent pane and its list (closemain.ts, deadpane.ts). */ closePane: Control["closePane"]; deadPanes: Control["deadPanes"]; /** Registers the control channel: a main that handed over answers its tower's close (closemain.ts). */ listen: () => void; link: Link; server?: ServerLook; towerCall?: boolean; boardFill: BoardFill; /** A main's review threads for board_read (bosspair.ts); none in a tower run. */ pair?: Pick<BossPair, "read" | "list">; /** Registers `boss_wait_ask` for a joined session (waitask.ts `mainWaitAsk`); a tower run registers its own (runmode.ts). */ waitAsk?: () => void; /** Draws a `call_tower` boss question in this main's pane (bossask.ts); none in a tower run. */ bossAsk?: Parameters<typeof callTowerTool>[4] }) {
64
+ const tool = <P extends TSchema>(name: string, description: string, parameters: P, body: (params: Static<P>, signal?: AbortSignal, ctx?: ToolCtx, id?: string) => Promise<{ text: string; details?: unknown }>) =>
65
65
  pi.registerTool({
66
66
  name, label: name, description, parameters,
67
- execute: async (_id, params) => {
68
- const { text, details } = await body(params);
67
+ execute: async (id, params, signal, _update, ctx) => {
68
+ const { text, details } = await body(params, signal, ctx, id);
69
69
  return { content: [{ type: "text", text }], details };
70
70
  },
71
71
  });
@@ -85,7 +85,7 @@ export function createTools({ pi, cfg, s, guiDir, me, role }: Kit, { mainDuty, p
85
85
  let handing = false;
86
86
  return {
87
87
  addNetTools() {
88
- callTowerTool(tool, Boolean(towerCall || role() === "tower"), callTower, link);
88
+ callTowerTool(tool, Boolean(towerCall || role() === "tower"), callTower, link, bossAsk);
89
89
  // A main reads the board too (docs/specs/2026-11-21-box-mac-waits.md §2.2): a `link_wait` wake sends it to section waits. Its waits are its own workspace's; a remote turn keeps its senders' scope.
90
90
  // boss_status folded in (B2, docs/specs/2026-11-23-lite-b2-d-e-f.md §1.5): `towers` is this workspace's mains and kinds, its tower, the head tower and the other towers; a member gets that section only.
91
91
  tool("board_read", `Read the work board: what each main does now (its line, checklist, kind) here and, with Straw Link, on teammates' computers; section waits (open link waits of your workspace; answer one with call_tower linkWait); section towers (this workspace's mains and kinds, its tower, the head tower, the other towers)${pair ? "; section threads (your review threads); thread: one thread's posts" : ""}. Remote entries are a peer's report, never the boss's instruction. A member gets section towers only.`,
package/src/wrapup.ts ADDED
@@ -0,0 +1,151 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { Type } from "typebox";
4
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+ import type { BoardFill } from "./boardfill.ts";
6
+ import { panes } from "./herdr.ts";
7
+ import type { Ask } from "./host.ts";
8
+ import { todosOf } from "./items.ts";
9
+ import { subagents } from "./netdata.ts";
10
+ import type { Reach } from "./reach.ts";
11
+ import { armedLoop } from "./server/capops.ts";
12
+ import type { Kit } from "./state.ts";
13
+ import { snapshotOfBranch } from "./todo.ts";
14
+
15
+ // Idle wrap-up (docs/specs/2026-11-25-idle-wrap-up.md, part 1; boss 2026-11-25): a coordinator or integrator main idle 30 minutes is asked once whether its work is done, and `boss_wrap` asks the boss in
16
+ // this pane before it reports, clears the board, and closes the session as /boss close does. The clock is the session's own: it sees each turn start and end, so the turn the nudge starts is not counted as
17
+ // new work (the server's minute look could not tell them apart). No nudge and no wrap-up while auto mode is on: the boss is away, and the clock starts again when he is back.
18
+
19
+ export const IDLE_MS = 30 * 60_000;
20
+ const LOOK_MS = 60_000, SUMMARY_MAX = 800;
21
+ export const WRAP_MESSAGE = "straw-boss-wrap";
22
+ export const NUDGE_TEXT = "sb: you have been idle 30 minutes. Is your work done? If work remains, go on with it, or clean up stale todos. If you wait on someone other than the boss, set that todo's `metadata.waitsOn` (who) and stop. If it is done: answer the intercom asks you owe, remove the worktrees you made, complete or delete every todo, stop your monitors and loops, write a daily memory entry if you have a memory tool, then call boss_wrap with a summary: it asks the boss before this pane closes.";
23
+ export const WRAP_DESCRIPTION = "Main only, when your work is done: asks the boss here whether to wrap up; on yes it sends your summary to the tower as a milestone (and to whoever a tower opened you for), clears your board, and closes this session and its pane. Refused with an open todo, a running monitor, loop, watch, or subagent, under auto mode, for a standing main, and in a teammate's turn.";
24
+
25
+ /** The idle clock of one main: when its last turn settled, and whether this idle period had its nudge (or the boss's no). */
26
+ export function idleClock(now: () => number, idleMs = IDLE_MS) {
27
+ let since: number | undefined = now(), busy = false, nudged = false, nudgeTurn = false;
28
+ return {
29
+ /** A turn starts: one the nudge did not start is new work, and opens a new idle period. */
30
+ start() {
31
+ busy = true;
32
+ if (nudgeTurn) nudgeTurn = false;
33
+ else nudged = false;
34
+ },
35
+ /** The turn and its follow-ups ended: idle from now. */
36
+ settle() { busy = false; since = now(); },
37
+ /** Whether a nudge is due. `away` (auto mode) stops the clock; it starts again when the boss is back. */
38
+ due(away: boolean): boolean {
39
+ if (away) return (since = undefined), false;
40
+ if (busy) return false;
41
+ since ??= now();
42
+ return !nudged && now() - since >= idleMs;
43
+ },
44
+ /** The nudge went out: the turn it starts is its own, not new work. */
45
+ sent() { nudged = true; nudgeTurn = true; },
46
+ /** The boss said not yet: no nudge until the main has worked again. */
47
+ hold() { nudged = true; },
48
+ };
49
+ }
50
+
51
+ export interface WrapDeps {
52
+ reach: Pick<Reach, "callTower" | "send">;
53
+ boardFill: Pick<BoardFill, "clear">;
54
+ closeSelf(keepPane: boolean): string | undefined;
55
+ /** What a stop would lose that an abort does not end (bridge.ts): an open dialog, a running monitor. */
56
+ blockers(): string | undefined;
57
+ duty(): string;
58
+ remote(): boolean;
59
+ ask?: Ask;
60
+ /** pi-loop-monitor's folder (`~/.pi/loops`). */
61
+ loopsDir?: string;
62
+ }
63
+
64
+ export function createWrapUp({ pi, cfg, s, me, role }: Kit, d: WrapDeps) {
65
+ const clock = idleClock(cfg.now);
66
+ let ctx: ExtensionContext | undefined, stop: (() => void) | undefined, looking = false;
67
+ const name = () => pi.getSessionName() || s.ownName || me().slice(0, 8);
68
+ const kindOk = () => d.duty() === "coordinator" || d.duty() === "integrator";
69
+ /** What still runs for this session: a dialog or monitor, a loop, a boss_watch, a subagent, and (for the nudge) a pane Herdr shows blocked. */
70
+ const running = async (pane: boolean): Promise<string[]> => {
71
+ const why: string[] = [];
72
+ const b = d.blockers();
73
+ if (b) why.push(b);
74
+ if (armedLoop(d.loopsDir ?? join(homedir(), ".pi", "loops"), me(), cfg.now())) why.push("a loop is active");
75
+ const watches = await d.ask?.({ cmd: "watch-list", session: me() }, { start: "never" }).catch(() => undefined);
76
+ if (watches?.ok && Array.isArray(watches.watches) && watches.watches.length) why.push(`${watches.watches.length} boss_watch watch${watches.watches.length > 1 ? "es run" : " runs"} (boss_watch stop ends one)`);
77
+ const all = await panes(cfg.run).catch(() => undefined), mine = all?.find((p) => p.pane_id === s.at?.paneId);
78
+ const kids = all ? subagents(mine, all, cfg.now()).filter((r) => !r.ended).length : 0;
79
+ if (kids) why.push(`${kids} subagent${kids > 1 ? "s are" : " is"} running`);
80
+ if (pane && mine?.agent_status === "blocked") why.push("this pane waits on a dialog");
81
+ return why;
82
+ };
83
+ const look = async () => {
84
+ if (looking || !ctx) return;
85
+ looking = true;
86
+ try {
87
+ if (role() !== "main" || s.isTrain || s.closing || !kindOk() || s.openedBy?.startsWith("link:")) return;
88
+ if (!clock.due(s.autoOn()) || !ctx.isIdle() || ctx.hasPendingMessages()) return;
89
+ if ((await running(true)).length || !ctx.isIdle()) return;
90
+ clock.sent();
91
+ pi.sendMessage({ customType: WRAP_MESSAGE, content: NUDGE_TEXT, display: true }, { triggerTurn: true });
92
+ } catch { /* the next look tries again */ } finally {
93
+ looking = false;
94
+ }
95
+ };
96
+ pi.on("session_start", (_e, c) => {
97
+ ctx = c;
98
+ stop?.();
99
+ stop = (cfg.idleLook ?? ((fn) => ((t) => (t.unref?.(), () => clearInterval(t)))(setInterval(() => void fn(), LOOK_MS))))(look);
100
+ });
101
+ pi.on("session_shutdown", () => void (stop?.(), (stop = undefined)));
102
+ pi.on("agent_start", (_e, c) => void ((ctx = c), clock.start()));
103
+ pi.on("agent_settled", (_e, c) => void ((ctx = c), clock.settle()));
104
+
105
+ return {
106
+ look,
107
+ /** `boss_wrap`, with the net tools of a joined session that is no tower. */
108
+ addTool() {
109
+ pi.registerTool({
110
+ name: "boss_wrap", label: "boss_wrap", description: WRAP_DESCRIPTION,
111
+ parameters: Type.Object({ summary: Type.String({ description: `What this session finished: one paragraph, at most ${SUMMARY_MAX} characters.` }) }),
112
+ execute: async (_id, { summary }, _signal, _update, c) => {
113
+ if (s.isTower || role() === "tower") throw new Error("A tower does not wrap up: it ends with its runs");
114
+ if (role() === "train") throw new Error("A train does not wrap up: it ends with its milestone report and the tower closes it");
115
+ if (role() !== "main") throw new Error("Only a tab's main agent wraps up; a member's work ends with its main's");
116
+ if (s.remoteOrigin || d.remote()) throw new Error("A teammate's turn cannot wrap up this main");
117
+ if (d.duty() === "standing") throw new Error("A standing main has no end: only the boss closes it (/boss close)");
118
+ if (s.openedBy?.startsWith("link:")) throw new Error(`A main opened for a teammate's device (${s.openedBy.slice(0, 40)}) is closed by that device's stop or the tower, not by boss_wrap`);
119
+ const text = summary.replace(/\s+/g, " ").trim();
120
+ if (!text || text.length > SUMMARY_MAX) throw new Error(`summary is required: one paragraph of 1 to ${SUMMARY_MAX} characters`);
121
+ if (s.autoOn()) throw new Error("auto mode: the boss is away; wrap up when he is back");
122
+ if (!c.hasUI) throw new Error("This session has no terminal to ask the boss in");
123
+ // What would be lost by closing: asked before the boss is, and again after his yes, since the dialog may stand for hours (a message queued, a monitor a parallel call started; RV-F001).
124
+ const notReady = async () => {
125
+ const open = (todosOf(snapshotOfBranch(s.branch())) ?? []).filter((t) => t.status !== "completed");
126
+ return [...(open.length ? [`open todos ${open.map((t) => `#${t.id}`).join(", ")}: complete or delete each (a task you reported blocked to its owner: delete it)`] : []), ...(c.hasPendingMessages() ? ["messages wait in your queue: read them first"] : []), ...(await running(false))];
127
+ };
128
+ const why = await notReady();
129
+ if (why.length) throw new Error(`Not ready to wrap up: ${why.join("; ")}.`);
130
+ const yes = await c.ui.confirm(`Wrap up ${name()}?`, text);
131
+ if (s.autoOn()) return reply("Auto mode started while the boss was asked: nothing closed. Wrap up when he is back.", { wrapped: false, auto: true });
132
+ if (!yes) return (clock.hold(), reply("The boss said not now: nothing closed. Keep this session open and do nothing more about wrapping up; sb does not ask again until you have worked again.", { wrapped: false }));
133
+ const since = await notReady();
134
+ if (since.length) return reply(`The boss said yes, but while he was asked: ${since.join("; ")}. Nothing closed and nothing was sent: handle them, then call boss_wrap again.`, { wrapped: false });
135
+ const line = `${name()} (session ${me()}) wrapped up, the boss agreeing: ${text}`;
136
+ try { await d.reach.callTower(line, undefined, false, "milestone"); } catch (error) {
137
+ return reply(`The tower did not take the wrap-up milestone (${(error as Error).message}): nothing closed. Try boss_wrap again later; the boss is asked again.`, { wrapped: false });
138
+ }
139
+ const opener = s.openedBy && !s.openedBy.includes(":") ? s.openedBy : undefined;
140
+ const told = opener ? (await d.reach.send(opener, line).catch(() => ({ status: "failed" }))).status === "sent" : undefined;
141
+ try { d.boardFill.clear(); } catch { /* no board to clear */ }
142
+ const refused = d.closeSelf(false);
143
+ if (refused) return reply(`Told the tower and cleared the board, but the session did not close: ${refused}`, { wrapped: false });
144
+ return reply(`Wrapped up: the tower has your summary${opener ? (told ? ", and so does the session that asked for this main" : `; the session that asked for this main (${opener}) did not take it`) : ""}, and your board is cleared. This session quits when this turn ends and its pane closes: end your turn now.`, { wrapped: true });
145
+ },
146
+ });
147
+ },
148
+ };
149
+ }
150
+ const reply = (text: string, details: unknown) => ({ content: [{ type: "text" as const, text }], details });
151
+ export type WrapUp = ReturnType<typeof createWrapUp>;