@kolohelios/dipping-bird 0.1.6 → 0.1.8

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
@@ -1,14 +1,15 @@
1
1
  # Dipping Bird
2
2
 
3
- An opt-in Pi extension that keeps an authorized task moving until the agent
4
- reports completion, a blocker, or a pause. Works in **jj workspaces**; plain Git
5
- repositories are not supported.
3
+ An opt-in Pi extension with two continuation modes: unbounded Nag reminders
4
+ for any workspace, or bounded, evidence-driven supervision in **jj workspaces**.
5
+ Neither mode grants the agent permission to do new work.
6
6
 
7
7
  This is a community package, not an official Pi-maintained extension.
8
8
 
9
9
  ## Use
10
10
 
11
- Tested with Pi 1.5.2. Requires Node.js 22.19+ and `jj` on Pi's PATH.
11
+ Tested with Pi 1.5.2. Requires Node.js 22.19+; supervised Bird also requires `jj`
12
+ on Pi's PATH.
12
13
  Install from npm:
13
14
 
14
15
  ```sh
@@ -33,8 +34,56 @@ goal explicitly starts a new supervision window, not a new permission grant.
33
34
  When upgrading from `0.1.4` or earlier, quit Pi before updating and start a new
34
35
  process afterward. Old in-flight startups have no receipts to recover on reload.
35
36
 
37
+ ## Nag reminders
38
+
39
+ ```text
40
+ /nag Keep implementing until the agreed acceptance criteria are satisfied.
41
+ /nag set Focus on the failing integration tests next.
42
+ /nag status
43
+ /nag off
44
+ ```
45
+
46
+ `/bird nag <prompt>` is an alias. Enabling Nag **does not start a turn**; after
47
+ a successful final boundary, Nag projects its prompt if no higher-priority work
48
+ is waiting. `/nag on` reuses the saved prompt. `set` alone never enables Nag.
49
+
50
+ Nag has **no jj pin, time/turn cap, checkpoint, or evidence requirement** and can
51
+ incur ongoing model costs. The `nag` tool lets the agent stop before completion
52
+ or asking for input, redirect the prompt, and re-arm when fresh input unblocks
53
+ the task. `/nag off` doesn't abort current work or clear queues. Escape during a run disables
54
+ Nag; provider errors don't trigger reminders. Reloads, forks, and tree navigation
55
+ restore saved prompts/counts with Nag **off**; use `/nag on` explicitly to re-arm.
56
+ If Nag state persistence fails, Nag stops locally: retry `/nag off` successfully
57
+ before reloading.
58
+
59
+ The `bird` tool can start first-time supervision during an authorized turn,
60
+ pause it, inspect it, or resume its original pin and remaining budget. It cannot
61
+ renew a window. Only one mode may continue work; neither tool may bypass an
62
+ explicit stop without fresh user input. Use `/bird stop` to stop either mode
63
+ and abort current work.
64
+
65
+ ### Optional queued-work integration
66
+
67
+ Native Pi user queues take priority automatically. Extensions using custom
68
+ steering or follow-up messages must synchronously claim this event while their
69
+ work is pending; Pi's public pending-message count doesn't include those queues:
70
+
71
+ ```typescript
72
+ pi.events.on("bird:yield-to-input", (claim) => {
73
+ if (hasDeliverableWork()) claim();
74
+ });
75
+ ```
76
+
77
+ The extension claiming priority is responsible for delivering its work. Nag
78
+ rechecks before projection; suppressed prompts don't enter future model context
79
+ or compaction and don't increment the count. Status and sidecars count context
80
+ projections, not confirmed provider delivery; later request or auth failures may
81
+ still count. No external inbox CLI or integration is required.
82
+
36
83
  ## Limits and safety
37
84
 
85
+ These limits apply to supervised Bird, not Nag.
86
+
38
87
  - At most **60 automatic continuations** or **two elapsed hours**, checked
39
88
  between runs. An in-flight tool is not forcibly preempted by these caps.
40
89
  - Pins the real working directory and eight-character jj change ID. Identity
@@ -66,6 +115,15 @@ manual run because the SDK's abort is session-wide. Restart Pi to cancel a stuck
66
115
  preflight rather than relying on reload. Host-level cancellation fixes remain
67
116
  necessary before this change is ready for release.
68
117
 
118
+ If priority work arrives after a Nag request has begun, cancellation can still
119
+ incur one no-action model turn before queued work proceeds. Priority checks
120
+ aren't preemption of an already projected response or its tools; use Escape to
121
+ interrupt work. As with manual Pi turns, steering received mid-response may not
122
+ be applied before its tool batch.
123
+
124
+ Nag deliberately follows Pi's successful boundaries, including token-limited
125
+ responses. Use supervised Bird rather than Nag when continuation limits matter.
126
+
69
127
  ## Privacy
70
128
 
71
129
  Bird makes no direct network/model calls, reads no credentials, and starts no
@@ -73,7 +131,11 @@ background services or timers. It stores its goal, workspace/change pin, limits,
73
131
  checkpoint summaries/references, and issued/consumed startup prompts as custom
74
132
  entries in Pi's session history.
75
133
  Do not put secrets or raw sensitive output in goals or checkpoints. Control
76
- characters are normalized; that is **not** secret redaction.
134
+ characters are normalized in supervised goals; that is **not** secret redaction.
135
+ Nag stores its prompt, enabled setting, and projection count in the session. A
136
+ projected reminder may append a `.nags` sidecar beside the session file containing
137
+ only its timestamp, session path, and entry ID—not the prompt. Don't put secrets
138
+ in reminder prompts either.
77
139
 
78
140
  ## Development
79
141
 
@@ -103,7 +165,7 @@ requests.
103
165
  The coverage gate measures all extension source, including unimported files.
104
166
  `just build` packs the release into `dist/`, installs it offline without peer or
105
167
  dev dependencies, and verifies its manifest, contents, and Pi discovery. Only
106
- `extensions/index.ts` is registered; the helper module is not a second extension.
168
+ `extensions/index.ts` is registered; helper modules aren't separate extensions.
107
169
 
108
170
  `just validate` also runs Shaka's repository preflight/whitespace checks and
109
171
  Nix checks. Shaka is pinned from FlakeHub in `flake.lock`. Its current
@@ -145,6 +207,11 @@ operation or overwrite stronger existing settings.
145
207
  See [architecture](architecture.md) and [decisions](architecture-decision-record.md)
146
208
  for lifecycle and tooling details.
147
209
 
210
+ ## Acknowledgments
211
+
212
+ Thanks to [Scott Parish (@srp)](https://github.com/srp) for the Nag workflow
213
+ and agent-control contributions.
214
+
148
215
  ## License
149
216
 
150
217
  Licensed under [MIT](LICENSE-MIT) OR [Apache-2.0](LICENSE-APACHE), at your option.
package/architecture.md CHANGED
@@ -23,8 +23,12 @@ flowchart LR
23
23
 
24
24
  - `extensions/core.ts` owns immutable state transitions, input bounds, prompt
25
25
  text, budget checks, and parsing persisted state.
26
- - `extensions/index.ts` registers `/bird`, `bird_checkpoint`, and Pi lifecycle
27
- handlers. Its revision counter discards stale asynchronous identity results.
26
+ - `extensions/index.ts` coordinates modes, `/bird`, `bird_checkpoint`, and Pi
27
+ lifecycle handlers. Its revision counter discards stale identity results.
28
+ - `extensions/bird-control.ts` exposes model-only supervision controls without
29
+ changing the saved pin or renewing budgets.
30
+ - `extensions/nag.ts` owns reminder commands, tools, and delivery priority;
31
+ `nag-state.ts` owns pure transitions, and `nag-marker.ts` writes sidecars.
28
32
  - Pi owns message scheduling, tool permissions, model calls, and persistence.
29
33
  The manifest exposes only `extensions/index.ts` as an extension entry point.
30
34
 
@@ -47,9 +51,24 @@ Once consumed, it no longer claims a later manual copy of that prompt.
47
51
  it does not duplicate work when another continuation or message is pending.
48
52
 
49
53
  `running`, `paused`, `blocked`, and `review` are the persisted modes. `review`
50
- means completion reported. Blocked, paused, and review states require an explicit
51
- user restart before Bird supervises further work. Compaction keeps the current
52
- window; reload and tree navigation do not re-arm it.
54
+ means completion reported. Blocked, paused, and review states cannot re-arm within
55
+ the same run. After fresh user input, the agent may resume remaining limits;
56
+ only a user command can create a new window. Compaction keeps the current window;
57
+ reload and tree navigation do not re-arm it.
58
+
59
+ Nag is a separate, uncapped session state. It proposes one native continuation
60
+ at `agent_before_settle`, not a nested run from notification-only settlement.
61
+ It yields there and again in `context` to native queues and synchronous
62
+ `bird:yield-to-input` claims. Queued
63
+ notices contain no prompt; the current prompt is projected only at delivery.
64
+ Historical notices are filtered from subsequent context, so suppressed prompts
65
+ never enter compaction. A canceled notice instructs one turn to take no action;
66
+ its assistant tool calls are suppressed. The projection count increments once
67
+ per notice, with optional timestamp/path/entry-ID correlation in a sidecar. This
68
+ is not proof of provider delivery. Both model tools honor explicit stops and
69
+ require delivery of matching fresh human input to re-arm after a stop. Submitted,
70
+ rejected, or locally handled input doesn't unlock an old tool batch. Nag restores
71
+ off after resource recovery or branch navigation, retaining its prompt/count.
53
72
 
54
73
  ## Operation
55
74
 
@@ -0,0 +1,58 @@
1
+ import { Type } from "typebox";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { BirdError, prompt, type State } from "./core.ts";
7
+
8
+ export function registerBirdControl(
9
+ pi: ExtensionAPI,
10
+ control: {
11
+ status: () => string;
12
+ pause: (ctx: ExtensionContext) => void;
13
+ arm: (
14
+ action: "start" | "resume",
15
+ goal: string | undefined,
16
+ signal: AbortSignal | undefined,
17
+ ctx: ExtensionContext,
18
+ ) => Promise<State>;
19
+ },
20
+ ): void {
21
+ pi.registerTool({
22
+ name: "bird",
23
+ label: "Bird supervision",
24
+ exposure: "model-only",
25
+ executionMode: "sequential",
26
+ description:
27
+ "Only on the user's request, start supervised Bird in the current turn, resume the saved goal within its original jj pin and budget, pause supervision without aborting work, or inspect status. Use bird_checkpoint for progress, blockers, and completion. Never replace a saved window, re-arm after an explicit stop without fresh user input, or switch to Nag to bypass a supervision stop. This grants no task or tool permissions.",
28
+ parameters: Type.Object(
29
+ {
30
+ action: Type.Union([
31
+ Type.Literal("start"),
32
+ Type.Literal("resume"),
33
+ Type.Literal("pause"),
34
+ Type.Literal("status"),
35
+ ]),
36
+ goal: Type.Optional(Type.String({ minLength: 1, maxLength: 4000 })),
37
+ },
38
+ { additionalProperties: false },
39
+ ),
40
+ async execute(_id, { action, goal }, signal, _update, ctx) {
41
+ if (signal?.aborted) throw new BirdError("Bird command cancelled.");
42
+ if (goal !== undefined && action !== "start")
43
+ throw new BirdError("Only start takes a goal.");
44
+ if (action === "pause") control.pause(ctx);
45
+ else if (action !== "status") {
46
+ const state = await control.arm(action, goal, signal, ctx);
47
+ return {
48
+ content: [{ type: "text", text: prompt(state) }],
49
+ details: undefined,
50
+ };
51
+ }
52
+ return {
53
+ content: [{ type: "text", text: control.status() }],
54
+ details: undefined,
55
+ };
56
+ },
57
+ });
58
+ }
@@ -1,3 +1,7 @@
1
+ export class BirdError extends Error {
2
+ override readonly name = "BirdError";
3
+ }
4
+
1
5
  export const MAX_CONTINUATIONS = 60;
2
6
  export const MAX_ELAPSED_MS = 2 * 60 * 60 * 1000;
3
7
  export const STATE_KEY = "dipping-bird-v1";
@@ -203,6 +207,38 @@ export function restore(raw: unknown): State | undefined {
203
207
  };
204
208
  }
205
209
 
210
+ export function resume(
211
+ state: State,
212
+ cwd: string,
213
+ change: string,
214
+ now: number,
215
+ ): State {
216
+ if (state.cwd !== cwd || state.change !== change)
217
+ throw new BirdError("Bird pin differs; resuming is refused.");
218
+ if (!hasBudget(state, now))
219
+ throw new BirdError(
220
+ "Bird's supervision cap was reached. Only the user can start a new window.",
221
+ );
222
+ return {
223
+ ...state,
224
+ mode: "running",
225
+ summary: "Resumed with remaining limits; no permissions renewed.",
226
+ };
227
+ }
228
+
229
+ export function formatSupervisionStatus(
230
+ state: State | undefined,
231
+ now: number,
232
+ ): string {
233
+ if (!state)
234
+ return "Bird is not started. Use /bird start to supervise this task.";
235
+ const remaining = Math.max(
236
+ 0,
237
+ Math.ceil((MAX_ELAPSED_MS - (now - state.startedAt)) / 60000),
238
+ );
239
+ return `Bird: ${state.mode === "review" ? "completion reported — inspect evidence; not independently certified" : state.mode}\nJJ change: ${state.change}; continuations ${state.continuations}/${MAX_CONTINUATIONS}; ${remaining} minutes left, checked between runs.\nGoal: ${state.goal}\nCheckpoint: ${state.summary}\nEvidence: ${state.evidence.join("; ") || "none"}`;
240
+ }
241
+
206
242
  export function prompt(state: State): string {
207
243
  return `[BIRD: acceptance-driven continuation, ${state.continuations}/${MAX_CONTINUATIONS} automatic continuations]
