@abyss-project/runtime 3.7.0 → 3.9.0

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.
@@ -64,7 +64,22 @@ export enum DiscordCapability {
64
64
  CREATE_THREAD = 'discord.createThread',
65
65
  /** Ends a poll of the bot before its time. Arguments: `DiscordEndPollArgs`. */
66
66
  END_POLL = 'discord.endPoll',
67
- }
67
+ /** Answers an autocomplete interaction with choices. Arguments: `DiscordAutocompleteArgs`. */
68
+ AUTOCOMPLETE = 'discord.autocomplete',
69
+ /** Downloads an attachment of the interaction or event. Arguments: `DiscordReadAttachmentArgs`; result: `DiscordReadAttachmentResult`. */
70
+ READ_ATTACHMENT = 'discord.readAttachment',
71
+ }
72
+
73
+ /** Choices an autocomplete answer carries at most (Discord's limit). */
74
+ export const DISCORD_AUTOCOMPLETE_MAX_CHOICES = 25;
75
+ /** Files a message carries at most (Discord's limit). */
76
+ export const DISCORD_MESSAGE_MAX_FILES = 10;
77
+ /** Total size of the files of a message, in bytes. */
78
+ export const DISCORD_MESSAGE_MAX_FILES_BYTES = 10 * 1024 * 1024;
79
+ /** Upper bound of `budget.maxFilePayloadBytes`: the largest payload a file call may carry. */
80
+ export const REFLEX_ATTACHMENT_MAX_BYTES_BOUND = 8 * 1024 * 1024;
81
+ /** Default size an attachment read may reach when the Service sets no limit. */
82
+ export const REFLEX_ATTACHMENT_DEFAULT_MAX_BYTES = 2 * 1024 * 1024;
68
83
 
