pi-roundtable 0.51.1 → 0.51.2

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/CHANGELOG.md CHANGED
@@ -5,6 +5,15 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.51.2] - 2026-11-17
9
+
10
+ ### Fixed
11
+
12
+ - `readAttachmentText` leaves the caller's bytes as they were: reading a PDF emptied the array, so the next piece read from the same bytes failed as `unreadable` or with a raw `TypeError`. Anything that goes wrong inside now rejects with an `AttachmentTextError`.
13
+ - On a questionnaire card that more than one person may answer, a form submit writes only the fields that person changed from what they wrote before: a second owner sending only a note no longer erases the text the first wrote.
14
+ - `readAttachmentText` and `read_attachment` never end a piece between the halves of a surrogate pair, so a piece no longer carries half an emoji; `offset`, `limit` and `total` are documented as UTF-16 units.
15
+ - A PDF is parsed in a worker thread, so a large or crafted file no longer holds every channel's event loop. `readAttachmentText` refuses a PDF over 25 MiB with the new code `tooLarge`, reads at most 2,000 pages and 5,000,000 characters (leading the text with `[PDF, <n> pages; text of the first <m> only]`), and refuses a parse that takes longer than 30 seconds as `unreadable`.
16
+
8
17
  ## [0.51.1] - 2026-11-17
9
18
 
10
19
  ### Fixed
