aboutsummaryrefslogtreecommitdiff
path: root/crates/dinggerd/assets/pi/pi-agent-state.ts
blob: d86f81236b44a1a20220c5043446bf6aece4ce2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
// installed by dingger
// managed by dingger; reinstalling or updating the integration overwrites this file.
// add custom hooks/plugins beside this file instead of editing it.

import crypto from "node:crypto";
import fs from "node:fs";
import net from "node:net";
import path from "node:path";

// The dingger hook receiver listens here; override with DINGGER_AGENT_SOCKET.
const socketPath =
  process.env.DINGGER_AGENT_SOCKET ||
  `${process.env.HOME}/.local/state/dingger/agent.sock`;

// tmux sets TMUX_PANE in the environment of every process it starts in a
// pane, so it names exactly the pane this pi runs in. (Asking tmux for "the
// current pane" is wrong: that is the session's active pane, not ours.)
const paneId = process.env.DINGGER_PANE_ID || process.env.TMUX_PANE;
const source = "dingger:pi";

// Filled in by `dingger install pi`: the daemon reloads an agent that
// reports another version (`dingger reload-agents`).
const extensionVersion = "__DINGGER_EXTENSION_VERSION__";

// Where the daemon asks this extension to reload: one socket per extension
// instance (a reload starts a new one beside the old), next to the daemon's.
const controlPath = path.join(
  path.dirname(socketPath),
  `pi-${process.pid}-${Math.random().toString(36).slice(2, 8)}.sock`,
);
let controlListening = false;

function enabled() {
  return !!paneId;
}

function sendRequestAttempt(request: unknown, timeoutMs: number): Promise<boolean> {
  if (!enabled()) {
    return Promise.resolve(true);
  }

  return new Promise((resolve) => {
    let done = false;
    let timeout: ReturnType<typeof setTimeout> | undefined;
    const finish = (delivered: boolean) => {
      if (done) return;
      done = true;
      if (timeout) {
        clearTimeout(timeout);
      }
      socket.destroy();
      resolve(delivered);
    };

    const socket = net.createConnection(socketPath);
    socket.on("error", () => finish(false));
    socket.on("connect", () => socket.write(`${JSON.stringify(request)}\n`));
    socket.on("data", () => finish(true));
    socket.on("end", () => finish(false));
    timeout = setTimeout(() => finish(false), timeoutMs);
    timeout.unref?.();
  });
}

// Whether the daemon got it.
async function sendRequest(request: unknown): Promise<boolean> {
  if (await sendRequestAttempt(request, 500)) {
    return true;
  }
  return sendRequestAttempt(request, 1500);
}

type AgentState = "working" | "blocked" | "idle";

// The session file, so `dingger restore` can resume this session with
// `pi --session <file>`. It changes with /new, /resume, and forks.
let sessionFile: string | undefined;

function updateSessionFile(ctx: any): void {
  try {
    const file = ctx?.sessionManager?.getSessionFile?.();
    sessionFile = typeof file === "string" && file.length > 0 ? file : undefined;
  } catch {
    sessionFile = undefined;
  }
}

// The agent's importance (/importance): it orders agents within a status
// in dingger's list and jump, and a low agent makes no sound. Saved in the
// session (a custom entry, never sent to the model), so it comes back with
// the conversation: on /resume, `pi --session`, and dingger's restore.
// Other extensions can follow it on the event bus: `dingger:importance`,
// `{ level }`, at session start and on every change.
type Importance = "low" | "normal" | "high";
const importanceLevels: Importance[] = ["high", "normal", "low"];
const importanceEntry = "dingger-importance";
let importance: Importance = "normal";

function savedImportance(ctx: any): Importance {
  try {
    const entries = ctx?.sessionManager?.getEntries?.() ?? [];
    for (let i = entries.length - 1; i >= 0; i--) {
      const entry = entries[i];
      if (entry?.type === "custom" && entry.customType === importanceEntry) {
        const level = entry.data?.level;
        return importanceLevels.includes(level) ? level : "normal";
      }
    }
  } catch {
    // An unreadable session: the default.
  }
  return "normal";
}

// The draft in the input box, as last reported: dingger marks a draft you
// left behind. Each session's draft is also kept in a file of its own, so
// it comes back when the session does after a crash, a restart, or
// `pi --session`.
let draft = "";
// How full the context window is, in percent, as pi's footer shows it;
// "" when unknown (right after compacting, before the next reply).
let context = "";
// The session's name ("" for none): dingger shows it as the agent's name,
// whatever the terminal title says.
let sessionName = "";
const draftDir = path.join(path.dirname(socketPath), "drafts");
// Enough to find the agent by it; the file keeps all of it.
const reportedDraftChars = 500;