69
84
  /**
70
85
  * Bounds the host applies to the arguments of `abyss.discord.*` before any call to Discord: a call
@@ -165,8 +180,16 @@ export interface DiscordPoll {
165
180
  allowMultiselect?: boolean;
166
181
  }
167
182
 
183
+ /** A file of a message: its content inline (base64) or an attachment of the interaction to forward. */
184
+ export type DiscordMessageFile = { name: string; description?: string } & (
185
+ | { contentBase64: string }
186
+ | { attachmentId: string }
187
+ );
188
+
168
189
  export interface DiscordMessage {
169
190
  content?: string;
191
+ /** At most `DISCORD_MESSAGE_MAX_FILES` files, `DISCORD_MESSAGE_MAX_FILES_BYTES` in total. */
192
+ files?: DiscordMessageFile[];
170
193
  embeds?: DiscordJsonObject[];
171
194
  components?: DiscordJsonObject[];
172
195
  /** Only the reply to an interaction can be ephemeral. */
@@ -357,6 +380,29 @@ export interface DiscordCreateThreadArgs extends DiscordAuditReason {
357
380
  autoArchiveMinutes?: number;
358
381
  }
359
382
 
383
+ export interface DiscordAutocompleteChoice {
384
+ name: string;
385
+ value: string | number;
386
+ nameLocalizations?: Record<string, string>;
387
+ }
388
+
389
+ /** At most `DISCORD_AUTOCOMPLETE_MAX_CHOICES` choices. */
390
+ export interface DiscordAutocompleteArgs {
391
+ choices: DiscordAutocompleteChoice[];
392
+ }
393
+
394
+ export interface DiscordReadAttachmentArgs {
395
+ attachmentId: string;
396
+ }
397
+
398
+ export interface DiscordReadAttachmentResult {
399
+ filename: string;
400
+ contentType: string | null;
401
+ /** Bytes. */
402
+ size: number;
403
+ contentBase64: string;
404
+ }
405
+
360
406
  export interface DiscordEndPollArgs {
361
407
  channelId: string;
362
408
  messageId: string;
@@ -455,6 +501,7 @@ export interface DiscordGuild {
455
501
  /** The kind of interaction a function was started by. */
456
502
  export enum DiscordInteractionKind {
457
503
  COMMAND = 'COMMAND',
504
+ AUTOCOMPLETE = 'AUTOCOMPLETE',
458
505
  COMPONENT = 'COMPONENT',
459
506
  MODAL = 'MODAL',
460
507
  }
@@ -464,6 +511,7 @@ export enum DiscordInteractionType {
464
511
  PING = 1,
465
512
  APPLICATION_COMMAND = 2,
466
513
  MESSAGE_COMPONENT = 3,
514
+ APPLICATION_COMMAND_AUTOCOMPLETE = 4,
467
515
  MODAL_SUBMIT = 5,
468
516
  }
469
517
 
@@ -474,6 +522,7 @@ export enum DiscordCallbackType {
474
522
  DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE = 5,
475
523
  DEFERRED_UPDATE_MESSAGE = 6,
476
524
  UPDATE_MESSAGE = 7,
525
+ APPLICATION_COMMAND_AUTOCOMPLETE_RESULT = 8,
477
526
  MODAL = 9,
478
527
  }
479
528
 
@@ -524,6 +573,8 @@ export interface DiscordInteractionInput {
524
573
  name: string;
525
574
  options: Record<string, string | number | boolean>;
526
575
  resolved?: DiscordResolved;
576
+ /** The option being typed; present only for an AUTOCOMPLETE interaction. */
577
+ focused?: { name: string; value: string };
527
578
  };
528
579
  /** `values` of a select menu; `resolved` details them for a user, role, channel or mentionable menu. */
529
580
  component?: { customId: string; values?: string[]; resolved?: DiscordResolved };
@@ -576,6 +627,8 @@ export interface DiscordMessageCreateData {
576
627
  mentions: string[];
577
628
  referencedMessageId: string | null;
578
629
  attachmentCount: number;
630
+ /** The files of the message, with the ids `discord.readAttachment` takes. */
631
+ attachments: DiscordAttachment[];
579
632
  /** ISO 8601. */
580
633
  createdAt: string;
581
634
  /** Present only when the trigger asks for the content (`includeContent`). */
@@ -14,6 +14,7 @@ import type { EvaluationItem, EvaluationResult } from '../../runner-protocol/eva
14
14
  import {
15
15
  CoreCapability,
16
16
  ExecutionStatus,
17
+ MAX_PROGRESS_OUTPUT_BYTES,
17
18
  MAX_PROGRESS_OUTPUT_CHARS,
18
19
  StepPhase,
19
20
  StepStatus,
@@ -178,9 +179,9 @@ describe('runInIsolate', () => {
178
179
  expect(finishedName?.durationMs).toBeGreaterThan(0);
179
180
  });
180
181
 
181
- it('truncates a large output in the progress, never in the run', async () => {
182
- const big = 'x'.repeat(MAX_PROGRESS_OUTPUT_CHARS * 2);
183
- const host = fakeHost(undefined, { 'input.name': big });
182
+ /** Runs the first step with `value` as its output and returns the progress of its end. */
183
+ const finishedProgressOf = async (value: unknown) => {
184
+ const host = fakeHost(undefined, { 'input.name': value });
184
185
  const outcome = outcomeOf(
185
186
  await runInIsolate(
186
187
  request({ definition: { ...definition, steps: [definition.steps[0]] } }),
@@ -188,9 +189,59 @@ describe('runInIsolate', () => {
188
189
  ),
189
190
  );
190
191
  expect(outcome.status).toBe(ExecutionStatus.SUCCEEDED);
191
- const finished = host.progress.find((p) => p.phase === StepPhase.FINISHED);
192
+ return host.progress.find((p) => p.phase === StepPhase.FINISHED);
193
+ };
194
+
195
+ // JSON of a string adds its two quotes: `jsonBytes` bytes of JSON hold `jsonBytes - 2` ASCII characters.
196
+ const asciiOfJsonBytes = (jsonBytes: number): string => 'x'.repeat(jsonBytes - 2);
197
+
198
+ it('keeps an output of exactly 64 KB of JSON whole', async () => {
199
+ const output = asciiOfJsonBytes(MAX_PROGRESS_OUTPUT_BYTES);
200
+ expect(Buffer.byteLength(JSON.stringify(output))).toBe(65_536);
201
+ const finished = await finishedProgressOf(output);
202
+ expect(finished?.output).toBe(output);
203
+ expect(finished?.outputTruncated).toBeUndefined();
204
+ expect(finished?.outputSizeBytes).toBeUndefined();
205
+ });
206
+
207
+ it('cuts an output of 64 KB + 1 byte to a 4 KB preview with its real size, never in the run', async () => {
208
+ const output = asciiOfJsonBytes(MAX_PROGRESS_OUTPUT_BYTES + 1);
209
+ const finished = await finishedProgressOf(output);
192
210
  expect(finished?.outputTruncated).toBe(true);
193
- expect((finished?.output as string).length).toBe(MAX_PROGRESS_OUTPUT_CHARS);
211
+ expect(finished?.outputSizeBytes).toBe(65_537);
212
+ expect(finished?.output).toBe(JSON.stringify(output).slice(0, MAX_PROGRESS_OUTPUT_CHARS));
213
+ expect(Buffer.byteLength(finished?.output as string)).toBe(4_096);
214
+ });
215
+
216
+ it('keeps a 4 KB to 64 KB output whole, where it used to be cut at 4096 characters', async () => {
217
+ const output = { rows: 'y'.repeat(30_000) };
218
+ const finished = await finishedProgressOf(output);
219
+ expect(finished?.output).toEqual(output);
220
+ expect(finished?.outputTruncated).toBeUndefined();
221
+ });
222
+
223
+ it('measures the preview and the real size in bytes, never cutting a multibyte character', async () => {
224
+ // Each "€" is 3 bytes: the 4 096-byte boundary falls inside one.
225
+ const output = `a${'€'.repeat(30_000)}`;
226
+ const json = JSON.stringify(output);
227
+ const finished = await finishedProgressOf(output);
228
+ expect(finished?.outputSizeBytes).toBe(Buffer.byteLength(json));
229
+ const preview = finished?.output as string;
230
+ expect(json.startsWith(preview)).toBe(true);
231
+ expect(preview).not.toContain('�');
232
+ // Quote + "a" + 1 364 whole "€" = 4 094 bytes; a 1 365th would end at 4 097.
233
+ expect(Buffer.byteLength(preview)).toBe(4_094);
234
+ });
235
+
236
+ it('counts a character outside the BMP as 4 bytes and keeps its two units together', async () => {
237
+ const output = '😀'.repeat(20_000);
238
+ const json = JSON.stringify(output);
239
+ const finished = await finishedProgressOf(output);
240
+ expect(finished?.outputSizeBytes).toBe(Buffer.byteLength(json));
241
+ const preview = finished?.output as string;
242
+ expect(json.startsWith(preview)).toBe(true);
243
+ // Quote + 1 023 whole emoji = 4 093 bytes; a 1 024th would end at 4 097.
244
+ expect(Buffer.byteLength(preview)).toBe(4_093);
194
245
  });
195
246
 
196
247
  it('refuses a capability the host did not expose, without calling it', async () => {
@@ -36,6 +36,7 @@ import type { EvaluationItem, EvaluationResult } from '../runner-protocol/evalua
36
36
  import {
37
37
  CoreCapability,
38
38
  ExecutionStatus,
39
+ MAX_PROGRESS_OUTPUT_BYTES,
39
40
  MAX_PROGRESS_OUTPUT_CHARS,
40
41
  StepPhase,
41
42
  StepStatus,
@@ -137,8 +138,49 @@ const isolatePolicy = (request: EngineRequest): RunPolicy => {
137
138
  };
138
139
  };
139
140
 
140
- /** The progress view of an output: the value itself, or the beginning of its JSON. */
141
- const outputPreview = (output: unknown): Pick<EngineProgress, 'output' | 'outputTruncated'> => {
141
+ /** UTF-8 width of the code point starting at `index`, and how many UTF-16 units it spans. */
142
+ const codePointAt = (text: string, index: number): { bytes: number; units: number } => {
143
+ const code = text.charCodeAt(index);
144
+ if (code < 0x80) {
145
+ return { bytes: 1, units: 1 };
146
+ }
147
+ if (code < 0x800) {
148
+ return { bytes: 2, units: 1 };
149
+ }
150
+ if (code >= 0xd800 && code <= 0xdbff) {
151
+ const next = text.charCodeAt(index + 1);
152
+ if (next >= 0xdc00 && next <= 0xdfff) {
153
+ return { bytes: 4, units: 2 };
154
+ }
155
+ }
156
+ return { bytes: 3, units: 1 };
157
+ };
158
+
159
+ /**
160
+ * Size of `text` in UTF-8 bytes (there is no `TextEncoder` in the isolate), and its longest prefix
161
+ * of at most `limit` bytes that ends on a character boundary.
162
+ */
163
+ const utf8Measure = (text: string, limit: number): { bytes: number; prefix: string } => {
164
+ let bytes = 0;
165
+ let prefixEnd = -1;
166
+ for (let index = 0; index < text.length; ) {
167
+ const point = codePointAt(text, index);
168
+ if (prefixEnd < 0 && bytes + point.bytes > limit) {
169
+ prefixEnd = index;
170
+ }
171
+ bytes += point.bytes;
172
+ index += point.units;
173
+ }
174
+ return { bytes, prefix: text.slice(0, prefixEnd < 0 ? text.length : prefixEnd) };
175
+ };
176
+
177
+ /**
178
+ * The progress view of an output: the value itself up to `MAX_PROGRESS_OUTPUT_BYTES` bytes of JSON;
179
+ * beyond, the first `MAX_PROGRESS_OUTPUT_CHARS` bytes of its JSON, its real size and the flag.
180
+ */
181
+ const outputPreview = (
182
+ output: unknown,
183
+ ): Pick<EngineProgress, 'output' | 'outputTruncated' | 'outputSizeBytes'> => {
142
184
  let json: string | undefined;
143
185
  try {
144
186
  json = JSON.stringify(output);
@@ -148,10 +190,11 @@ const outputPreview = (output: unknown): Pick<EngineProgress, 'output' | 'output
148
190
  if (json === undefined) {
149
191
  return {};
150
192
  }
151
- if (json.length <= MAX_PROGRESS_OUTPUT_CHARS) {
193
+ const { bytes, prefix } = utf8Measure(json, MAX_PROGRESS_OUTPUT_CHARS);
194
+ if (bytes <= MAX_PROGRESS_OUTPUT_BYTES) {
152
195
  return { output };
153
196
  }
154
- return { output: json.slice(0, MAX_PROGRESS_OUTPUT_CHARS), outputTruncated: true };
197
+ return { output: prefix, outputTruncated: true, outputSizeBytes: bytes };
155
198
  };
156
199
 
157
200
  /** Turns interpreter step notifications into `progress`, timing each step with `host.now`. */
@@ -0,0 +1,26 @@
1
+ import { REFLEX_ATTACHMENT_MAX_BYTES_BOUND } from '../../discord/discord.types';
2
+ import {
3
+ MAX_CALL_PAYLOAD_BYTES,
4
+ MAX_FILE_CALL_PAYLOAD_BYTES,
5
+ filePayloadBytesFor,
6
+ } from '../execution-protocol.types';
7
+
8
+ describe('filePayloadBytesFor', () => {
9
+ it('is the base64 size of the attachment plus 64 KiB of envelope', () => {
10
+ expect(filePayloadBytesFor(3)).toBe(4 + 65_536);
11
+ expect(filePayloadBytesFor(2 * 1024 * 1024)).toBe(
12
+ Math.ceil((2 * 1024 * 1024 * 4) / 3) + 65_536,
13
+ );
14
+ });
15
+
16
+ it('rounds the base64 size up', () => {
17
+ expect(filePayloadBytesFor(1)).toBe(2 + 65_536);
18
+ });
19
+
20
+ it('gives the highest grantable budget for the attachment bound', () => {
21
+ expect(MAX_FILE_CALL_PAYLOAD_BYTES).toBe(
22
+ filePayloadBytesFor(REFLEX_ATTACHMENT_MAX_BYTES_BOUND),
23
+ );
24
+ expect(MAX_FILE_CALL_PAYLOAD_BYTES).toBeGreaterThan(MAX_CALL_PAYLOAD_BYTES);
25
+ });
26
+ });
@@ -1,3 +1,4 @@
1
+ import { REFLEX_ATTACHMENT_MAX_BYTES_BOUND } from '../discord/discord.types';
1
2
  import type { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
2
3
  import type { RuntimeDefinition } from '../definition/definition.types';
3
4
  import type { RunState } from '../interpreter/interpreter.types';
@@ -11,7 +12,30 @@ export const EXECUTION_PROTOCOL = 'abyss-runtime.v2';
11
12
  /** Upper bound, in JSON bytes, on the arguments of one `call` and on the value of its result. */
12
13
  export const MAX_CALL_PAYLOAD_BYTES = 1_048_576;
13
14
 
14
- /** Upper bound, in characters of JSON, on the step output a `progress` message carries. */
15
+ /**
16
+ * `budget.maxFilePayloadBytes` for attachments of at most `maxAttachmentBytes`: their base64
17
+ * (4 bytes for 3) plus 64 KiB of envelope.
18
+ */
19
+ export const filePayloadBytesFor = (maxAttachmentBytes: number): number =>
20
+ Math.ceil((maxAttachmentBytes * 4) / 3) + 64 * 1024;
21
+
22
+ /**
23
+ * Highest `budget.maxFilePayloadBytes` a host may grant: `filePayloadBytesFor` the largest
24
+ * attachment a bot may configure, below the 16 MiB WebSocket frame of the runner.
25
+ */
26
+ export const MAX_FILE_CALL_PAYLOAD_BYTES = filePayloadBytesFor(REFLEX_ATTACHMENT_MAX_BYTES_BOUND);
27
+
28
+ /**
29
+ * Upper bound, in UTF-8 bytes of JSON, on the step output a `progress` message carries whole. Past
30
+ * it the message carries a preview of `MAX_PROGRESS_OUTPUT_CHARS` bytes and the real size.
31
+ */
32
+ export const MAX_PROGRESS_OUTPUT_BYTES = 65_536;
33
+
34
+ /**
35
+ * Size, in UTF-8 bytes of JSON, of the preview a `progress` message carries for a step output over
36
+ * `MAX_PROGRESS_OUTPUT_BYTES` (cut on a character boundary, so never more than this many bytes).
37
+ * The name predates the byte unit and is kept: renaming a published export needs a major version.
38
+ */
15
39
  export const MAX_PROGRESS_OUTPUT_CHARS = 4_096;
16
40
 
17
41
  /** Upper bound, in characters, on the `errorStack` of an outcome or a failed `progress`. */
@@ -79,6 +103,12 @@ export interface ExecutionBudget {
79
103
  * this number the runner answers them without relaying them to the host.
80
104
  */
81
105
  maxLogLines?: number;
106
+ /**
107
+ * When given, a call to a `discord.*` capability whose arguments carry a non-empty `files`
108
+ * array may weigh up to this many JSON bytes (instead of `MAX_CALL_PAYLOAD_BYTES`), and so
109
+ * may the result of `discord.readAttachment`. Every other call keeps the default bound.
110
+ */
111
+ maxFilePayloadBytes?: number;
82
112
  }
83
113
 
84
114
  /** Where the client code of a step failed: line and column in the step's own code. */
@@ -191,11 +221,18 @@ export interface ProgressMessage {
191
221
  /** On `finished`, measured by the runner. */
192
222
  metrics?: StepMetrics;
193
223
  /**
194
- * On `finished` with SUCCEEDED: the step's output, or, past `MAX_PROGRESS_OUTPUT_CHARS`, the
195
- * beginning of its JSON with `outputTruncated`.
224
+ * On `finished` with SUCCEEDED: the step's output whole when its JSON is at most
225
+ * `MAX_PROGRESS_OUTPUT_BYTES` bytes of UTF-8; past that, the first `MAX_PROGRESS_OUTPUT_CHARS`
226
+ * bytes of its JSON (a string, cut on a character boundary) with `outputTruncated` and
227
+ * `outputSizeBytes`.
196
228
  */
197
229
  output?: unknown;
198
230
  outputTruncated?: boolean;
231
+ /**
232
+ * With `outputTruncated`: the real size of the output's JSON, in UTF-8 bytes. Absent when the
233
+ * output could not be serialized (no preview either).
234
+ */
235
+ outputSizeBytes?: number;
199
236
  /** On `finished` with FAILED. */
200
237
  errorCode?: RuntimeErrorCode;
201
238
  /** On `finished` with FAILED by client code. */