208
244
  Goal: ${state.goal}
@@ -7,19 +7,23 @@ import type {
7
7
  } from "@earendil-works/pi-coding-agent";
8
8
  import {
9
9
  advance,
10
+ BirdError,
10
11
  checkpoint,
12
+ formatSupervisionStatus,
11
13
  hasBudget,
12
14
  MAX_CONTINUATIONS,
13
- MAX_ELAPSED_MS,
14
15
  pause,
15
16
  prompt,
16
17
  readStartReceipt,
17
18
  restore,
19
+ resume,
18
20
  start,
19
21
  START_KEY,
20
22
  STATE_KEY,
21
23
  type State,
22
24
  } from "./core.ts";
25
+ import { registerNag } from "./nag.ts";
26
+ import { registerBirdControl } from "./bird-control.ts";
23
27
 
24
28
  const DEFAULT_GOAL =
25
29
  "Finish the current conversation's task against its existing acceptance criteria and specs. Require evidence for every applicable criterion, native acceptance where required, and resolution of owner/vendor holds. Do not substitute offline test counts, more planning, or harness scaffolding for delivery.";
@@ -27,20 +31,29 @@ const DEFAULT_GOAL =
27
31
  export default function dippingBird(pi: ExtensionAPI): void {
28
32
  let state: State | undefined;
29
33
  let revision = 0;
34
+ let supervisedSinceInput = false;
35
+ let stoppedByUser = false;
36
+ let startingSupervision = false;
30
37
  let pendingStart:
31
38
  { state: State; prompt: string; ready: boolean } | undefined;
32
39
 
33
40
  const show = (ctx: ExtensionContext): void => {
34
- ctx.ui.setStatus(
35
- "dipping-bird",
36
- state
37
- ? `bird: ${state.mode === "review" ? "completion reported" : state.mode} ${state.continuations}/${MAX_CONTINUATIONS}`
38
- : undefined,
39
- );
41
+ try {
42
+ ctx.ui.setStatus(
43
+ "dipping-bird",
44
+ nag.status() ??
45
+ (state
46
+ ? `bird: ${state.mode === "review" ? "completion reported" : state.mode} ${state.continuations}/${MAX_CONTINUATIONS}`
47
+ : undefined),
48
+ );
49
+ } catch {
50
+ /* Status is cosmetic and may outlive its UI runner. */
51
+ }
40
52
  };
41
53
  const save = (ctx: ExtensionContext, next: State): void => {
42
54
  if (state !== next) revision++;
43
55
  state = next;
56
+ if (next.mode === "running") supervisedSinceInput = true;
44
57
  pi.appendEntry(STATE_KEY, next);
45
58
  show(ctx);
46
59
  };
@@ -96,6 +109,8 @@ export default function dippingBird(pi: ExtensionAPI): void {
96
109
  const recover = (ctx: ExtensionContext): void => {
97
110
  pendingStart = undefined;
98
111
  revision++;
112
+ supervisedSinceInput = false;
113
+ stoppedByUser = true;
99
114
  state = undefined;
100
115
  for (const entry of ctx.sessionManager.getBranch()) {
101
116
  if (entry.type === "custom" && entry.customType === STATE_KEY)
@@ -105,33 +120,104 @@ export default function dippingBird(pi: ExtensionAPI): void {
105
120
  else show(ctx);
106
121
  };
107
122
 
123
+ const nag = registerNag(pi, {
124
+ show,
125
+ canArm: (agent) =>
126
+ !startingSupervision &&
127
+ !pendingStart &&
128
+ state?.mode !== "running" &&
129
+ (!agent || (!supervisedSinceInput && !stoppedByUser)),
130
+ userStopped: () => {
131
+ stoppedByUser = true;
132
+ },
133
+ userDelivered: () => {
134
+ stoppedByUser = false;
135
+ supervisedSinceInput = state?.mode === "running";
136
+ },
137
+ });
138
+ registerBirdControl(pi, {
139
+ status: () => formatSupervisionStatus(state, Date.now()),
140
+ pause: (ctx) => {
141
+ stoppedByUser = true;
142
+ pendingStart = undefined;
143
+ revision++;
144
+ if (state?.mode === "running")
145
+ save(ctx, pause(state, "Paused by the agent."));
146
+ },
147
+ arm: async (action, goal, signal, ctx) => {
148
+ const busy =
149
+ nag.enabled() || pendingStart !== undefined || startingSupervision;
150
+ if (
151
+ stoppedByUser ||
152
+ (!busy && supervisedSinceInput && state?.mode !== "running")
153
+ )
154
+ throw new BirdError(
155
+ "Bird stopped in this run. Wait for fresh user input before arming it.",
156
+ );
157
+ if (busy)
158
+ throw new BirdError(
159
+ "Stop the active continuation or wait for Bird to start.",
160
+ );
161
+ const previous = state;
162
+ if (previous) supervisedSinceInput = true;
163
+ if (action === "start" && previous)
164
+ throw new BirdError(
165
+ "A Bird window already exists. Resume it or ask the user to start a new window.",
166
+ );
167
+ if (action === "resume" && !previous)
168
+ throw new BirdError("No saved Bird window to resume.");
169
+ if (previous?.mode === "running")
170
+ throw new BirdError("Bird is already running.");
171
+ startingSupervision = true;
172
+ supervisedSinceInput = true;
173
+ const ticket = ++revision;
174
+ try {
175
+ const pin = await identity(ctx);
176
+ if (revision !== ticket || signal?.aborted || stoppedByUser)
177
+ throw new BirdError("Bird start or resume was interrupted.");
178
+ const next = previous
179
+ ? resume(previous, pin.cwd, pin.change, Date.now())
180
+ : start(goal ?? DEFAULT_GOAL, pin.cwd, pin.change, Date.now());
181
+ try {
182
+ save(ctx, next);
183
+ } catch {
184
+ state = previous;
185
+ revision++;
186
+ show(ctx);
187
+ throw new BirdError(
188
+ "Session persistence failed; Bird was not armed.",
189
+ );
190
+ }
191
+ return next;
192
+ } finally {
193
+ startingSupervision = false;
194
+ }
195
+ },
196
+ });
197
+
108
198
  pi.registerCommand("bird", {
109
199
  description:
110
- "Acceptance-driven continuation: /bird start [goal], /bird stop, /bird status",
200
+ "Supervise with /bird start [goal], or arm a reminder with /bird nag <prompt>",
111
201
  handler: async (args, ctx) => {
112
202
  const [action, ...words] = args.trim().split(/\s+/);
203
+ if (action === "nag") {
204
+ nag.command(args.trim().slice(3), ctx);
205
+ return;
206
+ }
113
207
  if (action === "status" || !action) {
114
- const remaining = state
115
- ? Math.max(
116
- 0,
117
- Math.ceil(
118
- (MAX_ELAPSED_MS - (Date.now() - state.startedAt)) / 60000,
119
- ),
120
- )
121
- : 0;
122
- ctx.ui.notify(
123
- state
124
- ? `Bird: ${state.mode === "review" ? "completion reported — inspect evidence; not independently certified" : state.mode}\nJJ change: ${state.change}; continuations ${state.continuations}/${MAX_CONTINUATIONS}; ${remaining} minutes left, checked between runs.\nGoal: ${state.goal}\nCheckpoint: ${state.summary}\nEvidence: ${state.evidence.join("; ") || "none"}`
125
- : "Bird is not started. Use /bird start to supervise this task.",
126
- "info",
127
- );
208
+ ctx.ui.notify(formatSupervisionStatus(state, Date.now()), "info");
128
209
  return;
129
210
  }
130
211
  if (action === "stop") {
212
+ supervisedSinceInput = true;
213
+ nag.stop(ctx);
131
214
  pendingStart = undefined;
132
215
  revision++;
133
- if (state) save(ctx, pause(state, "Stopped explicitly by the user."));
134
- ctx.abort();
216
+ try {
217
+ if (state) save(ctx, pause(state, "Stopped explicitly by the user."));
218
+ } finally {
219
+ ctx.abort();
220
+ }
135
221
  ctx.ui.notify(
136
222
  "Bird stopped. Any delayed start will be aborted.",
137
223
  "info",
@@ -139,7 +225,10 @@ export default function dippingBird(pi: ExtensionAPI): void {
139
225
  return;
140
226
  }
141
227
  if (action !== "start") {
142
- ctx.ui.notify("Usage: /bird start [goal] | stop | status", "warning");
228
+ ctx.ui.notify(
229
+ "Usage: /bird start [goal] | nag <prompt> | stop | status",
230
+ "warning",
231
+ );
143
232
  return;
144
233
  }
145
234
  if (!ctx.isIdle()) {
@@ -149,7 +238,16 @@ export default function dippingBird(pi: ExtensionAPI): void {
149
238
  );
150
239
  return;
151
240
  }
241
+ if (nag.enabled() || startingSupervision) {
242
+ ctx.ui.notify(
243
+ "Turn Nag off or wait for the current Bird start.",
244
+ "warning",
245
+ );
246
+ return;
247
+ }
152
248
  pendingStart = undefined;
249
+ startingSupervision = true;
250
+ stoppedByUser = false;
153
251
  const ticket = ++revision;
154
252
  try {
155
253
  const pin = await identity(ctx);
@@ -204,6 +302,8 @@ export default function dippingBird(pi: ExtensionAPI): void {
204
302
  "Bird did not start: identity, goal or resume pin could not be verified.",
205
303
  "warning",
206
304
  );
305
+ } finally {
306
+ startingSupervision = false;
207
307
  }
208
308
  },
209
309
  });
@@ -286,6 +386,8 @@ export default function dippingBird(pi: ExtensionAPI): void {
286
386
  pendingStart = undefined;
287
387
  revision++;
288
388
  if (["stop", "pause"].includes(event.text.trim().toLowerCase())) {
389
+ supervisedSinceInput = true;
390
+ nag.stop(ctx);
289
391
  if (state) save(ctx, pause(state, "User requested a stop/pause."));
290
392
  }
291
393
  });
@@ -294,7 +396,6 @@ export default function dippingBird(pi: ExtensionAPI): void {
294
396
  event.messageType === "user" && consumeStart(ctx, event.prompt);
295
397
  const pending = pendingStart;
296
398
  if (pending) {
297
- pendingStart = undefined;
298
399
  const ticket = revision;
299
400
  if (
300
401
  event.messageType === "user" &&
@@ -304,7 +405,7 @@ export default function dippingBird(pi: ExtensionAPI): void {
304
405
  hasBudget(pending.state, Date.now())
305
406
  ) {
306
407
  pendingStart = { ...pending, ready: true };
307
- }
408
+ } else if (pendingStart === pending) pendingStart = undefined;
308
409
  }
309
410
  // Preflight can outlive stop; abort again once Pi owns the run.
310
411
  if (birdStart && !pendingStart?.ready) {
@@ -0,0 +1,40 @@
1
+ import { appendFile } from "node:fs/promises";
2
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
3
+
4
+ export type NagMarker = Readonly<{
5
+ timestamp: string;
6
+ session_file: string;
7
+ entry_id: string;
8
+ }>;
9
+ export type MarkerWriter = (marker: NagMarker) => Promise<void>;
10
+
11
+ export function markerForNag(
12
+ sessionFile: string | undefined,
13
+ branch: readonly SessionEntry[],
14
+ ): NagMarker | undefined {
15
+ if (!sessionFile) return undefined;
16
+ const entry = branch.findLast(
17
+ (item) => item.type === "custom_message" && item.customType === "pi-nag",
18
+ );
19
+ if (entry?.type !== "custom_message") return undefined;
20
+ return {
21
+ timestamp: entry.timestamp,
22
+ session_file: sessionFile,
23
+ entry_id: entry.id,
24
+ };
25
+ }
26
+
27
+ export async function appendNagMarker(
28
+ marker: NagMarker,
29
+ append: (
30
+ path: string,
31
+ data: string,
32
+ options: { mode: number },
33
+ ) => Promise<void> = appendFile,
34
+ ): Promise<void> {
35
+ await append(
36
+ `${marker.session_file.replace(/\.jsonl$/, "")}.nags`,
37
+ `${JSON.stringify(marker)}\n`,
38
+ { mode: 0o600 },
39
+ );
40
+ }
@@ -0,0 +1,77 @@
1
+ export class NagInputError extends Error {}
2
+
3
+ export type NagState = Readonly<{
4
+ enabled: boolean;
5
+ prompt: string;
6
+ count: number;
7
+ }>;
8
+ export type NagAction = "on" | "off" | "set" | "status";
9
+ export const initialState: NagState = { enabled: false, prompt: "", count: 0 };
10
+
11
+ export function updateState(
12
+ state: NagState,
13
+ action: NagAction,
14
+ prompt?: string,
15
+ ): NagState {
16
+ if (action === "status") return state;
17
+ if (action === "off") return { ...state, enabled: false };
18
+ if (action === "set") {
19
+ if (prompt === undefined || !prompt.trim())
20
+ throw new NagInputError("A prompt is required.");
21
+ return { ...state, prompt };
22
+ }
23
+ const nextPrompt = prompt === undefined ? state.prompt : prompt;
24
+ if (!nextPrompt.trim())
25
+ throw new NagInputError("Set a prompt before enabling nag.");
26
+ return {
27
+ enabled: true,
28
+ prompt: nextPrompt,
29
+ count: state.enabled ? state.count : 0,
30
+ };
31
+ }
32
+
33
+ export function parseCommand(args: string): {
34
+ action: NagAction;
35
+ prompt?: string;
36
+ } {
37
+ const text = args.trim();
38
+ if (!text) return { action: "status" };
39
+ const actions = ["on", "off", "set", "status"] as const;
40
+ const action = actions.find(
41
+ (word) =>
42
+ text === word ||
43
+ (text.startsWith(word) && /\s/.test(text.charAt(word.length))),
44
+ );
45
+ if (!action) return { action: "on", prompt: text };
46
+ const prompt = text.slice(action.length).trim();
47
+ if (prompt && action !== "on" && action !== "set")
48
+ throw new NagInputError(`/nag ${action} does not take a prompt.`);
49
+ return prompt ? { action, prompt } : { action };
50
+ }
51
+
52
+ export function parseState(data: unknown): NagState | undefined {
53
+ if (
54
+ !data ||
55
+ typeof data !== "object" ||
56
+ !("enabled" in data) ||
57
+ !("prompt" in data)
58
+ )
59
+ return undefined;
60
+ if (typeof data.enabled !== "boolean" || typeof data.prompt !== "string")
61
+ return undefined;
62
+ if (data.enabled && !data.prompt.trim()) return undefined;
63
+ const count = "count" in data ? data.count : 0;
64
+ if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0)
65
+ return undefined;
66
+ return { enabled: data.enabled, prompt: data.prompt, count };
67
+ }
68
+
69
+ export function formatStatus(state: NagState): string {
70
+ return `Nag is ${state.enabled ? "on" : "off"}. Count: ${state.count}. Prompt: ${state.prompt || "(not set)"}`;
71
+ }
72
+ export function statusIndicator(state: NagState): string | undefined {
73
+ return state.enabled ? `bird: nagging ${state.count}` : undefined;
74
+ }
75
+ export function nagMessage(state: NagState): string {
76
+ return `\`\`\`pi-nag\nnag: on\n\`\`\`\n\n${state.prompt}`;
77
+ }
@@ -0,0 +1,369 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { Type } from "typebox";
7
+ import {
8
+ appendNagMarker,
9
+ markerForNag,
10
+ type MarkerWriter,
11
+ } from "./nag-marker.ts";
12
+ import {
13
+ formatStatus,
14
+ NagInputError,
15
+ initialState,
16
+ nagMessage,
17
+ parseCommand,
18
+ parseState,
19
+ statusIndicator,
20
+ updateState,
21
+ type NagAction,
22
+ type NagState,
23
+ } from "./nag-state.ts";
24
+
25
+ const STATE_TYPE = "pi-nag-state";
26
+ const MESSAGE_TYPE = "pi-nag";
27
+ const CANCELLED_NOTICE =
28
+ "The automatic reminder was cancelled. Take no action and end this turn.";
29
+
30
+ export function registerNag(
31
+ pi: ExtensionAPI,
32
+ options: {
33
+ show: (ctx: ExtensionContext) => void;
34
+ canArm: (agent: boolean) => boolean;
35
+ userStopped: () => void;
36
+ userDelivered: () => void;
37
+ },
38
+ writeMarker: MarkerWriter = appendNagMarker,
39
+ ): {
40
+ command: (args: string, ctx: ExtensionContext) => void;
41
+ enabled: () => boolean;
42
+ status: () => string | undefined;
43
+ stop: (ctx: ExtensionContext) => void;
44
+ } {
45
+ let state: NagState = initialState;
46
+ let pendingNag: string | undefined;
47
+ let deliveredPrompt: string | undefined;
48
+ let skipTools = false;
49
+ let stoppedByUser = false;
50
+ let dirty = false;
51
+ let generation = 0;
52
+ let knownEntries = new Set<string>();
53
+ const humanPrompts = new Set<string>();
54
+
55
+ function restore(ctx: ExtensionContext): void {
56
+ const wasDirty = dirty;
57
+ generation++;
58
+ humanPrompts.clear();
59
+ state = initialState;
60
+ dirty = false;
61
+ pendingNag = deliveredPrompt = undefined;
62
+ skipTools = false;
63
+ stoppedByUser = true;
64
+ for (const entry of ctx.sessionManager.getBranch()) {
65
+ if (entry.type === "custom" && entry.customType === STATE_TYPE)
66
+ state = parseState(entry.data) ?? initialState;
67
+ }
68
+ if (state.enabled || wasDirty) change("off", undefined, ctx);
69
+ else options.show(ctx);
70
+ }
71
+ function save(next: NagState, ctx: ExtensionContext): boolean {
72
+ const ticket = ++generation;
73
+ try {
74
+ pi.appendEntry(STATE_TYPE, next);
75
+ } catch {
76
+ if (ticket !== generation) return false;
77
+ dirty = true;
78
+ state = { ...state, enabled: false };
79
+ options.show(ctx);
80
+ throw new NagInputError(
81
+ "Nag state could not be saved; Nag is off. Retry /nag off before reloading.",
82
+ );
83
+ }
84
+ if (ticket !== generation) return false;
85
+ state = next;
86
+ dirty = false;
87
+ options.show(ctx);
88
+ return true;
89
+ }
90
+ function change(
91
+ action: NagAction,
92
+ prompt: string | undefined,
93
+ ctx: ExtensionContext,
94
+ agent = false,
95
+ ): string {
96
+ if (prompt !== undefined && action !== "on" && action !== "set")
97
+ throw new NagInputError(`${action} does not take a prompt.`);
98
+ if (action === "on" && agent && stoppedByUser)
99
+ throw new NagInputError(
100
+ "Nag was stopped. Wait for a new user request before re-arming.",
101
+ );
102
+ if (action === "on" && !options.canArm(agent))
103
+ throw new NagInputError(
104
+ "Nag cannot take over supervised Bird. Stop Bird first and explicitly arm Nag.",
105
+ );
106
+ if (action === "off") {
107
+ humanPrompts.clear();
108
+ stoppedByUser = true;
109
+ options.userStopped();
110
+ }
111
+ const next = updateState(state, action, prompt);
112
+ if (next !== state) save(next, ctx);
113
+ return formatStatus(state);
114
+ }
115
+ function priorityInput(ctx: ExtensionContext): boolean {
116
+ if (ctx.hasPendingMessages()) return true;
117
+ let claimed = false;
118
+ pi.events.emit("bird:yield-to-input", () => {
119
+ claimed = true;
120
+ });
121
+ return claimed || ctx.hasPendingMessages();
122
+ }
123
+
124
+ pi.on("session_start", (_event, ctx) => restore(ctx));
125
+ pi.on("session_tree", (_event, ctx) => restore(ctx));
126
+ pi.on("input", (event) => {
127
+ if (event.source !== "extension") humanPrompts.add(event.text);
128
+ });
129
+ pi.on("context", (event, ctx) => {
130
+ const pendingIndex =
131
+ pendingNag === undefined
132
+ ? -1
133
+ : event.messages.findIndex(
134
+ (message) =>
135
+ message.role === "custom" &&
136
+ message.customType === MESSAGE_TYPE &&
137
+ message.details === pendingNag,
138
+ );
139
+ let replacement = deliveredPrompt;
140
+ const priorityAfter =
141
+ pendingIndex !== -1 &&
142
+ event.messages
143
+ .slice(pendingIndex + 1)
144
+ .some(
145
+ (message) =>
146
+ message.role === "user" ||
147
+ (message.role === "custom" && message.customType !== MESSAGE_TYPE),
148
+ );
149
+ const competingDraft =
150
+ pendingIndex !== -1 &&
151
+ ctx.sessionManager
152
+ .getBranch()
153
+ .some(
154
+ (entry) =>
155
+ entry.type === "custom_message" &&
156
+ entry.customType !== MESSAGE_TYPE &&
157
+ !knownEntries.has(entry.id),
158
+ );
159
+ if (priorityAfter || competingDraft) {
160
+ pendingNag = deliveredPrompt = replacement = undefined;
161
+ skipTools = false;
162
+ } else if (pendingIndex !== -1 && deliveredPrompt === undefined) {
163
+ const priority = priorityInput(ctx);
164
+ // Event listeners may synchronously run stop commands.
165
+ if (priority || !state.enabled || ctx.signal?.aborted) {
166
+ pendingNag = undefined;
167
+ replacement = CANCELLED_NOTICE;
168
+ skipTools = true;
169
+ } else {
170
+ try {
171
+ if (
172
+ !save({ ...state, count: state.count + 1 }, ctx) ||
173
+ !state.enabled
174
+ ) {
175
+ pendingNag = undefined;
176
+ skipTools = true;
177
+ return {
178
+ messages: event.messages.map((message, index) =>
179
+ index === pendingIndex && message.role === "custom"
180
+ ? { ...message, content: CANCELLED_NOTICE }
181
+ : message,
182
+ ),
183
+ };
184
+ }
185
+ deliveredPrompt = replacement = nagMessage(state);
186
+ const warn = () => {
187
+ try {
188
+ ctx.ui.notify("Could not write the Nag sidecar.", "warning");
189
+ } catch {
190
+ /* The optional writer may finish after its runner is replaced. */
191
+ }
192
+ };
193
+ try {
194
+ const marker = markerForNag(
195
+ ctx.sessionManager.getSessionFile(),
196
+ ctx.sessionManager.getBranch(),
197
+ );
198
+ if (marker) void writeMarker(marker).catch(warn);
199
+ } catch {
200
+ warn();
201
+ }
202
+ } catch {
203
+ pendingNag = undefined;
204
+ replacement = CANCELLED_NOTICE;
205
+ skipTools = true;
206
+ ctx.ui.notify(
207
+ "Nag state could not be saved; Nag is off. Retry /nag off before reloading.",
208
+ "error",
209
+ );
210
+ }
211
+ }
212
+ }
213
+ return {
214
+ messages: event.messages.flatMap((message, i) => {
215
+ if (message.role !== "custom" || message.customType !== MESSAGE_TYPE)
216
+ return [message];
217
+ return i === pendingIndex && replacement !== undefined
218
+ ? [{ ...message, content: replacement }]
219
+ : [];
220
+ }),
221
+ };
222
+ });
223
+ pi.on("message_end", ({ message }) => {
224
+ if (message.role === "user") {
225
+ if (humanPrompts.size) {
226
+ const text =
227
+ typeof message.content === "string"
228
+ ? message.content
229
+ : message.content
230
+ .filter((part) => part.type === "text")
231
+ .map((part) => part.text)
232
+ .join("");
233
+ if (humanPrompts.has(text)) {
234
+ humanPrompts.clear();
235
+ stoppedByUser = false;
236
+ options.userDelivered();
237
+ }
238
+ }
239
+ if (deliveredPrompt !== undefined)
240
+ pendingNag = deliveredPrompt = undefined;
241
+ skipTools = false;
242
+ }
243
+ if (
244
+ !skipTools ||
245
+ message.role !== "assistant" ||
246
+ message.stopReason === "error" ||
247
+ message.stopReason === "aborted"
248
+ )
249
+ return;
250
+ skipTools = false;
251
+ return { message: { ...message, content: [], stopReason: "stop" } };
252
+ });
253
+ pi.on("agent_before_settle", (event, ctx) => {
254
+ if (
255
+ event.outcome !== "completed" ||
256
+ event.continue ||
257
+ event.context.pendingMessages.length ||
258
+ !state.enabled ||
259
+ stoppedByUser
260
+ )
261
+ return;
262
+ if (priorityInput(ctx) || !state.enabled || stoppedByUser) return;
263
+ knownEntries = new Set(
264
+ ctx.sessionManager.getBranch().map((entry) => entry.id),
265
+ );
266
+ pendingNag = randomUUID();
267
+ deliveredPrompt = undefined;
268
+ return {
269
+ entries: [
270
+ ...event.entries,
271
+ {
272
+ type: "custom_message",
273
+ customType: MESSAGE_TYPE,
274
+ content: "Pi Nag: automatic continuation requested.",
275
+ display: true,
276
+ details: pendingNag,
277
+ },
278
+ ],
279
+ continue: true,
280
+ };
281
+ });
282
+ pi.on("agent_settled", (event, ctx) => {
283
+ humanPrompts.clear();
284
+ const unprojected =
285
+ pendingNag !== undefined && deliveredPrompt === undefined;
286
+ pendingNag = deliveredPrompt = undefined;
287
+ skipTools = false;
288
+ if ((event.aborted || unprojected) && state.enabled) {
289
+ stoppedByUser = true;
290
+ options.userStopped();
291
+ change("off", undefined, ctx);
292
+ ctx.ui.notify(
293
+ "Nag disabled after interruption or an unprojected continuation.",
294
+ "info",
295
+ );
296
+ }
297
+ });
298
+
299
+ function command(args: string, ctx: ExtensionContext): void {
300
+ try {
301
+ const parsed = parseCommand(args);
302
+ const status = change(parsed.action, parsed.prompt, ctx);
303
+ if (parsed.action === "on" && state.enabled) stoppedByUser = false;
304
+ ctx.ui.notify(status, "info");
305
+ } catch (error) {
306
+ ctx.ui.notify(
307
+ error instanceof Error ? error.message : String(error),
308
+ "error",
309
+ );
310
+ }
311
+ }
312
+ pi.registerCommand("nag", {
313
+ description:
314
+ "Arm a reminder with /nag <prompt>, or use on, set, off, status",
315
+ handler: async (args, ctx) => command(args, ctx),
316
+ });
317
+ pi.registerTool({
318
+ name: "nag",
319
+ label: "Nag",
320
+ executionMode: "sequential",
321
+ description:
322
+ "On the user's request, manage reminders (#nag or /nag). Use their wording or a short standalone task and stopping condition, not an evidence checklist. Actions: on with a prompt sets and enables; on alone reuses the saved prompt; set redirects without enabling; status inspects; off stops reminders without aborting work. There is no automatic turn or time cap. Turn Nag off before completion or asking for input, feedback, or permission. A redirect alone never enables an inactive reminder. After stopping to wait for input, re-arm only when fresh user input provides a way forward. Never re-arm after an explicit user stop or use Nag to bypass supervised Bird's stop, pin, or budget. This grants no task or tool permissions.",
323
+ parameters: Type.Object(
324
+ {
325
+ action: Type.Union([
326
+ Type.Literal("on"),
327
+ Type.Literal("off"),
328
+ Type.Literal("set"),
329
+ Type.Literal("status"),
330
+ ]),
331
+ prompt: Type.Optional(
332
+ Type.String({ description: "Prompt for on or set." }),
333
+ ),
334
+ },
335
+ { additionalProperties: false },
336
+ ),
337
+ async execute(_id, { action, prompt }, signal, _update, ctx) {
338
+ if (signal?.aborted) throw new NagInputError("Nag command cancelled.");
339
+ const status = change(action, prompt, ctx, true);
340
+ return {
341
+ content: [
342
+ { type: "text", text: action === "off" ? "Nag is off." : status },
343
+ ],
344
+ details: undefined,
345
+ };
346
+ },
347
+ });
348
+ return {
349
+ command,
350
+ // An unsaved stop reserves the mode until storage is reconciled.
351
+ enabled: () => state.enabled || dirty,
352
+ status: () => statusIndicator(state),
353
+ stop: (ctx) => {
354
+ humanPrompts.clear();
355
+ stoppedByUser = true;
356
+ options.userStopped();
357
+ if (state.enabled || dirty) {
358
+ try {
359
+ change("off", undefined, ctx);
360
+ } catch {
361
+ ctx.ui.notify(
362
+ "Nag could not persist its stop. Retry /nag off before reloading.",
363
+ "error",
364
+ );
365
+ }
366
+ }
367
+ },
368
+ };
369
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kolohelios/dipping-bird",
3
- "version": "0.1.6",
4
- "description": "Opt-in, bounded, evidence-driven continuation for the Pi coding agent (jj workspaces).",
3
+ "version": "0.1.8",
4
+ "description": "Opt-in reminders and bounded, evidence-driven jj supervision for the Pi coding agent.",
5
5
  "type": "module",
6
6
  "license": "MIT OR Apache-2.0",
7
7
  "author": "Jon Edwards <jkedwards@me.com>",
@@ -43,7 +43,7 @@
43
43
  "@earendil-works/pi-coding-agent": "1.5.2",
44
44
  "@eslint/js": "10.0.1",
45
45
  "@types/node": "26.6.6",
46
- "c8": "9.1.0",
46
+ "c8": "12.0.0",
47
47
  "eslint": "10.15.0",
48
48
  "globals": "17.14.0",
49
49
  "prettier": "3.10.1",
@@ -83,5 +83,5 @@
83
83
  "json-summary"
84
84
  ]
85
85
  },
86
- "x-release-commit": "ceffdf4b03d0e860caf3f8d3916670c047619b9c"
86
+ "x-release-commit": "10b5c56b821fbbb626c90ba81039aec1ab05980c"
87
87
  }