function draftFile(): string | undefined {
  return sessionFile ? path.join(draftDir, `${path.basename(sessionFile)}.draft`) : undefined;
}

function saveDraft(text: string): void {
  const file = draftFile();
  if (!file) {
    return;
  }
  try {
    if (text.trim()) {
      fs.mkdirSync(draftDir, { recursive: true });
      fs.writeFileSync(file, text);
    } else {
      fs.unlinkSync(file);
    }
  } catch {
    // None to remove, or nowhere to keep it.
  }
}

// The session's saved draft, into an empty input box.
function restoreDraft(ctx: any): void {
  const file = draftFile();
  if (!file) {
    return;
  }
  try {
    if ((ctx.ui.getEditorText() ?? "") !== "") {
      return;
    }
    const saved = fs.readFileSync(file, "utf8");
    if (saved.trim()) {
      ctx.ui.setEditorText(saved);
    }
  } catch {
    // No saved draft.
  }
}

function requestId(): string {
  return `${source}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
}

/** How a run ended, sent with the idle report that ends it. */
type RunEnd = { aborted?: boolean; error?: string };

/**
 * A provider error as one short readable line: the message inside a JSON
 * body ("401: invalid x-api-key"), else the first line.
 */
export function readableError(text: string): string {
  const first = text.split("\n").find((line) => line.trim()) ?? "";
  let line = first;
  const json = first.indexOf("{");
  if (json >= 0) {
    try {
      const body = JSON.parse(first.slice(json));
      const message = body?.error?.message ?? body?.message ?? body?.detail ?? body?.error;
      if (typeof message === "string" && message.trim()) {
        const status = first.slice(0, json).replace(/[\s:]+$/, "");
        line = status ? `${status}: ${message}` : message;
      }
    } catch {
      // Not JSON after all.
    }
  }
  line = line.replace(/\s+/g, " ").trim();
  return line.length > 100 ? `${line.slice(0, 99)}…` : line || "error";
}

async function report(state: AgentState | undefined, message?: string, end: RunEnd = {}): Promise<void> {
  await sendRequest({
    id: requestId(),
    method: "pane.report_agent",
    params: {
      pane_id: paneId!,
      source,
      agent: "pi",
      ...(state ? { state } : {}),
      message,
      // The run this idle report ends was cancelled (not done), or failed.
      ...(end.aborted ? { aborted: true } : {}),
      ...(end.error ? { error: end.error } : {}),
      importance,
      extension: extensionVersion,
      ...(controlListening ? { control: controlPath } : {}),
      draft: draft.slice(0, reportedDraftChars),
      context,
      name: sessionName,
      seq: Date.now() * 1000,
      ...(sessionFile ? { agent_session_path: sessionFile } : {}),
    },
  });
}

let sendInFlight = false;
let queuedState: { state: AgentState; message?: string; end: RunEnd } | undefined;

function queueState(state: AgentState, message?: string, end: RunEnd = {}): void {
  queuedState = { state, message, end };
  if (!sendInFlight) {
    void drainStateQueue();
  }
}

async function drainStateQueue(): Promise<void> {
  if (sendInFlight) {
    return;
  }

  sendInFlight = true;
  try {
    while (queuedState) {
      const next = queuedState;
      queuedState = undefined;
      await report(next.state, next.message, next.end);
    }
  } finally {
    sendInFlight = false;
    if (queuedState) {
      void drainStateQueue();
    }
  }
}

// ---- Session names -----------------------------------------------------
//
// Every session gets a short name of what it is about, from the model,
// after its first run settles, refreshed every few of your messages, and
// for an old unnamed session when you resume it. A name you give it
// (/name, `pi --name`, /autoname <name>) is never replaced. This runs in
// every pi session (print and JSON runs too, outside tmux too), not only
// where dingger watches. PI_AUTONAME_MODEL="provider/model-id" picks a
// (cheaper) model; the session's own model otherwise.
//
// It replaces the pi-auto-session-name package and reads the marker that
// package saved in sessions, so names it gave stay automatic.

/** A session entry recording an automatic name, and how many of your messages it covered. */
const autoNameEntry = "auto-session-name";
const nameChars = 100;
const renameEvery = 8;
const namePromptChars = 4000;
const nameMessageChars = 350;
const nameTimeoutMs = 30_000;

type Said = { role: "user" | "assistant"; text: string };

/** Message text without injected context blocks, on one line. */
function plainText(content: unknown): string {
  const text =
    typeof content === "string"
      ? content
      : Array.isArray(content)
        ? content
            .filter((part) => part?.type === "text" && typeof part.text === "string")
            .map((part) => part.text)
            .join("\n")
        : "";
  return text
    .replace(/<(system-reminder|selected-context|environment_context)>[\s\S]*?<\/\1>/gi, "")
    .replace(/\s+/g, " ")
    .trim();
}

/** At most `max` characters, cut at a word when one is near. */
function clip(text: string, max: number): string {
  if (text.length <= max) {
    return text;
  }
  const cut = text.slice(0, max);
  const space = cut.lastIndexOf(" ");
  return (space > max / 2 ? cut.slice(0, space) : cut).trim();
}

/** What was said on the session's branch. */
function conversation(entries: any[]): Said[] {
  return entries
    .filter((entry) => entry?.type === "message" && ["user", "assistant"].includes(entry.message?.role))
    .map((entry) => ({ role: entry.message.role, text: plainText(entry.message.content) }))
    .filter((said) => said.text);
}

/** The first message (what it set out to do) and the latest ones, within budget. */
function excerpt(said: Said[]): Said[] {
  const short = (one: Said) => ({ role: one.role, text: clip(one.text, nameMessageChars) });
  const first = short(said[0]);
  const latest: Said[] = [];
  let used = first.text.length;
  for (const one of said.slice(1).reverse()) {
    const next = short(one);
    if (used + next.text.length > namePromptChars || latest.length >= 8) {
      break;
    }
    latest.unshift(next);
    used += next.text.length;
  }
  return [first, ...latest];
}

export function namePrompt(said: Said[]): string {
  return [
    "Name this coding-agent session for a list of sessions.",
    "Answer with the name alone: one line of at most 14 words, without quotes or a final period.",
    'Say what the task or topic is, concretely (like "Fix the sidecar\'s reconnect after a daemon restart").',
    "Write it in the conversation's language.",
    "",
    "<conversation>",
    ...excerpt(said).map((one) => `${one.role === "user" ? "User" : "Assistant"}: ${one.text}`),
    "</conversation>",
  ].join("\n");
}

/** A model's answer as a name: one line, no quotes or label, no final punctuation. */
export function nameFrom(answer: string): string {
  const name = plainText(answer)
    .replace(/^(title|name):\s*/i, "")
    .replace(/^["'`“”«»]+|["'`“”«»]+$/g, "")
    .replace(/[.!?]+$/, "")
    .trim();
  return clip(name, nameChars);
}

