pi-daddy 0.55.0 → 0.56.1

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +9 -1
  3. package/dist/kernel/dashboard-choice.d.ts +58 -0
  4. package/dist/kernel/dashboard-choice.d.ts.map +1 -0
  5. package/dist/kernel/dashboard-choice.js +34 -0
  6. package/dist/kernel/dashboard-choice.js.map +1 -0
  7. package/dist/kernel/dashboard-observation.d.ts +6 -0
  8. package/dist/kernel/dashboard-observation.d.ts.map +1 -1
  9. package/dist/kernel/dashboard-observation.js.map +1 -1
  10. package/dist/products/dashboard-choice-picker.d.ts +22 -0
  11. package/dist/products/dashboard-choice-picker.d.ts.map +1 -0
  12. package/dist/products/dashboard-choice-picker.js +219 -0
  13. package/dist/products/dashboard-choice-picker.js.map +1 -0
  14. package/dist/products/dashboard-cli.d.ts.map +1 -1
  15. package/dist/products/dashboard-cli.js +16 -4
  16. package/dist/products/dashboard-cli.js.map +1 -1
  17. package/dist/products/dashboard-components.d.ts.map +1 -1
  18. package/dist/products/dashboard-components.js +21 -1
  19. package/dist/products/dashboard-components.js.map +1 -1
  20. package/dist/products/dashboard-display-controls.d.ts +1 -1
  21. package/dist/products/dashboard-display-controls.d.ts.map +1 -1
  22. package/dist/products/dashboard-display-controls.js +6 -1
  23. package/dist/products/dashboard-display-controls.js.map +1 -1
  24. package/dist/products/dashboard-panels.d.ts.map +1 -1
  25. package/dist/products/dashboard-panels.js +19 -0
  26. package/dist/products/dashboard-panels.js.map +1 -1
  27. package/dist/products/dashboard-screen.d.ts +5 -1
  28. package/dist/products/dashboard-screen.d.ts.map +1 -1
  29. package/dist/products/dashboard-screen.js +17 -6
  30. package/dist/products/dashboard-screen.js.map +1 -1
  31. package/dist/products/dashboard-session-client.d.ts +18 -5
  32. package/dist/products/dashboard-session-client.d.ts.map +1 -1
  33. package/dist/products/dashboard-session-client.js +92 -14
  34. package/dist/products/dashboard-session-client.js.map +1 -1
  35. package/extensions/dashboard-choice-controls.ts +152 -0
  36. package/extensions/dashboard-observation.ts +2 -0
  37. package/extensions/dashboard-session-server.ts +92 -17
  38. package/extensions/dashboard-sources.ts +12 -0
  39. package/extensions/dashboard-ui-prompts.ts +100 -0
  40. package/extensions/runtime-snapshot.ts +10 -0
  41. package/extensions/session.ts +2 -0
  42. package/package.json +2 -2
  43. package/src/kernel/dashboard-choice.ts +73 -0
  44. package/src/kernel/dashboard-observation.ts +6 -0
  45. package/src/products/dashboard-choice-picker.ts +228 -0
  46. package/src/products/dashboard-cli.ts +18 -3
  47. package/src/products/dashboard-components.ts +21 -1
  48. package/src/products/dashboard-display-controls.ts +7 -1
  49. package/src/products/dashboard-panels.ts +20 -0
  50. package/src/products/dashboard-screen.ts +19 -6
  51. package/src/products/dashboard-session-client.ts +129 -19
@@ -1,3 +1,4 @@
1
+ import type { DashboardChoiceDetail } from "../src/kernel/dashboard-choice.ts";
1
2
  import { isJevEditAction } from "../src/products/dashboard-settings.ts";
2
3
  import { dashboardObservation } from "./dashboard-observation.ts";
3
4
  import { dashboardSettingsSnapshot, dashboardJev, setDashboardLimit } from "./dashboard-settings.ts";
@@ -54,9 +55,25 @@ async function start(session: GrantsSession): Promise<DashboardSessionEndpoint>
54
55
  if (!input.includes("\n")) return;
55
56
  handled = true;
56
57
  const line = input.slice(0, input.indexOf("\n"));
