@andares/pi-toolkits 1.1.0 → 1.2.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 (39) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +31 -5
  3. package/README.zh-CN.md +31 -5
  4. package/package.json +5 -3
  5. package/src/features/review-page/assets/index-DPWL_ipb.css +1 -0
  6. package/src/features/review-page/assets/index-XxrDCe96.js +1 -0
  7. package/src/features/{spec → review-page}/assets/index.html +2 -2
  8. package/src/features/{spec → review-page}/blocks.test.ts +17 -0
  9. package/src/features/{spec → review-page}/blocks.ts +9 -0
  10. package/src/features/review-page/headings.test.ts +44 -0
  11. package/src/features/review-page/headings.ts +67 -0
  12. package/src/features/spec/assets.test.ts +18 -3
  13. package/src/features/spec/diff.test.ts +1 -1
  14. package/src/features/spec/diff.ts +1 -1
  15. package/src/features/spec/feedback.test.ts +1 -1
  16. package/src/features/spec/feedback.ts +1 -1
  17. package/src/features/spec/index.test.ts +42 -1
  18. package/src/features/spec/index.ts +2 -2
  19. package/src/features/spec/server.test.ts +64 -6
  20. package/src/features/spec/server.ts +21 -3
  21. package/src/features/spec/store.ts +1 -1
  22. package/src/features/talk/index.test.ts +286 -0
  23. package/src/features/talk/index.ts +301 -0
  24. package/src/features/talk/message.test.ts +212 -0
  25. package/src/features/talk/message.ts +152 -0
  26. package/src/features/talk/reply.test.ts +116 -0
  27. package/src/features/talk/reply.ts +92 -0
  28. package/src/features/talk/sections.test.ts +39 -0
  29. package/src/features/talk/sections.ts +44 -0
  30. package/src/features/talk/server.test.ts +284 -0
  31. package/src/features/talk/server.ts +232 -0
  32. package/src/features/uat/index.test.ts +19 -1
  33. package/src/index.ts +4 -0
  34. package/src/lib/web-review.test.ts +80 -0
  35. package/src/lib/web-review.ts +27 -5
  36. package/src/features/spec/assets/index-CdTerMvN.css +0 -1
  37. package/src/features/spec/assets/index-Dv52AIjX.js +0 -1
  38. /package/src/features/{spec → review-page}/render.test.ts +0 -0
  39. /package/src/features/{spec → review-page}/render.ts +0 -0