function autoName(pi) {
  let yours = false; // you named it: never rename
  let given: string | undefined; // the name this gave it
  let namedAt = 0; // your messages when it was named
  let pending: string | undefined; // a name just set, until pi says so
  let naming = false;

  function nameModel(ctx) {
    const spec = process.env.PI_AUTONAME_MODEL?.trim() ?? "";
    const slash = spec.indexOf("/");
    const chosen = slash > 0 ? ctx.modelRegistry.find(spec.slice(0, slash), spec.slice(slash + 1)) : undefined;
    return [chosen, ctx.model].find((model) => model && ctx.modelRegistry.hasConfiguredAuth(model));
  }

  async function ask(ctx, said: Said[]): Promise<string> {
    const model = nameModel(ctx);
    if (model) {
      try {
        const call = ctx.modelRegistry.complete(
          model,
          { messages: [{ role: "user", content: [{ type: "text", text: namePrompt(said) }], timestamp: Date.now() }] },
          { reasoningEffort: "low", cacheRetention: "none", sessionId: crypto.randomUUID() },
        );
        call.catch(() => {});
        const timeout = new Promise<never>((_, reject) => setTimeout(() => reject(new Error("timeout")), nameTimeoutMs).unref?.());
        const answer = await Promise.race([call, timeout]);
        const name = nameFrom(
          (answer?.content ?? []).filter((block) => block.type === "text").map((block) => block.text).join(" "),
        );
        if (name.length >= 3) {
          return name;
        }
      } catch {
        // The first message, then.
      }
    }
    return clip(said.find((one) => one.role === "user")?.text ?? "", nameChars);
  }

  async function nameSession(ctx, now = false): Promise<void> {
    if (naming || !ctx.sessionManager.getSessionFile()) {
      return;
    }
    const said = conversation(ctx.sessionManager.getBranch());
    const yourMessages = said.filter((one) => one.role === "user").length;
    if (yourMessages === 0 || (yours && !now)) {
      return;
    }
    if (!now && namedAt > 0 && yourMessages - namedAt < renameEvery) {
      return;
    }
    naming = true;
    try {
      const name = await ask(ctx, said);
      if (!name || (yours && !now)) {
        return;
      }
      pending = name;
      given = name;
      namedAt = yourMessages;
      pi.setSessionName(name);
      pi.appendEntry(autoNameEntry, { name, count: yourMessages });
      if (ctx.hasUI) {
        ctx.ui.notify(`Session named: ${name}`, "info");
      }
    } catch {
      // Naming never breaks a session.
    } finally {
      naming = false;
    }
  }

  // In print and JSON runs, before pi exits.
  const finish = (ctx, naming: Promise<void>) => (ctx.mode === "print" || ctx.mode === "json" ? naming : undefined);

  pi.on("session_start", async (_event, ctx) => {
    yours = false;
    given = undefined;
    namedAt = 0;
    pending = undefined;
    naming = false;
    for (const entry of ctx.sessionManager.getEntries()) {
      if (entry?.type === "custom" && entry.customType === autoNameEntry && entry.data) {
        given = typeof entry.data.name === "string" ? entry.data.name : given;
        namedAt = typeof entry.data.count === "number" ? entry.data.count : namedAt;
      }
    }
    const current = pi.getSessionName?.();
    yours = !!current && current !== given;
    // An old session never named: name it now.
    if (!yours && namedAt === 0) {
      await finish(ctx, nameSession(ctx).catch(() => {}));
    }
  });

  pi.on("session_info_changed", (event) => {
    if (pending !== undefined && event?.name === pending) {
      pending = undefined;
      return;
    }
    // Cleared: name it again; anything else is yours.
    yours = event?.name !== undefined;
  });

  pi.on("agent_settled", async (_event, ctx) => {
    await finish(ctx, nameSession(ctx).catch(() => {}));
  });

  pi.registerCommand("autoname", {
    description: "Name this session now, or give it a name: /autoname [name]",
    handler: async (args, ctx) => {
      const name = (args ?? "").trim();
      if (name) {
        yours = true;
        pi.setSessionName(name);
        if (ctx.hasUI) {
          ctx.ui.notify(`Session named: ${name}`, "info");
        }
        return;
      }
      if (ctx.hasUI) {
        ctx.ui.notify("Naming this session…", "info");
      }
      await nameSession(ctx, true);
    },
  });
}

