omp-superagent 0.1.7 → 0.1.9

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 (122) hide show
  1. package/DESIGN.md +27 -16
  2. package/README.ko.md +40 -19
  3. package/README.md +43 -18
  4. package/THIRD_PARTY_NOTICES.md +11 -11
  5. package/config.example.json +2 -1
  6. package/docs/OPERATIONS.md +285 -85
  7. package/docs/design/execution.md +133 -24
  8. package/docs/design/messaging.md +235 -50
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.8.md +21 -0
  11. package/docs/releases/0.1.9.md +18 -0
  12. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  13. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  15. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  16. package/host-owner/bin/notices/darwin-arm64/Cargo-LICENSES.txt +2 -0
  17. package/host-owner/bin/notices/darwin-arm64/Cargo-SOURCES.txt +2 -0
  18. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  19. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  20. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  21. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  22. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  23. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  24. package/host-owner/bin/notices/darwin-x64/Cargo-LICENSES.txt +2 -0
  25. package/host-owner/bin/notices/darwin-x64/Cargo-SOURCES.txt +2 -0
  26. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  27. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  28. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  29. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  30. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  31. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  32. package/host-owner/bin/notices/linux-arm64/Cargo-LICENSES.txt +3 -0
  33. package/host-owner/bin/notices/linux-arm64/Cargo-SOURCES.txt +3 -0
  34. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  35. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  36. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  37. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  38. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  39. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  40. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  41. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  42. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  43. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  44. package/host-owner/bin/notices/linux-x64/Cargo-LICENSES.txt +3 -0
  45. package/host-owner/bin/notices/linux-x64/Cargo-SOURCES.txt +3 -0
  46. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  47. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  48. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  49. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  50. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  51. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  52. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  53. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  54. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  55. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  56. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  57. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  58. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  59. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  60. package/package.json +17 -15
  61. package/skills/head/SKILL.md +3 -11
  62. package/skills/head/references/routing.md +23 -17
  63. package/skills/head/references/supervision.md +13 -1
  64. package/skills/lane/references/workflow.md +8 -8
  65. package/src/cli.ts +6 -3
  66. package/src/config.ts +5 -0
  67. package/src/contracts.ts +95 -10
  68. package/src/cron-jobs.ts +443 -19
  69. package/src/cron-pr-intake.ts +257 -0
  70. package/src/discord-command-registration.ts +34 -186
  71. package/src/extension.ts +31 -3
  72. package/src/gateway-client.ts +11 -59
  73. package/src/gateway-protocol.ts +35 -1
  74. package/src/head-quota.ts +80 -0
  75. package/src/head-recovery.ts +249 -1
  76. package/src/host-extension.ts +194 -5
  77. package/src/host-protocol.ts +16 -9
  78. package/src/host-sdk-helper.ts +105 -10
  79. package/src/host.ts +111 -29
  80. package/src/installed-omp.ts +116 -4
  81. package/src/lane-models.ts +8 -0
  82. package/src/managed-ulw-probe.ts +22 -20
  83. package/src/managed-ulw.ts +137 -24
  84. package/src/messenger-command-catalog.json +6 -3
  85. package/src/messenger-commands.ts +9 -2
  86. package/src/native-presets.ts +32 -5
  87. package/src/omp-usage.ts +254 -36
  88. package/src/operator.ts +77 -0
  89. package/src/pr-github-schema.ts +2 -0
  90. package/src/pr-github.ts +4 -2
  91. package/src/pr-intake-automation.ts +315 -0
  92. package/src/pr-intake-comment.ts +225 -0
  93. package/src/pr-intake-fix.ts +232 -0
  94. package/src/pr-intake-github.ts +479 -0
  95. package/src/pr-intake-material.ts +229 -0
  96. package/src/pr-intake-mode.ts +59 -0
  97. package/src/pr-intake-review.ts +397 -0
  98. package/src/pr-intake-tree.ts +68 -0
  99. package/src/pr-intake-work.ts +29 -0
  100. package/src/pr-review-models.ts +28 -0
  101. package/src/result-attachment.ts +60 -79
  102. package/src/runtime.ts +2968 -449
  103. package/src/setup-profiles.ts +26 -65
  104. package/src/slack-command-registration.ts +48 -197
  105. package/src/store.ts +507 -87
  106. package/src/superkit-skills.ts +22 -0
  107. package/src/telegram-command-languages.json +17 -0
  108. package/src/telegram-command-registration.ts +32 -134
  109. package/src/topic-history.ts +30 -17
  110. package/src/worker-bridge.ts +21 -0
  111. package/src/worker-enrollment.ts +2 -1
  112. package/src/worker-host.ts +0 -24
  113. package/src/worker-serve-prepare.ts +19 -0
  114. package/src/worker-service.ts +51 -47
  115. package/scripts/ci.ts +0 -44
  116. package/scripts/release.ts +0 -112
  117. package/scripts/test-omp.sh +0 -43
  118. package/src/discord-commands.ts +0 -29
  119. package/src/discord-markdown.ts +0 -172
  120. package/src/slack-commands.ts +0 -18
  121. package/src/telegram-signal.ts +0 -14
  122. package/src/worker-stdio.ts +0 -61