package/docs/plugins.md CHANGED
@@ -2960,7 +2960,10 @@ if (file?.id && file.messageId) {
2960
2960
  To give the model a file's text, pass the bytes to `readAttachmentText({ name, contentType?, bytes, offset?, limit? })` from the same entry; it reads as the core's `read_attachment` tool does.
2961
2961
  A text file (by its extension, a `text/*` or JSON, XML, YAML or TOML media type, or UTF-8 bytes with no NUL) is decoded; a PDF (by `.pdf`, `application/pdf` or its `%PDF-` start) has its text extracted, led by `[PDF, <n> pages]`.
2962
2962
  It resolves with `AttachmentText`: `kind` (`text` or `pdf`), `text` (at most `limit` characters from `offset`; default `ATTACHMENT_TEXT_LIMIT`, 60,000), `offset`, `nextOffset` when there is more, `total` characters and a PDF's `pages`.
2963
- It rejects with an `AttachmentTextError` whose `code` is `unsupported` (an image, audio, an archive or other binary), `unreadable` (a PDF that cannot be parsed) or `invalid` (an `offset` or `limit` that is not a whole number, or a `limit` below 1); its message names the file only.
2963
+ Characters, `offset`, `limit` and `total` count UTF-16 units, as a JavaScript string's `length` does. A piece never ends between the two halves of a surrogate pair (an emoji, for example): it stops one unit short, or with a `limit` of 1 at a pair takes both halves, and `nextOffset` follows it.
2964
+ It leaves `bytes` as it was, so the pieces of one file are read from one array.
2965
+ A PDF is parsed in a worker thread of its own, so a large or crafted file does not hold the host's event loop. It takes at most 25 MiB, reads at most 2,000 pages and 5,000,000 characters (its text is then led by `[PDF, <n> pages; text of the first <m> only]`, the same for every piece), and is refused when it takes longer than 30 seconds.
2966
+ It rejects with an `AttachmentTextError` whose `code` is `unsupported` (an image, audio, an archive or other binary), `unreadable` (a PDF that cannot be parsed or takes longer than 30 seconds, or bytes that cannot be read at all), `tooLarge` (a PDF over 25 MiB) or `invalid` (an `offset` or `limit` that is not a whole number, or a `limit` below 1); its message names the file only.
2964
2967
 
2965
2968
  ```ts
2966
2969
  import { AttachmentTextError, readAttachmentText } from "pi-roundtable/discord";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable",
3
- "version": "0.51.1",
3
+ "version": "0.51.2",
4
4
  "description": "A plugin-driven Pi agent server for one owner, reached through Discord or the web",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -168,10 +168,16 @@ export async function answerDeferred(
168
168
  const { texts, note } = formFields(form, (field) =>
169
169
  interaction.fields.getTextInputValue(field),
170
170
  );
171
+ // The form opened with what this user wrote before, not the shared draft; a field they left as
172
+ // it was is no change of theirs, so it must not overwrite what another wrote there since.
173
+ const before = form.written.get(by.user.id);
171
174
  const own: Written = { texts: [] };
172
- for (const [i, value] of texts)
173
- form.draft.texts[i] = own.texts[i] = value.trim() || undefined;
174
- form.draft.note = own.note = note.trim() || undefined;
175
+ for (const [i, value] of texts) {
176
+ own.texts[i] = value.trim() || undefined;
177
+ if (own.texts[i] !== before?.texts[i]) form.draft.texts[i] = own.texts[i];
178
+ }
179
+ own.note = note.trim() || undefined;
180
+ if (own.note !== before?.note) form.draft.note = own.note;
175
181
  form.written.set(by.user.id, own);
176
182
  }
177
183
  if (!submits) {
@@ -37,7 +37,9 @@ export interface QuestionnaireForm {
37
37
  draft: Draft;
38
38
  /**
39
39
  * The text answers and note each user last wrote and was allowed to, by user id: their form
40
- * opens with these, never with the shared draft, which may hold someone else's unsent text.
40
+ * opens with these, never with the shared draft, which may hold someone else's unsent text. A
41
+ * submit writes to the draft only the fields that differ from these, so a field a user left as
42
+ * their form showed it keeps what another wrote there.
41
43
  */
42
44
  written: Map<string, Written>;
43
45
  }
@@ -1,5 +1,5 @@
1
- import { extractText, getDocumentProxy } from "unpdf";
2
1
  import { plainText } from "../attachments/attachment-name.ts";
2
+ import { PDF_LIMITS, PdfTextError, pdfText } from "./pdf-text.ts";
3
3
 
4
4
  /** Characters one read returns by default, as the core's `read_attachment` tool reads; ask for a later `offset` for more. */
5
5
  export const ATTACHMENT_TEXT_LIMIT = 60_000;
@@ -52,6 +52,8 @@ function isPdf(name: string, type: string, head: Uint8Array): boolean {
52
52
  );
53
53
  }
54
54
 
55
+ const isHighSurrogate = (unit: number) => unit >= 0xd800 && unit <= 0xdbff;
56
+
55
57
  function looksLikeText(bytes: Uint8Array): boolean {
56
58
  const sample = bytes.subarray(0, 4096);
57
59
  if (sample.includes(0)) return false;
@@ -68,9 +70,13 @@ export interface AttachmentTextRequest {
68
70
  name: string;
69
71
  contentType?: string | null;
70
72
  bytes: Uint8Array;
71
- /** The character to start from; default 0. */
73
+ /** The character (UTF-16 unit) to start from; default 0. */
72
74
  offset?: number;
73
- /** The most characters returned; default `ATTACHMENT_TEXT_LIMIT`, 60,000. */
75
+ /**
76
+ * The most characters (UTF-16 units) returned; default `ATTACHMENT_TEXT_LIMIT`, 60,000. A piece
77
+ * never ends between the two halves of a surrogate pair, so it may hold one fewer, or, with a
78
+ * `limit` of 1 at a pair, both halves.
79
+ */
74
80
  limit?: number;
75
81
  }
76
82
 
@@ -78,13 +84,17 @@ export interface AttachmentTextRequest {
78
84
  export interface AttachmentText {
79
85
  /** `pdf` when the text was extracted from a PDF, else `text`. */
80
86
  kind: "text" | "pdf";
81
- /** The characters from `offset`, at most `limit` of them; a PDF's text starts with `[PDF, <n> pages]`. */
87
+ /**
88
+ * The characters from `offset`, at most `limit` of them; a PDF's text starts with
89
+ * `[PDF, <n> pages]`, or `[PDF, <n> pages; text of the first <m> only]` when it stopped after
90
+ * 2,000 pages or 5,000,000 characters.
91
+ */
82
92
  text: string;
83
93
  /** Where this piece starts. */
84
94
  offset: number;
85
95
  /** Where the next piece starts; absent when this piece reaches the end. */
86
96
  nextOffset?: number;
87
- /** Characters in the whole text. */
97
+ /** Characters (UTF-16 units, as `offset` and `limit` count) in the whole text. */
88
98
  total: number;
89
99
  /** A PDF's page count. */
90
100
  pages?: number;
@@ -92,10 +102,15 @@ export interface AttachmentText {
92
102
 
93
103
  /**
94
104
  * Why a file was not read as text: `unsupported` (not text or a PDF, such as an image, audio or an
95
- * archive), `unreadable` (a PDF that could not be parsed), `invalid` (an `offset` or `limit` that
96
- * is not a whole number, or a `limit` below 1).
105
+ * archive), `unreadable` (a PDF that could not be parsed or took longer than 30 seconds, or
106
+ * bytes that could not be read at all), `invalid` (an `offset` or `limit` that is not a whole
107
+ * number, or a `limit` below 1), `tooLarge` (a PDF over 25 MiB).
97
108
  */
98
- export type AttachmentTextErrorCode = "unsupported" | "unreadable" | "invalid";
109
+ export type AttachmentTextErrorCode =
110
+ | "unsupported"
111
+ | "unreadable"
112
+ | "invalid"
113
+ | "tooLarge";
99
114
 
100
115
  /** What `readAttachmentText` rejects with; `message` names the file, never its bytes. */
101
116
  export class AttachmentTextError extends Error {
@@ -116,7 +131,7 @@ export class AttachmentTextError extends Error {
116
131
  export async function readAttachmentText(
117
132
  request: AttachmentTextRequest,
118
133
  ): Promise<AttachmentText> {
119
- const { name, bytes } = request;
134
+ const { name } = request;
120
135
  const offset = request.offset ?? 0;
121
136
  const limit = request.limit ?? ATTACHMENT_TEXT_LIMIT;
122
137
  if (!Number.isInteger(offset) || offset < 0)
@@ -129,25 +144,50 @@ export async function readAttachmentText(
129
144
  "invalid",
130
145
  "limit must be a positive whole number",
131
146
  );
147
+ try {
148
+ return await read(request, offset, limit);
149
+ } catch (error) {
150
+ if (error instanceof AttachmentTextError) throw error;
151
+ throw new AttachmentTextError(
152
+ "unreadable",
153
+ `"${plainText(name)}" could not be read`,
154
+ );
155
+ }
156
+ }
157
+
158
+ async function read(
159
+ request: AttachmentTextRequest,
160
+ offset: number,
161
+ limit: number,
162
+ ): Promise<AttachmentText> {
163
+ const { name, bytes } = request;
132
164
  const type = mediaType(request.contentType);
133
165
  let kind: AttachmentText["kind"];
134
166
  let text: string;
135
167
  let pages: number | undefined;
136
168
  if (isPdf(name, type, bytes)) {
137
- let result: { totalPages: number; text: string };
169
+ if (bytes.byteLength > PDF_LIMITS.bytes)
170
+ throw new AttachmentTextError(
171
+ "tooLarge",
172
+ `"${plainText(name)}" is too large to read as a PDF (${bytes.byteLength} bytes; at most ${PDF_LIMITS.bytes})`,
173
+ );
174
+ let result: Awaited<ReturnType<typeof pdfText>>;
138
175
  try {
139
- result = await extractText(await getDocumentProxy(bytes), {
140
- mergePages: true,
141
- });
142
- } catch {
176
+ result = await pdfText(bytes);
177
+ } catch (error) {
143
178
  throw new AttachmentTextError(
144
179
  "unreadable",
145
- `"${plainText(name)}" could not be read as a PDF`,
180
+ error instanceof PdfTextError && error.reason === "slow"
181
+ ? `"${plainText(name)}" took too long to read as a PDF`
182
+ : `"${plainText(name)}" could not be read as a PDF`,
146
183
  );
147
184
  }
148
185
  kind = "pdf";
149
186
  pages = result.totalPages;
150
- text = `[PDF, ${result.totalPages} pages]\n${result.text}`;
187
+ const head = result.cut
188
+ ? `[PDF, ${result.totalPages} pages; text of the first ${result.pagesRead} only]`
189
+ : `[PDF, ${result.totalPages} pages]`;
190
+ text = `${head}\n${result.text}`;
151
191
  } else if (
152
192
  TEXT_EXTENSIONS.has(extension(name)) ||
153
193
  type.startsWith("text/") ||
@@ -162,7 +202,15 @@ export async function readAttachmentText(
162
202
  `"${plainText(name)}" is not a text or PDF file (${bytes.byteLength} bytes). Images are shown to you directly; audio or video can go to a tool that takes files.`,
163
203
  );
164
204
  }
165
- const end = Math.min(text.length, offset + limit);
205
+ let end = Math.min(text.length, offset + limit);
206
+ // A piece never ends between the halves of a surrogate pair: it stops before the pair, or, when
207
+ // that would leave it empty, takes the whole pair.
208
+ if (
209
+ end < text.length &&
210
+ end > offset &&
211
+ isHighSurrogate(text.charCodeAt(end - 1))
212
+ )
213
+ end += end - 1 > offset ? -1 : 1;
166
214
  return {
167
215
  kind,
168
216
  text: text.slice(offset, end),
@@ -0,0 +1,81 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ import { getDocumentProxy } from "unpdf";
3
+
4
+ /**
5
+ * Extracts a PDF's text off the host's thread (see `pdf-text.ts`): pdf.js parses in the thread that
6
+ * calls it, so a large or crafted file would hold every channel's event loop. It reads pages in
7
+ * order and stops after `pages` pages or once it holds `chars` characters, so the host is given a
8
+ * bounded text, the same for every read of the same bytes. Loaded outside a worker, which is what
9
+ * importing every module of the core does, it does nothing.
10
+ */
11
+ const limits = (
12
+ workerData as { pdfText?: { pages: number; chars: number } } | null
13
+ )?.pdfText;
14
+
15
+ /** What the worker answers: the text it read, or that pdf.js could not parse the file. */
16
+ export type PdfWorkerAnswer =
17
+ | {
18
+ ok: true;
19
+ totalPages: number;
20
+ pagesRead: number;
21
+ text: string;
22
+ cut: boolean;
23
+ }
24
+ | { ok: false };
25
+
26
+ const isHighSurrogate = (unit: number) => unit >= 0xd800 && unit <= 0xdbff;
27
+
28
+ async function extract(
29
+ bytes: Uint8Array,
30
+ max: { pages: number; chars: number },
31
+ ): Promise<PdfWorkerAnswer> {
32
+ const pdf = await getDocumentProxy(bytes);
33
+ try {
34
+ const texts: string[] = [];
35
+ let chars = 0;
36
+ let pagesRead = 0;
37
+ while (pagesRead < Math.min(pdf.numPages, max.pages) && chars < max.chars) {
38
+ const page = await pdf.getPage(pagesRead + 1);
39
+ const content = await page.getTextContent();
40
+ const text = content.items
41
+ .map((item) =>
42
+ "str" in item && item.str != null
43
+ ? item.str + (item.hasEOL ? "\n" : "")
44
+ : "",
45
+ )
46
+ .join("");
47
+ texts.push(text);
48
+ chars += text.length;
49
+ pagesRead += 1;
50
+ }
51
+ // As unpdf's `mergePages` joins pages: whitespace collapsed, line breaks kept, one blank line at most.
52
+ const merged = texts
53
+ .join("\n")
54
+ .replace(/[^\S\n]+/g, " ")
55
+ .replace(/ ?\n ?/g, "\n")
56
+ .replace(/\n{3,}/g, "\n\n");
57
+ let end = Math.min(merged.length, max.chars);
58
+ // A cut never ends between the halves of a surrogate pair.
59
+ if (end < merged.length && isHighSurrogate(merged.charCodeAt(end - 1)))
60
+ end -= 1;
61
+ return {
62
+ ok: true,
63
+ totalPages: pdf.numPages,
64
+ pagesRead,
65
+ text: merged.slice(0, end),
66
+ cut: pagesRead < pdf.numPages || end < merged.length,
67
+ };
68
+ } finally {
69
+ await pdf.loadingTask.destroy();
70
+ }
71
+ }
72
+
73
+ if (limits && parentPort) {
74
+ const port = parentPort;
75
+ port.on("message", (bytes: Uint8Array) => {
76
+ extract(bytes, limits).then(
77
+ (answer) => port.postMessage(answer),
78
+ () => port.postMessage({ ok: false } satisfies PdfWorkerAnswer),
79
+ );
80
+ });
81
+ }
@@ -0,0 +1,86 @@
1
+ import { Worker } from "node:worker_threads";
2
+ import { MAX_ATTACHMENT_BYTES } from "../attachments/attachment-fetcher.ts";
3
+ import type { PdfWorkerAnswer } from "./pdf-text-worker.ts";
4
+
5
+ /**
6
+ * The bounds of one PDF read. `bytes`: the largest file parsed, as large as the core reads any
7
+ * attachment. `pages` and `chars`: the text stops after this many pages, or once it holds this many
8
+ * characters (UTF-16 units), so every read of the same bytes gives the same text. `ms`: how long a
9
+ * parse may run before its worker is stopped and the read refused.
10
+ */
11
+ export const PDF_LIMITS = {
12
+ bytes: MAX_ATTACHMENT_BYTES,
13
+ pages: 2_000,
14
+ chars: 5_000_000,
15
+ ms: 30_000,
16
+ } as const;
17
+
18
+ /** A PDF's text as the worker read it; `cut` when it stopped at a limit before the end. */
19
+ export interface PdfText {
20
+ totalPages: number;
21
+ pagesRead: number;
22
+ text: string;
23
+ cut: boolean;
24
+ }
25
+
26
+ /** Why `pdfText` gave no text: pdf.js could not parse the file, or did not finish in time. */
27
+ export class PdfTextError extends Error {
28
+ readonly reason: "unreadable" | "slow";
29
+ constructor(reason: "unreadable" | "slow") {
30
+ super(
31
+ reason === "slow" ? "PDF parse timed out" : "PDF could not be parsed",
32
+ );
33
+ this.name = "PdfTextError";
34
+ this.reason = reason;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * A PDF's text, extracted in a worker of its own so the parse never holds the host's event loop,
40
+ * and stopped after `limits.ms`. The worker gets a copy of `bytes`; the caller's array is left as
41
+ * it was.
42
+ */
43
+ export function pdfText(
44
+ bytes: Uint8Array,
45
+ limits: { pages: number; chars: number; ms: number } = PDF_LIMITS,
46
+ ): Promise<PdfText> {
47
+ const copy = bytes.slice();
48
+ const worker = new Worker(new URL("./pdf-text-worker.ts", import.meta.url), {
49
+ workerData: {
50
+ pdfText: { pages: limits.pages, chars: limits.chars },
51
+ },
52
+ });
53
+ return new Promise<PdfText>((resolve, reject) => {
54
+ const timer = setTimeout(
55
+ () => settle(() => reject(new PdfTextError("slow"))),
56
+ limits.ms,
57
+ );
58
+ let done = false;
59
+ const settle = (then: () => void) => {
60
+ if (done) return;
61
+ done = true;
62
+ clearTimeout(timer);
63
+ void worker.terminate();
64
+ then();
65
+ };
66
+ worker.once("message", (answer: PdfWorkerAnswer) =>
67
+ settle(() =>
68
+ answer.ok
69
+ ? resolve({
70
+ totalPages: answer.totalPages,
71
+ pagesRead: answer.pagesRead,
72
+ text: answer.text,
73
+ cut: answer.cut,
74
+ })
75
+ : reject(new PdfTextError("unreadable")),
76
+ ),
77
+ );
78
+ worker.once("error", () =>
79
+ settle(() => reject(new PdfTextError("unreadable"))),
80
+ );
81
+ worker.once("exit", () =>
82
+ settle(() => reject(new PdfTextError("unreadable"))),
83
+ );
84
+ worker.postMessage(copy, [copy.buffer]);
85
+ });
86
+ }