export default function (pi) {
  // Everywhere pi runs, not only in tmux.
  autoName(pi);
  if (!enabled()) {
    return;
  }

  let agentActive = false;
  let blockedCount = 0;
  let blockedMessage: string | undefined;
  let lastState: AgentState | undefined;
  let lastMessage: string | undefined;

  function desiredState() {
    if (blockedCount > 0) {
      return { state: "blocked" as const, message: blockedMessage };
    }
    if (agentActive) {
      return { state: "working" as const, message: undefined };
    }
    return { state: "idle" as const, message: undefined };
  }

  function publishState(force = false, end: RunEnd = {}) {
    const next = desiredState();
    if (!force && next.state === lastState && next.message === lastMessage) {
      return;
    }
    lastState = next.state;
    lastMessage = next.message;
    queueState(next.state, next.message, next.state === "idle" ? end : {});
  }

  // How the current run is ending: pi says before it settles (not for a
  // cancelled run), and the last reply carries the error.
  let runOutcome: string | undefined;
  let replyError: string | undefined;
  pi.on("agent_before_settle", (event) => {
    runOutcome = event?.outcome;
  });
  pi.on("message_end", (event) => {
    const reply = event?.message;
    if (reply?.role === "assistant") {
      replyError = reply.stopReason === "error" ? (reply.errorMessage ?? "") : undefined;
    }
  });

  // A dialog that opens during a run (an extension asking before it goes
  // on): the agent waits on you, so it is blocked until the dialog closes.
  // One opened while idle comes from what you just did, and changes nothing.
  let dialogsBlocking = 0;
  pi.on("ui_prompt_start", (event, ctx) => {
    latestCtx = ctx;
    if (!agentActive) {
      return;
    }
    dialogsBlocking += 1;
    blockedCount += 1;
    blockedMessage = event?.title;
    publishState();
  });
  pi.on("ui_prompt_end", () => {
    if (dialogsBlocking === 0) {
      return;
    }
    dialogsBlocking -= 1;
    blockedCount = Math.max(0, blockedCount - 1);
    if (blockedCount === 0) {
      blockedMessage = undefined;
    }
    publishState();
  });

  pi.events.on("blocked", (data) => {
    if (!data?.active) {
      blockedCount = Math.max(0, blockedCount - 1);
      if (blockedCount === 0) {
        blockedMessage = undefined;
      }
      publishState();
      return;
    }

    blockedCount += 1;
    blockedMessage = data.label;
    publishState();
  });

  // No footer status: it would take a line of its own in pi.
  function announceImportance() {
    pi.events.emit("dingger:importance", { level: importance });
  }

  pi.registerCommand("importance", {
    description: "Set this agent's importance in dingger: high, normal, or low",
    // None once a level is typed out, so Enter runs the command at once.
    getArgumentCompletions: (prefix: string) =>
      importanceLevels.includes(prefix.trim() as Importance)
        ? null
        : importanceLevels
            .filter((level) => level.startsWith(prefix.trim()))
            .map((level) => ({ value: level, label: level })),
    handler: async (args: string, ctx: any) => {
      const wanted = args.trim();
      if (!wanted) {
        ctx.ui.notify(`importance: ${importance}`, "info");
        return;
      }
      if (!importanceLevels.includes(wanted as Importance)) {
        ctx.ui.notify("importance is high, normal, or low", "error");
        return;
      }
      if (wanted !== importance) {
        importance = wanted as Importance;
        pi.appendEntry(importanceEntry, { level: importance });
        announceImportance();
        // Without a state: the state stays as last reported.
        if (enabled()) {
          void report(undefined);
        }
      }
      ctx.ui.notify(`importance: ${importance}`, "info");
    },
  });

  // Like "mark as unread" in mail: dingger shows the agent as done again
  // (a pane option; nothing is saved in the session).
  pi.registerCommand("unread", {
    description: "Mark this agent unread in dingger: it shows as done until you come back to it",
    handler: async (_args: string, ctx: any) => {
      if (agentActive || blockedCount > 0) {
        ctx.ui.notify("only an idle agent can be marked unread", "error");
        return;
      }
      const delivered = await sendRequest({
        id: requestId(),
        method: "pane.mark_unread",
        params: { pane_id: paneId! },
      });
      if (delivered) {
        ctx.ui.notify("marked unread: dingger shows it as done until you come back to it", "info");
      } else {
        ctx.ui.notify("dingger is not running", "error");
      }
    },
  });

  // The latest context, for the control socket's checks and the input box.
  let latestCtx: any;
  let control: net.Server | undefined;

  // Read the input box once typing pauses; report and save it when it changed.
  let draftTimer: ReturnType<typeof setTimeout> | undefined;
  let stopWatchingInput: (() => void) | undefined;

  function checkDraft(): void {
    let text: string;
    try {
      text = latestCtx?.ui?.getEditorText?.() ?? "";
    } catch {
      return;
    }
    if (text === draft) {
      return;
    }
    draft = text;
    saveDraft(text);
    void report(undefined);
  }

  /** Report how full the context window is, when that changed. */
  function checkContext(ctx: any, quiet = false): void {
    let next = "";
    try {
      const percent = ctx?.getContextUsage?.()?.percent;
      if (typeof percent === "number" && Number.isFinite(percent)) {
        next = percent.toFixed(1);
      }
    } catch {
      return;
    }
    if (next === context) {
      return;
    }
    context = next;
    if (!quiet) {
      void report(undefined);
    }
  }

  function checkDraftSoon(): void {
    if (draftTimer) {
      clearTimeout(draftTimer);
    }
    draftTimer = setTimeout(checkDraft, 500);
    draftTimer.unref?.();
  }

  // Run only by the control socket below, which checked that pi is idle
  // with an empty input box: extensions can reload pi only from a command.
  pi.registerCommand("dingger-reload", {
    description: "Reload pi (dingger uses it to update its extension; same as /reload)",
    handler: async (_args: string, ctx: any) => {
      await ctx.reload();
    },
  });

  // Why this pi should not reload now, or undefined if it can.
  function reloadRefusal(): string | undefined {
    try {
      if (agentActive || blockedCount > 0 || latestCtx?.isIdle?.() !== true || latestCtx?.hasPendingMessages?.()) {
        return "busy";
      }
      if ((latestCtx?.ui?.getEditorText?.() ?? "").trim() !== "") {
        return "draft";
      }
    } catch {
      return "no context";
    }
    return undefined;
  }

  function startControl() {
    if (control) {
      return;
    }
    control = net.createServer((socket) => {
      let buffer = "";
      socket.on("error", () => socket.destroy());
      socket.on("data", (data) => {
        buffer += data.toString();
        const newline = buffer.indexOf("\n");
        if (newline < 0) {
          return;
        }
        let method: unknown;
        try {
          method = JSON.parse(buffer.slice(0, newline))?.method;
        } catch {
          method = undefined;
        }
        if (method !== "reload") {
          socket.end(`${JSON.stringify({ ok: false, reason: "unknown method" })}\n`);
          return;
        }
        const refusal = reloadRefusal();
        socket.end(`${JSON.stringify(refusal ? { ok: false, reason: refusal } : { ok: true })}\n`);
        if (!refusal) {
          // Checked and started in one go: no keystroke comes in between.
          pi.sendUserMessage("/dingger-reload", { expandPromptTemplates: true });
        }
      });
    });
    control.on("error", () => {
      controlListening = false;
    });
    try {
      fs.unlinkSync(controlPath);
    } catch {
      // None left over.
    }
    control.listen(controlPath, () => {
      controlListening = true;
      void report(undefined);
    });
    // The socket alone does not keep pi running.
    control.unref();
  }

  pi.on("session_shutdown", () => {
    // The input box as it is now: a quit right after typing comes before
    // the next check.
    if (draftTimer) {
      checkDraft();
    }
    stopWatchingInput?.();
    stopWatchingInput = undefined;
    if (draftTimer) {
      clearTimeout(draftTimer);
      draftTimer = undefined;
    }
    if (!control) {
      return;
    }
    control.close();
    control = undefined;
    controlListening = false;
    try {
      fs.unlinkSync(controlPath);
    } catch {
      // Gone already.
    }
  });

  pi.on("session_start", async (event, ctx) => {
    // TUI only: RPC/JSON/print modes are headless.
    if (ctx?.mode !== "tui") {
      return;
    }
    latestCtx = ctx;
    startControl();
    // A reload can replace this extension mid-run without emitting another agent_start.
    agentActive = ctx?.isIdle?.() === false;
    updateSessionFile(ctx);
    restoreDraft(ctx);
    // Before the first report, which carries it.
    draft = "";
    checkDraft();
    stopWatchingInput?.();
    // Every key reaches this before the input box: read the box after it.
    stopWatchingInput = ctx.ui.onTerminalInput?.(() => {
      checkDraftSoon();
      return undefined;
    });
    // Each session has its own: /new starts at normal, /resume brings its own back.
    importance = savedImportance(ctx);
    announceImportance();
    // The reports below carry them.
    checkContext(ctx, true);
    sessionName = pi.getSessionName?.() ?? "";
    publishState(true);
  });

  pi.on("agent_start", (_event, ctx) => {
    latestCtx = ctx;
    agentActive = true;
    runOutcome = undefined;
    replyError = undefined;
    updateSessionFile(ctx);
    publishState();
    // The prompt left the input box.
    checkDraftSoon();
  });

  // Each message fills the context (a prompt by pi's estimate, a reply by
  // its usage); compacting empties it; another model or branch changes it.
  for (const event of ["message_end", "session_compact", "model_select", "session_tree"]) {
    pi.on(event, (_event, ctx) => {
      latestCtx = ctx;
      checkContext(ctx);
    });
  }

  // /name, or a name given by an extension.
  pi.on("session_info_changed", (event) => {
    sessionName = event?.name ?? "";
    void report(undefined);
  });

  pi.on("agent_settled", (event, ctx) => {
    latestCtx = ctx;
    if (ctx?.isIdle?.() !== true) {
      return;
    }

    agentActive = false;
    // The last reply's usage: message_end comes before pi counts it.
    checkContext(ctx);
    // A cancelled run (Escape) is idle, not done; a failed one says why.
    const aborted = event?.aborted === true;
    const error = !aborted && runOutcome === "error" ? readableError(replyError ?? "") : undefined;
    publishState(false, { aborted, error });
    // Escape puts queued messages back into the input box.
    checkDraftSoon();
  });
}