pi-roundtable 0.50.2 → 0.51.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.
@@ -0,0 +1,174 @@
1
+ import { extractText, getDocumentProxy } from "unpdf";
2
+ import { plainText } from "../attachments/attachment-name.ts";
3
+
4
+ /** Characters one read returns by default, as the core's `read_attachment` tool reads; ask for a later `offset` for more. */
5
+ export const ATTACHMENT_TEXT_LIMIT = 60_000;
6
+
7
+ const TEXT_EXTENSIONS = new Set([
8
+ ".txt",
9
+ ".md",
10
+ ".markdown",
11
+ ".csv",
12
+ ".tsv",
13
+ ".json",
14
+ ".yaml",
15
+ ".yml",
16
+ ".xml",
17
+ ".html",
18
+ ".htm",
19
+ ".log",
20
+ ".ts",
21
+ ".js",
22
+ ".py",
23
+ ".sh",
24
+ ".toml",
25
+ ".ini",
26
+ ".srt",
27
+ ".vtt",
28
+ ]);
29
+
30
+ const TEXT_TYPES = new Set([
31
+ "application/json",
32
+ "application/xml",
33
+ "application/yaml",
34
+ "application/x-yaml",
35
+ "application/toml",
36
+ ]);
37
+
38
+ function extension(name: string): string {
39
+ const dot = name.lastIndexOf(".");
40
+ return dot < 0 ? "" : name.slice(dot).toLowerCase();
41
+ }
42
+
43
+ /** The media type without its parameters, lowercased; empty when none is given. */
44
+ const mediaType = (contentType: string | null | undefined) =>
45
+ (contentType ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
46
+
47
+ function isPdf(name: string, type: string, head: Uint8Array): boolean {
48
+ return (
49
+ extension(name) === ".pdf" ||
50
+ type === "application/pdf" ||
51
+ new TextDecoder().decode(head.subarray(0, 5)) === "%PDF-"
52
+ );
53
+ }
54
+
55
+ function looksLikeText(bytes: Uint8Array): boolean {
56
+ const sample = bytes.subarray(0, 4096);
57
+ if (sample.includes(0)) return false;
58
+ try {
59
+ new TextDecoder("utf-8", { fatal: true }).decode(sample);
60
+ return true;
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
66
+ /** A file to read as text: its name, its media type when known, and its bytes. */
67
+ export interface AttachmentTextRequest {
68
+ name: string;
69
+ contentType?: string | null;
70
+ bytes: Uint8Array;
71
+ /** The character to start from; default 0. */
72
+ offset?: number;
73
+ /** The most characters returned; default `ATTACHMENT_TEXT_LIMIT`, 60,000. */
74
+ limit?: number;
75
+ }
76
+
77
+ /** One piece of a file's text. */
78
+ export interface AttachmentText {
79
+ /** `pdf` when the text was extracted from a PDF, else `text`. */
80
+ kind: "text" | "pdf";
81
+ /** The characters from `offset`, at most `limit` of them; a PDF's text starts with `[PDF, <n> pages]`. */
82
+ text: string;
83
+ /** Where this piece starts. */
84
+ offset: number;
85
+ /** Where the next piece starts; absent when this piece reaches the end. */
86
+ nextOffset?: number;
87
+ /** Characters in the whole text. */
88
+ total: number;
89
+ /** A PDF's page count. */
90
+ pages?: number;
91
+ }
92
+
93
+ /**
94
+ * 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).
97
+ */
98
+ export type AttachmentTextErrorCode = "unsupported" | "unreadable" | "invalid";
99
+
100
+ /** What `readAttachmentText` rejects with; `message` names the file, never its bytes. */
101
+ export class AttachmentTextError extends Error {
102
+ readonly code: AttachmentTextErrorCode;
103
+ constructor(code: AttachmentTextErrorCode, message: string) {
104
+ super(message);
105
+ this.name = "AttachmentTextError";
106
+ this.code = code;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * A file's bytes as text, one piece at a time: a text file is decoded as UTF-8, a PDF's text is
112
+ * extracted, and anything else is refused with an `AttachmentTextError`. It is how the core's
113
+ * `read_attachment` tool reads, so a plugin that has a file's bytes (for example from
114
+ * `DISCORD.readAttachment`) reads it the same way.
115
+ */
116
+ export async function readAttachmentText(
117
+ request: AttachmentTextRequest,
118
+ ): Promise<AttachmentText> {
119
+ const { name, bytes } = request;
120
+ const offset = request.offset ?? 0;
121
+ const limit = request.limit ?? ATTACHMENT_TEXT_LIMIT;
122
+ if (!Number.isInteger(offset) || offset < 0)
123
+ throw new AttachmentTextError(
124
+ "invalid",
125
+ "offset must be a whole number from 0",
126
+ );
127
+ if (!Number.isInteger(limit) || limit < 1)
128
+ throw new AttachmentTextError(
129
+ "invalid",
130
+ "limit must be a positive whole number",
131
+ );
132
+ const type = mediaType(request.contentType);
133
+ let kind: AttachmentText["kind"];
134
+ let text: string;
135
+ let pages: number | undefined;
136
+ if (isPdf(name, type, bytes)) {
137
+ let result: { totalPages: number; text: string };
138
+ try {
139
+ result = await extractText(await getDocumentProxy(bytes), {
140
+ mergePages: true,
141
+ });
142
+ } catch {
143
+ throw new AttachmentTextError(
144
+ "unreadable",
145
+ `"${plainText(name)}" could not be read as a PDF`,
146
+ );
147
+ }
148
+ kind = "pdf";
149
+ pages = result.totalPages;
150
+ text = `[PDF, ${result.totalPages} pages]\n${result.text}`;
151
+ } else if (
152
+ TEXT_EXTENSIONS.has(extension(name)) ||
153
+ type.startsWith("text/") ||
154
+ TEXT_TYPES.has(type) ||
155
+ looksLikeText(bytes)
156
+ ) {
157
+ kind = "text";
158
+ text = new TextDecoder().decode(bytes);
159
+ } else {
160
+ throw new AttachmentTextError(
161
+ "unsupported",
162
+ `"${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
+ );
164
+ }
165
+ const end = Math.min(text.length, offset + limit);
166
+ return {
167
+ kind,
168
+ text: text.slice(offset, end),
169
+ offset,
170
+ ...(end < text.length ? { nextOffset: end } : {}),
171
+ total: text.length,
172
+ ...(pages === undefined ? {} : { pages }),
173
+ };
174
+ }
@@ -1,4 +1,9 @@
1
1
  import { DISCORD, type DiscordServices } from "../builtin/discord.ts";
2
+ import {
3
+ ATTACHMENT_READ_MAX_BYTES,
4
+ type AttachmentFacts,
5
+ readAttachment,
6
+ } from "../discord/attachment-read.ts";
2
7
  import { CommandCollection } from "../discord/command-collection.ts";
3
8
  import type { ComposedCommands } from "../discord/compose-commands.ts";
4
9
  import type {
@@ -29,14 +34,82 @@ export interface FakeDiscord {
29
34
  compose(): ComposedCommands;
30
35
  }
31
36
 
37
+ /**
38
+ * A file `fakeDiscord`'s `readAttachment` serves, as if posted with a message in a channel. Its
39
+ * `channelId`, `messageId` and `id` are Discord ids, digits only, as the real call requires.
40
+ */
41
+ export interface FakeDiscordAttachment {
42
+ channelId: string;
43
+ messageId: string;
44
+ /** The file's id, as `AttachmentRef.id` gives it. */
45
+ id: string;
46
+ name: string;
47
+ contentType?: string;
48
+ /** Its bytes; a string is UTF-8. */
49
+ bytes: Uint8Array | string;
50
+ title?: string;
51
+ description?: string;
52
+ /** Discord's CDN no longer serves it: a read rejects as `gone`. */
53
+ gone?: boolean;
54
+ }
55
+
56
+ /**
57
+ * `DISCORD.readAttachment` over `files`, with the real one's checks and errors (an id that is no
58
+ * Discord id, a file not on its message, a message of another channel, over `maxBytes`, gone),
59
+ * downloading from a stand-in CDN.
60
+ */
61
+ function fakeAttachmentReader(
62
+ files: readonly FakeDiscordAttachment[],
63
+ maxBytes: number,
64
+ ): DiscordServices["readAttachment"] {
65
+ const bytesOf = (file: FakeDiscordAttachment) =>
66
+ typeof file.bytes === "string"
67
+ ? new TextEncoder().encode(file.bytes)
68
+ : file.bytes;
69
+ const url = (file: FakeDiscordAttachment) =>
70
+ `https://cdn.discordapp.com/attachments/${file.channelId}/${file.id}/${encodeURIComponent(file.name)}`;
71
+ const fetchImpl = (async (address: string) => {
72
+ const file = files.find((f) => url(f) === address);
73
+ return file && !file.gone
74
+ ? new Response(bytesOf(file).slice())
75
+ : new Response(null, { status: 404 });
76
+ }) as unknown as typeof fetch;
77
+ return (request) =>
78
+ readAttachment(
79
+ {
80
+ files: async (channelId, messageId) => {
81
+ const on = files.filter(
82
+ (f) => f.channelId === channelId && f.messageId === messageId,
83
+ );
84
+ if (on.length === 0) return undefined;
85
+ return on.map(
86
+ (f): AttachmentFacts => ({
87
+ id: f.id,
88
+ name: f.name,
89
+ contentType: f.contentType ?? null,
90
+ size: bytesOf(f).byteLength,
91
+ url: url(f),
92
+ title: f.title ?? null,
93
+ description: f.description ?? null,
94
+ }),
95
+ );
96
+ },
97
+ },
98
+ request,
99
+ { maxBytes, fetchImpl },
100
+ );
101
+ }
102
+
32
103
  /**
33
104
  * A `DISCORD` service for a plugin that adds slash commands, without a Discord connection: the
34
105
  * plugin's `commands.add` calls are recorded, and `compose()` shows the tree Discord would get.
35
106
  * `rootCommand` is the root command's name, `roundtable` by default. `channelContext` is what
36
107
  * `DISCORD.channelContext` answers, by default no context, as on a host with it off. `voice` is
37
108
  * what `DISCORD.voice` is, such as a `fakeDiscordVoice()`; without it the plugin reads none, as on
38
- * a host with `discord.voice` off. Only `commands`, `guard`, `poster`, `channelContext`, and
39
- * `voice` are given; reading another member throws.
109
+ * a host with `discord.voice` off. `attachments` are the files `DISCORD.readAttachment` serves,
110
+ * none by default, read at most `attachmentMaxBytes` (default 10 MiB) as the host's
111
+ * `discord.attachmentRead.maxBytes` caps them. Only `commands`, `guard`, `poster`,
112
+ * `channelContext`, `readAttachment` and `voice` are given; reading another member throws.
40
113
  */
41
114
  export function fakeDiscord(
42
115
  options: {
@@ -45,6 +118,8 @@ export function fakeDiscord(
45
118
  channelContext?: DiscordServices["channelContext"];
46
119
  poster?: DiscordPoster;
47
120
  voice?: DiscordVoice;
121
+ attachments?: readonly FakeDiscordAttachment[];
122
+ attachmentMaxBytes?: number;
48
123
  } = {},
49
124
  ): FakeDiscord {
50
125
  const collection = new CommandCollection();
@@ -61,6 +136,10 @@ export function fakeDiscord(
61
136
  guard,
62
137
  poster,
63
138
  channelContext: options.channelContext ?? (async () => undefined),
139
+ readAttachment: fakeAttachmentReader(
140
+ options.attachments ?? [],
141
+ options.attachmentMaxBytes ?? ATTACHMENT_READ_MAX_BYTES,
142
+ ),
64
143
  voice: options.voice,
65
144
  }),
66
145
  poster,
@@ -12,6 +12,7 @@ export type {
12
12
  ChannelContextOptions,
13
13
  } from "../core/contract/channel-context.ts";
14
14
  export {
15
+ CONTEXT_ATTACHMENT_LINES,
15
16
  withChannelContext,
16
17
  withChannelContextImages,
17
18
  } from "../core/contract/channel-context.ts";
@@ -28,6 +29,15 @@ export type {
28
29
  export { agentPanel } from "../core/discord/agent-panel.ts";
29
30
  export type { DiscordPlaceProviderOptions } from "../core/discord/agent-places.ts";
30
31
  export { discordPlaceProvider } from "../core/discord/agent-places.ts";
32
+ export type {
33
+ AttachmentBytes,
34
+ AttachmentReadErrorCode,
35
+ AttachmentReadRequest,
36
+ } from "../core/discord/attachment-read.ts";
37
+ export {
38
+ ATTACHMENT_READ_MAX_BYTES,
39
+ AttachmentReadError,
40
+ } from "../core/discord/attachment-read.ts";
31
41
  export {
32
42
  CHANNEL_CONTEXT_DEFAULTS,
33
43
  formatChannelContext,
@@ -74,6 +84,7 @@ export {
74
84
  commandGuard,
75
85
  groupOption,
76
86
  ownerCommandModule,
87
+ ownerRefusal,
77
88
  ownerRootCommand,
78
89
  } from "../core/discord/owner-command.ts";
79
90
  export type { PanelContent } from "../core/discord/owner-panel.ts";
@@ -134,3 +145,13 @@ export type {
134
145
  export { VOICE_PCM } from "../core/discord/voice/voice.ts";
135
146
  export type { OwnerOperations } from "../core/modules/discord-admin/discord-admin.ts";
136
147
  export { DISCORD_ADMIN_TOOLS } from "../core/modules/discord-admin/discord-admin.ts";
148
+ export type {
149
+ AttachmentText,
150
+ AttachmentTextErrorCode,
151
+ AttachmentTextRequest,
152
+ } from "../core/shared/attachment-text.ts";
153
+ export {
154
+ ATTACHMENT_TEXT_LIMIT,
155
+ AttachmentTextError,
156
+ readAttachmentText,
157
+ } from "../core/shared/attachment-text.ts";
package/src/testing.ts CHANGED
@@ -85,7 +85,10 @@ export {
85
85
  testDatabaseUrl,
86
86
  } from "./core/testing/database.ts";
87
87
  export { eagerText, useEagerCatalog } from "./core/testing/eager-catalog.ts";
88
- export type { FakeDiscord } from "./core/testing/fake-discord.ts";
88
+ export type {
89
+ FakeDiscord,
90
+ FakeDiscordAttachment,
91
+ } from "./core/testing/fake-discord.ts";
89
92
  export { fakeDiscord } from "./core/testing/fake-discord.ts";
90
93
  export type {
91
94
  FakeDiscordPoster,