@@ -1,112 +0,0 @@
1
- #!/usr/bin/env bun
2
- import { constants } from "node:fs";
3
- import { access, mkdir, mkdtempDisposable } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join, resolve } from "node:path";
6
-
7
- const root = resolve(import.meta.dir, "..");
8
- const [mode, ...extra] = process.argv.slice(2);
9
- if (extra.length || mode !== undefined && mode !== "--publish" && mode !== "--replace")
10
- throw new Error("Usage: bun run release [--publish|--replace]");
11
-
12
- async function run(command: string[]): Promise<string> {
13
- const child = Bun.spawn(command, { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "inherit" });
14
- const text = await new Response(child.stdout).text();
15
- if (await child.exited !== 0) throw new Error(`Command failed: ${command.join(" ")}`);
16
- return text.trim();
17
- }
18
-
19
- if (await run(["git", "status", "--porcelain"]))
20
- throw new Error("Release packaging requires a clean checkout; commit the intended release changes first");
21
- const { name, version } = JSON.parse(await run(["git", "show", "HEAD:package.json"])) as { name: string; version: string };
22
- const tag = `v${version}`;
23
- const revision = await run(["git", "rev-parse", "HEAD"]);
24
- if (mode !== undefined) {
25
- if (process.env.GITHUB_REF_TYPE !== "tag" || process.env.GITHUB_REF_NAME !== tag)
26
- throw new Error(`Publishing requires the ${tag} tag workflow`);
27
- if (await run(["git", "rev-parse", `${tag}^{commit}`]) !== revision)
28
- throw new Error("Release tag does not identify the checked-out commit");
29
- }
30
- if (mode === "--replace" && process.env.GITHUB_EVENT_NAME !== "workflow_dispatch")
31
- throw new Error("Replacing a release requires the manual tag workflow");
32
- const notes = join(root, "docs/releases", `${version}.md`);
33
- if (!await Bun.file(notes).exists()) throw new Error(`Missing release notes: ${notes}`);
34
- const directory = join(root, "dist");
35
- await mkdir(directory, { recursive: true });
36
- const sourceFilename = `${name}-${version}.tar.gz`;
37
- const packageFilename = `${name}-${version}.tgz`;
38
- const nativePlatforms = ["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"] as const;
39
- const nativePackages = [
40
- { directory: "host-owner", binary: "omp-host-owner" },
41
- { directory: "gateway", binary: "omp-gateway" },
42
- ] as const;
43
-
44
- async function verifyNativePayload(directory: string): Promise<void> {
45
- for (const pkg of nativePackages) {
46
- const binDir = join(directory, pkg.directory, "bin");
47
- for (const platform of nativePlatforms) {
48
- await access(join(binDir, `${pkg.binary}-${platform}`), constants.X_OK);
49
- const notices = join(binDir, "notices", platform);
50
- await access(join(notices, "Cargo-LICENSES.txt"));
51
- await access(join(notices, "Cargo-SOURCES.txt"));
52
- await access(join(notices, "rust", "COPYRIGHT-library.html"));
53
- await access(join(notices, "rust", "licenses"));
54
- }
55
- }
56
- }
57
-
58
- if (mode === undefined) {
59
- // Each target's CI runner builds both packages with --locked; the archive
60
- // job assembles those same outputs instead of rebuilding any one target.
61
- await verifyNativePayload(root);
62
- const archive = join(directory, sourceFilename);
63
- const sourcePrefix = `${name}-${version}/`;
64
- await run(["git", "archive", "--format=tar.gz", `--prefix=${sourcePrefix}`, `--output=${archive}`, revision]);
65
- const sources = new Set((await run(["tar", "-tzf", archive])).split("\n"));
66
- if (!sources.has(`${sourcePrefix}.cargo/config.toml`)) throw new Error("Source archive lacks .cargo/config.toml");
67
- for (const pkg of nativePackages) {
68
- const prefix = `${sourcePrefix}${pkg.directory}/`;
69
- for (const file of ["Cargo.toml", "Cargo.lock", "src/main.rs"]) {
70
- if (!sources.has(`${prefix}${file}`)) throw new Error(`Source archive lacks ${pkg.directory}/${file}`);
71
- }
72
- if ([...sources].some(file => file.startsWith(`${prefix}target/`) || file.startsWith(`${prefix}bin/`))) {
73
- throw new Error(`The source archive contains generated ${pkg.directory} artifacts`);
74
- }
75
- }
76
- const npmArchive = join(directory, packageFilename);
77
- await run([process.execPath, "pm", "pack", "--ignore-scripts", "--filename", npmArchive]);
78
- const files = (await run(["tar", "-tzf", npmArchive])).split("\n");
79
- for (const pkg of nativePackages) {
80
- const prefix = `package/${pkg.directory}/`;
81
- if (files.some(file => file.startsWith(prefix) && file !== prefix && !file.startsWith(`${prefix}bin/`))) {
82
- throw new Error(`Unexpected ${pkg.directory} build or source data in the npm tarball`);
83
- }
84
- }
85
- // Packlist checks alone cannot detect a packer that strips executable bits.
86
- await using unpacked = await mkdtempDisposable(join(tmpdir(), "omp-sa-pack-"));
87
- await run(["tar", "-xzf", npmArchive, "-C", unpacked.path]);
88
- await verifyNativePayload(join(unpacked.path, "package"));
89
- }
90
-
91
- const assets: string[] = [];
92
- for (const filename of [sourceFilename, packageFilename]) {
93
- const path = join(directory, filename);
94
- const digest = new Bun.CryptoHasher("sha256").update(await Bun.file(path).arrayBuffer()).digest("hex");
95
- const checksum = `${path}.sha256`;
96
- const contents = `${digest} ${filename}\n`;
97
- if (mode === undefined) await Bun.write(checksum, contents);
98
- else if (await Bun.file(checksum).text() !== contents) throw new Error(`Packaged asset checksum mismatch: ${filename}`);
99
- assets.push(path, checksum);
100
- }
101
- console.log(`${mode === undefined ? "Packaged" : "Verified staged release for"} ${revision}\n${assets.join("\n")}`);
102
- if (mode === "--publish") {
103
- console.log(await run(["gh", "release", "create", tag, ...assets,
104
- "--verify-tag", "--title", `${name} ${version}`, "--notes-file", notes]));
105
- } else if (mode === "--replace") {
106
- // Check the live tag, not just the checkout used by earlier CI jobs.
107
- const remote = await run(["git", "ls-remote", "origin", `refs/tags/${tag}`, `refs/tags/${tag}^{}`]);
108
- if (remote.split("\n").at(-1)?.split("\t")[0] !== revision)
109
- throw new Error("Remote release tag no longer identifies the verified commit");
110
- console.log(await run(["gh", "release", "upload", tag, ...assets, "--clobber"]));
111
- console.log(await run(["gh", "release", "edit", tag, "--verify-tag", "--notes-file", notes]));
112
- }
@@ -1,43 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Run CI with a stock release in a private directory, without replacing the user's OMP.
3
- set -euo pipefail
4
- cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.."
5
-
6
- if [[ $# -gt 1 || ${OMP_TEST_COMMAND+x} ]]; then
7
- echo 'Usage: bash scripts/test-omp.sh [release-tag]; use bun run test:ci for OMP_TEST_COMMAND overrides.' >&2
8
- exit 2
9
- fi
10
- tag=${1-"$(bun --no-env-file -p '"v" + require("./package.json").dependencies["@oh-my-pi/pi-coding-agent"]')"}
11
- if [[ ! $tag =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
12
- echo "Expected an exact OMP release tag; got '$tag'." >&2
13
- exit 2
14
- fi
15
- # Install dependencies and build both Superagent executables before the test CLI exists.
16
- bun install --frozen-lockfile
17
- platform=$(bun --no-env-file -p '`${process.platform}-${process.arch}`')
18
- for binary in "host-owner/bin/omp-host-owner-$platform" "gateway/bin/omp-gateway-$platform"; do
19
- if [[ ! -x $binary ]]; then
20
- echo "Source installation did not create an executable $binary." >&2
21
- exit 1
22
- fi
23
- done
24
- asset=$(bun --no-env-file -p '`omp-${process.platform}-${process.arch}`')
25
- directory=$(mktemp -d "${TMPDIR:-/tmp}/omp-sa-test-cli.XXXXXXXX")
26
- trap 'rm -rf -- "$directory"' EXIT
27
- url="https://github.com/can1357/oh-my-pi/releases/download/$tag"
28
- echo "Testing stock OMP $tag ($asset)"
29
- for file in SHA256SUMS.txt "$asset"; do
30
- curl --fail --silent --show-error --location "$url/$file" --output "$directory/$file"
31
- done
32
- (
33
- cd -- "$directory"
34
- grep -E "^[[:xdigit:]]{64} $asset\$" SHA256SUMS.txt | shasum -a 256 -c -
35
- mv -- "$asset" omp
36
- chmod 700 omp
37
- )
38
- actual=$("$directory/omp" --version)
39
- if [[ $actual != "omp/${tag#v}" ]]; then
40
- echo "OMP release $tag reported '$actual'; refusing to test a different version." >&2
41
- exit 1
42
- fi
43
- PATH="$directory:$PATH" bun run test:ci
@@ -1,29 +0,0 @@
1
- import {
2
- ApplicationCommandOptionType, ApplicationCommandType, ApplicationIntegrationType, InteractionContextType,
3
- type RESTPostAPIChatInputApplicationCommandsJSONBody,
4
- } from "discord.js";
5
- import { MESSENGER_COMMANDS } from "./messenger-commands";
6
-
7
- /** The complete supported slash-command picker, also used for registration. */
8
- export const DISCORD_COMMANDS: readonly RESTPostAPIChatInputApplicationCommandsJSONBody[] = MESSENGER_COMMANDS.map(
9
- (command): RESTPostAPIChatInputApplicationCommandsJSONBody => ({
10
- type: ApplicationCommandType.ChatInput, name: command.name, description: command.description,
11
- contexts: [InteractionContextType.Guild, InteractionContextType.BotDM],
12
- integration_types: [ApplicationIntegrationType.GuildInstall],
13
- ...(command.text !== undefined ? { options: [{ type: ApplicationCommandOptionType.String, name: "text", description: command.text, required: false }] } : {}),
14
- }));
15
-
16
- /** Reject stale registrations/options instead of silently executing a different command. */
17
- export function parseDiscordCommand(name: string, options: unknown): string | null {
18
- const command = DISCORD_COMMANDS.find(command => command.name === name);
19
- if (!command || !Array.isArray(options)) return null;
20
- if (options.length === 0) return `/${name}`;
21
- if (!command.options?.length || options.length !== 1) return null;
22
- const option: unknown = options[0];
23
- if (!option || typeof option !== "object" || Array.isArray(option)) return null;
24
- const value = option as Record<string, unknown>;
25
- if (Object.keys(value).some(key => key !== "name" && key !== "type" && key !== "value") ||
26
- value.name !== "text" || value.type !== ApplicationCommandOptionType.String || typeof value.value !== "string") return null;
27
- const text = value.value.trim();
28
- return `/${name}${text ? ` ${text}` : ""}`;
29
- }
@@ -1,172 +0,0 @@
1
- /**
2
- * Markdown table rendering for the Discord transport.
3
- *
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.
11
- */
12
-
13
- type Align = "left" | "center" | "right";
14
-
15
- const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})/;
16
- const FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})[ \t\r]*$/;
17
- const BLOCK_START = /^ {0,3}(?:>|#{1,6}(?:[ \t]|$)|(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$))/;
18
- const DELIMITER_CELL = /^:?-+:?$/;
19
-
20
- /**
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.
25
- */
26
- function splitRow(line: string): string[] | null {
27
- const cells: string[] = [];
28
- let cell = "";
29
- let pipe = false;
30
- let leading = false;
31
- let tick = 0;
32
- 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 += "|";
38
- 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() === "";
51
- pipe = true;
52
- cells.push(cell);
53
- cell = "";
54
- continue;
55
- }
56
- cell += char;
57
- }
58
- 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;
63
- }
64
-
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");
75
- }
76
- return aligns;
77
- }
78
-
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);
88
- }
89
-
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);
93
- 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]!));
96
- }
97
- }
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);
106
- }
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 };
117
- }
118
-
119
- /**
120
- * Rewrite markdown pipe tables as aligned fenced blocks.
121
- *
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.
127
- */
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");
133
- const out: string[] = [];
134
- let fence: { char: string; length: number } | null = null;
135
- for (let index = 0; index < lines.length; index++) {
136
- const line = lines[index]!;
137
- const marker = FENCE_OPEN.exec(line)?.[1];
138
- if (fence) {
139
- 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
- continue;
143
- }
144
- if (marker) {
145
- fence = { char: marker[0]!, length: marker.length };
146
- out.push(line);
147
- continue;
148
- }
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;
154
- }
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");
164
- }
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;
170
- }
171
- return out.join("\n");
172
- }
@@ -1,18 +0,0 @@
1
- import { MESSENGER_COMMANDS } from "./messenger-commands";
2
-
3
- /** Slack reserves /help and /status, so every supported picker entry is namespaced. */
4
- export const SLACK_COMMANDS = MESSENGER_COMMANDS.map(command => ({
5
- command: `/superagent-${command.name}`,
6
- description: command.description,
7
- ...(command.text !== undefined ? { usage_hint: command.text } : {}),
8
- should_escape: false,
9
- }));
10
-
11
- /** Only registered names are accepted; invalid no-argument invocations are not commands. */
12
- export function parseSlackCommand(name: string, text: string): string | null {
13
- const command = MESSENGER_COMMANDS.find(command => name === `/superagent-${command.name}`);
14
- if (!command) return null;
15
- const argument = text.trim();
16
- if (argument && command.text === undefined) return null;
17
- return `/${command.name}${argument ? ` ${argument}` : ""}`;
18
- }
@@ -1,14 +0,0 @@
1
- import { AbortController as ApiAbortController, type AbortSignal as ApiAbortSignal } from "abort-controller";
2
-
3
- /** grammY's Node entrypoint requires its SDK signal; keep caller cancellation scoped to the API call. */
4
- export async function withTelegramSignal<T>(
5
- signal: AbortSignal | undefined, call: (signal: ApiAbortSignal | undefined) => Promise<T>,
6
- ): Promise<T> {
7
- if (!signal) return call(undefined);
8
- const controller = new ApiAbortController();
9
- const abort = () => controller.abort();
10
- signal.addEventListener("abort", abort, { once: true });
11
- if (signal.aborted) abort();
12
- try { return await call(controller.signal); }
13
- finally { signal.removeEventListener("abort", abort); }
14
- }
@@ -1,61 +0,0 @@
1
- import type { Socket } from "node:net";
2
- import type { Readable, Writable } from "node:stream";
3
- import { WorkerRefusal } from "./worker-request";
4
- import { WORKER_HEADER_BYTES } from "./worker-wire";
5
-
6
- export function workerHeader(input: Readable): Promise<Buffer> {
7
- return new Promise((resolve, reject) => {
8
- const chunks: Buffer[] = [];
9
- let length = 0;
10
- const stop = () => {
11
- clearTimeout(timer);
12
- input.off("readable", read).off("end", closed).off("close", closed).off("error", fail);
13
- };
14
- const fail = (error: Error) => { stop(); reject(error); };
15
- const closed = () => fail(new WorkerRefusal("Worker request ended before its header"));
16
- const read = () => {
17
- let chunk: Buffer | null;
18
- while ((chunk = input.read()) !== null) {
19
- const end = chunk.indexOf(10);
20
- length += end < 0 ? chunk.length : end + 1;
21
- if (length > WORKER_HEADER_BYTES) { fail(new WorkerRefusal("Worker request exceeds header limit")); return; }
22
- chunks.push(end < 0 ? chunk : chunk.subarray(0, end));
23
- if (end < 0) continue;
24
- stop();
25
- if (end + 1 < chunk.length) input.unshift(chunk.subarray(end + 1));
26
- resolve(Buffer.concat(chunks, length - 1));
27
- return;
28
- }
29
- };
30
- const timer = setTimeout(() => fail(new WorkerRefusal("Worker request header timed out")), 10_000);
31
- input.once("end", closed).once("close", closed).once("error", fail).on("readable", read);
32
- });
33
- }
34
-
35
- export function workerReply(output: Writable, reply: { readonly ok: true; readonly value: unknown } | { readonly ok: false; readonly error: string }): Promise<void> {
36
- const line = `${JSON.stringify(reply)}\n`;
37
- const framed = Buffer.byteLength(line) <= WORKER_HEADER_BYTES ? line
38
- : `${JSON.stringify({ ok: false, error: "Worker response exceeds header limit" })}\n`;
39
- return new Promise((resolve, reject) => output.write(framed, error => error ? reject(error) : resolve()));
40
- }
41
-
42
- /** An EOF on either transport detaches only this client. It is not a native exit receipt. */
43
- export async function bridgeWorker(input: Readable, output: Writable, socket: Socket): Promise<void> {
44
- const { promise, resolve } = Promise.withResolvers<void>();
45
- const detach = () => resolve();
46
- input.once("end", detach).once("close", detach).once("error", detach);
47
- output.once("close", detach).once("error", detach);
48
- socket.once("close", detach).once("error", detach);
49
- try {
50
- if (input.destroyed || input.readableEnded || output.destroyed || socket.destroyed) return;
51
- socket.pipe(output, { end: false });
52
- input.pipe(socket, { end: false });
53
- await promise;
54
- } finally {
55
- input.unpipe(socket).pause();
56
- socket.unpipe(output).destroy();
57
- input.off("end", detach).off("close", detach).off("error", detach);
58
- output.off("close", detach).off("error", detach);
59
- socket.off("close", detach).off("error", detach);
60
- }
61
- }