omp-superagent 0.1.7 → 0.1.8

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 (52) hide show
  1. package/DESIGN.md +21 -14
  2. package/README.ko.md +33 -15
  3. package/README.md +35 -14
  4. package/THIRD_PARTY_NOTICES.md +3 -3
  5. package/config.example.json +2 -1
  6. package/docs/OPERATIONS.md +232 -74
  7. package/docs/design/execution.md +54 -10
  8. package/docs/design/messaging.md +177 -43
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.8.md +21 -0
  11. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  13. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  17. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  18. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  19. package/package.json +8 -8
  20. package/scripts/ci.ts +3 -3
  21. package/scripts/test-omp.sh +2 -1
  22. package/src/cli.ts +3 -0
  23. package/src/config.ts +5 -0
  24. package/src/contracts.ts +26 -5
  25. package/src/cron-jobs.ts +443 -19
  26. package/src/cron-pr-intake.ts +257 -0
  27. package/src/discord-markdown.ts +350 -123
  28. package/src/extension.ts +9 -1
  29. package/src/head-quota.ts +80 -0
  30. package/src/head-recovery.ts +40 -1
  31. package/src/host-extension.ts +120 -4
  32. package/src/host-protocol.ts +11 -0
  33. package/src/host-sdk-helper.ts +105 -10
  34. package/src/host.ts +111 -29
  35. package/src/installed-omp.ts +116 -4
  36. package/src/managed-ulw.ts +137 -24
  37. package/src/messenger-command-catalog.json +1 -1
  38. package/src/native-presets.ts +32 -5
  39. package/src/omp-usage.ts +254 -36
  40. package/src/pr-github.ts +4 -2
  41. package/src/pr-intake-automation.ts +316 -0
  42. package/src/pr-intake-comment.ts +226 -0
  43. package/src/pr-intake-fix.ts +233 -0
  44. package/src/pr-intake-github.ts +480 -0
  45. package/src/pr-intake-material.ts +230 -0
  46. package/src/pr-intake-mode.ts +59 -0
  47. package/src/pr-intake-review.ts +397 -0
  48. package/src/pr-intake-tree.ts +69 -0
  49. package/src/pr-intake-work.ts +29 -0
  50. package/src/runtime.ts +1504 -192
  51. package/src/store.ts +249 -49
  52. package/src/topic-history.ts +30 -17
@@ -2,171 +2,398 @@
2
2
  * Markdown table rendering for the Discord transport.
3
3
  *
4
4
  * Discord has no pipe-table support: a table sent verbatim arrives as literal
5
- * `| a | b |` rows. Discord does render fenced blocks in a monospaced font, so a
6
- * table is converted into an aligned fenced block before it leaves this package.
7
- *
8
- * Column padding uses display width, not string length, so CJK and other wide
9
- * characters line up. Bun.stringWidth supplies the display width directly;
10
- * no OMP source checkout or private module is needed.
5
+ * `| a | b |` rows. Labeled lists preserve inline Markdown and wrap on
6
+ * narrow screens without requiring horizontal scrolling.
11
7
  */
12
8
 
13
- type Align = "left" | "center" | "right";
14
-
15
9
  const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})/;
16
10
  const FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})[ \t\r]*$/;
17
11
  const BLOCK_START = /^ {0,3}(?:>|#{1,6}(?:[ \t]|$)|(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$))/;
12
+ const INDENTED_CODE = /^(?: {4}| {0,3}\t)/;
18
13
  const DELIMITER_CELL = /^:?-+:?$/;
14
+ const LIST_MARKER = /^ {0,3}(?:[-+*]|\d{1,9}[.)])(?=[ \t]|$)/;
15
+ const THEMATIC_BREAK = /^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,})\r?$/;
16
+
17
+ function opensFence(line: string): string | undefined {
18
+ const match = FENCE_OPEN.exec(line);
19
+ const marker = match?.[1];
20
+ // An info string containing backticks makes a backtick opener inline code.
21
+ if (match && marker?.startsWith("`") && line.slice(match[0].length).includes("`")) return undefined;
22
+ return marker;
23
+ }
24
+
25
+ function relativeLine(line: string | undefined, margin: number): string | undefined {
26
+ const indent = line?.match(/^ */)?.[0].length ?? 0;
27
+ return indent >= margin ? line?.slice(margin) : undefined;
28
+ }
29
+
30
+ function listMargin(line: string): number | undefined {
31
+ const marker = LIST_MARKER.exec(line)?.[0];
32
+ if (!marker || THEMATIC_BREAK.test(line)) return undefined;
33
+ const spaces = line.slice(marker.length).match(/^ */)?.[0].length ?? 0;
34
+ return marker.length + (spaces >= 1 && spaces <= 4 ? spaces : 1);
35
+ }
36
+
37
+ function indentColumns(line: string): number {
38
+ let columns = 0;
39
+ for (const char of line) {
40
+ if (char === " ") columns++;
41
+ else if (char === "\t") columns += 4 - columns % 4;
42
+ else break;
43
+ }
44
+ return columns;
45
+ }
19
46
 