57
- void respond(session, token, line)
58
+ let request: DashboardWireRequest;
59
+ try {
60
+ request = JSON.parse(line);
61
+ if (!request || typeof request !== "object" || Array.isArray(request)) throw Error();
62
+ } catch {
63
+ socket.end(JSON.stringify({ ok: false, error: "Invalid dashboard request" }) + "\n");
64
+ return;
65
+ }
66
+ const choiceAction = request.action === "inspect-choice" || request.action === "answer-choice";
67
+ if (choiceAction && request.token === token) socket.setTimeout(30_000);
68
+ void respond(session, token, request, () => {
69
+ if (socket.destroyed) throw Error("Dashboard disconnected");
70
+ })
58
71
  .then((value) => socket.end(`${JSON.stringify(value)}\n`))
59
- .catch((error) => socket.end(`${JSON.stringify({ ok: false, error: String(error) })}\n`));
72
+ .catch((error) =>
73
+ socket.end(
74
+ `${JSON.stringify({ ok: false, error: choiceAction ? "Bookie could not confirm the choice request." : String(error) })}\n`,
75
+ ),
76
+ );
60
77
  });
61
78
  });
62
79
  await new Promise<void>((resolve, reject) => {
@@ -80,19 +97,40 @@ async function start(session: GrantsSession): Promise<DashboardSessionEndpoint>
80
97
  };
81
98
  }
82
99
 