@@ -0,0 +1,301 @@
1
+ /**
2
+ * `/ask-talk` — annotate the agent's last reply in the browser.
3
+ *
4
+ * Deliberately NOT a phase: it registers no tool, changes no tool set, touches no
5
+ * permission mode and adds nothing to the system prompt, so it costs nothing
6
+ * until the operator types it, and it works inside `/ask`, `/ask-spec` and
7
+ * `/ask-uat` alike.
8
+ *
9
+ * The page is a snapshot. Running the command again refreshes it: same reply ⇒
10
+ * notes and draft survive, different reply ⇒ they are cleared (the block ids are
11
+ * content hashes, so a new reply means new ids and every note would be orphaned).
12
+ */
13
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
14
+ import { openInBrowser } from "../../lib/opener.js";
15
+ import { parseBlocks } from "../review-page/blocks.js";
16
+ import { extractHeadings } from "../review-page/headings.js";
17
+ import { buildReplyMessage, type TalkNote } from "./message.js";
18
+ import { extractLastReply } from "./reply.js";
19
+ import { startTalkServer, type TalkServerHandle, type TalkSession } from "./server.js";
20
+
21
+ export const TALK_COMMAND = "ask-talk";
22
+ /**
23
+ * 7600 — the same pool `/ask-spec` and `/ask-uat` walk.
24
+ *
25
+ * Pages are told apart by their title, not by a port block: sharing the pool
26
+ * means several review pages can be open at once without a second range that
27
+ * only exists to be remembered. The block sits high because 34xx is routinely
28
+ * claimed by WSL / Windows port forwarders.
29
+ */
30
+ const PORT_START = 7600;
31
+
32
+ export interface TalkOptions {
33
+ openBrowser?: (url: string) => unknown;
34
+ portStart?: number;
35
+ portAttempts?: number;
36
+ closeDelayMs?: number;
37
+ }
38
+
39
+ function sessionIdOf(ctx: ExtensionContext): string {
40
+ try {
41
+ return ctx.sessionManager.getSessionId();
42
+ } catch {
43
+ return `pid-${process.pid}`;
44
+ }
45
+ }
46
+
47
+ /** Notes as an ordered list, for the message builder. */
48
+ function noteList(notes: Record<string, string>): TalkNote[] {
49
+ return Object.entries(notes).map(([blockId, text]) => ({ blockId, text }));
50
+ }
51
+
52
+ /** Plain text of a message content field (string or text blocks). */
53
+ function contentText(content: unknown): string {
54
+ if (typeof content === "string") return content;
55
+ if (!Array.isArray(content)) return "";
56
+ const parts: string[] = [];
57
+ for (const part of content) {
58
+ if (!part || typeof part !== "object") continue;
59
+ const block = part as { type?: unknown; text?: unknown };
60
+ if (block.type === "text" && typeof block.text === "string") parts.push(block.text);
61
+ }
62
+ return parts.join(" ");
63
+ }
64
+
65
+ /**
66
+ * The title of the session this page belongs to.
67
+ *
68
+ * The operator runs several sessions in parallel; "the last reply" is the same
69
+ * phrase in every window, so the page has to say WHICH session it is annotating.
70
+ * The session name is the host's own answer; before auto-naming has produced
71
+ * one, the first user message is what the operator recognizes.
72
+ */
73
+ function sessionTitle(ctx: ExtensionContext): string | undefined {
74
+ try {
75
+ const named = ctx.sessionManager.getSessionName?.();
76
+ const name = typeof named === "string" ? named.trim() : "";
77
+ if (name !== "") return name;
78
+ } catch {
79
+ // Older host without session names: fall through to the first prompt.
80
+ }
81
+ try {
82
+ for (const entry of ctx.sessionManager.getBranch() as Array<{
83
+ type?: unknown;
84
+ message?: { role?: unknown; content?: unknown };
85
+ }>) {
86
+ if (entry?.type !== "message" || entry.message?.role !== "user") continue;
87
+ const text = contentText(entry.message.content).replace(/\s+/g, " ").trim();
88
+ if (text !== "") return text.length > 80 ? `${text.slice(0, 79)}…` : text;
89
+ }
90
+ } catch {
91
+ // A branch that cannot be read is not worth failing the command over.
92
+ }
93
+ return undefined;
94
+ }
95
+
96
+ export function registerTalk(pi: ExtensionAPI, options: TalkOptions = {}): void {
97
+ const open = options.openBrowser ?? openInBrowser;
98
+
99
+ let session: TalkSession | undefined;
100
+ let server: TalkServerHandle | undefined;
101
+ let talkSessionId: string | undefined;
102
+ let ctxRef: ExtensionContext | undefined;
103
+
104
+ function closeServer(): void {
105
+ if (!server) return;
106
+ const closing = server;
107
+ server = undefined;
108
+ void closing.close();
109
+ }
110
+
111
+ /** Start (or restart) a server for this snapshot, with one consistent error path. */
112
+ async function openFresh(current: TalkSession, ctx: ExtensionContext): Promise<void> {
113
+ closeServer();
114
+ try {
115
+ const handle = await startServer(current);
116
+ server = handle;
117
+ open(handle.url);
118
+ ctx.ui.notify(`ask-talk: review open at ${handle.url}`, "info");
119
+ } catch (error) {
120
+ ctx.ui.notify(
121
+ `ask-talk: cannot start the review server — ${error instanceof Error ? error.message : String(error)}`,
122
+ "warning",
123
+ );
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Whether the annotated reply is still in the model's active context.
129
+ *
130
+ * A compaction can summarize away the very message being annotated; the
131
+ * message builder then repeats the reply once, because the quotes would
132
+ * otherwise point at text the model cannot see.
133
+ */
134
+ function replyInContext(ctx: ExtensionContext, entryId: string): boolean {
135
+ if (entryId === "") return true;
136
+ try {
137
+ const entries = ctx.sessionManager.buildContextEntries() as Array<{ id?: unknown }>;
138
+ return entries.some((entry) => entry.id === entryId);
139
+ } catch {
140
+ // Unknown shape on an older host: assume context is intact rather than
141
+ // paying for a full re-send of the reply on every Continue.
142
+ return true;
143
+ }
144
+ }
145
+
146
+ function startServer(current: TalkSession): Promise<TalkServerHandle> {
147
+ return startTalkServer({
148
+ session: current,
149
+ portStart: options.portStart ?? PORT_START,
150
+ portAttempts: options.portAttempts,
151
+ closeDelayMs: options.closeDelayMs,
152
+ onContinue: ({ notes, message }) => {
153
+ // off / shutdown / a session switch invalidates the snapshot at once;
154
+ // an already in-flight HTTP request must not leak into the next session.
155
+ if (session !== current) return;
156
+ // The operator may have started another run (and a compaction) while the
157
+ // page was open. Context survival is a property of Continue time, not of
158
+ // the moment the page was opened.
159
+ current.inContext = ctxRef ? replyInContext(ctxRef, current.entryId) : current.inContext;
160
+ const text = buildReplyMessage({
161
+ blocks: current.blocks,
162
+ notes: noteList(notes),
163
+ message,
164
+ inContext: current.inContext,
165
+ replyText: current.text,
166
+ });
167
+ if (text.trim() === "") return;
168
+ pi.sendUserMessage(text);
169
+ },
170
+ });
171
+ }
172
+
173
+ const command = {
174
+ description:
175
+ "Annotate the agent's last reply in the browser: block notes plus a message, sent back as one short message. `off` closes the page.",
176
+ handler: async (args: string, ctx: ExtensionContext) => {
177
+ const arg = args.trim();
178
+ ctxRef = ctx;
179
+
180
+ if (arg === "off") {
181
+ if (!session && !server) {
182
+ ctx.ui.notify("ask-talk: nothing open.", "info");
183
+ return;
184
+ }
185
+ closeServer();
186
+ session = undefined;
187
+ ctx.ui.notify("ask-talk: closed.", "info");
188
+ return;
189
+ }
190
+
191
+ if (arg !== "") {
192
+ ctx.ui.notify("ask-talk: takes no arguments (use `off` to close the page).", "warning");
193
+ return;
194
+ }
195
+
196
+ // The host persists an assistant message on `message_end`, so while a run
197
+ // is in flight the branch still ends with the PREVIOUS reply. Showing it
198
+ // would be silently wrong; say so instead.
199
+ if (!ctx.isIdle()) {
200
+ ctx.ui.notify(
201
+ "ask-talk: the agent is still running — finish or abort first, then run /ask-talk.",
202
+ "warning",
203
+ );
204
+ return;
205
+ }
206
+
207
+ let entries: unknown[] = [];
208
+ try {
209
+ entries = ctx.sessionManager.getBranch() as unknown[];
210
+ } catch {
211
+ entries = [];
212
+ }
213
+ const reply = extractLastReply(entries);
214
+ if (!reply) {
215
+ ctx.ui.notify(
216
+ "ask-talk: no reply to annotate yet — send a prompt and wait for the answer.",
217
+ "warning",
218
+ );
219
+ return;
220
+ }
221
+
222
+ const inContext = replyInContext(ctx, reply.entryId);
223
+ const sameReply =
224
+ session !== undefined && !session.sent && session.fingerprint === reply.fingerprint;
225
+
226
+ if (sameReply && session) {
227
+ session.inContext = inContext;
228
+ session.title = sessionTitle(ctx) ?? session.title;
229
+ if (server?.active() !== true) {
230
+ await openFresh(session, ctx);
231
+ return;
232
+ }
233
+ // Nothing about the snapshot changed, but the command is an explicit
234
+ // "show me": re-open the window instead of printing a URL the operator
235
+ // has to find. Re-fetching here would overwrite keystrokes still inside
236
+ // the page's save debounce window, so only the tab is new.
237
+ open(server.url);
238
+ ctx.ui.notify(`ask-talk: already showing this reply — ${server.url}`, "info");
239
+ return;
240
+ }
241
+
242
+ const blocks = parseBlocks(reply.text);
243
+ const next: TalkSession = {
244
+ text: reply.text,
245
+ blocks,
246
+ headings: extractHeadings(blocks),
247
+ title: sessionTitle(ctx),
248
+ entryId: reply.entryId,
249
+ model: reply.model,
250
+ at: reply.at,
251
+ fingerprint: reply.fingerprint,
252
+ notes: {},
253
+ draft: "",
254
+ sent: false,
255
+ inContext,
256
+ };
257
+
258
+ const previous = session;
259
+ const replaced = previous !== undefined && previous.fingerprint !== reply.fingerprint;
260
+ talkSessionId = sessionIdOf(ctx);
261
+
262
+ if (previous && server?.active()) {
263
+ // The routes and the Continue callback both close over the object passed
264
+ // to startTalkServer. Replace its CONTENTS, not just the `session`
265
+ // variable, or a refresh would serve and submit the previous reply.
266
+ Object.assign(previous, next);
267
+ session = previous;
268
+ server.broadcast("refresh", {});
269
+ // A refresh is also an explicit "show me": the old tab may have been
270
+ // closed, and a broadcast reaches no window. /ask-spec opens on every
271
+ // submit for the same reason.
272
+ open(server.url);
273
+ ctx.ui.notify(
274
+ `ask-talk: review refreshed${replaced ? " (notes cleared — this is a new reply)" : ""} — ${server.url}`,
275
+ "info",
276
+ );
277
+ return;
278
+ }
279
+
280
+ session = next;
281
+ await openFresh(next, ctx);
282
+ },
283
+ };
284
+
285
+ pi.registerCommand(TALK_COMMAND, command);
286
+
287
+ pi.on("session_shutdown", () => {
288
+ closeServer();
289
+ session = undefined;
290
+ });
291
+
292
+ pi.on("session_start", (_event, ctx) => {
293
+ const nextSessionId = sessionIdOf(ctx);
294
+ ctxRef = ctx;
295
+ if (nextSessionId === talkSessionId) return;
296
+ // A different session must not keep a page bound to the old reply.
297
+ talkSessionId = undefined;
298
+ session = undefined;
299
+ closeServer();
300
+ });
301
+ }
@@ -0,0 +1,212 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { parseBlocks } from "../review-page/blocks.js";
3
+ import { buildReplyMessage, clipForQuote, hasUnknownNote, QUOTE_LIMIT } from "./message.js";
4
+
5
+ const REPLY = [
6
+ "## Approach",
7
+ "",
8
+ "The page reads the blocks the server ships, never the rendered HTML.",
9
+ "",
10
+ "## Milestones",
11
+ "",
12
+ "M1 captures the reply, M2 renders the page.",
13
+ ].join("\n");
14
+
15
+ function build(notes: Array<{ blockId: string; text: string }>, message: string) {
16
+ const blocks = parseBlocks(REPLY);
17
+ const resolved = notes.map((note) => ({
18
+ blockId: note.blockId === "approach" ? blocks[1].id : note.blockId,
19
+ text: note.text,
20
+ }));
21
+ return {
22
+ text: buildReplyMessage({
23
+ blocks,
24
+ notes: resolved,
25
+ message,
26
+ inContext: true,
27
+ replyText: REPLY,
28
+ }),
29
+ blocks,
30
+ };
31
+ }
32
+
33
+ describe("buildReplyMessage", () => {
34
+ it("writes the two parts in a fixed shape", () => {
35
+ const { text } = build(
36
+ [
37
+ {
38
+ blockId: "approach",
39
+ text: "this reverses the order: ship the headings first",
40
+ },
41
+ ],
42
+ "also keep it short",
43
+ );
44
+ expect(text).toBe(
45
+ [
46
+ "## Notes on your last reply",
47
+ "",
48
+ "Address every note below; each one is attached to the part of your reply it quotes.",
49
+ "",
50
+ "### Approach",
51
+ "> The page reads the blocks the server ships, never the rendered HTML.",
52
+ "",
53
+ "- this reverses the order: ship the headings first",
54
+ "",
55
+ "## Operator's message",
56
+ "",
57
+ "also keep it short",
58
+ ].join("\n"),
59
+ );
60
+ });
61
+
62
+ it("sends bare composer text when there are no notes", () => {
63
+ const { text } = build([], "just this sentence");
64
+ expect(text).toBe("just this sentence");
65
+ });
66
+
67
+ it("sends only the notes when the composer is empty", () => {
68
+ const { text } = build([{ blockId: "approach", text: "wrong" }], "");
69
+ expect(text.startsWith("## Notes on your last reply")).toBe(true);
70
+ expect(text).not.toContain("## Operator's message");
71
+ expect(text.endsWith("- wrong")).toBe(true);
72
+ });
73
+
74
+ it("quotes a heading without its markers", () => {
75
+ const blocks = parseBlocks(REPLY);
76
+ const text = buildReplyMessage({
77
+ blocks,
78
+ notes: [{ blockId: blocks[0].id, text: "rename" }],
79
+ message: "",
80
+ inContext: true,
81
+ replyText: REPLY,
82
+ });
83
+ expect(text).toContain("### Approach");
84
+ expect(text).toContain("> Approach\n");
85
+ expect(text).not.toContain("> ## Approach");
86
+ });
87
+
88
+ it("uses the section path as the note heading", () => {
89
+ const blocks = parseBlocks(REPLY);
90
+ const { text } = build([{ blockId: blocks[3].id, text: "order is wrong" }], "");
91
+ expect(text).toContain("### Milestones");
92
+ });
93
+
94
+ it("labels notes above the first heading with the block label", () => {
95
+ const blocks = parseBlocks("preamble paragraph\n\n## Section\n\nbody");
96
+ const text = buildReplyMessage({
97
+ blocks,
98
+ notes: [{ blockId: blocks[0].id, text: "reword" }],
99
+ message: "",
100
+ inContext: true,
101
+ replyText: "",
102
+ });
103
+ expect(text).toContain("### preamble paragraph");
104
+ });
105
+
106
+ it("keeps document order, not the order the notes were written", () => {
107
+ const blocks = parseBlocks(REPLY);
108
+ const text = buildReplyMessage({
109
+ blocks,
110
+ notes: [
111
+ { blockId: blocks[3].id, text: "second note" },
112
+ { blockId: blocks[1].id, text: "first note" },
113
+ ],
114
+ message: "",
115
+ inContext: true,
116
+ replyText: REPLY,
117
+ });
118
+ expect(text.indexOf("first note")).toBeLessThan(text.indexOf("second note"));
119
+ });
120
+
121
+ it("keeps multi-line notes inside one bullet", () => {
122
+ const blocks = parseBlocks(REPLY);
123
+ const text = buildReplyMessage({
124
+ blocks,
125
+ notes: [{ blockId: blocks[1].id, text: "1. no\n2. yes" }],
126
+ message: "",
127
+ inContext: true,
128
+ replyText: REPLY,
129
+ });
130
+ expect(text).toContain("- 1. no\n 2. yes");
131
+ });
132
+
133
+ it("repeats the reply only when compaction pushed it out of context", () => {
134
+ const blocks = parseBlocks(REPLY);
135
+ const text = buildReplyMessage({
136
+ blocks,
137
+ notes: [{ blockId: blocks[1].id, text: "fix it" }],
138
+ message: "",
139
+ inContext: false,
140
+ replyText: REPLY,
141
+ });
142
+ expect(text).toContain("## Your last reply (full text)");
143
+ expect(text).toContain("M1 captures the reply");
144
+ });
145
+
146
+ it("drops blank notes instead of emitting an empty bullet", () => {
147
+ const blocks = parseBlocks(REPLY);
148
+ const text = buildReplyMessage({
149
+ blocks,
150
+ notes: [{ blockId: blocks[1].id, text: " " }],
151
+ message: "hello",
152
+ inContext: true,
153
+ replyText: REPLY,
154
+ });
155
+ expect(text).toBe("hello");
156
+ });
157
+ });
158
+
159
+ describe("clipForQuote", () => {
160
+ it("keeps short blocks intact", () => {
161
+ expect(clipForQuote("short block")).toBe("short block");
162
+ });
163
+
164
+ it("clips at a line boundary and marks the cut", () => {
165
+ const long = Array.from({ length: 40 }, (_, i) => `line ${i} of a long block`).join("\n");
166
+ const clipped = clipForQuote(long, 120);
167
+ expect(clipped.length).toBeLessThanOrEqual(140);
168
+ expect(clipped.endsWith("…")).toBe(true);
169
+ expect(clipped.split("\n").slice(0, -2).every((line) => /^line \d+ of a long block$/.test(line))).toBe(
170
+ true,
171
+ );
172
+ });
173
+
174
+ it("closes a fence it cut through", () => {
175
+ const long = ["```ts", ...Array.from({ length: 60 }, (_, i) => `const x${i} = ${i};`), "```"].join(
176
+ "\n",
177
+ );
178
+ const clipped = clipForQuote(long, 120);
179
+ expect(clipped.split("```").length % 2).toBe(1);
180
+ expect(clipped.trimEnd().endsWith("```")).toBe(true);
181
+ });
182
+
183
+ it("falls back to a hard slice when the first line alone exceeds the limit", () => {
184
+ const clipped = clipForQuote("x".repeat(QUOTE_LIMIT * 2), 50);
185
+ expect(clipped.length).toBe(50);
186
+ expect(clipped.endsWith("…")).toBe(true);
187
+ });
188
+ });
189
+
190
+ describe("hasUnknownNote", () => {
191
+ it("flags notes for blocks the reply does not contain", () => {
192
+ const blocks = parseBlocks(REPLY);
193
+ expect(
194
+ hasUnknownNote({
195
+ blocks,
196
+ notes: [{ blockId: "gone#0", text: "stale" }],
197
+ message: "",
198
+ inContext: true,
199
+ replyText: "",
200
+ }),
201
+ ).toBe(true);
202
+ expect(
203
+ hasUnknownNote({
204
+ blocks,
205
+ notes: [{ blockId: blocks[0].id, text: "fine" }],
206
+ message: "",
207
+ inContext: true,
208
+ replyText: "",
209
+ }),
210
+ ).toBe(false);
211
+ });
212
+ });
@@ -0,0 +1,152 @@
1
+ /**
2
+ * talk message — what `Continue` sends back.
3
+ *
4
+ * Two parts, and nothing else:
5
+ * 1. every note, each with the reply text it is attached to quoted above it;
6
+ * 2. the operator's overall message from the composer.
7
+ *
8
+ * The full reply is deliberately NOT echoed: it is already in the model's
9
+ * context, so quoting it again buys nothing and costs the whole answer. The
10
+ * quote exists to locate a block, which is why it is clipped.
11
+ *
12
+ * The one exception is a reply that compaction pushed out of the context — then
13
+ * the quotes point at text the model can no longer see, so the reply is sent
14
+ * once, in full. That is a rare, explicitly expensive path.
15
+ */
16
+ import type { Block } from "../review-page/blocks.js";
17
+ import { blockLabel } from "../review-page/blocks.js";
18
+ import { sectionPaths } from "./sections.js";
19
+
20
+ /** Longest quote — enough to find the block, not a second copy of the reply. */
21
+ export const QUOTE_LIMIT = 600;
22
+
23
+ export interface TalkNote {
24
+ blockId: string;
25
+ text: string;
26
+ }
27
+
28
+ export interface ReplyMessageInput {
29
+ blocks: readonly Block[];
30
+ /** Notes in any order; they are emitted in document order. */
31
+ notes: readonly TalkNote[];
32
+ /** Composer text. */
33
+ message: string;
34
+ /** Whether the whole reply is still in the model's active context. */
35
+ inContext: boolean;
36
+ replyText: string;
37
+ }
38
+
39
+ const FENCE_RE = /^ {0,3}(`{3,}|~{3,})/;
40
+
41
+ /**
42
+ * Clip a block for quoting, at a line boundary, closing an open fence.
43
+ *
44
+ * Line boundaries matter: half a code line reads as corruption, and a quote
45
+ * that leaves a fence open would swallow the rest of the message into a code
46
+ * block when the model's markdown renderer sees it.
47
+ */
48
+ export function clipForQuote(text: string, limit = QUOTE_LIMIT): string {
49
+ const trimmed = text.trim();
50
+ if (trimmed.length <= limit) return trimmed;
51
+
52
+ const lines = trimmed.split("\n");
53
+ const kept: string[] = [];
54
+ let size = 0;
55
+ for (const line of lines) {
56
+ // +2: the newline plus the ellipsis we may have to append.
57
+ if (size + line.length + 2 > limit) break;
58
+ kept.push(line);
59
+ size += line.length + 1;
60
+ }
61
+ if (kept.length === 0) return `${trimmed.slice(0, limit - 1)}…`;
62
+
63
+ let fence: { char: string; length: number } | undefined;
64
+ for (const line of kept) {
65
+ const match = FENCE_RE.exec(line);
66
+ if (!match) continue;
67
+ if (!fence) fence = { char: match[1][0], length: match[1].length };
68
+ else if (match[1][0] === fence.char && match[1].length >= fence.length) fence = undefined;
69
+ }
70
+ // The ellipsis goes INSIDE the fence: a marker after the closing run would read
71
+ // as prose continuing after the code block, which is not what was cut.
72
+ kept.push("…");
73
+ if (fence) kept.push(fence.char.repeat(fence.length));
74
+
75
+ return kept.join("\n");
76
+ }
77
+
78
+ /**
79
+ * Quote a block for the message body.
80
+ *
81
+ * A heading is quoted without its `#` markers: `> ## Alpha` right under the
82
+ * `### Alpha` label reads as a nested heading inside a blockquote, which is noise
83
+ * the model has to strip mentally. The text is what locates the block.
84
+ */
85
+ function quote(block: Block, limit = QUOTE_LIMIT): string {
86
+ const clipped = clipForQuote(block.text, limit);
87
+ const body =
88
+ block.kind === "heading"
89
+ ? clipped
90
+ .split("\n")
91
+ .map((line) => line.replace(/^ {0,3}#{1,6}\s+/, ""))
92
+ .join("\n")
93
+ : clipped;
94
+ return body
95
+ .split("\n")
96
+ .map((line) => (line === "" ? ">" : `> ${line}`))
97
+ .join("\n");
98
+ }
99
+
100
+ const HEADER = "## Notes on your last reply";
101
+ const INTRO =
102
+ "Address every note below; each one is attached to the part of your reply it quotes.";
103
+ const MESSAGE_HEADER = "## Operator's message";
104
+
105
+ /** Block label used when a section path cannot be resolved (defensive only). */
106
+ function fallbackLabel(block: Block): string {
107
+ return blockLabel(block, 60) || "reply";
108
+ }
109
+
110
+ export function buildReplyMessage(input: ReplyMessageInput): string {
111
+ const message = input.message.trim();
112
+ const paths = sectionPaths(input.blocks);
113
+
114
+ // Document order, not the order the notes were written in: the model reads
115
+ // them while scrolling the reply it is being asked to fix.
116
+ const ordered = input.blocks
117
+ .filter((block) => input.notes.some((note) => note.blockId === block.id))
118
+ .map((block) => ({ block, note: input.notes.find((note) => note.blockId === block.id)! }))
119
+ .filter(({ note }) => note.text.trim() !== "");
120
+
121
+ if (ordered.length === 0) {
122
+ // No notes: the composer text IS the message. No wrapper, nothing to parse.
123
+ return message;
124
+ }
125
+
126
+ const sections = ordered.map(({ block, note }) => {
127
+ const locus = paths.get(block.id) || fallbackLabel(block);
128
+ return [`### ${locus}`, quote(block), "", `- ${note.text.trim().replace(/\n+/g, "\n ")}`].join(
129
+ "\n",
130
+ );
131
+ });
132
+
133
+ const parts = [HEADER, "", INTRO, "", sections.join("\n\n")];
134
+ if (!input.inContext) {
135
+ parts.push(
136
+ "",
137
+ "## Your last reply (full text)",
138
+ "",
139
+ "The reply quoted above is no longer in your active context, so it is repeated here in full.",
140
+ "",
141
+ input.replyText.trim(),
142
+ );
143
+ }
144
+ if (message !== "") parts.push("", MESSAGE_HEADER, "", message);
145
+ return parts.join("\n");
146
+ }
147
+
148
+ /** True when a note points at a block that is not in the reply (stale page). */
149
+ export function hasUnknownNote(input: ReplyMessageInput): boolean {
150
+ const ids = new Set(input.blocks.map((block) => block.id));
151
+ return input.notes.some((note) => !ids.has(note.blockId) && note.text.trim() !== "");
152
+ }