20
47
  /**
21
- * Split one table row into trimmed cells.
22
- * Returns null when the line carries no unescaped pipe, so callers can end a
23
- * table body. `\|` and pipes inside backtick spans never split a cell, matching
24
- * how GFM reads a row.
48
+ * Split on structural pipes only. Inside inline code a table's pipe escape
49
+ * becomes a literal pipe; outside code Discord still interprets the escape.
25
50
  */
26
- function splitRow(line: string): string[] | null {
51
+ function splitRow(line: string | undefined): string[] | null {
52
+ if (line === undefined || !line.includes("|") || INDENTED_CODE.test(line)) return null;
53
+ // Unmatched backtick runs are literal prose and must not hide separators.
54
+ const lastTicks = new Map<number, number>();
55
+ for (const match of line.matchAll(/`+/g)) lastTicks.set(match[0].length, match.index);
27
56
  const cells: string[] = [];
28
- let cell = "";
57
+ let start = 0;
29
58
  let pipe = false;
30
- let leading = false;
31
- let tick = 0;
59
+ let decoded = "";
60
+ let ticks = 0;
32
61
  for (let index = 0; index < line.length; index++) {
33
- const char = line[index]!;
34
- if (char === "\\" && line[index + 1] === "|") {
35
- // A GFM escaped pipe is cell content, not a separator: inside the fence
36
- // it stays the literal `|` the author asked to display.
37
- cell += "|";
62
+ const char = line[index];
63
+ const following = line[index + 1];
64
+ if (ticks === 0 && char === "\\" && (following === "|" || following === "`" || following === "\\")) {
38
65
  index++;
39
- continue;
40
- }
41
- if (char === "`") {
42
- let run = 1;
43
- while (line[index + run] === "`") run++;
44
- tick = tick === run ? 0 : tick === 0 ? run : tick;
45
- cell += "`".repeat(run);
46
- index += run - 1;
47
- continue;
48
- }
49
- if (char === "|" && tick === 0) {
50
- if (!pipe) leading = cell.trim() === "";
66
+ } else if (ticks !== 0 && char === "\\" && following === "|") {
67
+ decoded += line.slice(start, index) + "|";
68
+ index++;
69
+ start = index + 1;
70
+ } else if (char === "`") {
71
+ const first = index;
72
+ while (line[index + 1] === "`") index++;
73
+ const run = index - first + 1;
74
+ if (ticks === run) ticks = 0;
75
+ else if (ticks === 0) {
76
+ if ((lastTicks.get(run) ?? first) > first) ticks = run;
77
+ else {
78
+ decoded += line.slice(start, first) + "\\`".repeat(run);
79
+ start = index + 1;
80
+ }
81
+ }
82
+ } else if (char === "|" && ticks === 0) {
83
+ const cell = (decoded + line.slice(start, index)).trim();
84
+ if (pipe || cell !== "") cells.push(cell);
51
85
  pipe = true;
52
- cells.push(cell);
53
- cell = "";
54
- continue;
86
+ decoded = "";
87
+ start = index + 1;
55
88
  }
56
- cell += char;
57
89
  }
58
90
  if (!pipe) return null;
59
- cells.push(cell);
60
- if (leading) cells.shift();
61
- if (cells.length > 0 && cells[cells.length - 1]!.trim() === "") cells.pop();
62
- return cells.length > 0 ? cells.map(value => value.trim()) : null;
91
+ const tail = (decoded + line.slice(start)).trim();
92
+ if (tail !== "") cells.push(tail);
93
+ return cells.length > 0 ? cells : null;
63
94
  }
64
95
 
65
- /** The delimiter row must have the same cell count as the header, as in GFM. */
66
- function parseDelimiter(line: string): Align[] | null {
67
- const cells = splitRow(line);
68
- if (!cells) return null;
69
- const aligns: Align[] = [];
70
- for (const cell of cells) {
71
- if (!DELIMITER_CELL.test(cell)) return null;
72
- const left = cell.startsWith(":");
73
- const right = cell.endsWith(":");
74
- aligns.push(left && right ? "center" : right ? "right" : "left");
96
+ /**
97
+ * Rewrite Markdown pipe tables as one labeled list item per row.
98
+ *
99
+ * Everything else passes through byte for byte. If the complete message would
100
+ * exceed the byte budget, return the original text for the existing delivery path.
101
+ */
102
+ export function renderDiscordMarkdown(text: string, maxBytes: number): string {
103
+ if (!text.includes("|") || Buffer.byteLength(text, "utf8") > maxBytes) return text;
104
+ const lines = text.split("\n");
105
+ const out: string[] = [];
106
+ let remaining = maxBytes;
107
+ const append = (line: string): boolean => {
108
+ const bytes = Buffer.byteLength(line, "utf8") + (out.length === 0 ? 0 : 1);
109
+ if (bytes > remaining) return false;
110
+ remaining -= bytes;
111
+ out.push(line);
112
+ return true;
113
+ };
114
+ const margins: number[] = [];
115
+ let fence: { readonly marker: string; readonly margin: number } | undefined;
116
+ for (let index = 0; index < lines.length; index++) {
117
+ const line = lines[index];
118
+ if (fence) {
119
+ const columns = indentColumns(line);
120
+ if (columns < fence.margin && line.trim()) {
121
+ fence = undefined; // The containing list item ended.
122
+ } else {
123
+ const close = columns >= fence.margin && columns < fence.margin + 4
124
+ ? FENCE_CLOSE.exec(line.replace(/^[ \t]*/, ""))?.[1]
125
+ : undefined;
126
+ if (close && close[0] === fence.marker[0] && close.length >= fence.marker.length) fence = undefined;
127
+ if (!append(line)) return text;
128
+ continue;
129
+ }
130
+ }
131
+ if (line.trim()) {
132
+ let margin = margins.at(-1);
133
+ while (margin !== undefined && relativeLine(line, margin) === undefined) {
134
+ margins.pop();
135
+ margin = margins.at(-1);
136
+ }
137
+ }
138
+ const margin = margins.at(-1) ?? 0;
139
+ const scoped = relativeLine(line, margin) ?? line;
140
+ const marker = opensFence(scoped);
141
+ const indent = listMargin(scoped);
142
+ if (marker) {
143
+ fence = { marker, margin };
144
+ } else if (indent !== undefined) {
145
+ const itemMargin = margin + indent;
146
+ margins.push(itemMargin);
147
+ const itemFence = opensFence(scoped.slice(indent));
148
+ if (itemFence) fence = { marker: itemFence, margin: itemMargin };
149
+ }
150
+ const delimiter = !marker && indent === undefined && scoped.includes("|") && !BLOCK_START.test(scoped)
151
+ ? splitRow(relativeLine(lines[index + 1], margin))
152
+ : null;
153
+ const header = delimiter?.every(cell => DELIMITER_CELL.test(cell)) ? splitRow(scoped) : null;
154
+ if (!header || header.length !== delimiter?.length) {
155
+ if (!append(line)) return text;
156
+ continue;
157
+ }
158
+ if (out.at(-1)?.trim() && !append("")) return text;
159
+ const indentation = line.slice(0, line.length - scoped.length);
160
+ const first = index + 2;
161
+ const bodyRow = (at: number) => {
162
+ const row = relativeLine(lines[at], margin);
163
+ return row === undefined || BLOCK_START.test(row) || opensFence(row) ? null : splitRow(row);
164
+ };
165
+ let next = first;
166
+ let row = bodyRow(next);
167
+ do {
168
+ if (next !== first && !append("")) return text;
169
+ const columns = Math.max(header.length, row?.length ?? 0);
170
+ for (let column = 0; column < columns; column++) {
171
+ const prefix = column === 0 ? "- " : " - ";
172
+ const label = header[column] || `Column ${column + 1}`;
173
+ const value = row?.[column];
174
+ if (!append(`${indentation}${prefix}${label}:${value ? ` ${value}` : ""}`)) return text;
175
+ }
176
+ if (row) row = bodyRow(++next);
177
+ } while (row);
178
+ let following = next;
179
+ while (following < lines.length && !lines[following]?.trim()) following++;
180
+ const firstFollowing = lines[following];
181
+ if (firstFollowing !== undefined && indentColumns(firstFollowing) >= margin + 4
182
+ && (!append("") || !append(`${indentation}---`))) return text;
183
+ if (lines[next]?.trim() && !append("")) return text;
184
+ index = next - 1;
75
185
  }
76
- return aligns;
186
+ return out.join("\n");
77
187
  }
78
188
 
79
- function pad(value: string, width: number, align: Align): string {
80
- const missing = width - Bun.stringWidth(value);
81
- if (missing <= 0) return value;
82
- if (align === "right") return " ".repeat(missing) + value;
83
- if (align === "center") {
84
- const left = Math.floor(missing / 2);
85
- return " ".repeat(left) + value + " ".repeat(missing - left);
86
- }
87
- return value + " ".repeat(missing);
189
+ export interface DiscordEmbedField { name: string; value: string; inline: boolean }
190
+ export interface DiscordEmbed {
191
+ title?: string;
192
+ description?: string;
193
+ color?: number;
194
+ fields?: DiscordEmbedField[];
195
+ image?: { url: string };
196
+ }
197
+
198
+ /** Discord's documented embed limits, counted in UTF-16 units like message text. */
199
+ const EMBEDS_PER_MESSAGE = 10;
200
+ const EMBED_TOTAL = 6000;
201
+ const EMBED_TITLE = 256;
202
+ const EMBED_DESCRIPTION = 4096;
203
+ const EMBED_FIELDS = 25;
204
+ const FIELD_NAME = 256;
205
+ const FIELD_VALUE = 1024;
206
+ const IMAGE_URL = 2048;
207
+ const CARD_DEPTH = 16;
208
+ const DIVIDER = "\u2500".repeat(16);
209
+ const CARD_OPEN = /^ {0,3}(`{3,}|~{3,})[ \t]*card[ \t\r]*$/;
210
+
211
+ class InvalidCard extends Error {}
212
+
213
+ function object(value: unknown): Record<string, unknown> | null {
214
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : null;
215
+ }
216
+
217
+ function text(props: Record<string, unknown>, key: string, required: boolean): string | undefined {
218
+ const value = props[key];
219
+ if (value === undefined && !required) return undefined;
220
+ if (typeof value !== "string" || !value.trim()) throw new InvalidCard();
221
+ return value;
222
+ }
223
+
224
+ function embedSize(embed: DiscordEmbed): number {
225
+ return (embed.title?.length ?? 0) + (embed.description?.length ?? 0)
226
+ + (embed.fields ?? []).reduce((sum, field) => sum + field.name.length + field.value.length, 0);
227
+ }
228
+
229
+ /**
230
+ * Convert one json-render spec (`{ root, elements }`) whose root is a Card.
231
+ * Any structural error, unknown component, reuse/cycle or Discord limit makes
232
+ * the whole spec invalid; the caller then keeps the original fence as text.
233
+ */
234
+ function cardEmbed(source: string): DiscordEmbed {
235
+ let spec: unknown;
236
+ try { spec = JSON.parse(source); } catch { throw new InvalidCard(); }
237
+ const root = object(spec);
238
+ const elements = root && object(root.elements);
239
+ if (!root || !elements || typeof root.root !== "string") throw new InvalidCard();
240
+ const parts: string[] = [];
241
+ const fields: DiscordEmbedField[] = [];
242
+ const embed: DiscordEmbed = {};
243
+ const seen = new Set<string>();
244
+ const visit = (id: unknown, depth: number, parent: string): void => {
245
+ if (typeof id !== "string" || depth > CARD_DEPTH || seen.has(id) || !Object.hasOwn(elements, id)) throw new InvalidCard();
246
+ seen.add(id);
247
+ const element = object(elements[id]);
248
+ if (!element) throw new InvalidCard();
249
+ const props = element.props === undefined ? {} : object(element.props);
250
+ const children = element.children === undefined ? [] : element.children;
251
+ if (!props || !Array.isArray(children)) throw new InvalidCard();
252
+ const type = element.type;
253
+ if (depth === 0 ? type !== "Card" : parent === "Fields" ? type !== "Field" : false) throw new InvalidCard();
254
+ switch (type) {
255
+ case "Card":
256
+ case "Section": {
257
+ const title = text(props, "title", false);
258
+ if (depth === 0) {
259
+ if (title !== undefined) embed.title = title;
260
+ const color = props.color;
261
+ if (typeof color === "number" && Number.isSafeInteger(color) && color >= 0 && color <= 0xffffff) embed.color = color;
262
+ else if (typeof color === "string" && /^#[0-9a-fA-F]{6}$/.test(color)) embed.color = Number.parseInt(color.slice(1), 16);
263
+ else if (color !== undefined) throw new InvalidCard();
264
+ } else if (title !== undefined) parts.push(`**${title}**`);
265
+ const description = type === "Card" ? text(props, "description", false) : undefined;
266
+ if (description !== undefined) parts.push(description);
267
+ break;
268
+ }
269
+ case "Text": parts.push(text(props, "text", true)!); break;
270
+ case "Fields": break;
271
+ case "Field": {
272
+ const inline = props.inline === undefined ? false : props.inline;
273
+ if (typeof inline !== "boolean") throw new InvalidCard();
274
+ fields.push({ name: text(props, "label", true)!, value: text(props, "value", true)!, inline });
275
+ break;
276
+ }
277
+ case "Table": {
278
+ const columns = props.columns;
279
+ const rows = props.rows;
280
+ if (!Array.isArray(columns) || columns.length === 0 || !columns.every(cell => typeof cell === "string")
281
+ || !Array.isArray(rows) || !rows.every(row => Array.isArray(row) && row.length === columns.length
282
+ && row.every(cell => typeof cell === "string"))) throw new InvalidCard();
283
+ const used = parts.reduce((sum, part) => sum + part.length, 0) + parts.length;
284
+ const table = cardTable([columns as string[], ...rows as string[][]], EMBED_DESCRIPTION - used);
285
+ if (!table) throw new InvalidCard();
286
+ parts.push(table);
287
+ break;
288
+ }
289
+ case "Divider": parts.push(DIVIDER); break;
290
+ case "Image": {
291
+ const url = text(props, "url", true)!;
292
+ if (embed.image || !url.startsWith("https://") || /\s/.test(url) || url.length > IMAGE_URL || !URL.canParse(url)) throw new InvalidCard();
293
+ embed.image = { url };
294
+ break;
295
+ }
296
+ default: throw new InvalidCard();
297
+ }
298
+ if (children.length > 0 && !["Card", "Section", "Fields"].includes(type)) throw new InvalidCard();
299
+ for (const child of children) visit(child, depth + 1, type);
300
+ };
301
+ visit(root.root, 0, "");
302
+ if (parts.length > 0) embed.description = parts.join("\n");
303
+ if (fields.length > 0) embed.fields = fields;
304
+ if ((embed.title?.length ?? 0) > EMBED_TITLE || (embed.description?.length ?? 0) > EMBED_DESCRIPTION
305
+ || fields.length > EMBED_FIELDS || fields.some(field => field.name.length > FIELD_NAME || field.value.length > FIELD_VALUE)
306
+ || embedSize(embed) > EMBED_TOTAL || !embed.title && !embed.description && !embed.fields && !embed.image) throw new InvalidCard();
307
+ return embed;
88
308
  }
89
309
 
90
- /** Check the byte budget before allocating any padded cells or separators. */
91
- function formatTable(rows: string[][], aligns: Align[], maxBytes: number): { lines: string[]; bytes: number } | null {
92
- const widths = aligns.map(() => 3);
310
+ function cardTable(rows: string[][], budget: number): string | null {
311
+ const widths = rows[0]!.map(() => 3);
312
+ let delta = 0;
93
313
  for (const row of rows) {
94
- for (let column = 0; column < row.length; column++) {
95
- widths[column] = Math.max(widths[column] ?? 3, Bun.stringWidth(row[column]!));
314
+ for (const [i, cell] of row.entries()) {
315
+ const columns = Bun.stringWidth(cell);
316
+ widths[i] = Math.max(widths[i]!, columns);
317
+ delta += cell.length - columns;
96
318
  }
97
319
  }
98
- const alignOf = (column: number): Align => aligns[column] ?? "left";
99
- const fence = "```";
100
- // Each row has a frame, display-width cells, and one newline. UTF-8 cell
101
- // bytes may exceed their display width; the separator contains only ASCII.
102
- const rowWidth = 3 * widths.length + 1 + widths.reduce((sum, width) => sum + width, 0);
103
- let bytes = 2 * fence.length + rows.length + 2 + (rows.length + 1) * rowWidth;
104
- for (const row of rows) {
105
- for (const cell of row) bytes += Buffer.byteLength(cell, "utf8") - Bun.stringWidth(cell);
320
+ const rowLength = 2 + 3 * widths.length + widths.reduce((sum, width) => sum + width, 0);
321
+ if (7 + (rows.length + 1) * rowLength + delta > budget) return null;
322
+ const lines = ["```"];
323
+ for (const [i, row] of rows.entries()) {
324
+ lines.push("| " + row.map((cell, column) => cell + " ".repeat(widths[column]! - Bun.stringWidth(cell))).join(" | ") + " |");
325
+ if (i === 0) lines.push("| " + widths.map(width => "-".repeat(width)).join(" | ") + " |");
106
326
  }
107
- if (bytes > maxBytes) return null;
108
- const line = (cells: string[]) =>
109
- `| ${widths.map((width, column) => pad(cells[column] ?? "", width, alignOf(column))).join(" | ")} |`;
110
- // Pure dashes keep the grid exact; alignment is already visible in the padded
111
- // cells, and `:` markers would only shift every following column by one.
112
- const separator = `| ${widths.map(width => "-".repeat(width)).join(" | ")} |`;
113
- const lines = [fence, line(rows[0]!), separator];
114
- for (let index = 1; index < rows.length; index++) lines.push(line(rows[index]!));
115
- lines.push(fence);
116
- return { lines, bytes };
327
+ lines.push("```");
328
+ return lines.join("\n");
117
329
  }
118
330
 
119
331
  /**
120
- * Rewrite markdown pipe tables as aligned fenced blocks.
332
+ * Move valid ```card fences out of the text and into Discord embeds.
121
333
  *
122
- * Everything else passes through byte for byte: prose, lists, headings, links,
123
- * blockquotes, inline code, and existing fenced blocks. Pipes inside a fence are
124
- * never treated as a table, and an already-converted table stays inside its own
125
- * fence, so the transform is idempotent. If alignment would exceed the complete
126
- * message's byte budget, return the original text for the existing delivery path.
334
+ * Fences nested in another code block are content, not cards. A spec that is
335
+ * invalid, or would exceed the message's 10 embeds or 6000 embed characters,
336
+ * stays verbatim as its original code block, which is also what Telegram and
337
+ * Slack show because they never call this.
127
338
  */
128
- export function renderDiscordMarkdown(text: string, maxBytes: number): string {
129
- if (!text.includes("|")) return text;
130
- let bytes = Buffer.byteLength(text, "utf8");
131
- if (bytes > maxBytes) return text;
132
- const lines = text.split("\n");
339
+ export function extractDiscordCards(source: string): { text: string; embeds: DiscordEmbed[] } {
340
+ if (!source.includes("card")) return { text: source, embeds: [] };
341
+ const lines = source.split("\n");
133
342
  const out: string[] = [];
134
- let fence: { char: string; length: number } | null = null;
343
+ const embeds: DiscordEmbed[] = [];
344
+ let total = 0;
345
+ const margins: number[] = [];
346
+ let fence: { marker: string; margin: number } | undefined;
135
347
  for (let index = 0; index < lines.length; index++) {
136
348
  const line = lines[index]!;
137
- const marker = FENCE_OPEN.exec(line)?.[1];
349
+ const columns = indentColumns(line);
350
+ if (fence && columns < fence.margin && line.trim()) fence = undefined;
138
351
  if (fence) {
352
+ const close = columns >= fence.margin && columns < fence.margin + 4
353
+ ? FENCE_CLOSE.exec(line.replace(/^[ \t]*/, ""))?.[1] : undefined;
354
+ if (close && close[0] === fence.marker[0] && close.length >= fence.marker.length) fence = undefined;
139
355
  out.push(line);
140
- const close = FENCE_CLOSE.exec(line)?.[1];
141
- if (close && close[0] === fence.char && close.length >= fence.length) fence = null;
142
356
  continue;
143
357
  }
144
- if (marker) {
145
- fence = { char: marker[0]!, length: marker.length };
146
- out.push(line);
147
- continue;
358
+ if (line.trim()) {
359
+ while (margins.length && relativeLine(line, margins.at(-1)!) === undefined) margins.pop();
148
360
  }
149
- const delimiter = !BLOCK_START.test(line) && index + 1 < lines.length ? parseDelimiter(lines[index + 1]!) : null;
150
- const header = delimiter ? splitRow(line) : null;
151
- if (!delimiter || !header || header.length !== delimiter.length) {
152
- out.push(line);
153
- continue;
361
+ const margin = margins.at(-1) ?? 0;
362
+ const scoped = relativeLine(line, margin) ?? line;
363
+ const card = margin === 0 ? CARD_OPEN.exec(scoped)?.[1] : undefined;
364
+ if (card) {
365
+ let end = index + 1;
366
+ for (; end < lines.length; end++) {
367
+ const close = FENCE_CLOSE.exec(lines[end]!)?.[1];
368
+ if (close && close[0] === card[0] && close.length >= card.length) break;
369
+ }
370
+ if (end < lines.length && embeds.length < EMBEDS_PER_MESSAGE) {
371
+ try {
372
+ const embed = cardEmbed(lines.slice(index + 1, end).join("\n"));
373
+ if (total + embedSize(embed) <= EMBED_TOTAL) {
374
+ embeds.push(embed);
375
+ total += embedSize(embed);
376
+ index = end;
377
+ continue;
378
+ }
379
+ } catch (error) { if (!(error instanceof InvalidCard)) throw error; }
380
+ }
154
381
  }
155
- const rows = [header];
156
- let sourceBytes = Buffer.byteLength(line, "utf8") + 1 + Buffer.byteLength(lines[index + 1]!, "utf8");
157
- let next = index + 2;
158
- for (; next < lines.length; next++) {
159
- if (FENCE_OPEN.test(lines[next]!) || BLOCK_START.test(lines[next]!)) break;
160
- const row = splitRow(lines[next]!);
161
- if (!row) break;
162
- rows.push(row);
163
- sourceBytes += 1 + Buffer.byteLength(lines[next]!, "utf8");
382
+ const marker = opensFence(scoped);
383
+ if (marker) fence = { marker, margin };
384
+ else {
385
+ const indent = listMargin(scoped);
386
+ if (indent !== undefined) {
387
+ const itemMargin = margin + indent;
388
+ margins.push(itemMargin);
389
+ const itemFence = opensFence(scoped.slice(indent));
390
+ if (itemFence) fence = { marker: itemFence, margin: itemMargin };
391
+ }
164
392
  }
165
- const table = formatTable(rows, delimiter, maxBytes - bytes + sourceBytes);
166
- if (!table) return text;
167
- bytes += table.bytes - sourceBytes;
168
- for (const rendered of table.lines) out.push(rendered);
169
- index = next - 1;
393
+ out.push(line);
170
394
  }
171
- return out.join("\n");
395
+ if (embeds.length === 0) return { text: source, embeds };
396
+ const occupied = (line: string) => !/^[ \t\r]*$/.test(line);
397
+ const start = out.findIndex(occupied);
398
+ return { text: start < 0 ? "" : out.slice(start, out.findLastIndex(occupied) + 1).join("\n"), embeds };
172
399
  }
package/src/extension.ts CHANGED
@@ -12,12 +12,14 @@ import { lanePlacement } from "./lane-rows";
12
12
  import { sameLaneModel } from "./lane-models";
13
13
  import { NativePresetManager } from "./native-presets";
14
14
  import { publishNativeSession } from "./native-sessions";
15
+ import { isPrReviewLane } from "./pr-intake-review";
15
16
  import { MODEL_PRESET_NAMES, WORKFLOW_NAMES } from "./contracts";
16
17
  import type { PrWatchCommand } from "./pr-watch";
17
18
  import type { LaneWatchCommand } from "./lane-watch";
18
19
  import { registerDecisionAsk } from "./decision-tool";
19
20
  import { registerResultAttach, RESULT_ATTACH_TOOL } from "./result-attachment";
20
21
  import { HEAD_ROTATION_GUARD, HEAD_ROTATION_PROBE, type RotationGuardEvent, type RotationProbeEvent } from "./head-rotation";
22
+ import { readHeadQuota } from "./head-quota";
21
23
 
22
24
  // Inject the role contract, not the references. Resolve the reference directory
23
25
  // from this package so a same-name workspace skill cannot change the procedure.
@@ -486,7 +488,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
486
488
  let messenger: ReturnType<typeof createGatewayMessenger>;
487
489
  try {
488
490
  for (const lane of store.lanes()) {
489
- if (lane.remote || !lane.sessionId) continue;
491
+ if (lane.remote || !lane.sessionId || isPrReviewLane(store, lane.id)) continue;
490
492
  const { sessionFile } = hostPaths(config, lane.id);
491
493
  if (lane.sessionFile !== sessionFile) throw new Error("Refusing to publish a lane outside its managed session path");
492
494
  await publishNativeSession(sessionFile, lane.cwd, lane.sessionId);
@@ -500,9 +502,15 @@ export default function superagentExtension(pi: ExtensionAPI): void {
500
502
  pi.logger.error(`Superagent: ${error instanceof Error ? error.message : String(error)}`);
501
503
  }, {
502
504
  topicMemory: ctx.memory,
505
+ readHeadQuota: (failure, sessionId, signal) => {
506
+ const session = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID)?.session;
507
+ return session instanceof pi.pi.AgentSession && session.sessionId === sessionId
508
+ ? readHeadQuota(session, failure, signal) : Promise.resolve(false);
509
+ },
503
510
  resolvePreset: async (name, thinkingContext) => (await nativePresets(ctx)).resolve(name, thinkingContext),
504
511
  inspectPresets: async () => (await nativePresets(ctx)).inspect(),
505
512
  syncPresetRoles: async canWrite => (await nativePresets(ctx)).syncRoles(store, canWrite, () => ctx.modelRegistry.refresh("offline")),
513
+ presetRolePaths: async () => (await nativePresets(ctx)).watchedPaths(),
506
514
  persistPreset: async selection => (await nativePresets(ctx)).persistSelection(selection),
507
515
  reapHeadJobs: async ({ sessionId, sessionFile }) => {
508
516
  const root = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID);
@@ -0,0 +1,80 @@
1
+ import type { AgentSession } from "@oh-my-pi/pi-coding-agent";
2
+ import { cfgRetryUsageReservePct } from "@oh-my-pi/pi-coding-agent/session/settings";
3
+ import { quotaTierFor } from "@oh-my-pi/pi-catalog/compat/behavior";
4
+ import type { HeadQuotaFailure } from "./head-recovery";
5
+
6
+ /** Match stock OMP's usage-report cache horizon, not a presumed provider reset time. */
7
+ export const HEAD_QUOTA_CHECK_MS = 5 * 60_000;
8
+
9
+ type QuotaSession = Pick<AgentSession, "modelRegistry" | "sessionId" | "settings"> & {
10
+ readonly model: Pick<NonNullable<AgentSession["model"]>, "provider" | "id" | "baseUrl" | "accountAccess"> | undefined;
11
+ };
12
+
13
+ export async function readHeadQuota(
14
+ session: QuotaSession,
15
+ failure: HeadQuotaFailure,
16
+ signal: AbortSignal,
17
+ ): Promise<boolean> {
18
+ const { model, sessionId } = session;
19
+ if (!model || model.provider !== failure.model.provider || model.id !== failure.model.id) return false;
20
+ const { authStorage } = session.modelRegistry;
21
+ const { health, usage, sessions, oauth } = authStorage;
22
+ if (typeof health?.model !== "function" || typeof usage?.reports !== "function"
23
+ || typeof sessions?.permits !== "function" || typeof oauth?.accounts !== "function"
24
+ || typeof oauth?.policy !== "function") return false;
25
+ const { provider, id, baseUrl } = model;
26
+ // Native health supplies model scope, entitlement, reserves and credential
27
+ // blocks, but can use a stale last-good report after a failed usage read.
28
+ const availability = await health.model(provider, { modelId: id, baseUrl, sessionId, signal,
29
+ reserveFraction: cfgRetryUsageReservePct.get(session.settings) / 100 });
30
+ const eligible = availability.accounts.filter(account => account.credentialType === "oauth"
31
+ && account.state === "healthy" && account.remainingFraction !== undefined && account.remainingFraction > 0
32
+ && sessions.permits(provider, sessionId, account.credentialId));
33
+ if (!eligible.length) return false;
34
+ const reports = await usage.reports({ provider, baseUrlResolver: () => baseUrl, signal });
35
+ if (signal.aborted || session.sessionId !== sessionId || session.model !== model) return false;
36
+ const now = Date.now();
37
+ const accounts = oauth.accounts(provider, sessionId);
38
+ // Request auth looks up the current discovery roster, which can change
39
+ // without replacing the session's model object.
40
+ const accountAccess = session.modelRegistry.find(provider, id)?.accountAccess ?? model.accountAccess;
41
+ const spark = quotaTierFor(provider, id) === "spark";
42
+ const windowPrefix = spark ? `${provider}:spark:` : `${provider}:`;
43
+ return reports?.some(report => {
44
+ const { fetchedAt, metadata } = report;
45
+ if (report.provider !== provider || !Number.isFinite(fetchedAt) || fetchedAt <= failure.failedAt
46
+ || fetchedAt > now || now - fetchedAt > HEAD_QUOTA_CHECK_MS || !metadata
47
+ || metadata.source === "ratelimit-headers" || metadata.headersUpdatedAt !== undefined) return false;
48
+ const meters = metadata.meterStates;
49
+ const meter: unknown = spark
50
+ ? meters && typeof meters === "object" && "spark" in meters ? meters.spark : null
51
+ : metadata;
52
+ if (!meter || typeof meter !== "object" || !("allowed" in meter) || meter.allowed !== true
53
+ || !("limitReached" in meter) || meter.limitReached !== false) return false;
54
+ // The verdict can include credit-funded overage. Check actual headroom in
55
+ // this report, not just the potentially older snapshot used by model health.
56
+ const windows = report.limits.filter(limit =>
57
+ limit.id === `${windowPrefix}primary` || limit.id === `${windowPrefix}secondary`);
58
+ const limits = windows.length || spark ? windows : report.limits.filter(limit => limit.id === `${provider}:spend-cap`);
59
+ // Local reports carry the credential row. A broker may carry only the
60
+ // Codex account ID; accept it only if it maps to exactly one native row.
61
+ const accountId = metadata.accountId;
62
+ const matching = metadata.credentialId === undefined && typeof accountId === "string" && accountId
63
+ ? accounts.filter(account => account.accountId === accountId) : [];
64
+ const credentialId = metadata.credentialId ?? (matching.length === 1 ? matching[0]?.credentialId : undefined);
65
+ const account = accounts.find(candidate => candidate.credentialId === credentialId);
66
+ if (!account || !eligible.some(candidate => candidate.credentialId === account.credentialId)
67
+ || !sessions.permits(provider, sessionId, account.credentialId)) return false;
68
+ // Use the identity precedence ModelRegistry uses for its discovered account roster.
69
+ const accountKey = account.accountId ?? account.email ?? account.projectId;
70
+ if (accountAccess && (!accountKey || !Object.hasOwn(accountAccess, accountKey))) return false;
71
+ const reservePct = oauth.policy(provider, account)?.reservePct ?? cfgRetryUsageReservePct.get(session.settings);
72
+ const reserveFraction = Math.max(0, Math.min(100, reservePct)) / 100;
73
+ return limits.length > 0 && limits.every(limit => {
74
+ const used = limit.amount.usedFraction;
75
+ // Match native isWithinUsageReserve's float slack at the boundary.
76
+ return limit.status !== "exhausted" && typeof used === "number" && used >= 0
77
+ && 1 - used > reserveFraction + 1e-9;
78
+ });
79
+ }) ?? false;
80
+ }