83
- async function respond(session: GrantsSession, token: string, line: string): Promise<Record<string, unknown>> {
84
- const request = JSON.parse(line) as {
85
- token?: unknown;
86
- action?: unknown;
87
- edits?: unknown;
88
- enabled?: unknown;
89
- key?: unknown;
90
- seconds?: unknown;
91
- option?: unknown;
92
- expectedOwner?: { sessionId?: unknown; cwd?: unknown; generation?: unknown };
93
- };
100
+ interface DashboardWireRequest {
101
+ token?: unknown;
102
+ action?: unknown;
103
+ edits?: unknown;
104
+ enabled?: unknown;
105
+ key?: unknown;
106
+ refreshChoices?: unknown;
107
+ seconds?: unknown;
108
+ option?: unknown;
109
+ sourceGeneration?: unknown;
110
+ choiceId?: unknown;
111
+ revision?: unknown;
112
+ answer?: unknown;
113
+ expectedOwner?: { sessionId?: unknown; cwd?: unknown; generation?: unknown };
114
+ }
115
+ async function respond(
116
+ session: GrantsSession,
117
+ token: string,
118
+ request: DashboardWireRequest,
119
+ checkClient: () => void,
120
+ ): Promise<Record<string, unknown>> {
94
121
  if (request.token !== token) return { ok: false, error: "unauthorised dashboard request" };
95
- if (request.action === "edit-jev" || (request.action !== "get" && request.expectedOwner !== undefined)) {
122
+ const choiceAction = request.action === "inspect-choice" || request.action === "answer-choice";
123
+ if (choiceAction) {
124
+ const allowed = ["token", "action", "expectedOwner", "sourceGeneration", "choiceId"];
125
+ if (request.action === "answer-choice") allowed.push("revision", "answer");
126
+ if (Object.keys(request).some((key) => !allowed.includes(key)))
127
+ return { ok: false, choiceOutcome: "refused", error: "Invalid choice request" };
128
+ }
129
+ if (
130
+ choiceAction ||
131
+ request.action === "edit-jev" ||
132
+ (request.action !== "get" && request.expectedOwner !== undefined)
133
+ ) {
96
134
  const observed = session.dashboardObservations?.(),
97
135
  expected = request.expectedOwner;
98
136
  if (
@@ -102,13 +140,41 @@ async function respond(session: GrantsSession, token: string, line: string): Pro
102
140
  expected.cwd !== observed.cwd ||
103
141
  expected.generation !== observed.generation
104
142
  )
105
- return { ok: false, error: "Dashboard owner changed before action; refresh and inspect the new session" };
143
+ return {
144
+ ok: false,
145
+ ...(choiceAction ? { choiceOutcome: "stale" } : {}),
146
+ error: "Dashboard owner changed before action; refresh and inspect the new session",
147
+ };
106
148
  }
107
149
  const lifecycle = session.reloadLifecycle,
108
150
  owner = lifecycle.autoMode;
109
151
  const displayOwner = session.dashboardObservations?.()?.generation;
110
- let jev;
111
- if (request.action === "set-limit") {
152
+ let jev, choiceDetail: DashboardChoiceDetail | undefined;
153
+ if (request.action === "inspect-choice") {
154
+ choiceDetail = await session.dashboardChoices?.inspect(request.sourceGeneration, request.choiceId, checkClient);
155
+ if (!choiceDetail)
156
+ return { ok: false, choiceOutcome: "stale", error: "Choice is no longer available. Refresh and reopen it." };
157
+ } else if (request.action === "answer-choice") {
158
+ const outcome = await session.dashboardChoices?.answer(
159
+ request.sourceGeneration,
160
+ request.choiceId,
161
+ request.revision,
162
+ request.answer,
163
+ checkClient,
164
+ );
165
+ if (outcome !== "saved")
166
+ return outcome === "unconfirmed"
167
+ ? {
168
+ ok: false,
169
+ choiceOutcome: "unconfirmed",
170
+ error: "Bookie could not confirm the save. Check project memory before retrying.",
171
+ }
172
+ : {
173
+ ok: false,
174
+ choiceOutcome: "refused",
175
+ error: "Bookie declined the answer. Refresh and check the choice and answer.",
176
+ };
177
+ } else if (request.action === "set-limit") {
112
178
  setDashboardLimit(session, request.key, request.seconds);
113
179
  } else if (request.action === "edit-jev") {
114
180
  if (!isJevEditAction(request.option)) return { ok: false, error: "Unknown JEV setting" };
@@ -138,8 +204,17 @@ async function respond(session: GrantsSession, token: string, line: string): Pro
138
204
  session.dashboardObservations?.()?.generation !== displayOwner
139
205
  )
140
206
  throw Error("Dashboard owner changed; action outcome requires reconciliation");
207
+ if (choiceDetail && !session.dashboardChoices?.currentDetail(request.sourceGeneration, choiceDetail))
208
+ return { ok: false, choiceOutcome: "stale", error: "Choice is no longer available. Refresh and reopen it." };
209
+ const choiceRefreshRequested =
210
+ request.action === "get" && request.refreshChoices === true && session.dashboardChoices?.requestRenewal();
211
+ const choiceControls = session.dashboardChoices?.controls();
141
212
  return {
142
213
  ok: true,
214
+ ...(choiceControls ? { choiceControls } : {}),
215
+ ...(choiceRefreshRequested ? { choiceRefreshRequested: true } : {}),
216
+ ...(choiceDetail ? { choiceDetail } : {}),
217
+ ...(request.action === "answer-choice" ? { choiceSaved: true } : {}),
143
218
  ...controls,
144
219
  ...dashboardObservation(session),
145
220
  ...(session.activity ? { activity: { ...session.activity } } : {}),
@@ -1,4 +1,5 @@
1
1
  /** Optional trusted producers publish display observations; no automatic work, tools, or persistent store. */
2
+ import { registerDashboardChoiceOwner } from "./dashboard-choice-controls.ts";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
5
  import {
@@ -34,6 +35,15 @@ export function registerDashboardSources(
34
35
  }
35
36
  return selected;
36
37
  };
38
+ const choices = registerDashboardChoiceOwner(
39
+ pi,
40
+ () => {
41
+ const selected = reconcile();
42
+ const source = sources.get("bookie-memory");
43
+ return selected && source ? { sessionId: selected.sessionId, cwd: selected.cwd, source } : undefined;
44
+ },
45
+ now,
46
+ );
37
47
  const off = pi.events?.on?.(DASHBOARD_SOURCE_EVENT, (input: unknown) => {
38
48
  const r = input as {
39
49
  version?: unknown;
@@ -102,6 +112,7 @@ export function registerDashboardSources(
102
112
  });
103
113
  });
104
114
  return {
115
+ choices,
105
116
  snapshot() {
106
117
  const selected = reconcile();
107
118
  return selected
@@ -117,6 +128,7 @@ export function registerDashboardSources(
117
128
  },
118
129
  close() {
119
130
  closed = true;
131
+ choices.close();
120
132
  off?.();
121
133
  sources.clear();
122
134
  owner = undefined;
@@ -0,0 +1,100 @@
1
+ /** Native Pi dialog observations; no authority, input values, transcript parsing or stored history. */
2
+ import { realpathSync } from "node:fs";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import type { DashboardInputPrompt } from "../src/kernel/dashboard-observation.ts";
5
+ import type { DashboardSourceOwner } from "./dashboard-sources.ts";
6
+
7
+ interface PromptEvent {
8
+ reason?: string;
9
+ kind?: string;
10
+ title?: string;
11
+ }
12
+ type Handler = (event: PromptEvent, ctx: ExtensionContext) => void;
13
+ /** Newer Pi emits these public hooks; old Pi accepts registrations but never emits them. */
14
+ type PromptHooks = { on(name: "ui_prompt_start" | "ui_prompt_end", handler: Handler): (() => void) | void };
15
+ const sameFolder = (cwd: string, canonical: string) => {
16
+ if (cwd === canonical) return true;
17
+ try {
18
+ return realpathSync(cwd) === canonical;
19
+ } catch {
20
+ return false;
21
+ }
22
+ };
23
+ const kinds = new Set(["select", "confirm", "input", "editor"]);
24
+ const clean = (value: string) =>
25
+ value
26
+ .replace(/[\p{Cc}\p{Cf}]/gu, " ")
27
+ .replace(/\s+/g, " ")
28
+ .trim()
29
+ .slice(0, 160);
30
+
31
+ export function registerDashboardPrompts(pi: ExtensionAPI, current: () => DashboardSourceOwner | undefined) {
32
+ let owner: DashboardSourceOwner | undefined, prompt: DashboardInputPrompt | undefined;
33
+ let closed = false,
34
+ bridged = false,
35
+ ordinal = 0;
36
+ const publish = (active: boolean, label?: string) => {
37
+ try {
38
+ pi.events?.emit?.("herdr:blocked", { active, ...(label ? { label } : {}) });
39
+ } catch {
40
+ /* Display failure cannot change a dialog or its permission result. */
41
+ }
42
+ };
43
+ const clear = () => {
44
+ prompt = undefined;
45
+ if (bridged) publish(false);
46
+ bridged = false;
47
+ };
48
+ const valid = (ctx?: ExtensionContext) => {
49
+ const next = closed ? undefined : current();
50
+ if (next !== owner) {
51
+ clear();
52
+ owner = next;
53
+ }
54
+ return (
55
+ !!owner &&
56
+ (!ctx ||
57
+ (ctx.hasUI &&
58
+ ctx.mode === "tui" &&
59
+ ctx.sessionManager.getSessionId() === owner.sessionId &&
60
+ sameFolder(ctx.cwd, owner.cwd)))
61
+ );
62
+ };
63
+ const start: Handler = (event, ctx) => {
64
+ if (!valid(ctx) || event.reason !== "ui_prompt" || !kinds.has(event.kind ?? "")) return;
65
+ const kind = event.kind as DashboardInputPrompt["kind"];
66
+ const label = clean(typeof event.title === "string" ? event.title : "") || "Pi is waiting for your answer";
67
+ // Pi reports the outermost native dialog once. Defensive duplicate observations must not
68
+ // increment Herdr's blocked counter and leave the pane stuck after one corresponding end.
69
+ if (prompt?.kind === kind && prompt.label === label) return;
70
+ clear();
71
+ prompt = { id: `input:${++ordinal}`, kind, label };
72
+ bridged = true;
73
+ publish(true, label);
74
+ };
75
+ const end: Handler = (event, ctx) => {
76
+ if (!valid(ctx) || event.reason !== "ui_prompt" || !prompt || event.kind !== prompt.kind) return;
77
+ const label = clean(typeof event.title === "string" ? event.title : "") || "Pi is waiting for your answer";
78
+ if (prompt.label === label) clear();
79
+ };
80
+ const hooks = pi as unknown as PromptHooks;
81
+ const offStart = hooks.on?.("ui_prompt_start", start);
82
+ const offEnd = hooks.on?.("ui_prompt_end", end);
83
+ const offShutdown = pi.on?.("session_shutdown", (_event, ctx) => {
84
+ if (valid(ctx)) clear();
85
+ });
86
+ return {
87
+ snapshot() {
88
+ valid();
89
+ return prompt ? { ...prompt } : undefined;
90
+ },
91
+ reset: clear,
92
+ close() {
93
+ clear();
94
+ closed = true;
95
+ offStart?.();
96
+ offEnd?.();
97
+ if (typeof offShutdown === "function") offShutdown();
98
+ },
99
+ };
100
+ }
@@ -1,3 +1,4 @@
1
+ import { registerDashboardPrompts } from "./dashboard-ui-prompts.ts";
1
2
  import { registerInitiativeRuntime } from "./initiative-runtime.ts";
2
3
  import { registerDashboardLive } from "./dashboard-live.ts";
3
4
  import { registerDashboardSources } from "./dashboard-sources.ts";
@@ -35,11 +36,18 @@ export function registerRuntimeSnapshot(
35
36
  : undefined,
36
37
  );
37
38
  session.dashboardObservations = () => dashboardSources.snapshot();
39
+ session.dashboardChoices = dashboardSources.choices;
38
40
  session.dashboardLive = registerDashboardLive(pi, () =>
39
41
  bound?.lifecycle === session.reloadLifecycle && session.reloadLifecycle.runtimeSnapshotGeneration === generation
40
42
  ? bound
41
43
  : undefined,
42
44
  );
45
+ const prompts = registerDashboardPrompts(pi, () =>
46
+ bound?.lifecycle === session.reloadLifecycle && session.reloadLifecycle.runtimeSnapshotGeneration === generation
47
+ ? bound
48
+ : undefined,
49
+ );
50
+ session.dashboardPrompt = prompts.snapshot;
43
51
  session.dashboardArtifacts = [];
44
52
 
45
53
  const artifactBridge = registerArtifactBridge(pi, () =>
@@ -241,9 +249,11 @@ export function registerRuntimeSnapshot(
241
249
  artifactBridge.close();
242
250
  void initiative.close().catch(() => undefined);
243
251
  dashboardSources.close();
252
+ prompts.close();
244
253
  };
245
254
  return {
246
255
  async bind(ctx) {
256
+ prompts.reset();
247
257
  const sequence = ++bindSequence,
248
258
  lifecycle = session.reloadLifecycle;
249
259
  lifecycle.runtimeSettlement = undefined;
@@ -151,8 +151,10 @@ export interface GrantsSession extends NativeSessionHost {
151
151
  dashboardInitiative?: () => DashboardSourceSnapshot | undefined;
152
152
  refreshInitiative?: () => void;
153
153
  ecosystemVersions?: () => EcosystemVersions;
154
+ dashboardPrompt?: () => import("../src/kernel/dashboard-observation.ts").DashboardInputPrompt | undefined;
154
155
  dashboardLive?: () => { turn?: DashboardContribution; activity: DashboardContribution[] };
155
156
  dashboardArtifacts?: DashboardSavedEvidence[];
157
+ dashboardChoices?: ReturnType<typeof import("./dashboard-choice-controls.ts").registerDashboardChoiceOwner>;
156
158
  dashboardObservations?: () => Omit<DashboardOwnerObservation, "version" | "resources" | "capture"> | undefined;
157
159
  autoMode?: AutoModeReader;
158
160
  autoModeFailure?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-daddy",
3
- "version": "0.55.0",
3
+ "version": "0.56.1",
4
4
  "description": "Capability governance for pi sub-agents: spawn Agent Skills (SKILL.md) definitions whose allowed-tools becomes a grant that can only narrow going down a delegation tree, enforced by pi's own --tools allowlist, with an append-only ledger.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -53,7 +53,7 @@
53
53
  "typecheck": "tsc -p tsconfig.check.json",
54
54
  "test": "node scripts/unit-tests.ts",
55
55
  "test:integration": "node --test test-integration/*.it.ts",
56
- "test:integration:ci": "node --test test-integration/approval.it.ts test-integration/governance.it.ts test-integration/activity.it.ts test-integration/auto-chain.it.ts test-integration/pi-sdk/automatic-start.it.ts",
56
+ "test:integration:ci": "node --test test-integration/approval.it.ts test-integration/governance.it.ts test-integration/activity.it.ts test-integration/auto-chain.it.ts test-integration/pi-sdk/automatic-start.it.ts test-integration/pi-sdk/dashboard-prompts.it.ts",
57
57
  "contracts:generate": "node scripts/generate-ledger-record-contract.ts",
58
58
  "prepack": "npm run build",
59
59
  "test:smoke": "node scripts/smoke-installed.mjs",
@@ -0,0 +1,73 @@
1
+ /** Private owner controls, available only on the authenticated dashboard connection. */
2
+ export const DASHBOARD_CHOICE_EVENT = "pi-daddy:bookie-choice-controls:v1";
3
+ export interface DashboardChoiceDetail {
4
+ id: string;
5
+ label: string;
6
+ title: string;
7
+ revision: string;
8
+ options: string[];
9
+ recommendation?: { option: string; reason: string; evidence: string };
10
+ }
11
+ export type DashboardChoiceAnswer = { option: string } | { custom: string };
12
+ export interface DashboardChoiceTarget {
13
+ choiceId: string;
14
+ sourceGeneration: string;
15
+ expectedOwner: { sessionId: string; cwd: string; generation: string };
16
+ }
17
+ export type DashboardChoiceAction = DashboardChoiceTarget &
18
+ ({ action: "inspect-choice" } | { action: "answer-choice"; revision: string; answer: DashboardChoiceAnswer });
19
+ export type DashboardChoiceOutcome = "saved" | "refused" | "unconfirmed";
20
+ export interface DashboardChoiceRegistration {
21
+ version: 1;
22
+ sessionId: string;
23
+ cwd: string;
24
+ sourceGeneration: string;
25
+ renew?(): Promise<void>;
26
+ inspect(id: string, assertCurrent: () => void): Promise<DashboardChoiceDetail | undefined>;
27
+ answer(
28
+ id: string,
29
+ revision: string,
30
+ answer: DashboardChoiceAnswer,
31
+ assertCurrent: () => void,
32
+ ): Promise<DashboardChoiceOutcome>;
33
+ reply(value: { version: 1; ok: false } | { version: 1; ok: true; close(): void }): void;
34
+ }
35
+ const record = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x);
36
+ const text = (v: unknown, length: number): v is string =>
37
+ typeof v === "string" &&
38
+ v.trim() === v &&
39
+ v.length > 0 &&
40
+ v.length <= length &&
41
+ !/[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/u.test(v);
42
+ const keys = (v: object, allowed: string[]) => Object.keys(v).every((k) => allowed.includes(k));
43
+ export const validChoiceId = (v: unknown): v is string =>
44
+ typeof v === "string" && /^open-choice-[a-zA-Z0-9_-]{1,128}$/.test(v);
45
+ export const validChoiceRevision = (v: unknown): v is string =>
46
+ typeof v === "string" && /^sha256:[a-f0-9]{64}$/.test(v);
47
+ export const validChoiceAnswer = (v: unknown): v is DashboardChoiceAnswer =>
48
+ record(v) && ((keys(v, ["option"]) && text(v.option, 120)) || (keys(v, ["custom"]) && text(v.custom, 240)));
49
+ export function validChoiceDetail(v: unknown): v is DashboardChoiceDetail {
50
+ if (
51
+ !record(v) ||
52
+ !keys(v, ["id", "label", "title", "revision", "options", "recommendation"]) ||
53
+ !validChoiceId(v.id) ||
54
+ !text(v.label, 240) ||
55
+ !text(v.title, 120) ||
56
+ !validChoiceRevision(v.revision) ||
57
+ !Array.isArray(v.options) ||
58
+ v.options.length > 8 ||
59
+ !v.options.every((option) => text(option, 120)) ||
60
+ new Set(v.options).size !== v.options.length
61
+ )
62
+ return false;
63
+ const rec = v.recommendation;
64
+ return (
65
+ rec === undefined ||
66
+ (record(rec) &&
67
+ keys(rec, ["option", "reason", "evidence"]) &&
68
+ text(rec.option, 120) &&
69
+ v.options.includes(rec.option) &&
70
+ text(rec.reason, 240) &&
71
+ text(rec.evidence, 240))
72
+ );
73
+ }
@@ -64,6 +64,11 @@ export interface DashboardSavedEvidence {
64
64
  sha256: string;
65
65
  description?: DashboardResultDescription;
66
66
  }
67
+ export interface DashboardInputPrompt {
68
+ id: string;
69
+ kind: "select" | "confirm" | "input" | "editor";
70
+ label: string;
71
+ }
67
72
  export interface DashboardOwnerObservation {
68
73
  version: 1;
69
74
  sessionId: string;
@@ -73,6 +78,7 @@ export interface DashboardOwnerObservation {
73
78
  observedAt: string;
74
79
  sources: DashboardSourceSnapshot[];
75
80
  logicalOwnerId?: string;
81
+ inputPrompt?: DashboardInputPrompt;
76
82
  turn?: DashboardContribution;
77
83
  activity?: DashboardContribution[];
78
84
  artifacts?: DashboardSavedEvidence[];
@@ -0,0 +1,228 @@
1
+ /** A Bookie question is inspected on Enter. The terminal never infers an option or writes during a redraw. */
2
+ import type { DashboardChoiceDetail, DashboardChoiceTarget } from "../kernel/dashboard-choice.ts";
3
+ import type { DashboardScreenState } from "./dashboard-screen.ts";
4
+ import type { createDashboardConnection } from "./dashboard-session-client.ts";
5
+
6
+ export interface ChoicePicker {
7
+ target: DashboardChoiceTarget;
8
+ phase: "loading" | "unavailable" | "options" | "custom" | "confirm" | "refused" | "saving" | "saved";
9
+ index: number;
10
+ draft: string;
11
+ detail?: DashboardChoiceDetail;
12
+ error?: string;
13
+ }
14
+
15
+ function current(screen: DashboardScreenState, picker: ChoicePicker) {
16
+ const choice = screen.items.find((item) => item.key === screen.selectedKey)?.choice;
17
+ return (
18
+ choice?.choiceId === picker.target.choiceId &&
19
+ choice.sourceGeneration === picker.target.sourceGeneration &&
20
+ choice.expectedOwner.sessionId === picker.target.expectedOwner.sessionId &&
21
+ choice.expectedOwner.cwd === picker.target.expectedOwner.cwd &&
22
+ choice.expectedOwner.generation === picker.target.expectedOwner.generation
23
+ );
24
+ }
25
+
26
+ export function openChoice(screen: DashboardScreenState): boolean {
27
+ const target = screen.items.find((item) => item.key === screen.selectedKey)?.choice;
28
+ if (!target) return false;
29
+ screen.picker = { target, phase: "loading", index: 0, draft: "" };
30
+ screen.view = "choice";
31
+ screen.offset = 0;
32
+ screen.manualScroll = false;
33
+ return true;
34
+ }
35
+
36
+ function close(screen: DashboardScreenState) {
37
+ screen.picker = undefined;
38
+ screen.view = "main";
39
+ screen.offset = 0;
40
+ screen.manualScroll = false;
41
+ }
42
+
43
+ export function choiceKey(
44
+ screen: DashboardScreenState,
45
+ key: string,
46
+ text?: string,
47
+ ): "answer-choice" | "quit" | undefined {
48
+ const picker = screen.picker;
49
+ if (!picker || key === "ctrl-c" || (key === "q" && picker.phase !== "custom")) return "quit";
50
+ if (key === "pageup" || key === "pagedown") {
51
+ screen.manualScroll = true;
52
+ screen.offset = Math.max(0, screen.offset + (key === "pageup" ? -8 : 8));
53
+ return;
54
+ }
55
+ if (key === "escape") {
56
+ if (picker.phase !== "saving") close(screen);
57
+ return;
58
+ }
59
+ const detail = picker.detail;
60
+ if (!detail || !current(screen, picker)) return;
61
+ if (picker.phase === "custom") {
62
+ if (key === "return") {
63
+ if (!picker.draft.trim()) {
64
+ picker.error = "Write an answer first.";
65
+ return;
66
+ }
67
+ picker.phase = "confirm";
68
+ screen.offset = 0;
69
+ } else if (key === "backspace") {
70
+ picker.draft = [...picker.draft].slice(0, -1).join("");
71
+ } else if (text && !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(text)) {
72
+ if ((picker.draft + text).length > 240) {
73
+ picker.error = "Use up to 240 characters.";
74
+ return;
75
+ }
76
+ picker.draft += text;
77
+ }
78
+ picker.error = undefined;
79
+ screen.manualScroll = false;
80
+ return;
81
+ }
82
+ if (picker.phase === "confirm" || picker.phase === "refused") {
83
+ if (picker.phase === "refused" && key === "r") {
84
+ picker.phase = "confirm";
85
+ picker.error = undefined;
86
+ screen.offset = 0;
87
+ return;
88
+ }
89
+ if (picker.phase === "confirm" && key === "return") {
90
+ picker.phase = "saving";
91
+ picker.error = undefined;
92
+ screen.offset = 0;
93
+ return "answer-choice";
94
+ }
95
+ if (key === "backspace" || key === "e") {
96
+ picker.phase = picker.index === detail.options.length ? "custom" : "options";
97
+ picker.error = undefined;
98
+ screen.offset = 0;
99
+ }
100
+ return;
101
+ }
102
+ if (picker.phase !== "options") return;
103
+ const last = detail.options.length + 1;
104
+ if (["up", "down", "k", "j"].includes(key)) {
105
+ picker.index = Math.max(0, Math.min(last, picker.index + (key === "up" || key === "k" ? -1 : 1)));
106
+ screen.manualScroll = false;
107
+ } else if (key === "return") {
108
+ if (picker.index === last) close(screen);
109
+ else picker.phase = picker.index === last - 1 ? "custom" : "confirm";
110
+ screen.offset = 0;
111
+ screen.manualScroll = false;
112
+ }
113
+ }
114
+
115
+ export function choiceKeys(screen: DashboardScreenState): string[] {
116
+ switch (screen.picker?.phase) {
117
+ case "options":
118
+ return ["↑↓ select · Enter choose", "Esc decide later"];
119
+ case "custom":
120
+ return ["Enter review · Esc cancel"];
121
+ case "confirm":
122
+ return ["Enter save to Bookie", "e edit · Esc cancel"];
123
+ case "refused":
124
+ return ["r review again · e edit", "Esc cancel"];
125
+ case "saving":
126
+ return ["Waiting for Bookie…"];
127
+ default:
128
+ return ["Esc back"];
129
+ }
130
+ }
131
+
132
+ /** Erase inspected note text and the draft when their source is no longer current. Keep an in-flight save's outcome visible. */
133
+ export function choiceBody(screen: DashboardScreenState): string[] {
134
+ const picker = screen.picker;
135
+ if (!picker) return [];
136
+ if (!current(screen, picker)) {
137
+ picker.detail = undefined;
138
+ picker.draft = "";
139
+ if (picker.phase !== "saving" && picker.phase !== "saved") picker.phase = "unavailable";
140
+ }
141
+ if (picker.phase === "saved") return ["Answer saved in Bookie."];
142
+ if (picker.phase === "saving") return ["Saving your answer in Bookie…"];
143
+ if (picker.phase === "loading") return ["Reading this choice from Bookie…"];
144
+ if (picker.phase === "unavailable" || !picker.detail)
145
+ return [
146
+ ...(picker.error ? [picker.error] : []),
147
+ "This choice is unavailable. Return to the list to check its current status.",
148
+ ];
149
+ const detail = picker.detail;
150
+ const issues = picker.error ? [picker.error, ""] : [];
151
+ if (picker.phase === "custom") return [...issues, detail.label, "", "Write your own answer", picker.draft + "▏"];
152
+ if (picker.phase === "confirm" || picker.phase === "refused")
153
+ return [
154
+ ...issues,
155
+ detail.label,
156
+ "",
157
+ "Save this answer in Bookie?",
158
+ "",
159
+ detail.options[picker.index] ?? picker.draft.trim(),
160
+ ];
161
+ return [
162
+ detail.label,
163
+ "From: " + detail.title,
164
+ "",
165
+ ...detail.options.map(
166
+ (option, i) =>
167
+ (i === picker.index ? "> " : " ") +
168
+ option +
169
+ (detail.recommendation?.option === option ? " · Recommended" : ""),
170
+ ),
171
+ (picker.index === detail.options.length ? "> " : " ") + "Write my own answer",
172
+ (picker.index === detail.options.length + 1 ? "> " : " ") + "Decide later",
173
+ ...(detail.recommendation
174
+ ? [
175
+ "",
176
+ "Recommended: " + detail.recommendation.option,
177
+ "Why: " + detail.recommendation.reason,
178
+ "Basis: " + detail.recommendation.evidence,
179
+ ]
180
+ : []),
181
+ ];
182
+ }
183
+
184
+ type ChoiceConnection = Pick<ReturnType<typeof createDashboardConnection>, "inspectChoice" | "change" | "state">;
185
+
186
+ export async function inspectChoice(screen: DashboardScreenState, connection: ChoiceConnection) {
187
+ const picker = screen.picker;
188
+ if (!picker || picker.phase !== "loading") return;
189
+ try {
190
+ const detail = await connection.inspectChoice(picker.target);
191
+ if (screen.picker !== picker || picker.phase !== "loading" || !current(screen, picker)) return;
192
+ picker.detail = detail;
193
+ picker.phase = "options";
194
+ } catch (error) {
195
+ if (screen.picker !== picker || picker.phase !== "loading") return;
196
+ picker.phase = "unavailable";
197
+ picker.error = error instanceof Error ? error.message : "Bookie could not open this choice.";
198
+ }
199
+ }
200
+
201
+ export async function saveChoice(screen: DashboardScreenState, connection: ChoiceConnection) {
202
+ const picker = screen.picker;
203
+ if (!picker || picker.phase !== "saving" || !picker.detail || !current(screen, picker)) return;
204
+ const option = picker.detail.options[picker.index];
205
+ const saved = await connection.change({
206
+ action: "answer-choice",
207
+ ...picker.target,
208
+ revision: picker.detail.revision,
209
+ answer: option === undefined ? { custom: picker.draft.trim() } : { option },
210
+ });
211
+ if (saved) {
212
+ picker.phase = "saved";
213
+ picker.detail = undefined;
214
+ picker.draft = "";
215
+ } else {
216
+ // A lost acknowledgment can follow a committed write. Reopen the live row before any further submission.
217
+ if (!connection.state.snapshot) {
218
+ picker.detail = undefined;
219
+ picker.draft = "";
220
+ }
221
+ picker.phase = picker.detail ? "refused" : "unavailable";
222
+ picker.error =
223
+ connection.state.error ??
224
+ (connection.state.acknowledgment?.state === "refused"
225
+ ? connection.state.acknowledgment.effect
226
+ : "Bookie could not save this answer.");
227
+ }
228
+ }