From 811042f7c953916574aaab32abb696cb2e393c46 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Wed, 18 Nov 2026 13:03:56 -0800 Subject: [PATCH 1/6] Never cut text mid-emoji before agents or notifications Raw UTF-16 .slice/.substring caps left a lone surrogate whenever an emoji straddled the cut. bb then sent that text into agent turns and instructions: Codex's JSON-RPC parser rejects the escaped lone surrogate and drops the message, so thread/start never answers and the thread fails after 60s. - Cut text with sliceUtf16Head/sliceUtf16Tail at every length cap (child output, plugin instructions, restart-resume notes, push notifications, terminal titles, tool results, status messages, ...). Forkable plugins carry a local copy since they cannot import @bb/text-utils. - Replace lone surrogates with U+FFFD where JSON-RPC leaves the runtime for a provider bridge, the Codex app-server, and ACP agents. - Add bb/no-raw-text-truncation to oxlint so new raw text caps fail lint. - Bump @get-bb/plugin-sdk to 0.6.159 (bundled bridge code changed). Co-Authored-By: Claude Opus 5.5 --- .oxlintrc.json | 12 +- .../provider-cli-install-failure.ts | 3 +- .../secondary-panel/BrowserTabContent.tsx | 6 +- .../timeline/GeneratedConversationMessage.tsx | 5 +- .../src/views/root-compose-initial-prompt.ts | 3 +- apps/cli/src/commands/plugin.ts | 3 +- apps/connect-next/src/mcp.ts | 10 +- apps/connect/src/machine-label.ts | 23 +- apps/connect/src/mcp-gate.ts | 10 +- apps/demo-server/package.json | 1 + apps/demo-server/src/demo-world.ts | 11 +- apps/desktop/src/browser-import/discovery.ts | 5 +- .../desktop/src/connect-machine-enrollment.ts | 11 +- .../src/desktop-browser-broker-client.ts | 3 +- apps/desktop/src/desktop-browser-view.ts | 3 +- apps/desktop/src/server-target.ts | 10 +- .../src/command-handlers/project.ts | 16 +- apps/host-daemon/src/enroll.ts | 3 +- apps/mobile/package.json | 1 + apps/mobile/src/lib/device-label.ts | 3 +- .../src/assets/install-machine-windows.mjs | 6 +- apps/server/src/services/desktop-browsers.ts | 3 +- .../environments/environment-engine.ts | 5 +- .../machines/provider-orchestration.ts | 14 +- .../src/services/plugins/install-sources.ts | 7 +- .../src/services/plugins/plugin-service.ts | 5 +- .../providers/provider-model-catalog-store.ts | 3 +- .../src/services/skills/registry-parse.ts | 6 +- .../services/skills/registry-skill-install.ts | 3 +- .../src/services/system/query-plan-audit.ts | 6 +- .../terminals/terminal-session-lifecycle.ts | 3 +- .../threads/child-thread-notifications.ts | 3 +- .../src/services/threads/restart-resume.ts | 3 +- .../services/threads/thread-runtime-config.ts | 5 +- .../src/services/threads/title-generation.ts | 18 +- .../child-thread-notifications.test.ts | 19 ++ .../test/threads/restart-resume.test.ts | 23 ++ .../threads/thread-runtime-config.test.ts | 46 ++++ apps/web/package.json | 1 + apps/web/src/landing/endpoints.ts | 7 +- apps/web/src/marketplace/marketplace-og.tsx | 5 +- apps/web/src/server/account.ts | 3 +- apps/web/src/server/oauth.ts | 10 +- packages/agent-runtime/package.json | 1 + .../src/runtime-provider-process.ts | 9 +- .../timeline/conversation-message-limits.ts | 6 +- packages/db/src/connection.ts | 5 +- packages/db/src/query-plan-test-guard.ts | 3 +- packages/domain/package.json | 1 + packages/domain/src/legacy-thread-events.ts | 3 +- packages/frp-client/package.json | 1 + packages/frp-client/src/supervisor.ts | 3 +- packages/plugin-build/package.json | 1 + .../src/scope-plugin-utilities.ts | 3 +- packages/plugin-sdk/package.json | 1 + .../plugin-sdk/src/internal/host-policy.ts | 13 +- packages/provider-bridge-acp/package.json | 1 + .../src/client/message-stream.ts | 3 +- .../src/tool-classification.ts | 3 +- .../src/bridge-kit/runtime-json-rpc.test.ts | 40 +++ .../src/bridge-kit/runtime-json-rpc.ts | 50 ++-- .../src/conformance/scenarios.ts | 3 +- .../test/no-raw-text-truncation.test.mjs | 83 ++++++ packages/text-utils/src/utf16.ts | 6 + packages/text-utils/test/utf16.test.ts | 13 + .../thread-view/src/item-record-messages.ts | 3 +- plugins/account-pool/src/hub.ts | 8 +- plugins/agent-annotations/page-script.ts | 55 ++-- plugins/ask-user-question/src/translate.ts | 8 +- plugins/automations/src/script-runner.ts | 8 +- plugins/bb-account/package.json | 1 + plugins/bb-account/src/plugin.ts | 3 +- plugins/browser-automation/app.tsx | 3 +- plugins/browser-automation/installer.ts | 5 +- plugins/browser-automation/preview.ts | 9 +- plugins/browser-automation/runtime.ts | 3 +- plugins/browser-automation/utf16.ts | 11 + plugins/concurrency-limit/server.ts | 8 +- plugins/connect/package.json | 1 + plugins/connect/src/machine-code.ts | 3 +- plugins/docs/server.ts | 64 +++-- .../environment-git-worktree/host/paths.ts | 15 +- plugins/github/server.ts | 8 +- plugins/mcp/src/tools.ts | 8 +- plugins/prompt-library/ranking.ts | 19 +- .../src/bridge/provider-commands.ts | 3 +- .../provider-claude-code/src/interactions.ts | 3 +- plugins/provider-claude-code/src/utf16.ts | 5 + .../provider-codex/src/ai/chatgpt-client.ts | 3 +- .../src/bridge/app-server-connection.ts | 3 +- plugins/provider-codex/src/utf16.ts | 13 + .../notification-text.test.ts | 13 + .../push-notifications/notification-text.ts | 8 +- plugins/secrets/src/server.ts | 8 +- pnpm-lock.yaml | 33 +++ scripts/oxlint-plugin.mjs | 247 ++++++++++++++++++ 96 files changed, 961 insertions(+), 219 deletions(-) create mode 100644 packages/scripts/test/no-raw-text-truncation.test.mjs create mode 100644 plugins/browser-automation/utf16.ts create mode 100644 plugins/provider-claude-code/src/utf16.ts create mode 100644 plugins/provider-codex/src/utf16.ts create mode 100644 plugins/push-notifications/notification-text.test.ts diff --git a/.oxlintrc.json b/.oxlintrc.json index 71ec348b1c6..5700f220a8c 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -9,7 +9,8 @@ "builtin": true }, "rules": { - "bb/no-comments": "error" + "bb/no-comments": "error", + "bb/no-raw-text-truncation": "error" }, "ignorePatterns": [ "**/node_modules/**", @@ -152,7 +153,14 @@ ], "rules": { "no-restricted-imports": "off", - "bb/no-blocking-child-process-call": "off" + "bb/no-blocking-child-process-call": "off", + "bb/no-raw-text-truncation": "off" + } + }, + { + "files": ["**/test/**", "**/testing/**"], + "rules": { + "bb/no-raw-text-truncation": "off" } }, { diff --git a/apps/app/src/components/provider-cli/provider-cli-install-failure.ts b/apps/app/src/components/provider-cli/provider-cli-install-failure.ts index e99fce0af8c..f3a5619aabc 100644 --- a/apps/app/src/components/provider-cli/provider-cli-install-failure.ts +++ b/apps/app/src/components/provider-cli/provider-cli-install-failure.ts @@ -1,4 +1,5 @@ import type { OnboardingFailureDetail } from "@bb/server-contract"; +import { sliceUtf16Tail } from "@bb/text-utils"; const CLASSIFIED_OUTPUT_TAIL_CHARS = 64 * 1024; const ANSI_ESCAPE_PATTERN = /\x1b\[[0-9;?]*[A-Za-z]/gu; @@ -41,7 +42,7 @@ export function classifyProviderCliInstallFailure(args: { } } const output = - `${args.output.slice(-CLASSIFIED_OUTPUT_TAIL_CHARS)}\n${errorMessage ?? ""}`.replace( + `${sliceUtf16Tail(args.output, CLASSIFIED_OUTPUT_TAIL_CHARS)}\n${errorMessage ?? ""}`.replace( ANSI_ESCAPE_PATTERN, "", ); diff --git a/apps/app/src/components/secondary-panel/BrowserTabContent.tsx b/apps/app/src/components/secondary-panel/BrowserTabContent.tsx index 76c8c48516e..40feb695bd4 100644 --- a/apps/app/src/components/secondary-panel/BrowserTabContent.tsx +++ b/apps/app/src/components/secondary-panel/BrowserTabContent.tsx @@ -68,6 +68,7 @@ import { import { isLocalOnlyUrl } from "@/lib/loopback-hostname"; import { PluginBrowserToolbarActions } from "@/components/plugin/PluginBrowserToolbarActions"; import { isImeComposing, isNonImeKey } from "@bb/shared-ui/lib/ime-keyboard"; +import { sliceUtf16Head } from "@bb/text-utils"; interface BrowserTabContentProps { tabId: string; @@ -973,7 +974,10 @@ export function BrowserTabContent({ const handleFindQueryChange = useCallback( (rawQuery: string) => { - const query = rawQuery.slice(0, BB_DESKTOP_BROWSER_MAX_FIND_TEXT_LENGTH); + const query = sliceUtf16Head( + rawQuery, + BB_DESKTOP_BROWSER_MAX_FIND_TEXT_LENGTH, + ); setFindQuery(query); if (query.length === 0) { clearFind(); diff --git a/apps/app/src/components/thread/timeline/GeneratedConversationMessage.tsx b/apps/app/src/components/thread/timeline/GeneratedConversationMessage.tsx index b48dd606a3c..0021c0a8500 100644 --- a/apps/app/src/components/thread/timeline/GeneratedConversationMessage.tsx +++ b/apps/app/src/components/thread/timeline/GeneratedConversationMessage.tsx @@ -48,6 +48,7 @@ import { GENERATED_MESSAGE_COLLAPSED_PREVIEW_CHAR_CAP, } from "@bb/client-core"; import { isNonImeKey } from "@bb/shared-ui/lib/ime-keyboard"; +import { sliceUtf16Head } from "@bb/text-utils"; interface AutomationLink { automationId: string; @@ -135,8 +136,8 @@ export function generatedConversationBodySlice({ export function generatedConversationCollapsedPreview( text: string, ): GeneratedConversationCollapsedPreview { - const previewWindow = text.slice( - 0, + const previewWindow = sliceUtf16Head( + text, GENERATED_MESSAGE_COLLAPSED_PREVIEW_CHAR_CAP + 1, ); const lineBreakMatch = /\r\n|\r|\n/u.exec(previewWindow); diff --git a/apps/app/src/views/root-compose-initial-prompt.ts b/apps/app/src/views/root-compose-initial-prompt.ts index 7cb5f0fb38d..661d2231648 100644 --- a/apps/app/src/views/root-compose-initial-prompt.ts +++ b/apps/app/src/views/root-compose-initial-prompt.ts @@ -1,3 +1,4 @@ +import { sliceUtf16Head } from "@bb/text-utils"; export const INITIAL_PROMPT_MAX_LENGTH = 8000; export const INITIAL_PROMPT_SEARCH_PARAM = "initialPrompt"; @@ -13,7 +14,7 @@ export function readInitialPromptFromSearch(search: string): string | null { if (raw === null) return null; const trimmed = raw.trim(); if (trimmed.length === 0) return null; - return trimmed.slice(0, INITIAL_PROMPT_MAX_LENGTH); + return sliceUtf16Head(trimmed, INITIAL_PROMPT_MAX_LENGTH); } export function stripInitialPromptFromSearch(search: string): string { diff --git a/apps/cli/src/commands/plugin.ts b/apps/cli/src/commands/plugin.ts index 02a602676a3..6e884b09097 100644 --- a/apps/cli/src/commands/plugin.ts +++ b/apps/cli/src/commands/plugin.ts @@ -52,6 +52,7 @@ import { resolveBbCliVersion } from "../version.js"; import { outputJson, type JsonOutputOptions } from "./helpers.js"; import { renderBorderlessTable } from "../table.js"; +import { sliceUtf16Head } from "@bb/text-utils"; interface NewPluginTarget { packageName: string; @@ -500,7 +501,7 @@ async function callPlugins( parsed = text ? JSON.parse(text) : {}; } catch { throw new Error( - `Unexpected response from /api/v1/plugins${path} (${response.status}): ${text.slice(0, 200)}`, + `Unexpected response from /api/v1/plugins${path} (${response.status}): ${sliceUtf16Head(text, 200)}`, ); } if (!response.ok && ![400, 404, 422].includes(response.status)) { diff --git a/apps/connect-next/src/mcp.ts b/apps/connect-next/src/mcp.ts index 43db19499b1..912d6b7dd6b 100644 --- a/apps/connect-next/src/mcp.ts +++ b/apps/connect-next/src/mcp.ts @@ -5,6 +5,7 @@ import { mcpResourceForOrigin, } from "@bb/connect-db"; import { json, type Reply } from "./reply.js"; +import { sliceUtf16Head } from "@bb/text-utils"; const MCP_CLIENT_NAME_HEADER_MAX_LENGTH = 80; const MCP_PATH_DECODE_ROUNDS = 4; @@ -81,11 +82,10 @@ export function mcpChallengeReply( } export function headerSafeClientName(value: string): string { - const safe = value - .replace(/[^\x20-\x7e]/gu, "?") - .trim() - .slice(0, MCP_CLIENT_NAME_HEADER_MAX_LENGTH) - .trim(); + const safe = sliceUtf16Head( + value.replace(/[^\x20-\x7e]/gu, "?").trim(), + MCP_CLIENT_NAME_HEADER_MAX_LENGTH, + ).trim(); return safe === "" ? "unknown" : safe; } diff --git a/apps/connect/src/machine-label.ts b/apps/connect/src/machine-label.ts index 9c3005bf699..3637b569856 100644 --- a/apps/connect/src/machine-label.ts +++ b/apps/connect/src/machine-label.ts @@ -12,6 +12,7 @@ import { verifyMachineCredentialDetails } from "./session.js"; import { methodNotAllowed } from "./json-response.js"; import { MACHINE_CREDENTIAL_HEADER } from "./protocol-headers.js"; import type { Env } from "./tunnel-do.js"; +import { sliceUtf16Head } from "@bb/text-utils"; function fallbackLabel(machineId: string): string { const idPrefix = machineId @@ -25,13 +26,14 @@ export function sanitizeMachineLabelBase( desiredName: string, machineId: string, ): string { - const label = desiredName - .trim() - .toLowerCase() - .replace(/[^a-z0-9]+/gu, "-") - .replace(/^-+|-+$/gu, "") - .slice(0, HANDLE_MAX_LENGTH) - .replace(/-+$/gu, ""); + const label = sliceUtf16Head( + desiredName + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/gu, "-") + .replace(/^-+|-+$/gu, ""), + HANDLE_MAX_LENGTH, + ).replace(/-+$/gu, ""); return label.length > 0 && validateLabel(label) === null ? label : fallbackLabel(machineId); @@ -40,9 +42,10 @@ export function sanitizeMachineLabelBase( function labelWithSuffix(base: string, ordinal: number): string { if (ordinal === 1) return base; const suffix = `-${ordinal}`; - const stem = base - .slice(0, HANDLE_MAX_LENGTH - suffix.length) - .replace(/-+$/gu, ""); + const stem = sliceUtf16Head(base, HANDLE_MAX_LENGTH - suffix.length).replace( + /-+$/gu, + "", + ); return `${stem}${suffix}`; } diff --git a/apps/connect/src/mcp-gate.ts b/apps/connect/src/mcp-gate.ts index 5c45bd43002..3df8a3712f3 100644 --- a/apps/connect/src/mcp-gate.ts +++ b/apps/connect/src/mcp-gate.ts @@ -12,6 +12,7 @@ import { first, } from "@bb/connect-db"; import { SettledLookupCache } from "./session.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export const MCP_GRANT_CACHE_TTL_MS = 30_000; const MCP_CLIENT_NAME_HEADER_MAX_LENGTH = 80; @@ -110,11 +111,10 @@ export function mcpChallengeResponse( } export function headerSafeClientName(value: string): string { - const safe = value - .replace(/[^\x20-\x7e]/gu, "?") - .trim() - .slice(0, MCP_CLIENT_NAME_HEADER_MAX_LENGTH) - .trim(); + const safe = sliceUtf16Head( + value.replace(/[^\x20-\x7e]/gu, "?").trim(), + MCP_CLIENT_NAME_HEADER_MAX_LENGTH, + ).trim(); return safe === "" ? "unknown" : safe; } diff --git a/apps/demo-server/package.json b/apps/demo-server/package.json index 2fff8ed5b68..503e63c2527 100644 --- a/apps/demo-server/package.json +++ b/apps/demo-server/package.json @@ -14,6 +14,7 @@ "dependencies": { "@bb/domain": "workspace:*", "@bb/server-contract": "workspace:*", + "@bb/text-utils": "workspace:*", "zod": "^4.6.7" }, "devDependencies": { diff --git a/apps/demo-server/src/demo-world.ts b/apps/demo-server/src/demo-world.ts index de4ff78a5e3..6def8dbcf43 100644 --- a/apps/demo-server/src/demo-world.ts +++ b/apps/demo-server/src/demo-world.ts @@ -57,6 +57,7 @@ import { threadResponse, type DemoThreadView, } from "./fixtures/world.js"; +import { sliceUtf16Head } from "@bb/text-utils"; const SYSTEM_CONFIG = systemConfigResponseSchema.parse({ ...configFixture, @@ -147,10 +148,12 @@ async function readJson(request: Request): Promise { } function promptText(input: readonly PromptInput[]): string { - return input - .flatMap((part) => (part.type === "text" ? [part.text] : [])) - .join("\n") - .slice(0, MAX_MESSAGE_CHARS); + return sliceUtf16Head( + input + .flatMap((part) => (part.type === "text" ? [part.text] : [])) + .join("\n"), + MAX_MESSAGE_CHARS, + ); } function uiPreferenceEntry(key: Key) { diff --git a/apps/desktop/src/browser-import/discovery.ts b/apps/desktop/src/browser-import/discovery.ts index 352c000d5f6..0ac2ff3857b 100644 --- a/apps/desktop/src/browser-import/discovery.ts +++ b/apps/desktop/src/browser-import/discovery.ts @@ -23,6 +23,7 @@ import { type BrowserImportPathContext, type BrowserImportSourceDefinition, } from "./sources.js"; +import { sliceUtf16Head } from "@bb/text-utils"; const MAX_DIRECTORIES = 2_000; const MAX_SOURCES = 100; @@ -239,7 +240,7 @@ async function detectProfiles( continue; if (detectCookieStorage(path) !== format) continue; claimed.add(actual); - found.push({ ...profile, name: profile.name.slice(0, 256) }); + found.push({ ...profile, name: sliceUtf16Head(profile.name, 256) }); break; } if (found.length >= MAX_PROFILES) break; @@ -308,7 +309,7 @@ export async function discoverBrowserImportSources( const name = known?.name ?? directoryName; sources.push({ id: `storage-${createHash("sha256").update(`${engine}\0${root}`).digest("hex")}`, - name: `${name.slice(0, 48)} (${engine === "chromium" ? "Chromium" : "Firefox"})`, + name: `${sliceUtf16Head(name, 48)} (${engine === "chromium" ? "Chromium" : "Firefox"})`, engine, platforms: [context.platform], userDataDirectory: () => root, diff --git a/apps/desktop/src/connect-machine-enrollment.ts b/apps/desktop/src/connect-machine-enrollment.ts index 440eac4675e..47a81355c26 100644 --- a/apps/desktop/src/connect-machine-enrollment.ts +++ b/apps/desktop/src/connect-machine-enrollment.ts @@ -6,6 +6,7 @@ import { redeemMachineCredential, type ConnectCredential, } from "@bb/connect-client"; +import { sliceUtf16Head } from "@bb/text-utils"; const CREATE_MACHINE_CODE_RPC = "createMachineCode"; @@ -58,10 +59,12 @@ function redeemFailureCode( } function desktopDeviceName(): string | undefined { - const name = hostname() - .replace(/\.local$/u, "") - .trim() - .slice(0, 128); + const name = sliceUtf16Head( + hostname() + .replace(/\.local$/u, "") + .trim(), + 128, + ); return name.length > 0 ? name : undefined; } diff --git a/apps/desktop/src/desktop-browser-broker-client.ts b/apps/desktop/src/desktop-browser-broker-client.ts index c4e31009832..9f0d22e7d15 100644 --- a/apps/desktop/src/desktop-browser-broker-client.ts +++ b/apps/desktop/src/desktop-browser-broker-client.ts @@ -11,6 +11,7 @@ import { desktopBrowserResultSchemas, } from "@bb/host-daemon-contract"; import type { DesktopBrowserBroker } from "./desktop-browser-broker.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export function isTrustedBrokerDescriptorFile(args: { isFile: boolean; @@ -259,7 +260,7 @@ export function createDesktopBrowserBrokerClient(args: { requestId: parsed.requestId, message: error instanceof Error - ? error.message.slice(0, 8192) + ? sliceUtf16Head(error.message, 8192) : "Desktop browser operation failed", }), ); diff --git a/apps/desktop/src/desktop-browser-view.ts b/apps/desktop/src/desktop-browser-view.ts index 5a373b04583..2b441e9814a 100644 --- a/apps/desktop/src/desktop-browser-view.ts +++ b/apps/desktop/src/desktop-browser-view.ts @@ -66,6 +66,7 @@ import { evaluatePopupRate, isAllowedBrowserUrl, } from "./desktop-browser-policy.js"; +import { sliceUtf16Head } from "@bb/text-utils"; const HIDDEN_PAGE_LIMIT = 4; const HIDDEN_PAGE_IDLE_MS = 5 * 60_000; @@ -88,7 +89,7 @@ const RENDERER_RECOVERY_DELAY_MS = 250; const RENDERER_RECOVERY_MAX_ATTEMPTS = 2; function truncate(value: string, max: number): string { - return value.length > max ? value.slice(0, max) : value; + return sliceUtf16Head(value, max); } function clampPopupDimension( diff --git a/apps/desktop/src/server-target.ts b/apps/desktop/src/server-target.ts index c6257b81ff6..0a86af73012 100644 --- a/apps/desktop/src/server-target.ts +++ b/apps/desktop/src/server-target.ts @@ -1,6 +1,7 @@ import { mkdir, readFile, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; import { z } from "zod"; +import { sliceUtf16Head } from "@bb/text-utils"; export const SERVER_TARGET_FILE_NAME = "server-target.json"; export const MAX_SERVER_NAME_LENGTH = 64; @@ -88,11 +89,10 @@ const persistedServerTargetSchema = z.looseObject({ type PersistedServerTarget = z.infer; export function normalizeServerName(rawName: string): string | null { - const name = rawName - .trim() - .replace(/\s+/gu, " ") - .slice(0, MAX_SERVER_NAME_LENGTH) - .trimEnd(); + const name = sliceUtf16Head( + rawName.trim().replace(/\s+/gu, " "), + MAX_SERVER_NAME_LENGTH, + ).trimEnd(); return name.length === 0 ? null : name; } diff --git a/apps/host-daemon/src/command-handlers/project.ts b/apps/host-daemon/src/command-handlers/project.ts index 59f294c3770..71f3f100e30 100644 --- a/apps/host-daemon/src/command-handlers/project.ts +++ b/apps/host-daemon/src/command-handlers/project.ts @@ -6,17 +6,19 @@ import { runGit, WorkspaceError, } from "bb-environment-provider-host/workspace-git"; +import { sliceUtf16Head } from "@bb/text-utils"; const PROJECT_CLONE_TIMEOUT_MS = 20 * 60 * 1000; function normalizeProjectSlug(value: string): string { - const slug = value - .trim() - .toLowerCase() - .replace(/[^a-z0-9]+/gu, "-") - .replace(/^-+|-+$/gu, "") - .slice(0, 80) - .replace(/-+$/u, ""); + const slug = sliceUtf16Head( + value + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/gu, "-") + .replace(/^-+|-+$/gu, ""), + 80, + ).replace(/-+$/u, ""); return slug || "project"; } diff --git a/apps/host-daemon/src/enroll.ts b/apps/host-daemon/src/enroll.ts index 1eba063fe70..bfd8ba1684d 100644 --- a/apps/host-daemon/src/enroll.ts +++ b/apps/host-daemon/src/enroll.ts @@ -1,4 +1,5 @@ import { hostDaemonEnrollResponseSchema } from "@bb/host-daemon-contract"; +import { sliceUtf16Head } from "@bb/text-utils"; interface EnrollHostArgs { fetchFn?: typeof fetch; @@ -23,7 +24,7 @@ function summarizeErrorDetail(detail: string): string { if (compact.length <= 200) { return compact; } - return `${compact.slice(0, 197)}...`; + return `${sliceUtf16Head(compact, 197)}...`; } export async function enrollDaemonHost( diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 1a247c00176..aa4be9ec343 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -26,6 +26,7 @@ "@bb/mobile-bridge": "workspace:*", "@bb/sdk": "workspace:*", "@bb/server-contract": "workspace:*", + "@bb/text-utils": "workspace:*", "@expo/ui": "58.0.27", "@gorhom/bottom-sheet": "^5.2.14", "@hugeicons/core-free-icons": "~4.3.4", diff --git a/apps/mobile/src/lib/device-label.ts b/apps/mobile/src/lib/device-label.ts index c1735bdbcba..1d818215d09 100644 --- a/apps/mobile/src/lib/device-label.ts +++ b/apps/mobile/src/lib/device-label.ts @@ -1,8 +1,9 @@ import Constants from "expo-constants"; import { Platform } from "react-native"; +import { sliceUtf16Head } from "@bb/text-utils"; export function describeThisDevice(): string { const name = Constants.deviceName?.trim(); - if (name && name.length > 0) return name.slice(0, 128); + if (name && name.length > 0) return sliceUtf16Head(name, 128); return Platform.OS === "android" ? "Android device" : "iPhone"; } diff --git a/apps/server/src/assets/install-machine-windows.mjs b/apps/server/src/assets/install-machine-windows.mjs index 581e5ab2edd..305cff4601a 100644 --- a/apps/server/src/assets/install-machine-windows.mjs +++ b/apps/server/src/assets/install-machine-windows.mjs @@ -412,7 +412,11 @@ async function downloadPackage({ bootstrap, dataDir, npmPrefix }) { const body = await response.json(); if (body !== null && typeof body.message === "string") { details.push( - `Server: ${body.message.replace(/[\x00-\x1f\x7f-\x9f]/gu, " ").slice(0, 2000)}`, + `Server: ${Array.from( + body.message.replace(/[\x00-\x1f\x7f-\x9f]/gu, " "), + ) + .slice(0, 2000) + .join("")}`, ); } } catch {} diff --git a/apps/server/src/services/desktop-browsers.ts b/apps/server/src/services/desktop-browsers.ts index 99a0c2c46ad..cb7f2d10279 100644 --- a/apps/server/src/services/desktop-browsers.ts +++ b/apps/server/src/services/desktop-browsers.ts @@ -31,6 +31,7 @@ import { callHostOnlineRpc, callHostOnlineRpcForWork, } from "./hosts/online-rpc.js"; +import { sliceUtf16Head } from "@bb/text-utils"; interface LeaseEntry { lease: ExperimentalDesktopBrowserLease; @@ -116,7 +117,7 @@ function toStoredBrowserTab( id: tab.tabId, kind: "browser" as const, environmentId: null, - title: tab.title.slice(0, 1024) || null, + title: sliceUtf16Head(tab.title, 1024) || null, url: tab.url, desktopTarget: { hostId: scope.hostId, diff --git a/apps/server/src/services/environments/environment-engine.ts b/apps/server/src/services/environments/environment-engine.ts index 88ab09bbea1..4342ada8053 100644 --- a/apps/server/src/services/environments/environment-engine.ts +++ b/apps/server/src/services/environments/environment-engine.ts @@ -133,6 +133,7 @@ import { } from "../hosts/online-rpc.js"; import { ApiError } from "../../errors.js"; import { defineItemSweep, type ItemSweep } from "../system/item-sweep.js"; +import { sliceUtf16Head } from "@bb/text-utils"; type Deps = ThreadProvisioningDeps; @@ -289,9 +290,9 @@ function provisioningReporter( step: (text) => report( (row) => { - row.statusMessage = text.slice(0, 200); + row.statusMessage = sliceUtf16Head(text, 200); }, - text.slice(0, 200), + sliceUtf16Head(text, 200), ), log: (text) => report((row) => { diff --git a/apps/server/src/services/machines/provider-orchestration.ts b/apps/server/src/services/machines/provider-orchestration.ts index 8f4b1259363..5354c6f6a6c 100644 --- a/apps/server/src/services/machines/provider-orchestration.ts +++ b/apps/server/src/services/machines/provider-orchestration.ts @@ -59,6 +59,7 @@ import { toHostWithStatus } from "../lib/entity-lookup.js"; import { perDbRegistry } from "../lib/per-db-registry.js"; import { defineItemSweep, type ItemSweep } from "../system/item-sweep.js"; import { emitPluginHostDeleted } from "../plugins/plugin-thread-events.js"; +import { sliceUtf16Head, sliceUtf16Tail } from "@bb/text-utils"; type Deps = ThreadProvisioningDeps; type MachineLifecycleDeps = Pick; @@ -186,7 +187,7 @@ function createReporter( const current = getHost(deps.db, owner.id); if (!createOwns(current, owner) || current.phase !== "creating") return; updateHost(deps.db, deps.hub, owner.id, { - statusMessage: text.slice(0, 500), + statusMessage: sliceUtf16Head(text, 500), }); deps.hub.notifyHost(owner.id, ["host-connected"]); }, @@ -194,9 +195,10 @@ function createReporter( const current = getHost(deps.db, owner.id); if (!createOwns(current, owner) || current.phase !== "creating") return; updateHost(deps.db, deps.hub, owner.id, { - pendingLog: ( - current.pendingLog + (text.endsWith("\n") ? text : `${text}\n`) - ).slice(-16_384), + pendingLog: sliceUtf16Tail( + current.pendingLog + (text.endsWith("\n") ? text : `${text}\n`), + 16_384, + ), }); deps.hub.notifyHost(owner.id, ["host-connected"]); }, @@ -221,12 +223,12 @@ function lifecycleReporter( ) return; updateHost(deps.db, deps.hub, hostId, { - statusMessage: text.slice(0, 500), + statusMessage: sliceUtf16Head(text, 500), }); deps.hub.notifyHost(hostId, ["host-connected"]); }, log: (text) => { - deps.logger.info({ hostId }, text.slice(-16_384)); + deps.logger.info({ hostId }, sliceUtf16Tail(text, 16_384)); }, }; } diff --git a/apps/server/src/services/plugins/install-sources.ts b/apps/server/src/services/plugins/install-sources.ts index 28b1ff67945..4f0f176c519 100644 --- a/apps/server/src/services/plugins/install-sources.ts +++ b/apps/server/src/services/plugins/install-sources.ts @@ -27,6 +27,7 @@ import { installCancellationSignal, PluginInstallCancelledError, } from "./install-cancellation.js"; +import { sliceUtf16Tail } from "@bb/text-utils"; type ParsedGitSelector = | { kind: "ref"; ref: string } @@ -642,7 +643,7 @@ export async function runInstallCommand( stdoutBytes += chunk.byteLength; const limit = options?.maxStdoutBytes; if (limit === undefined) { - if (stdout.length > 8192) stdout = stdout.slice(-8192); + if (stdout.length > 8192) stdout = sliceUtf16Tail(stdout, 8192); } else if (stdoutBytes > limit && !overflowed) { overflowed = true; killCommand(); @@ -650,7 +651,7 @@ export async function runInstallCommand( }); child.stderr.on("data", (chunk: Buffer) => { stderr += chunk.toString("utf8"); - if (stderr.length > 8192) stderr = stderr.slice(-8192); + if (stderr.length > 8192) stderr = sliceUtf16Tail(stderr, 8192); }); let cancelled = false; const cancel = () => { @@ -696,7 +697,7 @@ export async function runInstallCommand( resolve(); return; } - const tail = stderr.trim().slice(-1000); + const tail = sliceUtf16Tail(stderr.trim(), 1000); reject( new Error( `${command} ${args[0]} failed (exit ${code ?? "signal"})${tail ? `: ${tail}` : ""}`, diff --git a/apps/server/src/services/plugins/plugin-service.ts b/apps/server/src/services/plugins/plugin-service.ts index 7db6c5c892d..964039b0d41 100644 --- a/apps/server/src/services/plugins/plugin-service.ts +++ b/apps/server/src/services/plugins/plugin-service.ts @@ -209,6 +209,7 @@ import type { import type { PluginMachineProviderBridge } from "./plugin-machine-provider-registry.js"; import { fillPluginPresentation } from "./plugin-presentation.js"; import { defineItemSweep, type ItemSweep } from "../system/item-sweep.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export type { PluginAgentToolContribution, PluginMentionResolveResult, @@ -524,7 +525,9 @@ class PluginRpcBoundaryError extends Error { ) .join("; "); const summary = - issues && issues.length > 300 ? `${issues.slice(0, 299)}…` : issues; + issues && issues.length > 300 + ? `${sliceUtf16Head(issues, 299)}…` + : issues; super(summary ? `${rpcError.message} (${summary})` : rpcError.message); this.name = "PluginRpcBoundaryError"; } diff --git a/apps/server/src/services/providers/provider-model-catalog-store.ts b/apps/server/src/services/providers/provider-model-catalog-store.ts index ff4840d0dc5..66ee9e48b56 100644 --- a/apps/server/src/services/providers/provider-model-catalog-store.ts +++ b/apps/server/src/services/providers/provider-model-catalog-store.ts @@ -35,6 +35,7 @@ import { requireBridgeLaunchForProviderId, resolveBridgeLaunchForProviderId, } from "../system/provider-bridge-launch.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export const PROVIDER_MODEL_CATALOG_PUSH_COALESCE_MS = 250; export const PROVIDER_MODEL_CATALOG_MEMORY_ENTRY_LIMIT = 256; @@ -180,7 +181,7 @@ export function toProviderModelCatalogFailureDetail( return null; } return collapsed.length > FAILURE_DETAIL_MAX_LENGTH - ? `${collapsed.slice(0, FAILURE_DETAIL_MAX_LENGTH - 1).trimEnd()}\u2026` + ? `${sliceUtf16Head(collapsed, FAILURE_DETAIL_MAX_LENGTH - 1).trimEnd()}\u2026` : collapsed; } diff --git a/apps/server/src/services/skills/registry-parse.ts b/apps/server/src/services/skills/registry-parse.ts index fa5eee91544..d97c7ddab48 100644 --- a/apps/server/src/services/skills/registry-parse.ts +++ b/apps/server/src/services/skills/registry-parse.ts @@ -4,6 +4,7 @@ import type { RegistrySkillDetail, RegistrySkillFile, } from "@bb/server-contract"; +import { sliceUtf16Head } from "@bb/text-utils"; export const SKILLS_BASE_URL = "https://www.skills.sh"; const DEFAULT_PAGE_SIZE = 24; @@ -178,7 +179,8 @@ export function parsePublicDetail( .trim(); return { topic: topic === null ? null : decodeHtml(topic), - summary: summary && summary.length > 0 ? summary.slice(0, 280) : null, + summary: + summary && summary.length > 0 ? sliceUtf16Head(summary, 280) : null, }; } @@ -222,7 +224,7 @@ export function parsePublicDetailSkill( summary: detail.summary ?? (typeof body.description === "string" - ? body.description.slice(0, 280) + ? sliceUtf16Head(body.description, 280) : null), }; } diff --git a/apps/server/src/services/skills/registry-skill-install.ts b/apps/server/src/services/skills/registry-skill-install.ts index 7d709734eed..4f48436de99 100644 --- a/apps/server/src/services/skills/registry-skill-install.ts +++ b/apps/server/src/services/skills/registry-skill-install.ts @@ -11,6 +11,7 @@ import { REGISTRY_SKILL_PROVENANCE_FILE_NAME, writeRegistrySkillProvenance, } from "./registry-skill-provenance.js"; +import { sliceUtf16Head } from "@bb/text-utils"; const SKILL_FILE_NAME = "SKILL.md"; const SKILLS_INSTALL_TIMEOUT_MS = 120_000; @@ -28,7 +29,7 @@ interface InstallCommandResult { function appendBounded(current: string, chunk: unknown): string { if (current.length >= MAX_INSTALL_OUTPUT_BYTES) return current; - return `${current}${String(chunk)}`.slice(0, MAX_INSTALL_OUTPUT_BYTES); + return sliceUtf16Head(`${current}${String(chunk)}`, MAX_INSTALL_OUTPUT_BYTES); } function registrySkillsCliInvocation(args: { diff --git a/apps/server/src/services/system/query-plan-audit.ts b/apps/server/src/services/system/query-plan-audit.ts index bcd2431cdc6..ede62462fe3 100644 --- a/apps/server/src/services/system/query-plan-audit.ts +++ b/apps/server/src/services/system/query-plan-audit.ts @@ -7,6 +7,7 @@ import { import { dirname } from "node:path"; import { fileURLToPath } from "node:url"; import type { ServerLogger } from "../../types.js"; +import { sliceUtf16Head } from "@bb/text-utils"; const MAX_LOGGED_SQL_LENGTH = 1_000; const SERVER_BUNDLE = { @@ -55,7 +56,10 @@ export function createGatedQueryPlanObserver(options: { caller: finding.caller, detail: finding.detail, plan: finding.plan, - sql: finding.sql.replace(/\s+/g, " ").slice(0, MAX_LOGGED_SQL_LENGTH), + sql: sliceUtf16Head( + finding.sql.replace(/\s+/g, " "), + MAX_LOGGED_SQL_LENGTH, + ), }, "Slow SQLite query plan", ); diff --git a/apps/server/src/services/terminals/terminal-session-lifecycle.ts b/apps/server/src/services/terminals/terminal-session-lifecycle.ts index e3cd32a0225..4ed1d7d172e 100644 --- a/apps/server/src/services/terminals/terminal-session-lifecycle.ts +++ b/apps/server/src/services/terminals/terminal-session-lifecycle.ts @@ -55,6 +55,7 @@ import { PendingRpcRegistry, } from "./pending-rpc-registry.js"; import { TerminalOutputFlowControl } from "./terminal-output-flow-control.js"; +import { sliceUtf16Head } from "@bb/text-utils"; const DEFAULT_TERMINAL_OPEN_TIMEOUT_MS = 10_000; const DEFAULT_TERMINAL_CLOSE_TIMEOUT_MS = 5_000; @@ -375,7 +376,7 @@ function titleFromCommand(command: string): string { if (normalized.length <= 80) { return normalized; } - return `${normalized.slice(0, 77)}...`; + return `${sliceUtf16Head(normalized, 77)}...`; } function initialTitleForTerminal( diff --git a/apps/server/src/services/threads/child-thread-notifications.ts b/apps/server/src/services/threads/child-thread-notifications.ts index f3b79e2670b..e83db67f43b 100644 --- a/apps/server/src/services/threads/child-thread-notifications.ts +++ b/apps/server/src/services/threads/child-thread-notifications.ts @@ -28,6 +28,7 @@ import { systemMessageKindForTemplate, } from "./system-message-kind.js"; import { getTurnFinalOutput } from "./thread-data.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export type ChildThreadNotificationSource = ParentSystemThreadMentionSource; @@ -152,7 +153,7 @@ function truncateChildThreadOutput(text: string, limit: number): string { if (retainedLength === 0) { return CHILD_THREAD_OUTPUT_TRUNCATION_MARKER.trimStart(); } - return `${text.slice(0, retainedLength).trimEnd()}${CHILD_THREAD_OUTPUT_TRUNCATION_MARKER}`; + return `${sliceUtf16Head(text, retainedLength).trimEnd()}${CHILD_THREAD_OUTPUT_TRUNCATION_MARKER}`; } function formatChildThreadCompletionOutputExcerpt( diff --git a/apps/server/src/services/threads/restart-resume.ts b/apps/server/src/services/threads/restart-resume.ts index 08d0bc7cddb..4b4ccffd6af 100644 --- a/apps/server/src/services/threads/restart-resume.ts +++ b/apps/server/src/services/threads/restart-resume.ts @@ -27,6 +27,7 @@ import { type FailedTurnRecord, } from "./turn-failed.js"; import { retryTurnAfterRestart } from "./turn-retry.js"; +import { sliceUtf16Head } from "@bb/text-utils"; type RestartResumeDeps = LoggedPendingInteractionWorkSessionDeps; @@ -57,7 +58,7 @@ function readCommand(data: string): string | null { } const command = parsed.data.item.command.trim(); return command.length > MAX_NAMED_COMMAND_CHARS - ? `${command.slice(0, MAX_NAMED_COMMAND_CHARS)}…` + ? `${sliceUtf16Head(command, MAX_NAMED_COMMAND_CHARS)}…` : command; } diff --git a/apps/server/src/services/threads/thread-runtime-config.ts b/apps/server/src/services/threads/thread-runtime-config.ts index 1b99ddc91b7..23da68871dd 100644 --- a/apps/server/src/services/threads/thread-runtime-config.ts +++ b/apps/server/src/services/threads/thread-runtime-config.ts @@ -38,6 +38,7 @@ import { import { readWorkspaceAgentContext } from "./workspace-agent-context.js"; import { resolveDeprecatedWorkspaceProvisionType } from "../environments/environment-response.js"; import { markTurnTraceSpan } from "../system/turn-trace.js"; +import { sliceUtf16Head } from "@bb/text-utils"; const UPDATE_ENVIRONMENT_DIRECTORY_INSTRUCTIONS = "If the user asks you to move this thread to another checkout, worktree, or directory, make sure the target directory exists, then call `update_environment_directory` with its absolute path. After it succeeds, end the current turn; bb starts the next turn in the updated environment automatically so you can continue there."; @@ -248,9 +249,7 @@ export async function resolveThreadRuntimeCommandConfig( continue; } if (text === null || text.trim().length === 0) continue; - if (text.length > PLUGIN_DYNAMIC_INSTRUCTIONS_MAX_CHARS) { - text = text.slice(0, PLUGIN_DYNAMIC_INSTRUCTIONS_MAX_CHARS); - } + text = sliceUtf16Head(text, PLUGIN_DYNAMIC_INSTRUCTIONS_MAX_CHARS); instructionSections.push( `The following instructions come from the BB plugin "${contribution.pluginId}":`, text, diff --git a/apps/server/src/services/threads/title-generation.ts b/apps/server/src/services/threads/title-generation.ts index 73c18c6177f..5410716b413 100644 --- a/apps/server/src/services/threads/title-generation.ts +++ b/apps/server/src/services/threads/title-generation.ts @@ -13,6 +13,7 @@ import { import { countWords, displayWidth, + sliceUtf16Head, truncateToWidth, truncateToWidthAtWordBoundary, } from "@bb/text-utils"; @@ -173,14 +174,15 @@ export function sanitizeGeneratedTitle(value: string): string | null { } export function sanitizeGeneratedBranchSlug(value: string): string | null { - const slug = value - .trim() - .toLowerCase() - .replace(/[^a-z0-9]+/gu, "-") - .replace(/-{2,}/gu, "-") - .replace(/^-+|-+$/gu, "") - .slice(0, MAX_BRANCH_SLUG_LENGTH) - .replace(/-+$/u, ""); + const slug = sliceUtf16Head( + value + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/gu, "-") + .replace(/-{2,}/gu, "-") + .replace(/^-+|-+$/gu, ""), + MAX_BRANCH_SLUG_LENGTH, + ).replace(/-+$/u, ""); return slug.length > 0 ? slug : null; } diff --git a/apps/server/test/services/threads/child-thread-notifications.test.ts b/apps/server/test/services/threads/child-thread-notifications.test.ts index 2bdbedde753..9307d87f01d 100644 --- a/apps/server/test/services/threads/child-thread-notifications.test.ts +++ b/apps/server/test/services/threads/child-thread-notifications.test.ts @@ -55,6 +55,25 @@ describe("child thread notifications", () => { expect(message).not.toContain("Child thread updates:"); }); + it("cuts long final output without splitting an emoji", () => { + const retainedLength = 4_000 - "\n\n[... output truncated ...]".length; + const message = renderBatchMessage({ + items: [ + { + activeWorkflowCount: 0, + childThread: testThread({ id: "thr_child", title: "Long report" }), + terminalOutput: `${"x".repeat(retainedLength - 1)}\u{1F600}${"y".repeat(100)}`, + turnStatus: "completed", + }, + ], + }); + + expect(message).not.toMatch(/[\uD800-\uDFFF]/u); + expect(message).toContain( + `${"x".repeat(retainedLength - 1)}\n\n[... output truncated ...]`, + ); + }); + it("omits output for a single failed outcome", () => { const message = renderBatchMessage({ items: [ diff --git a/apps/server/test/threads/restart-resume.test.ts b/apps/server/test/threads/restart-resume.test.ts index 188df79ec02..037a4b86563 100644 --- a/apps/server/test/threads/restart-resume.test.ts +++ b/apps/server/test/threads/restart-resume.test.ts @@ -676,6 +676,29 @@ describe("resuming threads after a restart", () => { }); }); + it("names a long background command without splitting an emoji", async () => { + await withTestHarness(async (harness) => { + continueAfterRestarts(harness, true); + const fixture = seedHostWithProject(harness); + const waiting = seedRunningThread(harness, fixture, { + text: "Run the migration", + }); + seedBackgroundCommand(harness, fixture, waiting, { + command: `echo ${"x".repeat(194)}\u{1F600} done`, + description: "Echo a long line", + id: "task-echo", + }); + finishTurn(harness, waiting.thread.id); + + await restartDaemon(harness, fixture); + await sweepPastResume(harness); + + const text = requestTexts(harness, waiting.thread.id).at(-1); + expect(text).toContain(`\`echo ${"x".repeat(194)}…\``); + expect(text).not.toMatch(/[\uD800-\uDFFF]/u); + }); + }); + it("wakes an idle thread whose background command the daemon stopped as it shut down, once", async () => { await withTestHarness(async (harness) => { continueAfterRestarts(harness, true); diff --git a/apps/server/test/threads/thread-runtime-config.test.ts b/apps/server/test/threads/thread-runtime-config.test.ts index 81408f971c4..551afe1de5e 100644 --- a/apps/server/test/threads/thread-runtime-config.test.ts +++ b/apps/server/test/threads/thread-runtime-config.test.ts @@ -1457,5 +1457,51 @@ describe("thread runtime config", () => { expect(instructions).not.toContain("x".repeat(32_769)); }); }); + + it("cuts long plugin instructions without splitting an emoji", async () => { + await withTestHarness(async (harness) => { + const hostId = "host-runtime-plugin-instr-emoji"; + seedHostSession(harness.deps, { id: hostId }); + const { project } = seedProjectWithSource(harness.deps, { + hostId, + path: "/tmp/runtime-plugin-instr-emoji", + }); + const environment = seedEnvironment(harness.deps, { + hostId, + projectId: project.id, + path: "/tmp/runtime-plugin-instr-emoji", + }); + const thread = seedThread(harness.deps, { + projectId: project.id, + environmentId: environment.id, + }); + stubContributions({ + instructions: [ + { + pluginId: "emoji", + provider: () => `${"x".repeat(32_767)}\u{1F600} beyond the cap`, + }, + ], + }); + + const runtimeConfig = await resolveThreadRuntimeCommandConfig( + harness.deps, + { + thread, + model: "test-model", + environment: { + hostId: environment.hostId, + id: environment.id, + path: environment.path, + status: environment.status, + }, + }, + ); + + expect(runtimeConfig.instructions).not.toMatch(/[\uD800-\uDFFF]/u); + expect(runtimeConfig.instructions).toContain("x".repeat(32_767)); + expect(runtimeConfig.instructions).not.toContain("beyond the cap"); + }); + }); }); }); diff --git a/apps/web/package.json b/apps/web/package.json index 6e2195c6780..b3d965a2e75 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -18,6 +18,7 @@ "@bb/connect-db-pg": "workspace:*", "@bb/domain": "workspace:*", "@bb/shared-ui": "workspace:*", + "@bb/text-utils": "workspace:*", "@bb/tunnel-contract": "workspace:*", "@better-auth/drizzle-adapter": "^1.7.18", "@fontsource-variable/inter": "^5.3.0", diff --git a/apps/web/src/landing/endpoints.ts b/apps/web/src/landing/endpoints.ts index ee4f3b5c295..7d31172f8b4 100644 --- a/apps/web/src/landing/endpoints.ts +++ b/apps/web/src/landing/endpoints.ts @@ -7,6 +7,7 @@ import { VISIT_PARAM_NAMES, } from "./site"; import type { CtaPlacement, DesktopPlatform } from "./site"; +import { sliceUtf16Head } from "@bb/text-utils"; const POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/capture/?ip=0"; const TRACKING_SOURCE = "landing_worker_redirect"; @@ -507,9 +508,5 @@ function getNonEmptySearchParam( } function truncateProperty(value: string): string { - if (value.length <= MAX_URL_PROPERTY_LENGTH) { - return value; - } - - return value.slice(0, MAX_URL_PROPERTY_LENGTH); + return sliceUtf16Head(value, MAX_URL_PROPERTY_LENGTH); } diff --git a/apps/web/src/marketplace/marketplace-og.tsx b/apps/web/src/marketplace/marketplace-og.tsx index e599db482aa..7076aea3fb2 100644 --- a/apps/web/src/marketplace/marketplace-og.tsx +++ b/apps/web/src/marketplace/marketplace-og.tsx @@ -8,6 +8,7 @@ import { marketplaceAssetUrl, resolveMarketplaceCategory, } from "./marketplace-view-model.js"; +import { sliceUtf16Head } from "@bb/text-utils"; const INK = "#333333"; const DIM = "#6b6b6b"; @@ -30,7 +31,7 @@ interface MarketplaceOgArtwork { function clip(text: string, length: number) { if (text.length <= length) return text; - const cut = text.slice(0, length - 1); + const cut = sliceUtf16Head(text, length - 1); const space = cut.lastIndexOf(" "); const words = space > length * 0.6 ? cut.slice(0, space) : cut; return `${words.replace(/[\s.,;:!?—–-]+$/u, "")}…`; @@ -38,7 +39,7 @@ function clip(text: string, length: number) { function summary(text: string, length: number) { if (text.length <= length) return text; - const sentenceEnd = text.slice(0, length).lastIndexOf(". "); + const sentenceEnd = sliceUtf16Head(text, length).lastIndexOf(". "); return sentenceEnd > length * 0.4 ? text.slice(0, sentenceEnd + 1) : clip(text, length); diff --git a/apps/web/src/server/account.ts b/apps/web/src/server/account.ts index 26a4094dd79..73f9c0ec7c8 100644 --- a/apps/web/src/server/account.ts +++ b/apps/web/src/server/account.ts @@ -24,6 +24,7 @@ import { tunnelUrlForServerUrl, } from "./api.js"; import { generateConnectCode, generateToken } from "./tokens.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export const LINK_POLL_INTERVAL_MS = 2_000; export const LINK_DELIVERY_GRACE_MS = 2 * 60 * 1000; @@ -444,7 +445,7 @@ function labelSlug(value: string): string { } function fitLabel(value: string): string { - return value.slice(0, HANDLE_MAX_LENGTH).replace(/-+$/u, ""); + return sliceUtf16Head(value, HANDLE_MAX_LENGTH).replace(/-+$/u, ""); } export function suggestHandle(githubLogin: string | null): string { diff --git a/apps/web/src/server/oauth.ts b/apps/web/src/server/oauth.ts index a0ff1706c31..4a1aca7ff63 100644 --- a/apps/web/src/server/oauth.ts +++ b/apps/web/src/server/oauth.ts @@ -32,6 +32,7 @@ import { first, } from "@bb/connect-db"; import type { Env } from "./env.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export const OAUTH_CLIENT_METADATA_MAX_BYTES = 5 * 1024; export const OAUTH_CLIENT_METADATA_TIMEOUT_MS = 5_000; @@ -296,11 +297,10 @@ function parseClientMetadataDocument( } const clientName = typeof document.client_name === "string" - ? document.client_name - .replace(INVISIBLE_CONTROL_CHARACTERS, "") - .trim() - .slice(0, OAUTH_CLIENT_NAME_MAX_LENGTH) - .trim() + ? sliceUtf16Head( + document.client_name.replace(INVISIBLE_CONTROL_CHARACTERS, "").trim(), + OAUTH_CLIENT_NAME_MAX_LENGTH, + ).trim() : ""; if (!clientName) { return { ok: false, message: "client metadata has no client_name" }; diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.json index 4de0ed712cb..3f6c7771466 100644 --- a/packages/agent-runtime/package.json +++ b/packages/agent-runtime/package.json @@ -28,6 +28,7 @@ "@bb/domain": "workspace:*", "@bb/process-utils": "workspace:*", "@bb/provider-bridge-protocol": "workspace:*", + "@bb/text-utils": "workspace:*", "zod": "^4.6.7" }, "devDependencies": { diff --git a/packages/agent-runtime/src/runtime-provider-process.ts b/packages/agent-runtime/src/runtime-provider-process.ts index 5d9fc4dc419..a30ee3b9f29 100644 --- a/packages/agent-runtime/src/runtime-provider-process.ts +++ b/packages/agent-runtime/src/runtime-provider-process.ts @@ -27,6 +27,7 @@ import type { AgentRuntimeProcessExitThreadState, AgentRuntimeSkillRoot, } from "./types.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export interface RuntimeProviderProcess extends ManagedProcess { adapter: BridgeProtocolAdapter; @@ -192,9 +193,13 @@ export class RuntimeProviderProcessManager { try { if (hasChildProcessExited(providerProcess.child)) { - const stderr = formatProviderStderr( + const formattedStderr = formatProviderStderr( providerProcess.stderrTail, - )?.slice(0, 500); + ); + const stderr = + formattedStderr === null + ? null + : sliceUtf16Head(formattedStderr, 500); throw new Error( `Provider "${args.providerId}" exited during startup with ${formatChildProcessExitStatus(providerProcess.child)}` + (stderr ? `\nstderr: ${stderr}` : ""), diff --git a/packages/client-core/src/timeline/conversation-message-limits.ts b/packages/client-core/src/timeline/conversation-message-limits.ts index 6afeaa611cd..ba8d609a393 100644 --- a/packages/client-core/src/timeline/conversation-message-limits.ts +++ b/packages/client-core/src/timeline/conversation-message-limits.ts @@ -1,4 +1,5 @@ import { isRawThreadId } from "@bb/domain"; +import { sliceUtf16Head } from "@bb/text-utils"; export const USER_MESSAGE_CHAR_CAP = 4096; @@ -66,10 +67,9 @@ export function boundedMarkdownPreview( return { parseAsMarkdown: true, text, wasCapped: false }; } - const previewWindow = text.slice(0, cap + 1); - const cappedText = previewWindow.slice(0, cap); + const cappedText = sliceUtf16Head(text, cap); const capSplitsToken = - !isWhitespace(cappedText.at(-1)) && !isWhitespace(previewWindow[cap]); + !isWhitespace(cappedText.at(-1)) && !isWhitespace(text[cappedText.length]); if (!capSplitsToken) { return cappedMarkdownPreview(cappedText); } diff --git a/packages/db/src/connection.ts b/packages/db/src/connection.ts index 0b3a2e32c50..84688317365 100644 --- a/packages/db/src/connection.ts +++ b/packages/db/src/connection.ts @@ -10,6 +10,7 @@ import { type QueryDiagnosticsLogFields, } from "./query-diagnostics.js"; import * as schema from "./schema.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export interface SlowDbQueryLogFields { bindingArgumentCount: number; @@ -159,8 +160,8 @@ function formatSqlForLog( if (normalized.length <= maxLength) { return normalized; } - return `${normalized.slice( - 0, + return `${sliceUtf16Head( + normalized, maxLength - SQL_TRUNCATION_SUFFIX.length, )}${SQL_TRUNCATION_SUFFIX}`; } diff --git a/packages/db/src/query-plan-test-guard.ts b/packages/db/src/query-plan-test-guard.ts index e4ed12650d5..d3e15d40486 100644 --- a/packages/db/src/query-plan-test-guard.ts +++ b/packages/db/src/query-plan-test-guard.ts @@ -13,6 +13,7 @@ import { } from "./query-plan-guard.js"; import { QUERY_PLAN_ALLOWLIST } from "./query-plan-allowlist.js"; import { createMigratedConnection } from "./testing.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export type QueryPlanReportRow = | ({ kind: "finding" } & QueryPlanFindingReport) @@ -153,7 +154,7 @@ export function formatQueryPlanViolations( return violations .map( (violation) => - `${violation.rule} on ${violation.table} in ${violation.caller}: ${violation.detail}\n plan: ${violation.plan.join(" | ")}\n sql: ${violation.sql.replace(/\s+/g, " ").slice(0, 400)}`, + `${violation.rule} on ${violation.table} in ${violation.caller}: ${violation.detail}\n plan: ${violation.plan.join(" | ")}\n sql: ${sliceUtf16Head(violation.sql.replace(/\s+/g, " "), 400)}`, ) .join("\n\n"); } diff --git a/packages/domain/package.json b/packages/domain/package.json index 27dd08f5e50..486f820350e 100644 --- a/packages/domain/package.json +++ b/packages/domain/package.json @@ -118,6 +118,7 @@ "test": "vitest run --config vitest.config.ts" }, "dependencies": { + "@bb/text-utils": "workspace:*", "zod": "^4.6.7" }, "devDependencies": { diff --git a/packages/domain/src/legacy-thread-events.ts b/packages/domain/src/legacy-thread-events.ts index 7827862742b..aeab477c9a6 100644 --- a/packages/domain/src/legacy-thread-events.ts +++ b/packages/domain/src/legacy-thread-events.ts @@ -1,5 +1,6 @@ import type { ThreadEventItemPresentation } from "./item-presentation.js"; import type { ThreadEventType } from "./provider-event.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export const LEGACY_CODEX_GOAL_EXTENSION_KIND = "provider-codex/goal"; @@ -205,7 +206,7 @@ export function formatToolCallCommand( const compact = entries .map(([k, v]) => { const vs = typeof v === "string" ? v.trim() : JSON.stringify(v); - const display = vs.length > 40 ? `${vs.slice(0, 37)}...` : vs; + const display = vs.length > 40 ? `${sliceUtf16Head(vs, 37)}...` : vs; return `${k}: ${display}`; }) .join(", "); diff --git a/packages/frp-client/package.json b/packages/frp-client/package.json index 38d55c6dc19..e9d99b0438e 100644 --- a/packages/frp-client/package.json +++ b/packages/frp-client/package.json @@ -22,6 +22,7 @@ }, "dependencies": { "@bb/process-utils": "workspace:*", + "@bb/text-utils": "workspace:*", "@bb/tunnel-contract": "workspace:*" }, "devDependencies": { diff --git a/packages/frp-client/src/supervisor.ts b/packages/frp-client/src/supervisor.ts index 2dc58193836..8c8c05a239a 100644 --- a/packages/frp-client/src/supervisor.ts +++ b/packages/frp-client/src/supervisor.ts @@ -12,6 +12,7 @@ import { type TunnelServer, } from "./config.js"; import { cleanFrpcLine, parseFrpcLine } from "./log.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export interface FrpcLogger { info(message: string): void; @@ -89,7 +90,7 @@ export const requestFrpcReload: FrpcReloadRequest = async ( signal: AbortSignal.timeout(timeoutMs), }); if (!response.ok) { - const body = (await response.text()).slice(0, 500); + const body = sliceUtf16Head(await response.text(), 500); throw new Error(`frpc reload answered HTTP ${response.status} ${body}`); } }; diff --git a/packages/plugin-build/package.json b/packages/plugin-build/package.json index 9c0f50b023e..506550ea29d 100644 --- a/packages/plugin-build/package.json +++ b/packages/plugin-build/package.json @@ -27,6 +27,7 @@ "dependencies": { "@bb/domain": "workspace:*", "@bb/process-utils": "workspace:*", + "@bb/text-utils": "workspace:*", "@get-bb/plugin-sdk": "workspace:*", "es-module-lexer": "^2.3.2", "npm": "11.21.2", diff --git a/packages/plugin-build/src/scope-plugin-utilities.ts b/packages/plugin-build/src/scope-plugin-utilities.ts index e89a4eb3f71..9b496d6fb70 100644 --- a/packages/plugin-build/src/scope-plugin-utilities.ts +++ b/packages/plugin-build/src/scope-plugin-utilities.ts @@ -1,4 +1,5 @@ import { HOST_TAILWIND_CSS } from "./generated/plugin-theme.generated.js"; +import { sliceUtf16Head } from "@bb/text-utils"; const NESTED_STYLE_RULE_AT_RULES = new Set([ "media", @@ -216,7 +217,7 @@ function assertNoUnscopedClassRule(statement: Statement): void { if (!prelude.includes(".")) return; throw new Error( `Compiled plugin CSS has a class rule outside the utilities layer ` + - `(${prelude.slice(0, 80)}). Its utilities would leak into the host ` + + `(${sliceUtf16Head(prelude, 80)}). Its utilities would leak into the host ` + `page; check the Tailwind version against buildTailwindCss()'s input.`, ); } diff --git a/packages/plugin-sdk/package.json b/packages/plugin-sdk/package.json index d4388316b34..38d3df983fd 100644 --- a/packages/plugin-sdk/package.json +++ b/packages/plugin-sdk/package.json @@ -180,6 +180,7 @@ "@bb/server-contract": "workspace:*", "@bb/skill-index": "workspace:*", "@bb/test-helpers": "workspace:*", + "@bb/text-utils": "workspace:*", "@bb/tsconfig": "workspace:*", "@testing-library/react": "^16.3.3", "@types/better-sqlite3": "^7.6.13", diff --git a/packages/plugin-sdk/src/internal/host-policy.ts b/packages/plugin-sdk/src/internal/host-policy.ts index 4eee2a2c2de..aac0a70d5e1 100644 --- a/packages/plugin-sdk/src/internal/host-policy.ts +++ b/packages/plugin-sdk/src/internal/host-policy.ts @@ -70,6 +70,7 @@ import type { StandardSchemaV1Issue, StandardSchemaV1Result, } from "../rpc-contract.js"; +import { sliceUtf16Head } from "@bb/text-utils"; /** * Shared registration policy for the real plugin host and the in-process fake. @@ -2842,10 +2843,9 @@ export function runPluginStorageMigrations( database.exec("ALTER TABLE _bb_migrations ADD COLUMN statement_hash TEXT"); } const rows = database - .prepare< - [], - { id: number; statement_hash: string | null } - >("SELECT id, statement_hash FROM _bb_migrations ORDER BY id") + .prepare<[], { id: number; statement_hash: string | null }>( + "SELECT id, statement_hash FROM _bb_migrations ORDER BY id", + ) .all(); const applied = new Map(); for (const row of rows) applied.set(row.id, row.statement_hash); @@ -3630,7 +3630,10 @@ export function normalizePluginAgentConfiguration(args: { const instructions = typeof output.instructions === "string" && output.instructions.trim().length > 0 - ? output.instructions.slice(0, PLUGIN_DYNAMIC_INSTRUCTIONS_MAX_CHARS) + ? sliceUtf16Head( + output.instructions, + PLUGIN_DYNAMIC_INSTRUCTIONS_MAX_CHARS, + ) : null; const toolSelections = normalizePluginAgentToolSelections({ knownIds: args.knownToolIds, diff --git a/packages/provider-bridge-acp/package.json b/packages/provider-bridge-acp/package.json index c7375b89938..0d413df89b7 100644 --- a/packages/provider-bridge-acp/package.json +++ b/packages/provider-bridge-acp/package.json @@ -27,6 +27,7 @@ "@bb/domain": "workspace:*", "@bb/process-utils": "workspace:*", "@bb/provider-bridge-protocol": "workspace:*", + "@bb/text-utils": "workspace:*", "zod": "^4.6.7" }, "devDependencies": { diff --git a/packages/provider-bridge-acp/src/client/message-stream.ts b/packages/provider-bridge-acp/src/client/message-stream.ts index 1b3beeacaac..3c44d66c4a1 100644 --- a/packages/provider-bridge-acp/src/client/message-stream.ts +++ b/packages/provider-bridge-acp/src/client/message-stream.ts @@ -1,4 +1,5 @@ import type { AnyMessage, Stream } from "@agentclientprotocol/sdk"; +import { serializeJsonRpcLine } from "@bb/provider-bridge-protocol/bridge-kit"; import { createInterface } from "node:readline"; import type { Readable, Writable } from "node:stream"; import { isJsonObject } from "../session/decode.js"; @@ -114,7 +115,7 @@ export function createAcpMessageStream( outstandingRequestIds.add(id); } } - options.output.write(`${JSON.stringify(message)}\n`); + options.output.write(`${serializeJsonRpcLine(message)}\n`); }, }); diff --git a/packages/provider-bridge-acp/src/tool-classification.ts b/packages/provider-bridge-acp/src/tool-classification.ts index ce59ba7fc4d..916a598d25b 100644 --- a/packages/provider-bridge-acp/src/tool-classification.ts +++ b/packages/provider-bridge-acp/src/tool-classification.ts @@ -27,6 +27,7 @@ import { type AcpToolCallPathOptions, } from "./tool-call-operation.js"; import { extractAcpContentText, type AcpToolCallUpdateEvent } from "./wire.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export interface AcpClassifiedToolCall { item: DeltaItemShape; @@ -81,7 +82,7 @@ function truncatedPayloadText(text: string): string { return text; } const removed = text.length - ACP_TOOL_PAYLOAD_MAX_CHARS; - return `${text.slice(0, ACP_TOOL_PAYLOAD_MAX_CHARS)}\n…[${removed.toLocaleString("en-US")} more characters truncated]`; + return `${sliceUtf16Head(text, ACP_TOOL_PAYLOAD_MAX_CHARS)}\n…[${removed.toLocaleString("en-US")} more characters truncated]`; } export function boundAcpToolPayload(value: unknown): unknown { diff --git a/packages/provider-bridge-protocol/src/bridge-kit/runtime-json-rpc.test.ts b/packages/provider-bridge-protocol/src/bridge-kit/runtime-json-rpc.test.ts index efb8cec361f..3d2e365896e 100644 --- a/packages/provider-bridge-protocol/src/bridge-kit/runtime-json-rpc.test.ts +++ b/packages/provider-bridge-protocol/src/bridge-kit/runtime-json-rpc.test.ts @@ -196,6 +196,46 @@ describe("runtime JSON-RPC transport", () => { } }); + it("never sends a lone surrogate to the provider process", async () => { + const child = spawnEchoChild(); + const linesPromise = readChildStdoutLines(child, 2); + const emoji = "\u{1F600}"; + const cutEmoji = `cut ${emoji.slice(0, 1)}`; + const pending = new Map(); + try { + const request = sendJsonRpcRequest({ + child, + getNextId: () => 1, + message: { + kind: "request", + method: "turn/start", + params: { input: [{ type: "text", text: `${cutEmoji} ${emoji}` }] }, + }, + pending, + resultSchema: z.unknown(), + }); + sendJsonRpcResult({ child, id: 2, result: { output: cutEmoji } }); + + const lines = await linesPromise; + for (const line of lines) { + expect(line).not.toMatch(/\\ud[89a-f][0-9a-f]{2}/iu); + } + expect(lines.map((line) => JSON.parse(line))).toEqual([ + { + jsonrpc: "2.0", + id: 1, + method: "turn/start", + params: { input: [{ type: "text", text: `cut \uFFFD ${emoji}` }] }, + }, + { jsonrpc: "2.0", id: 2, result: { output: "cut \uFFFD" } }, + ]); + settleJsonRpcResponse({ id: 1, pending, response: { result: null } }); + await expect(request).resolves.toBeNull(); + } finally { + await stopChild(child); + } + }); + it("serializes requests and validates their settled results", async () => { const child = spawnEchoChild(); const linesPromise = readChildStdoutLines(child, 2); diff --git a/packages/provider-bridge-protocol/src/bridge-kit/runtime-json-rpc.ts b/packages/provider-bridge-protocol/src/bridge-kit/runtime-json-rpc.ts index 1330abb8f2c..274f0dd396c 100644 --- a/packages/provider-bridge-protocol/src/bridge-kit/runtime-json-rpc.ts +++ b/packages/provider-bridge-protocol/src/bridge-kit/runtime-json-rpc.ts @@ -1,4 +1,5 @@ import { isClosedProcessStdinError } from "@bb/process-utils"; +import { toWellFormedUtf16 } from "@bb/text-utils"; import type { ChildProcess } from "node:child_process"; import type { Writable } from "node:stream"; import { z } from "zod"; @@ -199,13 +200,24 @@ function ensureJsonRpcStdinErrorHandler(stdin: Writable): void { stdin.on("error", handleJsonRpcStdinError); } -function writeJsonRpcLine(child: ChildProcess, line: string): void { +function wellFormedStrings(_key: string, value: unknown): unknown { + return typeof value === "string" ? toWellFormedUtf16(value) : value; +} + +export function serializeJsonRpcLine(message: object): string { + return JSON.stringify(message, wellFormedStrings); +} + +function writeJsonRpcMessage( + child: ChildProcess, + message: JsonRpcObject, +): void { const stdin = child.stdin; if (!stdin || stdin.destroyed || !stdin.writable) { return; } ensureJsonRpcStdinErrorHandler(stdin); - stdin.write(line + "\n"); + stdin.write(`${serializeJsonRpcLine(message)}\n`); } export function parseJsonRpcLine(line: string): ParsedJsonRpcLine { @@ -333,33 +345,27 @@ export function sendJsonRpcRequest( reject(error); }, }); - writeJsonRpcLine(args.child, JSON.stringify(withId)); + writeJsonRpcMessage(args.child, withId); }); } export function sendJsonRpcResult(args: SendJsonRpcResultArgs): void { - writeJsonRpcLine( - args.child, - JSON.stringify({ - jsonrpc: "2.0", - id: args.id, - result: args.result, - }), - ); + writeJsonRpcMessage(args.child, { + jsonrpc: "2.0", + id: args.id, + result: args.result, + }); } export function sendJsonRpcError(args: SendJsonRpcErrorArgs): void { - writeJsonRpcLine( - args.child, - JSON.stringify({ - jsonrpc: "2.0", - id: args.id, - error: { - code: args.code ?? -32000, - message: args.message, - }, - }), - ); + writeJsonRpcMessage(args.child, { + jsonrpc: "2.0", + id: args.id, + error: { + code: args.code ?? -32000, + message: args.message, + }, + }); } export function sendProviderResponseEncodeErrorIfKnown( diff --git a/packages/provider-bridge-protocol/src/conformance/scenarios.ts b/packages/provider-bridge-protocol/src/conformance/scenarios.ts index b4640c9bcb9..019634e2662 100644 --- a/packages/provider-bridge-protocol/src/conformance/scenarios.ts +++ b/packages/provider-bridge-protocol/src/conformance/scenarios.ts @@ -26,6 +26,7 @@ import { type JsonRpcWireMessage, } from "./client.js"; import type { ConformanceCheckResult } from "./types.js"; +import { sliceUtf16Head } from "@bb/text-utils"; export interface ConformanceSessionFixture { cwd: string; @@ -605,7 +606,7 @@ export async function runSessionLifecycleScenarios( : fail( "events/schema-valid", title2, - `${invalid.length} assembled event(s) failed validation; first: ${JSON.stringify(invalid[0]?.event).slice(0, 400)}`, + `${invalid.length} assembled event(s) failed validation; first: ${sliceUtf16Head(JSON.stringify(invalid[0]?.event), 400)}`, ), ); } diff --git a/packages/scripts/test/no-raw-text-truncation.test.mjs b/packages/scripts/test/no-raw-text-truncation.test.mjs new file mode 100644 index 00000000000..71f38ac7e80 --- /dev/null +++ b/packages/scripts/test/no-raw-text-truncation.test.mjs @@ -0,0 +1,83 @@ +import { execFile } from "node:child_process"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +const execFileAsync = promisify(execFile); +const ROOT = fileURLToPath(new URL("../../../", import.meta.url)); +const OXLINT = join(ROOT, "node_modules", ".bin", "oxlint"); + +const flagged = [ + "export const a = (text: string) => text.slice(0, MAX_CHARS);", + "export const b = (command: string) => `${command.slice(0, 200)}…`;", + "export const c = (value: string, limit: number) => value.trim().slice(0, limit);", + "export const d = (stderr: string) => stderr.slice(-8192);", + "export const e = (name: string) => name.substring(0, 40);", + "export const f = (ref: string, title: string) => `${ref}: ${title}`.slice(0, 120);", + "export const g = (output: string, maxLength: number) => output.slice(0, maxLength - 1).trimEnd();", +]; +const allowed = [ + "export const h = (items: string[]) => items.slice(0, MAX_ITEMS);", + "export const i = (line: string, separatorIndex: number) => line.slice(0, separatorIndex);", + "export const j = (sha: string) => sha.slice(0, 12);", + "export const k = (commit: string) => `${commit.slice(0, 7)}`;", + "export const l = (text: string) => text.slice(0, -1);", + "export const m = (code: string) => `${code.slice(0, 4)}-${code.slice(4)}`;", + "export const n = (text: string, end: number) => text.slice(0, end);", +]; + +describe("bb/no-raw-text-truncation", () => { + let dir; + + beforeAll(async () => { + dir = await mkdtemp(join(tmpdir(), "no-raw-text-truncation-")); + await writeFile( + join(dir, ".oxlintrc.json"), + JSON.stringify({ + jsPlugins: [join(ROOT, "scripts", "oxlint-plugin.mjs")], + categories: { correctness: "off" }, + rules: { "bb/no-raw-text-truncation": "error" }, + }), + ); + await writeFile( + join(dir, "fixture.ts"), + [ + "declare const MAX_CHARS: number;", + "declare const MAX_ITEMS: number;", + ...flagged, + ...allowed, + ].join("\n"), + ); + }); + + afterAll(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + it("flags length-capped text cuts and leaves index, array, and id cuts alone", async () => { + const result = await execFileAsync( + OXLINT, + [ + "-c", + join(dir, ".oxlintrc.json"), + "-f", + "unix", + join(dir, "fixture.ts"), + ], + { cwd: dir }, + ).catch((error) => error); + const flaggedLines = [ + ...String(result.stdout).matchAll( + /fixture\.ts:(\d+):\d+:.*no-raw-text-truncation/gu, + ), + ].map((match) => Number(match[1])); + + const firstCaseLine = 3; + expect(flaggedLines).toEqual( + flagged.map((_source, index) => firstCaseLine + index), + ); + }); +}); diff --git a/packages/text-utils/src/utf16.ts b/packages/text-utils/src/utf16.ts index e5f1ec625db..87fedc5c924 100644 --- a/packages/text-utils/src/utf16.ts +++ b/packages/text-utils/src/utf16.ts @@ -39,3 +39,9 @@ export function sliceUtf16HeadAndTail( tail: sliceUtf16Tail(value, tailChars), }; } + +const LONE_SURROGATE = /[\uD800-\uDFFF]/gu; + +export function toWellFormedUtf16(value: string): string { + return value.replace(LONE_SURROGATE, "�"); +} diff --git a/packages/text-utils/test/utf16.test.ts b/packages/text-utils/test/utf16.test.ts index 522cda4f1a0..b61850fb2c6 100644 --- a/packages/text-utils/test/utf16.test.ts +++ b/packages/text-utils/test/utf16.test.ts @@ -3,6 +3,7 @@ import { sliceUtf16Head, sliceUtf16HeadAndTail, sliceUtf16Tail, + toWellFormedUtf16, } from "../src/index.js"; describe("sliceUtf16HeadAndTail", () => { @@ -29,3 +30,15 @@ describe("sliceUtf16HeadAndTail", () => { expect(sliceUtf16Tail("abcdef", -1)).toBe(""); }); }); + +describe("toWellFormedUtf16", () => { + it("replaces lone surrogates and keeps pairs", () => { + const pair = "\u{1F600}"; + expect(toWellFormedUtf16(`a${pair.slice(0, 1)}b`)).toBe("a\uFFFDb"); + expect(toWellFormedUtf16(`a${pair.slice(1)}`)).toBe("a\uFFFD"); + expect(toWellFormedUtf16(`${pair}${pair.slice(1)}${pair}`)).toBe( + `${pair}\uFFFD${pair}`, + ); + expect(toWellFormedUtf16(`ok ${pair}`)).toBe(`ok ${pair}`); + }); +}); diff --git a/packages/thread-view/src/item-record-messages.ts b/packages/thread-view/src/item-record-messages.ts index 2ddf23ba4e9..9cce4fff5e0 100644 --- a/packages/thread-view/src/item-record-messages.ts +++ b/packages/thread-view/src/item-record-messages.ts @@ -29,6 +29,7 @@ import { extractShellCommandFromString, parseShellCommandIntents, } from "./tool-call-parsing.js"; +import { sliceUtf16Head } from "@bb/text-utils"; type CallStatus = EventProjectionToolCallMessage["status"]; @@ -169,7 +170,7 @@ function normalizeReasoningDetail(detail: string): string { const trimmed = detail.trim(); if (trimmed.length <= MAX_REASONING_DETAIL_CHARS) return trimmed; const dropped = trimmed.length - MAX_REASONING_DETAIL_CHARS; - return `${trimmed.slice(0, MAX_REASONING_DETAIL_CHARS)}\n…[${dropped.toLocaleString("en-US")} more characters truncated]`; + return `${sliceUtf16Head(trimmed, MAX_REASONING_DETAIL_CHARS)}\n…[${dropped.toLocaleString("en-US")} more characters truncated]`; } function reasoningFinalText(item: ThreadEventItem | null): string { diff --git a/plugins/account-pool/src/hub.ts b/plugins/account-pool/src/hub.ts index 9a88d4b2b4c..3ee194edba1 100644 --- a/plugins/account-pool/src/hub.ts +++ b/plugins/account-pool/src/hub.ts @@ -41,6 +41,12 @@ import type { } from "./store.js"; import { parentRequestHeaders, type ParentPool } from "./parent-pool.js"; +function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + const ROUTE = "/api/v1/plugins/account-pool/http"; const DEFAULT_REFRESH_URL = "https://platform.claude.com/v1/oauth/token"; const DEFAULT_USAGE_URL = "https://api.anthropic.com/api/oauth/usage"; @@ -1451,7 +1457,7 @@ export class AccountPoolHub { private setError(accountId: string, message: string | null): void { const quota = this.options.quotas.get(accountId); - const error = message?.slice(0, 1_000) ?? null; + const error = message === null ? null : sliceUtf16Head(message, 1_000); if (quota.error === error) return; this.options.quotas.put({ ...quota, error }); this.options.onAccountsChanged(); diff --git a/plugins/agent-annotations/page-script.ts b/plugins/agent-annotations/page-script.ts index fb19a7d21f7..568a6851cfb 100644 --- a/plugins/agent-annotations/page-script.ts +++ b/plugins/agent-annotations/page-script.ts @@ -60,6 +60,12 @@ function installAgentAnnotations( return event.key === key && !event.isComposing && event.keyCode !== 229; } + function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); + } + const attributePrefix = "data-bb-annotation-"; const attributeKeys = [ "id", @@ -183,9 +189,9 @@ function installAgentAnnotations( const label = element.getAttribute("aria-label") ?? (text.length > 0 && text.length <= 40 ? text : ""); - const suffix = label.length > 0 ? ` "${label.slice(0, 40)}"` : ""; - return `${element.tagName.toLowerCase()}${id}${classes}${suffix}`.slice( - 0, + const suffix = label.length > 0 ? ` "${sliceUtf16Head(label, 40)}"` : ""; + return sliceUtf16Head( + `${element.tagName.toLowerCase()}${id}${classes}${suffix}`, 200, ); } @@ -222,7 +228,7 @@ function installAgentAnnotations( ); current = parent; } - return segments.join(" > ").slice(0, 2000); + return sliceUtf16Head(segments.join(" > "), 2000); } function describe(element: Element) { @@ -232,14 +238,14 @@ function installAgentAnnotations( for (const key of attributeKeys) { const value = element.getAttribute(key); if (value !== null && value.length > 0) { - attributes[key] = value.slice(0, 400); + attributes[key] = sliceUtf16Head(value, 400); } } const styles: Record = {}; for (const key of styleKeys) { const value = computed.getPropertyValue(key); if (value.length > 0) { - styles[key] = value.slice(0, 400); + styles[key] = sliceUtf16Head(value, 400); } } const visibleText = @@ -247,10 +253,10 @@ function installAgentAnnotations( ? element.innerText : (element.textContent ?? ""); return { - tagName: element.tagName.toLowerCase().slice(0, 64), + tagName: sliceUtf16Head(element.tagName.toLowerCase(), 64), name: elementName(element), selector: selectorFor(element), - text: collapse(visibleText).slice(0, 160), + text: sliceUtf16Head(collapse(visibleText), 160), attributes, rect: { x: Math.round(rect.left + scrollX), @@ -357,7 +363,7 @@ function installAgentAnnotations( const annotation = { id, number, - comment: trimmed.slice(0, 4000), + comment: sliceUtf16Head(trimmed, 4000), element, pin, outline, @@ -373,9 +379,9 @@ function installAgentAnnotations( annotation: { id, number, - comment: trimmed.slice(0, 4000), - url: location.href.slice(0, 4096), - title: document.title.slice(0, 1024), + comment: sliceUtf16Head(trimmed, 4000), + url: sliceUtf16Head(location.href, 4096), + title: sliceUtf16Head(document.title, 1024), viewport: { width: innerWidth, height: innerHeight }, element: describe(element), }, @@ -398,7 +404,7 @@ function installAgentAnnotations( } function update(annotation: PinnedAnnotation, comment: string): void { - const trimmed = comment.trim().slice(0, 4000); + const trimmed = sliceUtf16Head(comment.trim(), 4000); if (trimmed.length === 0) { return; } @@ -437,7 +443,7 @@ function installAgentAnnotations( const targetText = part("span", "target-text"); targetText.textContent = element.getAttribute("aria-label") ?? - collapse(element.textContent ?? "").slice(0, 160); + sliceUtf16Head(collapse(element.textContent ?? ""), 160); title.append(tag, targetText); header.append(title); const textarea = document.createElement("textarea"); @@ -612,6 +618,12 @@ function installAgentAnnotations( } function probeReactComponents(annotationId: string) { + function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); + } + const element = document.querySelector( `[data-bb-annotation-${annotationId}]`, ); @@ -643,7 +655,10 @@ function probeReactComponents(annotationId: string) { ? null : (type.displayName ?? candidate.displayName ?? candidate.name); if (typeof name === "string" && name.length > 0) { - components.push({ name: name.slice(0, 200), source: sourceOf(fiber) }); + components.push({ + name: sliceUtf16Head(name, 200), + source: sourceOf(fiber), + }); } fiber = fiber.return; } @@ -655,8 +670,8 @@ function probeReactComponents(annotationId: string) { }): string | null { const debugSource = node._debugSource; if (debugSource !== undefined && typeof debugSource.fileName === "string") { - return `${debugSource.fileName}:${String(debugSource.lineNumber)}`.slice( - 0, + return sliceUtf16Head( + `${debugSource.fileName}:${String(debugSource.lineNumber)}`, 1000, ); } @@ -675,9 +690,9 @@ function probeReactComponents(annotationId: string) { ), ); const match = frameLine?.match(/\(?((?:https?|file):\/\/[^\s)]+)\)?$/); - return ( - match?.[1]?.replace(/\?[^:]*(?=:\d+:\d+$)/, "").slice(0, 1000) ?? null - ); + return match?.[1] === undefined + ? null + : sliceUtf16Head(match[1].replace(/\?[^:]*(?=:\d+:\d+$)/, ""), 1000); } } diff --git a/plugins/ask-user-question/src/translate.ts b/plugins/ask-user-question/src/translate.ts index cb717b3d76e..a7524f44b4d 100644 --- a/plugins/ask-user-question/src/translate.ts +++ b/plugins/ask-user-question/src/translate.ts @@ -10,6 +10,12 @@ import { } from "./contracts.js"; import { NOT_UNIQUE_MESSAGE } from "./tool-definition.js"; +function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + export function validateToolInput(input: ToolInput): string | null { const prompts = input.questions.map((question) => question.question); if (new Set(prompts).size !== prompts.length) return NOT_UNIQUE_MESSAGE; @@ -43,7 +49,7 @@ function normalizePreview(preview: string | undefined): string | undefined { if (preview === undefined) return undefined; const trimmed = preview.trim(); if (trimmed.length === 0) return undefined; - return trimmed.slice(0, MAX_OPTION_PREVIEW_LENGTH); + return sliceUtf16Head(trimmed, MAX_OPTION_PREVIEW_LENGTH); } export function buildInteractionPayload(input: ToolInput): InteractionPayload { diff --git a/plugins/automations/src/script-runner.ts b/plugins/automations/src/script-runner.ts index 0f47c75131d..ee0da57a365 100644 --- a/plugins/automations/src/script-runner.ts +++ b/plugins/automations/src/script-runner.ts @@ -17,6 +17,12 @@ import { scriptsRoot, } from "./script-files.js"; +function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + const execFileAsync = experimental_execHostFile; const SCRIPT_OUTPUT_MAX_BYTES = 1024 * 1024; const SCRIPT_FAILURE_DETAIL_MAX_CHARS = 200; @@ -152,7 +158,7 @@ function firstStderrLine(stderr: string): string | null { .trim(); if (trimmed.length > 0) { return trimmed.length > SCRIPT_FAILURE_DETAIL_MAX_CHARS - ? `${trimmed.slice(0, SCRIPT_FAILURE_DETAIL_MAX_CHARS - 1)}…` + ? `${sliceUtf16Head(trimmed, SCRIPT_FAILURE_DETAIL_MAX_CHARS - 1)}…` : trimmed; } } diff --git a/plugins/bb-account/package.json b/plugins/bb-account/package.json index 0b8b66b583a..d94983fe507 100644 --- a/plugins/bb-account/package.json +++ b/plugins/bb-account/package.json @@ -29,6 +29,7 @@ "dependencies": { "@bb/connect-client": "workspace:*", "@bb/shared-ui": "workspace:*", + "@bb/text-utils": "workspace:*", "zod": "^4.6.7" }, "devDependencies": { diff --git a/plugins/bb-account/src/plugin.ts b/plugins/bb-account/src/plugin.ts index fea6ae74fcf..a7582529683 100644 --- a/plugins/bb-account/src/plugin.ts +++ b/plugins/bb-account/src/plugin.ts @@ -15,11 +15,12 @@ import { } from "./login.js"; import { registerAccountRpc } from "./rpc.js"; import { createKvAccountStore } from "./store.js"; +import { sliceUtf16Head } from "@bb/text-utils"; const CLIENT_NAME_MAX_LENGTH = 100; function clientName(): string { - const name = hostname().trim().slice(0, CLIENT_NAME_MAX_LENGTH); + const name = sliceUtf16Head(hostname().trim(), CLIENT_NAME_MAX_LENGTH); return name.length > 0 ? name : "bb"; } diff --git a/plugins/browser-automation/app.tsx b/plugins/browser-automation/app.tsx index 099121aadcd..2d217ae5fc1 100644 --- a/plugins/browser-automation/app.tsx +++ b/plugins/browser-automation/app.tsx @@ -35,6 +35,7 @@ import { type LightboxTarget, } from "./lightbox-store.js"; import { PREVIEW_DIRECTIVE_ID } from "./preview-directive.js"; +import { sliceUtf16Head } from "./utf16.js"; const MIN_POLL_INTERVAL_MS = 400; const MAX_RETRY_INTERVAL_MS = 15_000; @@ -97,7 +98,7 @@ function pageLocation(url: string): string { if (parsed.protocol === "file:") return decodeURIComponent(parsed.pathname); return parsed.protocol; } catch { - return url.slice(0, 80); + return sliceUtf16Head(url, 80); } } diff --git a/plugins/browser-automation/installer.ts b/plugins/browser-automation/installer.ts index ae04b07817e..00b2c679500 100644 --- a/plugins/browser-automation/installer.ts +++ b/plugins/browser-automation/installer.ts @@ -29,6 +29,7 @@ import { join } from "node:path"; import { pipeline } from "node:stream/promises"; import { setTimeout as delay } from "node:timers/promises"; import { z } from "zod"; +import { sliceUtf16Tail } from "./utf16.js"; export const runtimePlatforms = [ "linux-x64", @@ -242,7 +243,9 @@ async function runCommand( function tail(text: string): string { const trimmed = text.trim(); - return trimmed.length > 1_500 ? `…${trimmed.slice(-1_500)}` : trimmed; + return trimmed.length > 1_500 + ? `…${sliceUtf16Tail(trimmed, 1_500)}` + : trimmed; } const signaturesSchema = z diff --git a/plugins/browser-automation/preview.ts b/plugins/browser-automation/preview.ts index 5bf6e223880..ea52591815e 100644 --- a/plugins/browser-automation/preview.ts +++ b/plugins/browser-automation/preview.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import type { PreviewFrame, PreviewSize } from "./contracts.js"; +import { sliceUtf16Head } from "./utf16.js"; const messageSchema = z.object({ id: z.number().int().optional(), @@ -209,8 +210,8 @@ export function createPreview( latest = { ...latest, sequence: ++sequence, - url: info.url.slice(0, 2_000), - title: info.title.slice(0, 300), + url: sliceUtf16Head(info.url, 2_000), + title: sliceUtf16Head(info.title, 300), }; for (const waiter of [...waiters]) waiter.check(); } @@ -254,8 +255,8 @@ export function createPreview( data: frame.data, width: frame.metadata.deviceWidth, height: frame.metadata.deviceHeight, - url: (target?.url ?? "").slice(0, 2_000), - title: (target?.title ?? "").slice(0, 300), + url: sliceUtf16Head(target?.url ?? "", 2_000), + title: sliceUtf16Head(target?.title ?? "", 300), }; for (const waiter of [...waiters]) waiter.check(); } diff --git a/plugins/browser-automation/runtime.ts b/plugins/browser-automation/runtime.ts index ebf68a83a3b..af83a88eed8 100644 --- a/plugins/browser-automation/runtime.ts +++ b/plugins/browser-automation/runtime.ts @@ -16,6 +16,7 @@ import { outputSchema, type RunOutput } from "./contracts.js"; import { createPreview, type PreviewSource } from "./preview.js"; import { execute, OutputLimitError, supervise } from "./process.js"; import type { ResolvedRuntime } from "./runtime-pin.js"; +import { sliceUtf16Head } from "./utf16.js"; const frameSchema = z.discriminatedUnion("type", [ z.object({ @@ -143,7 +144,7 @@ export async function decodeOutput( for (const value of endpoint.searchParams.values()) if (value) safeText = safeText.split(value).join("[credential]"); return outputSchema.parse({ - text: safeText.slice(0, 160_000), + text: sliceUtf16Head(safeText, 160_000), images, exitCode, }); diff --git a/plugins/browser-automation/utf16.ts b/plugins/browser-automation/utf16.ts new file mode 100644 index 00000000000..ac583b536ed --- /dev/null +++ b/plugins/browser-automation/utf16.ts @@ -0,0 +1,11 @@ +export function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + +export function sliceUtf16Tail(value: string, maxChars: number): string { + const start = Math.max(0, value.length - Math.max(0, maxChars)); + const first = value.charCodeAt(start); + return value.slice(first >= 0xdc00 && first <= 0xdfff ? start + 1 : start); +} diff --git a/plugins/concurrency-limit/server.ts b/plugins/concurrency-limit/server.ts index 58685c434d7..f7b89fbbf5a 100644 --- a/plugins/concurrency-limit/server.ts +++ b/plugins/concurrency-limit/server.ts @@ -17,6 +17,12 @@ import { type LimitConfiguration, } from "./limits.js"; +function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + const CONFIGURATION_KEY = "configuration"; const CAPACITIES_KEY = "host-capacities"; const CONFIGURATION_CHANGED_CHANNEL = "configuration-changed"; @@ -130,7 +136,7 @@ function waitDecision( reason: reason.length <= MAX_REASON_LENGTH ? reason - : `${reason.slice(0, MAX_REASON_LENGTH - 1)}…`, + : `${sliceUtf16Head(reason, MAX_REASON_LENGTH - 1)}…`, }; } diff --git a/plugins/connect/package.json b/plugins/connect/package.json index 2bc4e415324..4dc11a7b214 100644 --- a/plugins/connect/package.json +++ b/plugins/connect/package.json @@ -30,6 +30,7 @@ "@bb/connect-client": "workspace:*", "@bb/domain": "workspace:*", "@bb/shared-ui": "workspace:*", + "@bb/text-utils": "workspace:*", "@bb/tunnel-client": "workspace:*", "@bb/tunnel-contract": "workspace:*", "bb-plugin-bb-account": "workspace:*", diff --git a/plugins/connect/src/machine-code.ts b/plugins/connect/src/machine-code.ts index 53286ffc998..ed6f55207b2 100644 --- a/plugins/connect/src/machine-code.ts +++ b/plugins/connect/src/machine-code.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import { deriveConnectBaseUrl } from "@bb/connect-client"; +import { sliceUtf16Head } from "@bb/text-utils"; export interface MachineCode { code: string; @@ -31,7 +32,7 @@ export async function redeemMachineCode(args: { code: args.code, ...(args.deviceName === null ? {} - : { deviceName: args.deviceName.slice(0, 128) }), + : { deviceName: sliceUtf16Head(args.deviceName, 128) }), kind: "host", }), signal: AbortSignal.any([args.signal, AbortSignal.timeout(10_000)]), diff --git a/plugins/docs/server.ts b/plugins/docs/server.ts index 52c92670fd0..6354bc36870 100644 --- a/plugins/docs/server.ts +++ b/plugins/docs/server.ts @@ -48,6 +48,12 @@ import { type WatchVault, } from "./vault-watches.js"; +function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + const DEFAULT_DIR = "~/Notes"; const PREVIEW_LENGTH = 100; const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024; @@ -276,11 +282,12 @@ function summarizeMarkdown( : documentHeadingIndex >= 0 ? documentHeadingIndex : firstContentIndex; - const title = ( + const title = sliceUtf16Head( document.title ?? - (titleLineIndex >= 0 ? cleanedLines[titleLineIndex] : null) ?? - fallback - ).slice(0, 120); + (titleLineIndex >= 0 ? cleanedLines[titleLineIndex] : null) ?? + fallback, + 120, + ); const firstHeadingIndex = lines.findIndex( (line) => markdownHeadingLevel(line) !== null, ); @@ -290,16 +297,18 @@ function summarizeMarkdown( : firstHeadingIndex >= 0 && cleanedLines[firstHeadingIndex] === title ? firstHeadingIndex : -1; - const preview = cleanedLines - .filter( - (line, index) => - index !== previewHeadingIndex && - line && - line !== title && - !line.startsWith("::html{"), - ) - .join(" ") - .slice(0, PREVIEW_LENGTH); + const preview = sliceUtf16Head( + cleanedLines + .filter( + (line, index) => + index !== previewHeadingIndex && + line && + line !== title && + !line.startsWith("::html{"), + ) + .join(" "), + PREVIEW_LENGTH, + ); return { title, preview }; } @@ -308,21 +317,24 @@ function deriveTitle(content: string, fallback: string): string { } function kebabCase(text: string): string { - return text - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-+|-+$/g, "") - .slice(0, 80) - .replace(/-+$/g, ""); + return sliceUtf16Head( + text + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""), + 80, + ).replace(/-+$/g, ""); } function sanitizeName(raw: string): string { - return raw - .replace(/\.(md|html?)$/i, "") - .replace(/[/\\:*?"<>|]/g, "-") - .replace(/\s+/g, " ") - .trim() - .slice(0, 80); + return sliceUtf16Head( + raw + .replace(/\.(md|html?)$/i, "") + .replace(/[/\\:*?"<>|]/g, "-") + .replace(/\s+/g, " ") + .trim(), + 80, + ); } function parseVaultRow(value: unknown): Vault { diff --git a/plugins/environment-git-worktree/host/paths.ts b/plugins/environment-git-worktree/host/paths.ts index f333930a52e..f6aa492af88 100644 --- a/plugins/environment-git-worktree/host/paths.ts +++ b/plugins/environment-git-worktree/host/paths.ts @@ -2,6 +2,12 @@ import { WorkspaceError } from "bb-environment-provider-host/git"; import { createHash } from "node:crypto"; import path from "node:path"; +function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + const REPO_DIR_NAME_PATTERN = /^[A-Za-z0-9._][A-Za-z0-9._-]*$/; const WINDOWS_RESERVED_NAME_PATTERN = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu; @@ -54,13 +60,12 @@ function slugRepoDirName(candidate: string): string { .replace(/\p{Mark}+/gu, "") .replace(/[^A-Za-z0-9._-]+/gu, "-") .replace(/^[._-]+|[._-]+$/gu, ""); - const readable = ( + const readable = sliceUtf16Head( WINDOWS_RESERVED_NAME_PATTERN.test(normalizedReadable) ? `repo-${normalizedReadable}` - : normalizedReadable - ) - .slice(0, readableLimit) - .replace(/[._-]+$/u, ""); + : normalizedReadable, + readableLimit, + ).replace(/[._-]+$/u, ""); return `${readable || "repo"}-${suffix}`; } diff --git a/plugins/github/server.ts b/plugins/github/server.ts index fe68c98debf..dfae4bbb2c4 100644 --- a/plugins/github/server.ts +++ b/plugins/github/server.ts @@ -13,6 +13,12 @@ import { } from "@get-bb/plugin-sdk"; import { z } from "zod"; +function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + const SYNC_INTERVAL_MS = 15 * 60_000; const SYNC_RETRY_MAX_MS = 5 * 60_000; const SYNC_RETRY_BASE_MS = 30_000; @@ -1009,7 +1015,7 @@ export default async function plugin(bb: BbPluginApi) { const thread = await bb.sdk.threads.spawn({ projectId, environment: { type: "project-default" }, - title: `${ref}: ${title}`.slice(0, 120), + title: sliceUtf16Head(`${ref}: ${title}`, 120), prompt, }); await addLink({ diff --git a/plugins/mcp/src/tools.ts b/plugins/mcp/src/tools.ts index b8954efd0be..46be4a13020 100644 --- a/plugins/mcp/src/tools.ts +++ b/plugins/mcp/src/tools.ts @@ -13,6 +13,12 @@ import { type SandboxLimits, } from "./sandbox.js"; +function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + export const SCRIPT_TOTAL_DEADLINE_MS = 25_000; const CLI_CALL_TIMEOUT_MS = 24_000; const SLEEP_MAX_MS = 20_000; @@ -68,7 +74,7 @@ export interface ToolDependencies { function truncate(text: string): string { if (text.length <= RESULT_MAX_CHARS) return text; - return `${text.slice(0, RESULT_MAX_CHARS)}\n[truncated: ${text.length - RESULT_MAX_CHARS} more characters. Return less: filter or slice inside the script.]`; + return `${sliceUtf16Head(text, RESULT_MAX_CHARS)}\n[truncated: ${text.length - RESULT_MAX_CHARS} more characters. Return less: filter or slice inside the script.]`; } function errorMessage(error: unknown): string { diff --git a/plugins/prompt-library/ranking.ts b/plugins/prompt-library/ranking.ts index 47195d36d7a..9937565aab5 100644 --- a/plugins/prompt-library/ranking.ts +++ b/plugins/prompt-library/ranking.ts @@ -1,5 +1,11 @@ import type { PromptSnippet } from "./contract.js"; +function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + const SNIPPET_LENGTH = 160; const SNIPPET_LEAD = 32; const WORD = /[\p{L}\p{N}]+/gu; @@ -61,7 +67,7 @@ function foldCase(text: string): string { } function normalizeOpening(text: string): string { - return foldCase(text.trimStart().slice(0, OPENING_LENGTH)).replace( + return foldCase(sliceUtf16Head(text.trimStart(), OPENING_LENGTH)).replace( /\s+/gu, " ", ); @@ -213,7 +219,8 @@ export function createSearchIndex() { const index = documents.length; for (const [word, count] of counts) { const list = postings.get(word); - if (list === undefined) postings.set([...word].join(""), [index, count]); + if (list === undefined) + postings.set([...word].join(""), [index, count]); else list.push(index, count); } totalLength += length; @@ -246,7 +253,10 @@ export function createSearchIndex() { const count = documents.length + extras.length; const averageLength = (totalLength + - analyzedExtras.reduce((sum, entry) => sum + entry.analyzed.length, 0)) / + analyzedExtras.reduce( + (sum, entry) => sum + entry.analyzed.length, + 0, + )) / Math.max(1, count); const inverseFrequency = terms.map((_, termIndex) => { const frequency = @@ -263,8 +273,7 @@ export function createSearchIndex() { length: number, matches: readonly TermMatch[], ): SearchMatch { - const norm = - BM25_K1 * (1 - BM25_B + (BM25_B * length) / averageLength); + const norm = BM25_K1 * (1 - BM25_B + (BM25_B * length) / averageLength); let quality = 0; let relevance = 0; matches.forEach(({ weight, frequency }, termIndex) => { diff --git a/plugins/provider-claude-code/src/bridge/provider-commands.ts b/plugins/provider-claude-code/src/bridge/provider-commands.ts index 9bf2e76e96a..c225fe6bd61 100644 --- a/plugins/provider-claude-code/src/bridge/provider-commands.ts +++ b/plugins/provider-claude-code/src/bridge/provider-commands.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import { probeClaudeInitialization } from "./initialization-probe.js"; import { isClaudeSkillPluginName } from "./skill-plugins.js"; +import { sliceUtf16Head } from "../utf16.js"; export const PROVIDER_COMMANDS_STATE_KIND = "bb/provider-commands"; @@ -88,7 +89,7 @@ function isInjectedSkill(name: string): boolean { function truncate(value: string, maxLength: number): string { return value.length <= maxLength ? value - : `${value.slice(0, maxLength - 1).trimEnd()}…`; + : `${sliceUtf16Head(value, maxLength - 1).trimEnd()}…`; } export function toProviderCommandsState( diff --git a/plugins/provider-claude-code/src/interactions.ts b/plugins/provider-claude-code/src/interactions.ts index 2a6b93d654f..4ddbde32bff 100644 --- a/plugins/provider-claude-code/src/interactions.ts +++ b/plugins/provider-claude-code/src/interactions.ts @@ -41,6 +41,7 @@ import { getClaudeFileEditPath, parseClaudeBashCommand, } from "./tool-classification.js"; +import { sliceUtf16Head } from "./utf16.js"; interface ClaudeSessionRulesArgs { permissions: PendingInteractionGrantedPermissionProfile; @@ -194,7 +195,7 @@ function buildClaudeUserQuestion( } return { question: question.prompt, - header: question.shortLabel ?? question.prompt.slice(0, 12), + header: question.shortLabel ?? sliceUtf16Head(question.prompt, 12), options: question.options.map((option) => ({ label: option.label, description: option.description ?? option.label, diff --git a/plugins/provider-claude-code/src/utf16.ts b/plugins/provider-claude-code/src/utf16.ts new file mode 100644 index 00000000000..fe13ee3d0cd --- /dev/null +++ b/plugins/provider-claude-code/src/utf16.ts @@ -0,0 +1,5 @@ +export function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} diff --git a/plugins/provider-codex/src/ai/chatgpt-client.ts b/plugins/provider-codex/src/ai/chatgpt-client.ts index 84a4218135f..073c886d336 100644 --- a/plugins/provider-codex/src/ai/chatgpt-client.ts +++ b/plugins/provider-codex/src/ai/chatgpt-client.ts @@ -15,6 +15,7 @@ import { type CodexOpenAiApiKeyCredentials, } from "./codex-auth.js"; import { AiServiceFailure } from "./failure.js"; +import { sliceUtf16Head } from "../utf16.js"; type InferenceCompleteCommand = CodexAiCompleteInput; type VoiceTranscribeCommand = CodexAiTranscribeInput; @@ -346,7 +347,7 @@ async function readErrorText( maxBytes: CODEX_ERROR_TEXT_MAX_BYTES, overflowBehavior: "truncate", }).catch(() => ""); - return text.length > 400 ? `${text.slice(0, 400)}...` : text; + return text.length > 400 ? `${sliceUtf16Head(text, 400)}...` : text; } type FailureCodes = [generic: CodexAiFailureCode, detail: string]; diff --git a/plugins/provider-codex/src/bridge/app-server-connection.ts b/plugins/provider-codex/src/bridge/app-server-connection.ts index 08f47bb02be..162f149660e 100644 --- a/plugins/provider-codex/src/bridge/app-server-connection.ts +++ b/plugins/provider-codex/src/bridge/app-server-connection.ts @@ -6,6 +6,7 @@ import { experimental_spawnPortableProcess, } from "@get-bb/plugin-sdk/provider-bridge"; import type { z } from "zod"; +import { wellFormedJsonStrings } from "../utf16.js"; const STDERR_TAIL_MAX_CHUNKS = 40; const CLOSE_AFTER_EXIT_GRACE_MS = 1_000; @@ -218,7 +219,7 @@ export function createCodexAppServerConnection( } return; } - stdin.write(JSON.stringify(message) + "\n"); + stdin.write(`${JSON.stringify(message, wellFormedJsonStrings)}\n`); } function finalizeExit(status: { diff --git a/plugins/provider-codex/src/utf16.ts b/plugins/provider-codex/src/utf16.ts new file mode 100644 index 00000000000..22ac097d7cd --- /dev/null +++ b/plugins/provider-codex/src/utf16.ts @@ -0,0 +1,13 @@ +const LONE_SURROGATE = /[\uD800-\uDFFF]/gu; + +export function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + +export function wellFormedJsonStrings(_key: string, value: unknown): unknown { + return typeof value === "string" + ? value.replace(LONE_SURROGATE, "\uFFFD") + : value; +} diff --git a/plugins/push-notifications/notification-text.test.ts b/plugins/push-notifications/notification-text.test.ts new file mode 100644 index 00000000000..73605ecce65 --- /dev/null +++ b/plugins/push-notifications/notification-text.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "vitest"; +import { truncate } from "./notification-text.js"; + +describe("truncate", () => { + it("never leaves half of an emoji before the ellipsis", () => { + const text = `${"a".repeat(8)}\u{1F600}${"b".repeat(10)}`; + + const truncated = truncate(text, 10); + + expect(truncated).toBe(`${"a".repeat(8)}…`); + expect(truncated).not.toMatch(/[\uD800-\uDFFF]/u); + }); +}); diff --git a/plugins/push-notifications/notification-text.ts b/plugins/push-notifications/notification-text.ts index 9a85ac831bf..4efd43a4563 100644 --- a/plugins/push-notifications/notification-text.ts +++ b/plugins/push-notifications/notification-text.ts @@ -1,3 +1,9 @@ +function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + const REFERENCED_TITLE_MAX_LENGTH = 40; const CODE_FENCE_PATTERN = /^\s*(```|~~~)/u; const BREAK_PATTERN = /^\s{0,3}(?:#{1,6}(?:\s|$)|([-*_])(?:\s*\1){2,}\s*$)/u; @@ -10,7 +16,7 @@ const THREAD_REFERENCE_PATTERN = export function truncate(text: string, maxLength: number): string { if (text.length <= maxLength) return text; - return `${text.slice(0, maxLength - 1).trimEnd()}…`; + return `${sliceUtf16Head(text, maxLength - 1).trimEnd()}…`; } function* paragraphs(markdown: string): Generator { diff --git a/plugins/secrets/src/server.ts b/plugins/secrets/src/server.ts index 617219e5eda..1c08995d6fd 100644 --- a/plugins/secrets/src/server.ts +++ b/plugins/secrets/src/server.ts @@ -15,6 +15,12 @@ import { } from "./secret-request.js"; import { assertNoDuplicateAssignments, reconcileDotenv } from "./dotenv.js"; +function sliceUtf16Head(value: string, maxChars: number): string { + const end = Math.min(value.length, Math.max(0, maxChars)); + const last = value.charCodeAt(end - 1); + return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); +} + interface ParsedRequest { names: string[]; purpose: string | null; @@ -163,7 +169,7 @@ const ROW_LABEL_MAX_LENGTH = 80; const ROW_TITLE_MAX_LENGTH = 160; function clampToLength(text: string, max: number): string { - return text.length <= max ? text : `${text.slice(0, max - 1)}\u2026`; + return text.length <= max ? text : `${sliceUtf16Head(text, max - 1)}\u2026`; } function httpStatus(error: unknown): number | null { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f22b9bd78d7..08bb6a9fbbd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -693,6 +693,9 @@ importers: '@bb/server-contract': specifier: workspace:* version: link:../../packages/server-contract + '@bb/text-utils': + specifier: workspace:* + version: link:../../packages/text-utils zod: specifier: 4.6.7 version: 4.6.7 @@ -990,6 +993,9 @@ importers: '@bb/server-contract': specifier: workspace:* version: link:../../packages/server-contract + '@bb/text-utils': + specifier: workspace:* + version: link:../../packages/text-utils '@expo/ui': specifier: 58.0.27 version: 58.0.27(@babel/core@7.29.13)(expo@58.0.23)(react-dom@19.3.1(react@19.3.1))(react-native-worklets@0.13.0(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.3.0)(react@19.3.1))(react@19.3.1))(react-native@0.88.1(@babel/core@7.29.13)(@react-native/metro-config@0.88.1(@babel/core@7.29.13))(@types/react@19.3.0)(react@19.3.1))(react@19.3.1) @@ -1358,6 +1364,9 @@ importers: '@bb/shared-ui': specifier: workspace:* version: link:../../packages/shared-ui + '@bb/text-utils': + specifier: workspace:* + version: link:../../packages/text-utils '@bb/tunnel-contract': specifier: workspace:* version: link:../../packages/tunnel-contract @@ -1613,6 +1622,9 @@ importers: '@bb/provider-bridge-protocol': specifier: workspace:* version: link:../provider-bridge-protocol + '@bb/text-utils': + specifier: workspace:* + version: link:../text-utils zod: specifier: 4.6.7 version: 4.6.7 @@ -2148,6 +2160,9 @@ importers: packages/domain: dependencies: + '@bb/text-utils': + specifier: workspace:* + version: link:../text-utils zod: specifier: 4.6.7 version: 4.6.7 @@ -2219,6 +2234,9 @@ importers: '@bb/process-utils': specifier: workspace:* version: link:../process-utils + '@bb/text-utils': + specifier: workspace:* + version: link:../text-utils '@bb/tunnel-contract': specifier: workspace:* version: link:../tunnel-contract @@ -2456,6 +2474,9 @@ importers: '@bb/process-utils': specifier: workspace:* version: link:../process-utils + '@bb/text-utils': + specifier: workspace:* + version: link:../text-utils '@get-bb/plugin-sdk': specifier: workspace:* version: link:../plugin-sdk @@ -2680,6 +2701,9 @@ importers: '@bb/test-helpers': specifier: workspace:* version: link:../test-helpers + '@bb/text-utils': + specifier: workspace:* + version: link:../text-utils '@bb/tsconfig': specifier: workspace:* version: link:../tsconfig @@ -2783,6 +2807,9 @@ importers: '@bb/provider-bridge-protocol': specifier: workspace:* version: link:../provider-bridge-protocol + '@bb/text-utils': + specifier: workspace:* + version: link:../text-utils zod: specifier: 4.6.7 version: 4.6.7 @@ -3723,6 +3750,9 @@ importers: '@bb/shared-ui': specifier: workspace:* version: link:../../packages/shared-ui + '@bb/text-utils': + specifier: workspace:* + version: link:../../packages/text-utils zod: specifier: 4.6.7 version: 4.6.7 @@ -4116,6 +4146,9 @@ importers: '@bb/shared-ui': specifier: workspace:* version: link:../../packages/shared-ui + '@bb/text-utils': + specifier: workspace:* + version: link:../../packages/text-utils '@bb/tunnel-client': specifier: workspace:* version: link:../../packages/tunnel-client diff --git a/scripts/oxlint-plugin.mjs b/scripts/oxlint-plugin.mjs index f3667f7cc31..c45e9c60972 100644 --- a/scripts/oxlint-plugin.mjs +++ b/scripts/oxlint-plugin.mjs @@ -333,6 +333,252 @@ const imeSafeKeyHandlers = { }, }; +const rawTextTruncationMessage = + "Cutting text at a length cap can split a surrogate pair (an emoji) and leave a lone surrogate, which Codex and the Claude API reject. Use sliceUtf16Head or sliceUtf16Tail from @bb/text-utils (or the plugin's own copy in a forkable plugin)."; +const stringOnlyCutMethods = new Set(["substring", "substr"]); +const stringProducingMethods = new Set([ + "join", + "normalize", + "padEnd", + "padStart", + "replace", + "replaceAll", + "stringify", + "text", + "toLocaleLowerCase", + "toLocaleUpperCase", + "toLowerCase", + "toUpperCase", + "trim", + "trimEnd", + "trimStart", +]); +const stringConsumingMethods = new Set([ + "charAt", + "charCodeAt", + "codePointAt", + "endsWith", + "localeCompare", + "normalize", + "padEnd", + "padStart", + "replace", + "replaceAll", + "split", + "startsWith", + "toLowerCase", + "toUpperCase", + "trim", + "trimEnd", + "trimStart", +]); +const asciiOnlyReceiverName = + /(?:sha|hash|commit|digest|hex|uuid|iso|date|Id|ID|^id)$/u; +const textReceiverName = + /(?:text|title|message|prompt|output|summary|content|body|label|description|command|instructions?|reason|detail|comment|query|preview|stderr|stdout|snippet|excerpt|markdown|subject|heading|name)$/iu; +const looseTextReceiverName = + /(?:value|trimmed|normalized|collapsed|sanitized|cleaned|str|string|href|url)$/iu; +const constantName = /^[A-Z][A-Z0-9_]*$/u; +const capName = /(?:max|limit|budget|cap|chars|width|retained|keep)/iu; +const SHORT_ID_PREFIX_MAX = 16; + +function unwrapExpression(node) { + let current = node; + while ( + current.type === "ParenthesizedExpression" || + current.type === "TSAsExpression" || + current.type === "TSNonNullExpression" || + current.type === "ChainExpression" + ) { + current = current.expression; + } + return current; +} + +function finalName(node) { + const expression = unwrapExpression(node); + if (expression.type === "Identifier") return expression.name; + if ( + expression.type === "MemberExpression" && + !expression.computed && + expression.property.type === "Identifier" + ) { + return expression.property.name; + } + return null; +} + +function calledMethodName(node) { + const expression = unwrapExpression(node); + if (expression.type === "AwaitExpression") { + return calledMethodName(expression.argument); + } + if (expression.type !== "CallExpression") return null; + if (expression.callee.type === "Identifier") return expression.callee.name; + return finalName(expression.callee); +} + +function isNumericLiteral(node) { + const expression = unwrapExpression(node); + return expression.type === "Literal" && typeof expression.value === "number"; +} + +function isNamedCap(node) { + const expression = unwrapExpression(node); + if ( + expression.type !== "Identifier" && + expression.type !== "MemberExpression" + ) { + return false; + } + if (expression.type === "Identifier" && expression.name === "length") { + return true; + } + const name = finalName(expression); + return name !== null && (constantName.test(name) || capName.test(name)); +} + +function isLengthCap(node) { + const expression = unwrapExpression(node); + if (isNumericLiteral(expression)) return expression.value >= 1; + if (isNamedCap(expression)) return true; + if ( + expression.type === "BinaryExpression" && + (expression.operator === "-" || expression.operator === "+") + ) { + return isLengthCap(expression.left) && !isNumericLiteral(expression.left) + ? true + : isNamedCap(expression.right) || + (expression.operator === "-" && isNumericLiteral(expression.left)); + } + if (expression.type === "CallExpression") { + const name = calleeName(expression.callee); + return ( + (name === "Math.max" || name === "Math.min") && + expression.arguments.some(isLengthCap) + ); + } + return false; +} + +function cutLength(node) { + const [first, second] = node.arguments; + if (first === undefined) return null; + const start = unwrapExpression(first); + if (start.type === "Literal" && start.value === 0) { + return second !== undefined && isLengthCap(second) ? second : null; + } + if ( + second === undefined && + start.type === "UnaryExpression" && + start.operator === "-" && + isLengthCap(start.argument) + ) { + return start.argument; + } + return null; +} + +function receiverTextConfidence(receiver) { + const expression = unwrapExpression(receiver); + if (expression.type === "TemplateLiteral") return "likely"; + if (expression.type === "Literal") { + return typeof expression.value === "string" ? "likely" : null; + } + if ( + expression.type === "CallExpression" && + expression.callee.type === "Identifier" && + expression.callee.name === "String" + ) { + return "likely"; + } + const method = calledMethodName(expression); + if (method !== null) + return stringProducingMethods.has(method) ? "likely" : null; + const name = finalName(expression); + if (name === null) return null; + if (textReceiverName.test(name)) return "certain"; + return looseTextReceiverName.test(name) ? "likely" : null; +} + +function isUsedAsString(node) { + const parent = node.parent; + if (parent === undefined || parent === null) return false; + if (parent.type === "TemplateLiteral") return true; + if (parent.type === "BinaryExpression" && parent.operator === "+") { + const other = parent.left === node ? parent.right : parent.left; + const sibling = unwrapExpression(other); + return ( + sibling.type === "TemplateLiteral" || + (sibling.type === "Literal" && typeof sibling.value === "string") + ); + } + if ( + parent.type === "MemberExpression" && + parent.object === node && + !parent.computed && + parent.property.type === "Identifier" + ) { + return stringConsumingMethods.has(parent.property.name); + } + return false; +} + +function isAsciiOnlyReceiver(receiver) { + const expression = unwrapExpression(receiver); + const method = calledMethodName(expression); + if ( + method === "digest" || + method === "toISOString" || + method === "randomUUID" + ) { + return true; + } + const name = finalName(expression); + return name !== null && asciiOnlyReceiverName.test(name); +} + +function isShortIdPrefix(length) { + const expression = unwrapExpression(length); + if (expression.type === "BinaryExpression") { + return isShortIdPrefix(expression.left); + } + return ( + isNumericLiteral(expression) && expression.value <= SHORT_ID_PREFIX_MAX + ); +} + +const noRawTextTruncation = { + create(context) { + return { + CallExpression(node) { + const callee = unwrapExpression(node.callee); + if ( + callee.type !== "MemberExpression" || + callee.computed || + callee.property.type !== "Identifier" + ) { + return; + } + const method = callee.property.name; + if (method !== "slice" && !stringOnlyCutMethods.has(method)) return; + const length = cutLength(node); + if (length === null || isAsciiOnlyReceiver(callee.object)) return; + const confidence = stringOnlyCutMethods.has(method) + ? "certain" + : receiverTextConfidence(callee.object); + if ( + confidence === "certain" || + ((confidence === "likely" || isUsedAsString(node)) && + !isShortIdPrefix(length)) + ) { + context.report({ node, message: rawTextTruncationMessage }); + } + }, + }; + }, +}; + export const rules = { "forkable-plugin-imports": forkablePluginImports, "ime-safe-key-handlers": imeSafeKeyHandlers, @@ -341,6 +587,7 @@ export const rules = { "no-native-title-on-button": noNativeTitleOnButton, "no-native-title-with-aria-label": noNativeTitleWithAriaLabel, "no-raw-resize-observer": noRawResizeObserver, + "no-raw-text-truncation": noRawTextTruncation, }; export default { From 98ba9d04ac86cf308f333b1bcc720f46cfef593a Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Wed, 18 Nov 2026 13:12:42 -0800 Subject: [PATCH 2/6] Run oxlint through node in the truncation rule test so it works on Windows Co-Authored-By: Claude Opus 5.5 --- packages/scripts/test/no-raw-text-truncation.test.mjs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/scripts/test/no-raw-text-truncation.test.mjs b/packages/scripts/test/no-raw-text-truncation.test.mjs index 71f38ac7e80..06aa116752a 100644 --- a/packages/scripts/test/no-raw-text-truncation.test.mjs +++ b/packages/scripts/test/no-raw-text-truncation.test.mjs @@ -8,7 +8,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; const execFileAsync = promisify(execFile); const ROOT = fileURLToPath(new URL("../../../", import.meta.url)); -const OXLINT = join(ROOT, "node_modules", ".bin", "oxlint"); +const OXLINT = join(ROOT, "node_modules", "oxlint", "bin", "oxlint"); const flagged = [ "export const a = (text: string) => text.slice(0, MAX_CHARS);", @@ -59,8 +59,9 @@ describe("bb/no-raw-text-truncation", () => { it("flags length-capped text cuts and leaves index, array, and id cuts alone", async () => { const result = await execFileAsync( - OXLINT, + process.execPath, [ + OXLINT, "-c", join(dir, ".oxlintrc.json"), "-f", @@ -68,7 +69,10 @@ describe("bb/no-raw-text-truncation", () => { join(dir, "fixture.ts"), ], { cwd: dir }, - ).catch((error) => error); + ).catch((error) => { + if (typeof error.code !== "number") throw error; + return error; + }); const flaggedLines = [ ...String(result.stdout).matchAll( /fixture\.ts:(\d+):\d+:.*no-raw-text-truncation/gu, From dfe6917c18259c975b4df3e90d3ba68feacb9128 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Wed, 18 Nov 2026 13:42:44 -0800 Subject: [PATCH 3/6] Bump the plugin SDK to 0.6.160 Co-Authored-By: Claude Opus 5.5 --- packages/domain/src/plugin-sdk-version.ts | 2 +- packages/plugin-sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/domain/src/plugin-sdk-version.ts b/packages/domain/src/plugin-sdk-version.ts index 763233b3e01..45adcc2bcf6 100644 --- a/packages/domain/src/plugin-sdk-version.ts +++ b/packages/domain/src/plugin-sdk-version.ts @@ -1,3 +1,3 @@ -export const PLUGIN_SDK_VERSION = "0.6.159"; +export const PLUGIN_SDK_VERSION = "0.6.160"; export const PLUGIN_SDK_MAJOR = Number(PLUGIN_SDK_VERSION.split(".", 1)[0]); diff --git a/packages/plugin-sdk/package.json b/packages/plugin-sdk/package.json index 38d3df983fd..05a8a00fba1 100644 --- a/packages/plugin-sdk/package.json +++ b/packages/plugin-sdk/package.json @@ -1,6 +1,6 @@ { "name": "@get-bb/plugin-sdk", - "version": "0.6.159", + "version": "0.6.160", "license": "MIT", "homepage": "https://github.com/get-bb/bb#readme", "bugs": { From 811d979380177af3ccd8e1dc9635e699d6b2cb2b Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Wed, 18 Nov 2026 14:22:55 -0800 Subject: [PATCH 4/6] Drop the truncation lint rule and keep safe cuts where text is seen The provider JSON-RPC boundary already makes every string well-formed, so the name-based lint rule only forced rewrites of cuts on text that cannot hold a surrogate pair: ASCII slugs, handles, hostnames and URLs, plus log-only and dev-tooling output. Revert those, keep safe cuts on text that reaches an agent or a person, and serialize JSON-RPC lines with plain JSON.stringify unless the output holds an escaped lone surrogate. Co-Authored-By: Claude Opus 5.5 --- .oxlintrc.json | 12 +- apps/connect-next/src/mcp.ts | 10 +- apps/connect/src/machine-label.ts | 23 +- apps/connect/src/mcp-gate.ts | 10 +- .../desktop/src/connect-machine-enrollment.ts | 11 +- .../src/command-handlers/project.ts | 16 +- .../machines/provider-orchestration.ts | 2 +- .../src/services/system/query-plan-audit.ts | 6 +- .../src/services/threads/title-generation.ts | 18 +- apps/web/src/landing/endpoints.ts | 7 +- apps/web/src/server/account.ts | 3 +- packages/db/src/connection.ts | 5 +- packages/db/src/query-plan-test-guard.ts | 3 +- packages/frp-client/package.json | 1 - packages/frp-client/src/supervisor.ts | 3 +- packages/plugin-build/package.json | 1 - .../src/scope-plugin-utilities.ts | 3 +- .../src/bridge-kit/runtime-json-rpc.ts | 5 +- .../src/conformance/scenarios.ts | 3 +- .../test/no-raw-text-truncation.test.mjs | 87 ------ plugins/agent-annotations/page-script.ts | 4 +- plugins/bb-account/package.json | 1 - plugins/bb-account/src/plugin.ts | 3 +- plugins/browser-automation/preview.ts | 4 +- plugins/docs/server.ts | 13 +- .../environment-git-worktree/host/paths.ts | 15 +- plugins/prompt-library/ranking.ts | 19 +- .../src/bridge/app-server-connection.ts | 4 +- plugins/provider-codex/src/utf16.ts | 13 +- pnpm-lock.yaml | 9 - scripts/oxlint-plugin.mjs | 247 ------------------ 31 files changed, 91 insertions(+), 470 deletions(-) delete mode 100644 packages/scripts/test/no-raw-text-truncation.test.mjs diff --git a/.oxlintrc.json b/.oxlintrc.json index 5700f220a8c..71ec348b1c6 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -9,8 +9,7 @@ "builtin": true }, "rules": { - "bb/no-comments": "error", - "bb/no-raw-text-truncation": "error" + "bb/no-comments": "error" }, "ignorePatterns": [ "**/node_modules/**", @@ -153,14 +152,7 @@ ], "rules": { "no-restricted-imports": "off", - "bb/no-blocking-child-process-call": "off", - "bb/no-raw-text-truncation": "off" - } - }, - { - "files": ["**/test/**", "**/testing/**"], - "rules": { - "bb/no-raw-text-truncation": "off" + "bb/no-blocking-child-process-call": "off" } }, { diff --git a/apps/connect-next/src/mcp.ts b/apps/connect-next/src/mcp.ts index 912d6b7dd6b..43db19499b1 100644 --- a/apps/connect-next/src/mcp.ts +++ b/apps/connect-next/src/mcp.ts @@ -5,7 +5,6 @@ import { mcpResourceForOrigin, } from "@bb/connect-db"; import { json, type Reply } from "./reply.js"; -import { sliceUtf16Head } from "@bb/text-utils"; const MCP_CLIENT_NAME_HEADER_MAX_LENGTH = 80; const MCP_PATH_DECODE_ROUNDS = 4; @@ -82,10 +81,11 @@ export function mcpChallengeReply( } export function headerSafeClientName(value: string): string { - const safe = sliceUtf16Head( - value.replace(/[^\x20-\x7e]/gu, "?").trim(), - MCP_CLIENT_NAME_HEADER_MAX_LENGTH, - ).trim(); + const safe = value + .replace(/[^\x20-\x7e]/gu, "?") + .trim() + .slice(0, MCP_CLIENT_NAME_HEADER_MAX_LENGTH) + .trim(); return safe === "" ? "unknown" : safe; } diff --git a/apps/connect/src/machine-label.ts b/apps/connect/src/machine-label.ts index 3637b569856..9c3005bf699 100644 --- a/apps/connect/src/machine-label.ts +++ b/apps/connect/src/machine-label.ts @@ -12,7 +12,6 @@ import { verifyMachineCredentialDetails } from "./session.js"; import { methodNotAllowed } from "./json-response.js"; import { MACHINE_CREDENTIAL_HEADER } from "./protocol-headers.js"; import type { Env } from "./tunnel-do.js"; -import { sliceUtf16Head } from "@bb/text-utils"; function fallbackLabel(machineId: string): string { const idPrefix = machineId @@ -26,14 +25,13 @@ export function sanitizeMachineLabelBase( desiredName: string, machineId: string, ): string { - const label = sliceUtf16Head( - desiredName - .trim() - .toLowerCase() - .replace(/[^a-z0-9]+/gu, "-") - .replace(/^-+|-+$/gu, ""), - HANDLE_MAX_LENGTH, - ).replace(/-+$/gu, ""); + const label = desiredName + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/gu, "-") + .replace(/^-+|-+$/gu, "") + .slice(0, HANDLE_MAX_LENGTH) + .replace(/-+$/gu, ""); return label.length > 0 && validateLabel(label) === null ? label : fallbackLabel(machineId); @@ -42,10 +40,9 @@ export function sanitizeMachineLabelBase( function labelWithSuffix(base: string, ordinal: number): string { if (ordinal === 1) return base; const suffix = `-${ordinal}`; - const stem = sliceUtf16Head(base, HANDLE_MAX_LENGTH - suffix.length).replace( - /-+$/gu, - "", - ); + const stem = base + .slice(0, HANDLE_MAX_LENGTH - suffix.length) + .replace(/-+$/gu, ""); return `${stem}${suffix}`; } diff --git a/apps/connect/src/mcp-gate.ts b/apps/connect/src/mcp-gate.ts index 3df8a3712f3..5c45bd43002 100644 --- a/apps/connect/src/mcp-gate.ts +++ b/apps/connect/src/mcp-gate.ts @@ -12,7 +12,6 @@ import { first, } from "@bb/connect-db"; import { SettledLookupCache } from "./session.js"; -import { sliceUtf16Head } from "@bb/text-utils"; export const MCP_GRANT_CACHE_TTL_MS = 30_000; const MCP_CLIENT_NAME_HEADER_MAX_LENGTH = 80; @@ -111,10 +110,11 @@ export function mcpChallengeResponse( } export function headerSafeClientName(value: string): string { - const safe = sliceUtf16Head( - value.replace(/[^\x20-\x7e]/gu, "?").trim(), - MCP_CLIENT_NAME_HEADER_MAX_LENGTH, - ).trim(); + const safe = value + .replace(/[^\x20-\x7e]/gu, "?") + .trim() + .slice(0, MCP_CLIENT_NAME_HEADER_MAX_LENGTH) + .trim(); return safe === "" ? "unknown" : safe; } diff --git a/apps/desktop/src/connect-machine-enrollment.ts b/apps/desktop/src/connect-machine-enrollment.ts index 47a81355c26..440eac4675e 100644 --- a/apps/desktop/src/connect-machine-enrollment.ts +++ b/apps/desktop/src/connect-machine-enrollment.ts @@ -6,7 +6,6 @@ import { redeemMachineCredential, type ConnectCredential, } from "@bb/connect-client"; -import { sliceUtf16Head } from "@bb/text-utils"; const CREATE_MACHINE_CODE_RPC = "createMachineCode"; @@ -59,12 +58,10 @@ function redeemFailureCode( } function desktopDeviceName(): string | undefined { - const name = sliceUtf16Head( - hostname() - .replace(/\.local$/u, "") - .trim(), - 128, - ); + const name = hostname() + .replace(/\.local$/u, "") + .trim() + .slice(0, 128); return name.length > 0 ? name : undefined; } diff --git a/apps/host-daemon/src/command-handlers/project.ts b/apps/host-daemon/src/command-handlers/project.ts index 71f3f100e30..59f294c3770 100644 --- a/apps/host-daemon/src/command-handlers/project.ts +++ b/apps/host-daemon/src/command-handlers/project.ts @@ -6,19 +6,17 @@ import { runGit, WorkspaceError, } from "bb-environment-provider-host/workspace-git"; -import { sliceUtf16Head } from "@bb/text-utils"; const PROJECT_CLONE_TIMEOUT_MS = 20 * 60 * 1000; function normalizeProjectSlug(value: string): string { - const slug = sliceUtf16Head( - value - .trim() - .toLowerCase() - .replace(/[^a-z0-9]+/gu, "-") - .replace(/^-+|-+$/gu, ""), - 80, - ).replace(/-+$/u, ""); + const slug = value + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/gu, "-") + .replace(/^-+|-+$/gu, "") + .slice(0, 80) + .replace(/-+$/u, ""); return slug || "project"; } diff --git a/apps/server/src/services/machines/provider-orchestration.ts b/apps/server/src/services/machines/provider-orchestration.ts index 5354c6f6a6c..ed9b03cb458 100644 --- a/apps/server/src/services/machines/provider-orchestration.ts +++ b/apps/server/src/services/machines/provider-orchestration.ts @@ -228,7 +228,7 @@ function lifecycleReporter( deps.hub.notifyHost(hostId, ["host-connected"]); }, log: (text) => { - deps.logger.info({ hostId }, sliceUtf16Tail(text, 16_384)); + deps.logger.info({ hostId }, text.slice(-16_384)); }, }; } diff --git a/apps/server/src/services/system/query-plan-audit.ts b/apps/server/src/services/system/query-plan-audit.ts index ede62462fe3..bcd2431cdc6 100644 --- a/apps/server/src/services/system/query-plan-audit.ts +++ b/apps/server/src/services/system/query-plan-audit.ts @@ -7,7 +7,6 @@ import { import { dirname } from "node:path"; import { fileURLToPath } from "node:url"; import type { ServerLogger } from "../../types.js"; -import { sliceUtf16Head } from "@bb/text-utils"; const MAX_LOGGED_SQL_LENGTH = 1_000; const SERVER_BUNDLE = { @@ -56,10 +55,7 @@ export function createGatedQueryPlanObserver(options: { caller: finding.caller, detail: finding.detail, plan: finding.plan, - sql: sliceUtf16Head( - finding.sql.replace(/\s+/g, " "), - MAX_LOGGED_SQL_LENGTH, - ), + sql: finding.sql.replace(/\s+/g, " ").slice(0, MAX_LOGGED_SQL_LENGTH), }, "Slow SQLite query plan", ); diff --git a/apps/server/src/services/threads/title-generation.ts b/apps/server/src/services/threads/title-generation.ts index 5410716b413..73c18c6177f 100644 --- a/apps/server/src/services/threads/title-generation.ts +++ b/apps/server/src/services/threads/title-generation.ts @@ -13,7 +13,6 @@ import { import { countWords, displayWidth, - sliceUtf16Head, truncateToWidth, truncateToWidthAtWordBoundary, } from "@bb/text-utils"; @@ -174,15 +173,14 @@ export function sanitizeGeneratedTitle(value: string): string | null { } export function sanitizeGeneratedBranchSlug(value: string): string | null { - const slug = sliceUtf16Head( - value - .trim() - .toLowerCase() - .replace(/[^a-z0-9]+/gu, "-") - .replace(/-{2,}/gu, "-") - .replace(/^-+|-+$/gu, ""), - MAX_BRANCH_SLUG_LENGTH, - ).replace(/-+$/u, ""); + const slug = value + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/gu, "-") + .replace(/-{2,}/gu, "-") + .replace(/^-+|-+$/gu, "") + .slice(0, MAX_BRANCH_SLUG_LENGTH) + .replace(/-+$/u, ""); return slug.length > 0 ? slug : null; } diff --git a/apps/web/src/landing/endpoints.ts b/apps/web/src/landing/endpoints.ts index 7d31172f8b4..ee4f3b5c295 100644 --- a/apps/web/src/landing/endpoints.ts +++ b/apps/web/src/landing/endpoints.ts @@ -7,7 +7,6 @@ import { VISIT_PARAM_NAMES, } from "./site"; import type { CtaPlacement, DesktopPlatform } from "./site"; -import { sliceUtf16Head } from "@bb/text-utils"; const POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/capture/?ip=0"; const TRACKING_SOURCE = "landing_worker_redirect"; @@ -508,5 +507,9 @@ function getNonEmptySearchParam( } function truncateProperty(value: string): string { - return sliceUtf16Head(value, MAX_URL_PROPERTY_LENGTH); + if (value.length <= MAX_URL_PROPERTY_LENGTH) { + return value; + } + + return value.slice(0, MAX_URL_PROPERTY_LENGTH); } diff --git a/apps/web/src/server/account.ts b/apps/web/src/server/account.ts index 73f9c0ec7c8..26a4094dd79 100644 --- a/apps/web/src/server/account.ts +++ b/apps/web/src/server/account.ts @@ -24,7 +24,6 @@ import { tunnelUrlForServerUrl, } from "./api.js"; import { generateConnectCode, generateToken } from "./tokens.js"; -import { sliceUtf16Head } from "@bb/text-utils"; export const LINK_POLL_INTERVAL_MS = 2_000; export const LINK_DELIVERY_GRACE_MS = 2 * 60 * 1000; @@ -445,7 +444,7 @@ function labelSlug(value: string): string { } function fitLabel(value: string): string { - return sliceUtf16Head(value, HANDLE_MAX_LENGTH).replace(/-+$/u, ""); + return value.slice(0, HANDLE_MAX_LENGTH).replace(/-+$/u, ""); } export function suggestHandle(githubLogin: string | null): string { diff --git a/packages/db/src/connection.ts b/packages/db/src/connection.ts index 84688317365..0b3a2e32c50 100644 --- a/packages/db/src/connection.ts +++ b/packages/db/src/connection.ts @@ -10,7 +10,6 @@ import { type QueryDiagnosticsLogFields, } from "./query-diagnostics.js"; import * as schema from "./schema.js"; -import { sliceUtf16Head } from "@bb/text-utils"; export interface SlowDbQueryLogFields { bindingArgumentCount: number; @@ -160,8 +159,8 @@ function formatSqlForLog( if (normalized.length <= maxLength) { return normalized; } - return `${sliceUtf16Head( - normalized, + return `${normalized.slice( + 0, maxLength - SQL_TRUNCATION_SUFFIX.length, )}${SQL_TRUNCATION_SUFFIX}`; } diff --git a/packages/db/src/query-plan-test-guard.ts b/packages/db/src/query-plan-test-guard.ts index d3e15d40486..e4ed12650d5 100644 --- a/packages/db/src/query-plan-test-guard.ts +++ b/packages/db/src/query-plan-test-guard.ts @@ -13,7 +13,6 @@ import { } from "./query-plan-guard.js"; import { QUERY_PLAN_ALLOWLIST } from "./query-plan-allowlist.js"; import { createMigratedConnection } from "./testing.js"; -import { sliceUtf16Head } from "@bb/text-utils"; export type QueryPlanReportRow = | ({ kind: "finding" } & QueryPlanFindingReport) @@ -154,7 +153,7 @@ export function formatQueryPlanViolations( return violations .map( (violation) => - `${violation.rule} on ${violation.table} in ${violation.caller}: ${violation.detail}\n plan: ${violation.plan.join(" | ")}\n sql: ${sliceUtf16Head(violation.sql.replace(/\s+/g, " "), 400)}`, + `${violation.rule} on ${violation.table} in ${violation.caller}: ${violation.detail}\n plan: ${violation.plan.join(" | ")}\n sql: ${violation.sql.replace(/\s+/g, " ").slice(0, 400)}`, ) .join("\n\n"); } diff --git a/packages/frp-client/package.json b/packages/frp-client/package.json index e9d99b0438e..38d55c6dc19 100644 --- a/packages/frp-client/package.json +++ b/packages/frp-client/package.json @@ -22,7 +22,6 @@ }, "dependencies": { "@bb/process-utils": "workspace:*", - "@bb/text-utils": "workspace:*", "@bb/tunnel-contract": "workspace:*" }, "devDependencies": { diff --git a/packages/frp-client/src/supervisor.ts b/packages/frp-client/src/supervisor.ts index 8c8c05a239a..2dc58193836 100644 --- a/packages/frp-client/src/supervisor.ts +++ b/packages/frp-client/src/supervisor.ts @@ -12,7 +12,6 @@ import { type TunnelServer, } from "./config.js"; import { cleanFrpcLine, parseFrpcLine } from "./log.js"; -import { sliceUtf16Head } from "@bb/text-utils"; export interface FrpcLogger { info(message: string): void; @@ -90,7 +89,7 @@ export const requestFrpcReload: FrpcReloadRequest = async ( signal: AbortSignal.timeout(timeoutMs), }); if (!response.ok) { - const body = sliceUtf16Head(await response.text(), 500); + const body = (await response.text()).slice(0, 500); throw new Error(`frpc reload answered HTTP ${response.status} ${body}`); } }; diff --git a/packages/plugin-build/package.json b/packages/plugin-build/package.json index 506550ea29d..9c0f50b023e 100644 --- a/packages/plugin-build/package.json +++ b/packages/plugin-build/package.json @@ -27,7 +27,6 @@ "dependencies": { "@bb/domain": "workspace:*", "@bb/process-utils": "workspace:*", - "@bb/text-utils": "workspace:*", "@get-bb/plugin-sdk": "workspace:*", "es-module-lexer": "^2.3.2", "npm": "11.21.2", diff --git a/packages/plugin-build/src/scope-plugin-utilities.ts b/packages/plugin-build/src/scope-plugin-utilities.ts index 9b496d6fb70..e89a4eb3f71 100644 --- a/packages/plugin-build/src/scope-plugin-utilities.ts +++ b/packages/plugin-build/src/scope-plugin-utilities.ts @@ -1,5 +1,4 @@ import { HOST_TAILWIND_CSS } from "./generated/plugin-theme.generated.js"; -import { sliceUtf16Head } from "@bb/text-utils"; const NESTED_STYLE_RULE_AT_RULES = new Set([ "media", @@ -217,7 +216,7 @@ function assertNoUnscopedClassRule(statement: Statement): void { if (!prelude.includes(".")) return; throw new Error( `Compiled plugin CSS has a class rule outside the utilities layer ` + - `(${sliceUtf16Head(prelude, 80)}). Its utilities would leak into the host ` + + `(${prelude.slice(0, 80)}). Its utilities would leak into the host ` + `page; check the Tailwind version against buildTailwindCss()'s input.`, ); } diff --git a/packages/provider-bridge-protocol/src/bridge-kit/runtime-json-rpc.ts b/packages/provider-bridge-protocol/src/bridge-kit/runtime-json-rpc.ts index 274f0dd396c..e96fc796edb 100644 --- a/packages/provider-bridge-protocol/src/bridge-kit/runtime-json-rpc.ts +++ b/packages/provider-bridge-protocol/src/bridge-kit/runtime-json-rpc.ts @@ -205,7 +205,10 @@ function wellFormedStrings(_key: string, value: unknown): unknown { } export function serializeJsonRpcLine(message: object): string { - return JSON.stringify(message, wellFormedStrings); + const line = JSON.stringify(message); + return line.includes("\\ud") + ? JSON.stringify(message, wellFormedStrings) + : line; } function writeJsonRpcMessage( diff --git a/packages/provider-bridge-protocol/src/conformance/scenarios.ts b/packages/provider-bridge-protocol/src/conformance/scenarios.ts index 019634e2662..b4640c9bcb9 100644 --- a/packages/provider-bridge-protocol/src/conformance/scenarios.ts +++ b/packages/provider-bridge-protocol/src/conformance/scenarios.ts @@ -26,7 +26,6 @@ import { type JsonRpcWireMessage, } from "./client.js"; import type { ConformanceCheckResult } from "./types.js"; -import { sliceUtf16Head } from "@bb/text-utils"; export interface ConformanceSessionFixture { cwd: string; @@ -606,7 +605,7 @@ export async function runSessionLifecycleScenarios( : fail( "events/schema-valid", title2, - `${invalid.length} assembled event(s) failed validation; first: ${sliceUtf16Head(JSON.stringify(invalid[0]?.event), 400)}`, + `${invalid.length} assembled event(s) failed validation; first: ${JSON.stringify(invalid[0]?.event).slice(0, 400)}`, ), ); } diff --git a/packages/scripts/test/no-raw-text-truncation.test.mjs b/packages/scripts/test/no-raw-text-truncation.test.mjs deleted file mode 100644 index 06aa116752a..00000000000 --- a/packages/scripts/test/no-raw-text-truncation.test.mjs +++ /dev/null @@ -1,87 +0,0 @@ -import { execFile } from "node:child_process"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { fileURLToPath } from "node:url"; -import { promisify } from "node:util"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; - -const execFileAsync = promisify(execFile); -const ROOT = fileURLToPath(new URL("../../../", import.meta.url)); -const OXLINT = join(ROOT, "node_modules", "oxlint", "bin", "oxlint"); - -const flagged = [ - "export const a = (text: string) => text.slice(0, MAX_CHARS);", - "export const b = (command: string) => `${command.slice(0, 200)}…`;", - "export const c = (value: string, limit: number) => value.trim().slice(0, limit);", - "export const d = (stderr: string) => stderr.slice(-8192);", - "export const e = (name: string) => name.substring(0, 40);", - "export const f = (ref: string, title: string) => `${ref}: ${title}`.slice(0, 120);", - "export const g = (output: string, maxLength: number) => output.slice(0, maxLength - 1).trimEnd();", -]; -const allowed = [ - "export const h = (items: string[]) => items.slice(0, MAX_ITEMS);", - "export const i = (line: string, separatorIndex: number) => line.slice(0, separatorIndex);", - "export const j = (sha: string) => sha.slice(0, 12);", - "export const k = (commit: string) => `${commit.slice(0, 7)}`;", - "export const l = (text: string) => text.slice(0, -1);", - "export const m = (code: string) => `${code.slice(0, 4)}-${code.slice(4)}`;", - "export const n = (text: string, end: number) => text.slice(0, end);", -]; - -describe("bb/no-raw-text-truncation", () => { - let dir; - - beforeAll(async () => { - dir = await mkdtemp(join(tmpdir(), "no-raw-text-truncation-")); - await writeFile( - join(dir, ".oxlintrc.json"), - JSON.stringify({ - jsPlugins: [join(ROOT, "scripts", "oxlint-plugin.mjs")], - categories: { correctness: "off" }, - rules: { "bb/no-raw-text-truncation": "error" }, - }), - ); - await writeFile( - join(dir, "fixture.ts"), - [ - "declare const MAX_CHARS: number;", - "declare const MAX_ITEMS: number;", - ...flagged, - ...allowed, - ].join("\n"), - ); - }); - - afterAll(async () => { - await rm(dir, { recursive: true, force: true }); - }); - - it("flags length-capped text cuts and leaves index, array, and id cuts alone", async () => { - const result = await execFileAsync( - process.execPath, - [ - OXLINT, - "-c", - join(dir, ".oxlintrc.json"), - "-f", - "unix", - join(dir, "fixture.ts"), - ], - { cwd: dir }, - ).catch((error) => { - if (typeof error.code !== "number") throw error; - return error; - }); - const flaggedLines = [ - ...String(result.stdout).matchAll( - /fixture\.ts:(\d+):\d+:.*no-raw-text-truncation/gu, - ), - ].map((match) => Number(match[1])); - - const firstCaseLine = 3; - expect(flaggedLines).toEqual( - flagged.map((_source, index) => firstCaseLine + index), - ); - }); -}); diff --git a/plugins/agent-annotations/page-script.ts b/plugins/agent-annotations/page-script.ts index 568a6851cfb..dc1de125b68 100644 --- a/plugins/agent-annotations/page-script.ts +++ b/plugins/agent-annotations/page-script.ts @@ -253,7 +253,7 @@ function installAgentAnnotations( ? element.innerText : (element.textContent ?? ""); return { - tagName: sliceUtf16Head(element.tagName.toLowerCase(), 64), + tagName: element.tagName.toLowerCase().slice(0, 64), name: elementName(element), selector: selectorFor(element), text: sliceUtf16Head(collapse(visibleText), 160), @@ -380,7 +380,7 @@ function installAgentAnnotations( id, number, comment: sliceUtf16Head(trimmed, 4000), - url: sliceUtf16Head(location.href, 4096), + url: location.href.slice(0, 4096), title: sliceUtf16Head(document.title, 1024), viewport: { width: innerWidth, height: innerHeight }, element: describe(element), diff --git a/plugins/bb-account/package.json b/plugins/bb-account/package.json index d94983fe507..0b8b66b583a 100644 --- a/plugins/bb-account/package.json +++ b/plugins/bb-account/package.json @@ -29,7 +29,6 @@ "dependencies": { "@bb/connect-client": "workspace:*", "@bb/shared-ui": "workspace:*", - "@bb/text-utils": "workspace:*", "zod": "^4.6.7" }, "devDependencies": { diff --git a/plugins/bb-account/src/plugin.ts b/plugins/bb-account/src/plugin.ts index a7582529683..fea6ae74fcf 100644 --- a/plugins/bb-account/src/plugin.ts +++ b/plugins/bb-account/src/plugin.ts @@ -15,12 +15,11 @@ import { } from "./login.js"; import { registerAccountRpc } from "./rpc.js"; import { createKvAccountStore } from "./store.js"; -import { sliceUtf16Head } from "@bb/text-utils"; const CLIENT_NAME_MAX_LENGTH = 100; function clientName(): string { - const name = sliceUtf16Head(hostname().trim(), CLIENT_NAME_MAX_LENGTH); + const name = hostname().trim().slice(0, CLIENT_NAME_MAX_LENGTH); return name.length > 0 ? name : "bb"; } diff --git a/plugins/browser-automation/preview.ts b/plugins/browser-automation/preview.ts index ea52591815e..cfd6e3cf87d 100644 --- a/plugins/browser-automation/preview.ts +++ b/plugins/browser-automation/preview.ts @@ -210,7 +210,7 @@ export function createPreview( latest = { ...latest, sequence: ++sequence, - url: sliceUtf16Head(info.url, 2_000), + url: info.url.slice(0, 2_000), title: sliceUtf16Head(info.title, 300), }; for (const waiter of [...waiters]) waiter.check(); @@ -255,7 +255,7 @@ export function createPreview( data: frame.data, width: frame.metadata.deviceWidth, height: frame.metadata.deviceHeight, - url: sliceUtf16Head(target?.url ?? "", 2_000), + url: (target?.url ?? "").slice(0, 2_000), title: sliceUtf16Head(target?.title ?? "", 300), }; for (const waiter of [...waiters]) waiter.check(); diff --git a/plugins/docs/server.ts b/plugins/docs/server.ts index 6354bc36870..c715316e328 100644 --- a/plugins/docs/server.ts +++ b/plugins/docs/server.ts @@ -317,13 +317,12 @@ function deriveTitle(content: string, fallback: string): string { } function kebabCase(text: string): string { - return sliceUtf16Head( - text - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-+|-+$/g, ""), - 80, - ).replace(/-+$/g, ""); + return text + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 80) + .replace(/-+$/g, ""); } function sanitizeName(raw: string): string { diff --git a/plugins/environment-git-worktree/host/paths.ts b/plugins/environment-git-worktree/host/paths.ts index f6aa492af88..f333930a52e 100644 --- a/plugins/environment-git-worktree/host/paths.ts +++ b/plugins/environment-git-worktree/host/paths.ts @@ -2,12 +2,6 @@ import { WorkspaceError } from "bb-environment-provider-host/git"; import { createHash } from "node:crypto"; import path from "node:path"; -function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - const REPO_DIR_NAME_PATTERN = /^[A-Za-z0-9._][A-Za-z0-9._-]*$/; const WINDOWS_RESERVED_NAME_PATTERN = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu; @@ -60,12 +54,13 @@ function slugRepoDirName(candidate: string): string { .replace(/\p{Mark}+/gu, "") .replace(/[^A-Za-z0-9._-]+/gu, "-") .replace(/^[._-]+|[._-]+$/gu, ""); - const readable = sliceUtf16Head( + const readable = ( WINDOWS_RESERVED_NAME_PATTERN.test(normalizedReadable) ? `repo-${normalizedReadable}` - : normalizedReadable, - readableLimit, - ).replace(/[._-]+$/u, ""); + : normalizedReadable + ) + .slice(0, readableLimit) + .replace(/[._-]+$/u, ""); return `${readable || "repo"}-${suffix}`; } diff --git a/plugins/prompt-library/ranking.ts b/plugins/prompt-library/ranking.ts index 9937565aab5..47195d36d7a 100644 --- a/plugins/prompt-library/ranking.ts +++ b/plugins/prompt-library/ranking.ts @@ -1,11 +1,5 @@ import type { PromptSnippet } from "./contract.js"; -function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - const SNIPPET_LENGTH = 160; const SNIPPET_LEAD = 32; const WORD = /[\p{L}\p{N}]+/gu; @@ -67,7 +61,7 @@ function foldCase(text: string): string { } function normalizeOpening(text: string): string { - return foldCase(sliceUtf16Head(text.trimStart(), OPENING_LENGTH)).replace( + return foldCase(text.trimStart().slice(0, OPENING_LENGTH)).replace( /\s+/gu, " ", ); @@ -219,8 +213,7 @@ export function createSearchIndex() { const index = documents.length; for (const [word, count] of counts) { const list = postings.get(word); - if (list === undefined) - postings.set([...word].join(""), [index, count]); + if (list === undefined) postings.set([...word].join(""), [index, count]); else list.push(index, count); } totalLength += length; @@ -253,10 +246,7 @@ export function createSearchIndex() { const count = documents.length + extras.length; const averageLength = (totalLength + - analyzedExtras.reduce( - (sum, entry) => sum + entry.analyzed.length, - 0, - )) / + analyzedExtras.reduce((sum, entry) => sum + entry.analyzed.length, 0)) / Math.max(1, count); const inverseFrequency = terms.map((_, termIndex) => { const frequency = @@ -273,7 +263,8 @@ export function createSearchIndex() { length: number, matches: readonly TermMatch[], ): SearchMatch { - const norm = BM25_K1 * (1 - BM25_B + (BM25_B * length) / averageLength); + const norm = + BM25_K1 * (1 - BM25_B + (BM25_B * length) / averageLength); let quality = 0; let relevance = 0; matches.forEach(({ weight, frequency }, termIndex) => { diff --git a/plugins/provider-codex/src/bridge/app-server-connection.ts b/plugins/provider-codex/src/bridge/app-server-connection.ts index 162f149660e..490e2640f24 100644 --- a/plugins/provider-codex/src/bridge/app-server-connection.ts +++ b/plugins/provider-codex/src/bridge/app-server-connection.ts @@ -6,7 +6,7 @@ import { experimental_spawnPortableProcess, } from "@get-bb/plugin-sdk/provider-bridge"; import type { z } from "zod"; -import { wellFormedJsonStrings } from "../utf16.js"; +import { serializeWellFormedJson } from "../utf16.js"; const STDERR_TAIL_MAX_CHUNKS = 40; const CLOSE_AFTER_EXIT_GRACE_MS = 1_000; @@ -219,7 +219,7 @@ export function createCodexAppServerConnection( } return; } - stdin.write(`${JSON.stringify(message, wellFormedJsonStrings)}\n`); + stdin.write(`${serializeWellFormedJson(message)}\n`); } function finalizeExit(status: { diff --git a/plugins/provider-codex/src/utf16.ts b/plugins/provider-codex/src/utf16.ts index 22ac097d7cd..1efaa11fbc9 100644 --- a/plugins/provider-codex/src/utf16.ts +++ b/plugins/provider-codex/src/utf16.ts @@ -6,8 +6,13 @@ export function sliceUtf16Head(value: string, maxChars: number): string { return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); } -export function wellFormedJsonStrings(_key: string, value: unknown): unknown { - return typeof value === "string" - ? value.replace(LONE_SURROGATE, "\uFFFD") - : value; +function wellFormedStrings(_key: string, value: unknown): unknown { + return typeof value === "string" ? value.replace(LONE_SURROGATE, "�") : value; +} + +export function serializeWellFormedJson(message: unknown): string { + const line = JSON.stringify(message); + return line.includes("\\ud") + ? JSON.stringify(message, wellFormedStrings) + : line; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 08bb6a9fbbd..45f41297c4f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2234,9 +2234,6 @@ importers: '@bb/process-utils': specifier: workspace:* version: link:../process-utils - '@bb/text-utils': - specifier: workspace:* - version: link:../text-utils '@bb/tunnel-contract': specifier: workspace:* version: link:../tunnel-contract @@ -2474,9 +2471,6 @@ importers: '@bb/process-utils': specifier: workspace:* version: link:../process-utils - '@bb/text-utils': - specifier: workspace:* - version: link:../text-utils '@get-bb/plugin-sdk': specifier: workspace:* version: link:../plugin-sdk @@ -3750,9 +3744,6 @@ importers: '@bb/shared-ui': specifier: workspace:* version: link:../../packages/shared-ui - '@bb/text-utils': - specifier: workspace:* - version: link:../../packages/text-utils zod: specifier: 4.6.7 version: 4.6.7 diff --git a/scripts/oxlint-plugin.mjs b/scripts/oxlint-plugin.mjs index c45e9c60972..f3667f7cc31 100644 --- a/scripts/oxlint-plugin.mjs +++ b/scripts/oxlint-plugin.mjs @@ -333,252 +333,6 @@ const imeSafeKeyHandlers = { }, }; -const rawTextTruncationMessage = - "Cutting text at a length cap can split a surrogate pair (an emoji) and leave a lone surrogate, which Codex and the Claude API reject. Use sliceUtf16Head or sliceUtf16Tail from @bb/text-utils (or the plugin's own copy in a forkable plugin)."; -const stringOnlyCutMethods = new Set(["substring", "substr"]); -const stringProducingMethods = new Set([ - "join", - "normalize", - "padEnd", - "padStart", - "replace", - "replaceAll", - "stringify", - "text", - "toLocaleLowerCase", - "toLocaleUpperCase", - "toLowerCase", - "toUpperCase", - "trim", - "trimEnd", - "trimStart", -]); -const stringConsumingMethods = new Set([ - "charAt", - "charCodeAt", - "codePointAt", - "endsWith", - "localeCompare", - "normalize", - "padEnd", - "padStart", - "replace", - "replaceAll", - "split", - "startsWith", - "toLowerCase", - "toUpperCase", - "trim", - "trimEnd", - "trimStart", -]); -const asciiOnlyReceiverName = - /(?:sha|hash|commit|digest|hex|uuid|iso|date|Id|ID|^id)$/u; -const textReceiverName = - /(?:text|title|message|prompt|output|summary|content|body|label|description|command|instructions?|reason|detail|comment|query|preview|stderr|stdout|snippet|excerpt|markdown|subject|heading|name)$/iu; -const looseTextReceiverName = - /(?:value|trimmed|normalized|collapsed|sanitized|cleaned|str|string|href|url)$/iu; -const constantName = /^[A-Z][A-Z0-9_]*$/u; -const capName = /(?:max|limit|budget|cap|chars|width|retained|keep)/iu; -const SHORT_ID_PREFIX_MAX = 16; - -function unwrapExpression(node) { - let current = node; - while ( - current.type === "ParenthesizedExpression" || - current.type === "TSAsExpression" || - current.type === "TSNonNullExpression" || - current.type === "ChainExpression" - ) { - current = current.expression; - } - return current; -} - -function finalName(node) { - const expression = unwrapExpression(node); - if (expression.type === "Identifier") return expression.name; - if ( - expression.type === "MemberExpression" && - !expression.computed && - expression.property.type === "Identifier" - ) { - return expression.property.name; - } - return null; -} - -function calledMethodName(node) { - const expression = unwrapExpression(node); - if (expression.type === "AwaitExpression") { - return calledMethodName(expression.argument); - } - if (expression.type !== "CallExpression") return null; - if (expression.callee.type === "Identifier") return expression.callee.name; - return finalName(expression.callee); -} - -function isNumericLiteral(node) { - const expression = unwrapExpression(node); - return expression.type === "Literal" && typeof expression.value === "number"; -} - -function isNamedCap(node) { - const expression = unwrapExpression(node); - if ( - expression.type !== "Identifier" && - expression.type !== "MemberExpression" - ) { - return false; - } - if (expression.type === "Identifier" && expression.name === "length") { - return true; - } - const name = finalName(expression); - return name !== null && (constantName.test(name) || capName.test(name)); -} - -function isLengthCap(node) { - const expression = unwrapExpression(node); - if (isNumericLiteral(expression)) return expression.value >= 1; - if (isNamedCap(expression)) return true; - if ( - expression.type === "BinaryExpression" && - (expression.operator === "-" || expression.operator === "+") - ) { - return isLengthCap(expression.left) && !isNumericLiteral(expression.left) - ? true - : isNamedCap(expression.right) || - (expression.operator === "-" && isNumericLiteral(expression.left)); - } - if (expression.type === "CallExpression") { - const name = calleeName(expression.callee); - return ( - (name === "Math.max" || name === "Math.min") && - expression.arguments.some(isLengthCap) - ); - } - return false; -} - -function cutLength(node) { - const [first, second] = node.arguments; - if (first === undefined) return null; - const start = unwrapExpression(first); - if (start.type === "Literal" && start.value === 0) { - return second !== undefined && isLengthCap(second) ? second : null; - } - if ( - second === undefined && - start.type === "UnaryExpression" && - start.operator === "-" && - isLengthCap(start.argument) - ) { - return start.argument; - } - return null; -} - -function receiverTextConfidence(receiver) { - const expression = unwrapExpression(receiver); - if (expression.type === "TemplateLiteral") return "likely"; - if (expression.type === "Literal") { - return typeof expression.value === "string" ? "likely" : null; - } - if ( - expression.type === "CallExpression" && - expression.callee.type === "Identifier" && - expression.callee.name === "String" - ) { - return "likely"; - } - const method = calledMethodName(expression); - if (method !== null) - return stringProducingMethods.has(method) ? "likely" : null; - const name = finalName(expression); - if (name === null) return null; - if (textReceiverName.test(name)) return "certain"; - return looseTextReceiverName.test(name) ? "likely" : null; -} - -function isUsedAsString(node) { - const parent = node.parent; - if (parent === undefined || parent === null) return false; - if (parent.type === "TemplateLiteral") return true; - if (parent.type === "BinaryExpression" && parent.operator === "+") { - const other = parent.left === node ? parent.right : parent.left; - const sibling = unwrapExpression(other); - return ( - sibling.type === "TemplateLiteral" || - (sibling.type === "Literal" && typeof sibling.value === "string") - ); - } - if ( - parent.type === "MemberExpression" && - parent.object === node && - !parent.computed && - parent.property.type === "Identifier" - ) { - return stringConsumingMethods.has(parent.property.name); - } - return false; -} - -function isAsciiOnlyReceiver(receiver) { - const expression = unwrapExpression(receiver); - const method = calledMethodName(expression); - if ( - method === "digest" || - method === "toISOString" || - method === "randomUUID" - ) { - return true; - } - const name = finalName(expression); - return name !== null && asciiOnlyReceiverName.test(name); -} - -function isShortIdPrefix(length) { - const expression = unwrapExpression(length); - if (expression.type === "BinaryExpression") { - return isShortIdPrefix(expression.left); - } - return ( - isNumericLiteral(expression) && expression.value <= SHORT_ID_PREFIX_MAX - ); -} - -const noRawTextTruncation = { - create(context) { - return { - CallExpression(node) { - const callee = unwrapExpression(node.callee); - if ( - callee.type !== "MemberExpression" || - callee.computed || - callee.property.type !== "Identifier" - ) { - return; - } - const method = callee.property.name; - if (method !== "slice" && !stringOnlyCutMethods.has(method)) return; - const length = cutLength(node); - if (length === null || isAsciiOnlyReceiver(callee.object)) return; - const confidence = stringOnlyCutMethods.has(method) - ? "certain" - : receiverTextConfidence(callee.object); - if ( - confidence === "certain" || - ((confidence === "likely" || isUsedAsString(node)) && - !isShortIdPrefix(length)) - ) { - context.report({ node, message: rawTextTruncationMessage }); - } - }, - }; - }, -}; - export const rules = { "forkable-plugin-imports": forkablePluginImports, "ime-safe-key-handlers": imeSafeKeyHandlers, @@ -587,7 +341,6 @@ export const rules = { "no-native-title-on-button": noNativeTitleOnButton, "no-native-title-with-aria-label": noNativeTitleWithAriaLabel, "no-raw-resize-observer": noRawResizeObserver, - "no-raw-text-truncation": noRawTextTruncation, }; export default { From 6dd035674d35b73fdb6708a6e69da2d1fa99ce9c Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Wed, 18 Nov 2026 14:33:40 -0800 Subject: [PATCH 5/6] Bump the plugin SDK to 0.6.161 Co-Authored-By: Claude Opus 5.5 --- packages/domain/src/plugin-sdk-version.ts | 2 +- packages/plugin-sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/domain/src/plugin-sdk-version.ts b/packages/domain/src/plugin-sdk-version.ts index 45adcc2bcf6..b1832abd476 100644 --- a/packages/domain/src/plugin-sdk-version.ts +++ b/packages/domain/src/plugin-sdk-version.ts @@ -1,3 +1,3 @@ -export const PLUGIN_SDK_VERSION = "0.6.160"; +export const PLUGIN_SDK_VERSION = "0.6.161"; export const PLUGIN_SDK_MAJOR = Number(PLUGIN_SDK_VERSION.split(".", 1)[0]); diff --git a/packages/plugin-sdk/package.json b/packages/plugin-sdk/package.json index af12a195e47..44c9e08435a 100644 --- a/packages/plugin-sdk/package.json +++ b/packages/plugin-sdk/package.json @@ -1,6 +1,6 @@ { "name": "@get-bb/plugin-sdk", - "version": "0.6.160", + "version": "0.6.161", "license": "MIT", "homepage": "https://github.com/get-bb/bb#readme", "bugs": { From 2d6fa480c054107b82ec30ca9451597d567a52d8 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Wed, 18 Nov 2026 14:48:44 -0800 Subject: [PATCH 6/6] Give plugins bb's UTF-16 cut and JSON-RPC serializer through the SDK Plugins carried their own copies of sliceUtf16Head/Tail and the Codex bridge its own well-formed JSON writer. Export core's functions instead: experimental_sliceUtf16Head from the SDK root and /app, experimental_sliceUtf16Head/Tail from /host (the host root runtime is a stub), and experimental_serializeJsonRpcLine from /provider-bridge. Plugins that use the runtime-provided root or /app export require SDK 0.6.161. Co-Authored-By: Claude Opus 5.5 --- apps/app/src/lib/plugin-sdk-app-impl.tsx | 2 + docs/api_to_audit.md | 46 +++++++++++++++++++ packages/plugin-sdk/src/app-contract.ts | 6 +++ packages/plugin-sdk/src/app.ts | 3 ++ packages/plugin-sdk/src/host.ts | 9 ++++ packages/plugin-sdk/src/index.ts | 7 +++ packages/plugin-sdk/src/provider-bridge.ts | 8 ++++ packages/plugin-sdk/src/testing/app.tsx | 2 + plugins/account-pool/package.json | 2 +- plugins/account-pool/src/hub.ts | 7 +-- plugins/ask-user-question/package.json | 2 +- plugins/ask-user-question/src/translate.ts | 7 +-- plugins/automations/package.json | 2 +- plugins/automations/src/script-runner.ts | 7 +-- plugins/browser-automation/app.tsx | 2 +- plugins/browser-automation/installer.ts | 2 +- plugins/browser-automation/package.json | 2 +- plugins/browser-automation/preview.ts | 2 +- plugins/browser-automation/runtime.ts | 2 +- plugins/browser-automation/utf16.ts | 11 ----- plugins/concurrency-limit/package.json | 2 +- plugins/concurrency-limit/server.ts | 7 +-- plugins/docs/package.json | 2 +- plugins/docs/server.ts | 7 +-- plugins/github/package.json | 2 +- plugins/github/server.ts | 7 +-- plugins/mcp/package.json | 2 +- plugins/mcp/src/tools.ts | 7 +-- plugins/plugin-api-docs/src/surfaces.ts | 4 ++ .../src/bridge/provider-commands.ts | 2 +- .../provider-claude-code/src/interactions.ts | 2 +- plugins/provider-claude-code/src/utf16.ts | 5 -- .../provider-codex/src/ai/chatgpt-client.ts | 2 +- .../src/bridge/app-server-connection.ts | 4 +- plugins/provider-codex/src/utf16.ts | 18 -------- .../push-notifications/notification-text.ts | 7 +-- plugins/push-notifications/package.json | 2 +- plugins/secrets/package.json | 2 +- plugins/secrets/src/server.ts | 7 +-- 39 files changed, 115 insertions(+), 107 deletions(-) delete mode 100644 plugins/browser-automation/utf16.ts delete mode 100644 plugins/provider-claude-code/src/utf16.ts delete mode 100644 plugins/provider-codex/src/utf16.ts diff --git a/apps/app/src/lib/plugin-sdk-app-impl.tsx b/apps/app/src/lib/plugin-sdk-app-impl.tsx index 3d4834bbbbf..1142c0bb93c 100644 --- a/apps/app/src/lib/plugin-sdk-app-impl.tsx +++ b/apps/app/src/lib/plugin-sdk-app-impl.tsx @@ -1,5 +1,6 @@ import { applicationLinkApprovals } from "./application-url"; import { matchesAppShortcutKey } from "@bb/domain"; +import { sliceUtf16Head } from "@bb/text-utils"; import { LazyPluginMarkdown, LazyPluginDiff, @@ -187,6 +188,7 @@ export const pluginSdkAppImplementation = { experimental_FailedVoiceRecordings: FailedVoiceRecordings, experimental_ShortcutHint: AppCommandShortcutHint, experimental_matchesShortcutKey: matchesAppShortcutKey, + experimental_sliceUtf16Head: sliceUtf16Head, experimental_ImageLightbox: ImageLightbox, experimental_PromptMentionIcon: ComposerMentionIcon, experimental_describePromptMention: describePromptMention, diff --git a/docs/api_to_audit.md b/docs/api_to_audit.md index 012998997f1..7e616f5dc97 100644 --- a/docs/api_to_audit.md +++ b/docs/api_to_audit.md @@ -45,6 +45,32 @@ Docs: Plugin Guide, The bb SDK (`plugins/plugin-api-docs/src/surfaces.ts`). Before stabilization, audit drive/UNC ambiguity, separator and case rules, relative escapes, and whether more callers need resolution rather than joining. +## UTF-16-safe cuts (`@get-bb/plugin-sdk`, `@get-bb/plugin-sdk/app`, `@get-bb/plugin-sdk/host`) + +`experimental_sliceUtf16Head(value, maxChars)` keeps at most `maxChars` UTF-16 +code units from the start of `value`, and `experimental_sliceUtf16Tail(value, +maxChars)` (`@get-bb/plugin-sdk/host` only) keeps them from the end. When the +cut would land inside a surrogate pair, the whole pair is dropped, so the +result never holds a lone surrogate (half an emoji). A negative `maxChars` +returns an empty string. The root and `/app` exports serve server and app +code; `/host` serves host workers and provider bridges, whose root SDK runtime +is a stub. + +These re-export `sliceUtf16Head` / `sliceUtf16Tail` from `@bb/text-utils`, +the helpers core uses to cap child-thread output, plugin instructions, +restart-resume notes, timeline output, terminal titles and queued-message +failure reasons; the `/app` export is that function, installed by +`plugin-sdk-app-impl.tsx`. Plugin callers: Account Pool, Ask User Question, +Automations, Browser Automation, Concurrency Limit, Docs, GitHub, MCP, Push +Notifications, Secrets, and the Claude Code and Codex providers. Agent +Annotations keeps an inline copy because its page script is stringified into +the browser. Docs: Plugin Guide, The bb SDK +(`plugins/plugin-api-docs/src/surfaces.ts`). + +Before stabilization, decide whether callers need grapheme-safe cuts (joined +emoji, combining marks) rather than surrogate-safe ones, and whether +`/app` and the root need the tail variant. + ## Application link approvals (`@get-bb/plugin-sdk/app`) `experimental_getApplicationLinkApprovals()` lists approved URL schemes on the @@ -1494,6 +1520,26 @@ gone) instead of a raw `ChildProcess` plus a fire-and-forget kill. Confirm argument quoting for `.cmd` targets with untrusted arguments, and whether `detached` belongs in the public shape. +## `experimental_serializeJsonRpcLine` (`@get-bb/plugin-sdk/provider-bridge`) + +`experimental_serializeJsonRpcLine(message)` returns `JSON.stringify(message)` +unless the line holds an escaped lone surrogate; then it serializes again with +every lone surrogate in a string replaced by U+FFFD. A lone surrogate is +valid in JavaScript but not in UTF-8, and Codex's serde-based app-server +rejects its `\ud83d` escape and drops the whole message without answering, +so a bridge writing to a provider's stdin uses this instead of +`JSON.stringify`. The result has no trailing newline. + +Core callers: `bridge-kit/runtime-json-rpc.ts` serializes every request, +result and error the daemon sends to a bridge with it, and the ACP message +stream writes to ACP agents with it. Plugin callers: the Codex provider's +app-server writer. Docs: Plugin Guide, Agent providers +(`plugins/plugin-api-docs/src/surfaces.ts`). + +Before stabilization, decide whether bridges should get a whole stdin writer +(newline, closed-stdin handling) instead of a serializer, and whether the +Claude Code bridge's SDK transport needs the same guard. + ## `experimental_BridgeRecoveryError` **Kept experimental (2026-08-22).** It stabilizes together with diff --git a/packages/plugin-sdk/src/app-contract.ts b/packages/plugin-sdk/src/app-contract.ts index f45d7136f5c..a6c6d48c4ab 100644 --- a/packages/plugin-sdk/src/app-contract.ts +++ b/packages/plugin-sdk/src/app-contract.ts @@ -6334,6 +6334,12 @@ export interface PluginSdkApp { event: ExperimentalShortcutKeyEvent, key: string, ): boolean; + /** + * Cuts `value` to at most `maxChars` UTF-16 code units without splitting a + * surrogate pair, so an emoji at the cut is dropped whole instead of leaving + * half of it. Experimental: see docs/api_to_audit.md. + */ + experimental_sliceUtf16Head(value: string, maxChars: number): string; experimental_ImageLightbox: ComponentType; experimental_PromptMentionIcon: ComponentType; /** diff --git a/packages/plugin-sdk/src/app.ts b/packages/plugin-sdk/src/app.ts index 8ca6f433a02..29da21c10ed 100644 --- a/packages/plugin-sdk/src/app.ts +++ b/packages/plugin-sdk/src/app.ts @@ -256,6 +256,9 @@ export const experimental_PromptMentionIcon = runtimeComponent( export const experimental_matchesShortcutKey = runtimeFunction( "experimental_matchesShortcutKey", ); +export const experimental_sliceUtf16Head = runtimeFunction( + "experimental_sliceUtf16Head", +); export const experimental_describePromptMention = runtimeFunction( "experimental_describePromptMention", ); diff --git a/packages/plugin-sdk/src/host.ts b/packages/plugin-sdk/src/host.ts index 531381df997..dbedde825b2 100644 --- a/packages/plugin-sdk/src/host.ts +++ b/packages/plugin-sdk/src/host.ts @@ -38,6 +38,15 @@ export { export { experimental_killProcessesWithCwdUnder } from "./kill-processes.js"; +/** + * Cut text to at most `maxChars` UTF-16 code units from the start or the end + * without splitting a surrogate pair. Experimental: see docs/api_to_audit.md. + */ +export { + sliceUtf16Head as experimental_sliceUtf16Head, + sliceUtf16Tail as experimental_sliceUtf16Tail, +} from "@bb/text-utils"; + export { experimental_readProcessIdentity, type ExperimentalProcessIdentity, diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts index e479fe06dbb..36d1837e45b 100644 --- a/packages/plugin-sdk/src/index.ts +++ b/packages/plugin-sdk/src/index.ts @@ -39,3 +39,10 @@ export { getRelativeHostPath as experimental_getRelativeHostPath, getHostPathComparisonKey as experimental_getHostPathComparisonKey, } from "@bb/domain"; + +/** + * Cuts `value` to at most `maxChars` UTF-16 code units without splitting a + * surrogate pair, so an emoji at the cut is dropped whole instead of leaving + * half of it. Experimental: see docs/api_to_audit.md. + */ +export { sliceUtf16Head as experimental_sliceUtf16Head } from "@bb/text-utils"; diff --git a/packages/plugin-sdk/src/provider-bridge.ts b/packages/plugin-sdk/src/provider-bridge.ts index 551190ec9ca..83263569de0 100644 --- a/packages/plugin-sdk/src/provider-bridge.ts +++ b/packages/plugin-sdk/src/provider-bridge.ts @@ -280,6 +280,14 @@ export { spawnPortableProcess as experimental_spawnPortableProcess } from "@bb/p */ export { killPortableProcess as experimental_killPortableProcess } from "@bb/process-utils"; +/** + * Serializes one JSON-RPC message for a provider's stdin the way bb's runtime + * does, replacing any lone surrogate in a string with U+FFFD so strict JSON + * parsers such as Codex's accept the line. Experimental: see + * docs/api_to_audit.md. + */ +export { serializeJsonRpcLine as experimental_serializeJsonRpcLine } from "@bb/provider-bridge-protocol/bridge-kit"; + // --------------------------------------------------------------------------- // 4. The domain vocabulary the protocol's payloads reference // --------------------------------------------------------------------------- diff --git a/packages/plugin-sdk/src/testing/app.tsx b/packages/plugin-sdk/src/testing/app.tsx index ed62473b2fc..81b01d132cf 100644 --- a/packages/plugin-sdk/src/testing/app.tsx +++ b/packages/plugin-sdk/src/testing/app.tsx @@ -165,6 +165,7 @@ import { type JsonValue, } from "@get-bb/plugin-sdk"; import { matchesAppShortcutKey } from "@bb/domain"; +import { sliceUtf16Head } from "@bb/text-utils"; import { isComposerDraftEmpty } from "../internal/composer-view.js"; import { appendComposerDraft, @@ -1867,6 +1868,7 @@ const testPluginSdkApp = { experimental_FailedVoiceRecordings: TestFailedVoiceRecordings, experimental_ShortcutHint: TestShortcutHint, experimental_matchesShortcutKey: matchesAppShortcutKey, + experimental_sliceUtf16Head: sliceUtf16Head, experimental_ImageLightbox: TestImageLightbox, experimental_PromptMentionIcon: TestPromptMentionIcon, experimental_describePromptMention( diff --git a/plugins/account-pool/package.json b/plugins/account-pool/package.json index b6ddfa1f91d..6e72b247833 100644 --- a/plugins/account-pool/package.json +++ b/plugins/account-pool/package.json @@ -6,7 +6,7 @@ "description": "Routes Claude and Codex API traffic across provider account pools.", "engines": { "bb": ">=0.0", - "bbPluginSdk": ">=0.6.86" + "bbPluginSdk": ">=0.6.161" }, "bb": { "name": "Account Pooler [Experimental]", diff --git a/plugins/account-pool/src/hub.ts b/plugins/account-pool/src/hub.ts index 3ee194edba1..754e55c669d 100644 --- a/plugins/account-pool/src/hub.ts +++ b/plugins/account-pool/src/hub.ts @@ -1,3 +1,4 @@ +import { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk"; import { retryAvailabilitySchema, type RetryAvailability, @@ -41,12 +42,6 @@ import type { } from "./store.js"; import { parentRequestHeaders, type ParentPool } from "./parent-pool.js"; -function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - const ROUTE = "/api/v1/plugins/account-pool/http"; const DEFAULT_REFRESH_URL = "https://platform.claude.com/v1/oauth/token"; const DEFAULT_USAGE_URL = "https://api.anthropic.com/api/oauth/usage"; diff --git a/plugins/ask-user-question/package.json b/plugins/ask-user-question/package.json index 825da70c772..932b9ee5bb1 100644 --- a/plugins/ask-user-question/package.json +++ b/plugins/ask-user-question/package.json @@ -6,7 +6,7 @@ "description": "Let any provider ask the user a multiple-choice question, the way Claude Code's AskUserQuestion does natively.", "engines": { "bb": ">=0.0", - "bbPluginSdk": ">=0.6.30" + "bbPluginSdk": ">=0.6.161" }, "bb": { "name": "Ask User Question", diff --git a/plugins/ask-user-question/src/translate.ts b/plugins/ask-user-question/src/translate.ts index a7524f44b4d..1d0ac1da66c 100644 --- a/plugins/ask-user-question/src/translate.ts +++ b/plugins/ask-user-question/src/translate.ts @@ -1,3 +1,4 @@ +import { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk"; import { MAX_OPTION_PREVIEW_LENGTH, type InteractionAnswer, @@ -10,12 +11,6 @@ import { } from "./contracts.js"; import { NOT_UNIQUE_MESSAGE } from "./tool-definition.js"; -function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - export function validateToolInput(input: ToolInput): string | null { const prompts = input.questions.map((question) => question.question); if (new Set(prompts).size !== prompts.length) return NOT_UNIQUE_MESSAGE; diff --git a/plugins/automations/package.json b/plugins/automations/package.json index 77a86dc3ba2..efcaf2f2401 100644 --- a/plugins/automations/package.json +++ b/plugins/automations/package.json @@ -6,7 +6,7 @@ "type": "module", "engines": { "bb": ">=0.0", - "bbPluginSdk": ">=0.6.113" + "bbPluginSdk": ">=0.6.161" }, "bb": { "name": "Automations", diff --git a/plugins/automations/src/script-runner.ts b/plugins/automations/src/script-runner.ts index ee0da57a365..da26e57bd55 100644 --- a/plugins/automations/src/script-runner.ts +++ b/plugins/automations/src/script-runner.ts @@ -1,3 +1,4 @@ +import { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk"; import { experimental_hostToolchain as hostToolchain, experimental_execHostFile, @@ -17,12 +18,6 @@ import { scriptsRoot, } from "./script-files.js"; -function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - const execFileAsync = experimental_execHostFile; const SCRIPT_OUTPUT_MAX_BYTES = 1024 * 1024; const SCRIPT_FAILURE_DETAIL_MAX_CHARS = 200; diff --git a/plugins/browser-automation/app.tsx b/plugins/browser-automation/app.tsx index 2d217ae5fc1..8280979475a 100644 --- a/plugins/browser-automation/app.tsx +++ b/plugins/browser-automation/app.tsx @@ -35,7 +35,7 @@ import { type LightboxTarget, } from "./lightbox-store.js"; import { PREVIEW_DIRECTIVE_ID } from "./preview-directive.js"; -import { sliceUtf16Head } from "./utf16.js"; +import { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk/app"; const MIN_POLL_INTERVAL_MS = 400; const MAX_RETRY_INTERVAL_MS = 15_000; diff --git a/plugins/browser-automation/installer.ts b/plugins/browser-automation/installer.ts index 00b2c679500..b5c6fd80d4a 100644 --- a/plugins/browser-automation/installer.ts +++ b/plugins/browser-automation/installer.ts @@ -29,7 +29,7 @@ import { join } from "node:path"; import { pipeline } from "node:stream/promises"; import { setTimeout as delay } from "node:timers/promises"; import { z } from "zod"; -import { sliceUtf16Tail } from "./utf16.js"; +import { experimental_sliceUtf16Tail as sliceUtf16Tail } from "@get-bb/plugin-sdk/host"; export const runtimePlatforms = [ "linux-x64", diff --git a/plugins/browser-automation/package.json b/plugins/browser-automation/package.json index c5699f0624a..3c3db122681 100644 --- a/plugins/browser-automation/package.json +++ b/plugins/browser-automation/package.json @@ -6,7 +6,7 @@ "description": "Let BB control the in-app browser and browsers on connected machines, with inline previews for headless sessions.", "engines": { "bb": ">=0.41", - "bbPluginSdk": ">=0.6.113" + "bbPluginSdk": ">=0.6.161" }, "bb": { "name": "Browser Automation", diff --git a/plugins/browser-automation/preview.ts b/plugins/browser-automation/preview.ts index cfd6e3cf87d..7070fabd0d1 100644 --- a/plugins/browser-automation/preview.ts +++ b/plugins/browser-automation/preview.ts @@ -1,6 +1,6 @@ import { z } from "zod"; import type { PreviewFrame, PreviewSize } from "./contracts.js"; -import { sliceUtf16Head } from "./utf16.js"; +import { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk/host"; const messageSchema = z.object({ id: z.number().int().optional(), diff --git a/plugins/browser-automation/runtime.ts b/plugins/browser-automation/runtime.ts index af83a88eed8..76a898d0ad3 100644 --- a/plugins/browser-automation/runtime.ts +++ b/plugins/browser-automation/runtime.ts @@ -16,7 +16,7 @@ import { outputSchema, type RunOutput } from "./contracts.js"; import { createPreview, type PreviewSource } from "./preview.js"; import { execute, OutputLimitError, supervise } from "./process.js"; import type { ResolvedRuntime } from "./runtime-pin.js"; -import { sliceUtf16Head } from "./utf16.js"; +import { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk/host"; const frameSchema = z.discriminatedUnion("type", [ z.object({ diff --git a/plugins/browser-automation/utf16.ts b/plugins/browser-automation/utf16.ts deleted file mode 100644 index ac583b536ed..00000000000 --- a/plugins/browser-automation/utf16.ts +++ /dev/null @@ -1,11 +0,0 @@ -export function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - -export function sliceUtf16Tail(value: string, maxChars: number): string { - const start = Math.max(0, value.length - Math.max(0, maxChars)); - const first = value.charCodeAt(start); - return value.slice(first >= 0xdc00 && first <= 0xdfff ? start + 1 : start); -} diff --git a/plugins/concurrency-limit/package.json b/plugins/concurrency-limit/package.json index e2eb8a20614..471a2ca7a25 100644 --- a/plugins/concurrency-limit/package.json +++ b/plugins/concurrency-limit/package.json @@ -6,7 +6,7 @@ "description": "Control the number of concurrent threads that are running in bb", "engines": { "bb": ">=0.0", - "bbPluginSdk": ">=0.4.102" + "bbPluginSdk": ">=0.6.161" }, "bb": { "name": "Concurrency limit", diff --git a/plugins/concurrency-limit/server.ts b/plugins/concurrency-limit/server.ts index f7b89fbbf5a..6c7981e1ab9 100644 --- a/plugins/concurrency-limit/server.ts +++ b/plugins/concurrency-limit/server.ts @@ -6,6 +6,7 @@ import { type BbPluginApi, type MessageDispatchHookDecision, type PluginThreadEventName, + experimental_sliceUtf16Head as sliceUtf16Head, } from "@get-bb/plugin-sdk"; import { z } from "zod"; import { concurrencyLimitHostContract } from "./contract.js"; @@ -17,12 +18,6 @@ import { type LimitConfiguration, } from "./limits.js"; -function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - const CONFIGURATION_KEY = "configuration"; const CAPACITIES_KEY = "host-capacities"; const CONFIGURATION_CHANGED_CHANNEL = "configuration-changed"; diff --git a/plugins/docs/package.json b/plugins/docs/package.json index 51a0ab36244..7a4d543015e 100644 --- a/plugins/docs/package.json +++ b/plugins/docs/package.json @@ -23,7 +23,7 @@ ], "engines": { "bb": ">=0.0", - "bbPluginSdk": ">=0.6.113" + "bbPluginSdk": ">=0.6.161" }, "bb": { "name": "Docs", diff --git a/plugins/docs/server.ts b/plugins/docs/server.ts index c715316e328..a6605f43c2e 100644 --- a/plugins/docs/server.ts +++ b/plugins/docs/server.ts @@ -4,6 +4,7 @@ import { experimental_joinHostPath as joinPath, experimental_getHostPathDirname as getHostPathDirname, experimental_getRelativeHostPath as getRelativeHostPath, + experimental_sliceUtf16Head as sliceUtf16Head, } from "@get-bb/plugin-sdk"; import { proposalSchema, type Proposal } from "./proposals.js"; import os from "node:os"; @@ -48,12 +49,6 @@ import { type WatchVault, } from "./vault-watches.js"; -function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - const DEFAULT_DIR = "~/Notes"; const PREVIEW_LENGTH = 100; const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024; diff --git a/plugins/github/package.json b/plugins/github/package.json index 197b07fc158..410557866ec 100644 --- a/plugins/github/package.json +++ b/plugins/github/package.json @@ -23,7 +23,7 @@ ], "engines": { "bb": ">=0.0", - "bbPluginSdk": ">=0.6.86" + "bbPluginSdk": ">=0.6.161" }, "bb": { "name": "GitHub", diff --git a/plugins/github/server.ts b/plugins/github/server.ts index dfae4bbb2c4..b7f739e94da 100644 --- a/plugins/github/server.ts +++ b/plugins/github/server.ts @@ -10,15 +10,10 @@ import { defineCli, type BbPluginApi, type PluginCliResult, + experimental_sliceUtf16Head as sliceUtf16Head, } from "@get-bb/plugin-sdk"; import { z } from "zod"; -function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - const SYNC_INTERVAL_MS = 15 * 60_000; const SYNC_RETRY_MAX_MS = 5 * 60_000; const SYNC_RETRY_BASE_MS = 30_000; diff --git a/plugins/mcp/package.json b/plugins/mcp/package.json index b49658cdfb7..30628f18d71 100644 --- a/plugins/mcp/package.json +++ b/plugins/mcp/package.json @@ -6,7 +6,7 @@ "description": "Control bb from ChatGPT, Claude and other MCP clients.", "engines": { "bb": ">=0.0", - "bbPluginSdk": ">=0.6.86" + "bbPluginSdk": ">=0.6.161" }, "bb": { "name": "MCP server", diff --git a/plugins/mcp/src/tools.ts b/plugins/mcp/src/tools.ts index 46be4a13020..e9fa679ad4c 100644 --- a/plugins/mcp/src/tools.ts +++ b/plugins/mcp/src/tools.ts @@ -1,3 +1,4 @@ +import { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk"; import type { CliRunner } from "./cli-runner.js"; import { SEARCH_DEFAULT_LIMIT, @@ -13,12 +14,6 @@ import { type SandboxLimits, } from "./sandbox.js"; -function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - export const SCRIPT_TOTAL_DEADLINE_MS = 25_000; const CLI_CALL_TIMEOUT_MS = 24_000; const SLEEP_MAX_MS = 20_000; diff --git a/plugins/plugin-api-docs/src/surfaces.ts b/plugins/plugin-api-docs/src/surfaces.ts index 3607af05a34..55269f1fb0b 100644 --- a/plugins/plugin-api-docs/src/surfaces.ts +++ b/plugins/plugin-api-docs/src/surfaces.ts @@ -844,6 +844,7 @@ export const SURFACE_GROUPS: SurfaceGroup[] = [ "ExperimentalPluginProviderEnvHealth", "experimental_spawnPortableProcess", "experimental_killPortableProcess", + "experimental_serializeJsonRpcLine", "PluginProviders", ], firstParty: [ @@ -1648,6 +1649,7 @@ export const SURFACE_GROUPS: SurfaceGroup[] = [ "Recognize drive roots (including C:) and UNC paths with either Windows separator, regardless of the server OS; reject rootless backslashes and drive-relative paths such as C:foo during resolution", "Join relative paths, obtain dirname/basename, derive a slash-separated relative path within a root, and create case-insensitive Windows comparison keys with the experimental host-path helpers; invalid absolute inputs return null", "Check lexical containment separately with experimental_isHostPathWithin({ rootPath, candidatePath }): resolution allows .. escapes, and neither helper resolves symlinks", + "Cap text with experimental_sliceUtf16Head(value, maxChars) from @get-bb/plugin-sdk, @get-bb/plugin-sdk/app or @get-bb/plugin-sdk/host (and experimental_sliceUtf16Tail from @get-bb/plugin-sdk/host) so a cut never leaves half an emoji, which strict agent providers such as Codex reject", ], apiSymbols: [ "BbPluginApi", @@ -1660,6 +1662,8 @@ export const SURFACE_GROUPS: SurfaceGroup[] = [ "experimental_getHostPathBasename", "experimental_getRelativeHostPath", "experimental_getHostPathComparisonKey", + "experimental_sliceUtf16Head", + "experimental_sliceUtf16Tail", "PluginBbSdk.hosts.get", "PluginBbSdk.hosts.experimental_discoverRepos", "PluginBbSdk.experimental_promptHistory.list", diff --git a/plugins/provider-claude-code/src/bridge/provider-commands.ts b/plugins/provider-claude-code/src/bridge/provider-commands.ts index c225fe6bd61..e685c1f7000 100644 --- a/plugins/provider-claude-code/src/bridge/provider-commands.ts +++ b/plugins/provider-claude-code/src/bridge/provider-commands.ts @@ -1,7 +1,7 @@ import { z } from "zod"; import { probeClaudeInitialization } from "./initialization-probe.js"; import { isClaudeSkillPluginName } from "./skill-plugins.js"; -import { sliceUtf16Head } from "../utf16.js"; +import { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk/host"; export const PROVIDER_COMMANDS_STATE_KIND = "bb/provider-commands"; diff --git a/plugins/provider-claude-code/src/interactions.ts b/plugins/provider-claude-code/src/interactions.ts index 4ddbde32bff..8e15a6ba93c 100644 --- a/plugins/provider-claude-code/src/interactions.ts +++ b/plugins/provider-claude-code/src/interactions.ts @@ -41,7 +41,7 @@ import { getClaudeFileEditPath, parseClaudeBashCommand, } from "./tool-classification.js"; -import { sliceUtf16Head } from "./utf16.js"; +import { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk/host"; interface ClaudeSessionRulesArgs { permissions: PendingInteractionGrantedPermissionProfile; diff --git a/plugins/provider-claude-code/src/utf16.ts b/plugins/provider-claude-code/src/utf16.ts deleted file mode 100644 index fe13ee3d0cd..00000000000 --- a/plugins/provider-claude-code/src/utf16.ts +++ /dev/null @@ -1,5 +0,0 @@ -export function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} diff --git a/plugins/provider-codex/src/ai/chatgpt-client.ts b/plugins/provider-codex/src/ai/chatgpt-client.ts index 073c886d336..51d48725595 100644 --- a/plugins/provider-codex/src/ai/chatgpt-client.ts +++ b/plugins/provider-codex/src/ai/chatgpt-client.ts @@ -15,7 +15,7 @@ import { type CodexOpenAiApiKeyCredentials, } from "./codex-auth.js"; import { AiServiceFailure } from "./failure.js"; -import { sliceUtf16Head } from "../utf16.js"; +import { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk/host"; type InferenceCompleteCommand = CodexAiCompleteInput; type VoiceTranscribeCommand = CodexAiTranscribeInput; diff --git a/plugins/provider-codex/src/bridge/app-server-connection.ts b/plugins/provider-codex/src/bridge/app-server-connection.ts index 490e2640f24..64c7d2facb8 100644 --- a/plugins/provider-codex/src/bridge/app-server-connection.ts +++ b/plugins/provider-codex/src/bridge/app-server-connection.ts @@ -3,10 +3,10 @@ import { createInterface, type Interface } from "node:readline"; import { experimental_killPortableProcess, experimental_recordProviderChildIo, + experimental_serializeJsonRpcLine, experimental_spawnPortableProcess, } from "@get-bb/plugin-sdk/provider-bridge"; import type { z } from "zod"; -import { serializeWellFormedJson } from "../utf16.js"; const STDERR_TAIL_MAX_CHUNKS = 40; const CLOSE_AFTER_EXIT_GRACE_MS = 1_000; @@ -219,7 +219,7 @@ export function createCodexAppServerConnection( } return; } - stdin.write(`${serializeWellFormedJson(message)}\n`); + stdin.write(`${experimental_serializeJsonRpcLine(message)}\n`); } function finalizeExit(status: { diff --git a/plugins/provider-codex/src/utf16.ts b/plugins/provider-codex/src/utf16.ts deleted file mode 100644 index 1efaa11fbc9..00000000000 --- a/plugins/provider-codex/src/utf16.ts +++ /dev/null @@ -1,18 +0,0 @@ -const LONE_SURROGATE = /[\uD800-\uDFFF]/gu; - -export function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - -function wellFormedStrings(_key: string, value: unknown): unknown { - return typeof value === "string" ? value.replace(LONE_SURROGATE, "�") : value; -} - -export function serializeWellFormedJson(message: unknown): string { - const line = JSON.stringify(message); - return line.includes("\\ud") - ? JSON.stringify(message, wellFormedStrings) - : line; -} diff --git a/plugins/push-notifications/notification-text.ts b/plugins/push-notifications/notification-text.ts index 4efd43a4563..6de75c3419b 100644 --- a/plugins/push-notifications/notification-text.ts +++ b/plugins/push-notifications/notification-text.ts @@ -1,9 +1,4 @@ -function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - +import { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk"; const REFERENCED_TITLE_MAX_LENGTH = 40; const CODE_FENCE_PATTERN = /^\s*(```|~~~)/u; const BREAK_PATTERN = /^\s{0,3}(?:#{1,6}(?:\s|$)|([-*_])(?:\s*\1){2,}\s*$)/u; diff --git a/plugins/push-notifications/package.json b/plugins/push-notifications/package.json index 02348e58041..78698a21a05 100644 --- a/plugins/push-notifications/package.json +++ b/plugins/push-notifications/package.json @@ -6,7 +6,7 @@ "description": "Notifications for threads that need attention on mobile, web, and desktop", "engines": { "bb": ">=0.0", - "bbPluginSdk": ">=0.6.116" + "bbPluginSdk": ">=0.6.161" }, "bb": { "name": "Push notifications", diff --git a/plugins/secrets/package.json b/plugins/secrets/package.json index a4ecf646ca8..9367c89a688 100644 --- a/plugins/secrets/package.json +++ b/plugins/secrets/package.json @@ -6,7 +6,7 @@ "description": "Securely request credentials from a user and reconcile them into dotenv files.", "engines": { "bb": ">=0.0", - "bbPluginSdk": ">=0.6.113" + "bbPluginSdk": ">=0.6.161" }, "bb": { "name": "Secrets", diff --git a/plugins/secrets/src/server.ts b/plugins/secrets/src/server.ts index 1c08995d6fd..12159174deb 100644 --- a/plugins/secrets/src/server.ts +++ b/plugins/secrets/src/server.ts @@ -6,6 +6,7 @@ import { type BbPluginApi, type PluginCliContext, type PluginCliResult, + experimental_sliceUtf16Head as sliceUtf16Head, } from "@get-bb/plugin-sdk"; import { z } from "zod"; import { @@ -15,12 +16,6 @@ import { } from "./secret-request.js"; import { assertNoDuplicateAssignments, reconcileDotenv } from "./dotenv.js"; -function sliceUtf16Head(value: string, maxChars: number): string { - const end = Math.min(value.length, Math.max(0, maxChars)); - const last = value.charCodeAt(end - 1); - return value.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end); -} - interface ParsedRequest { names: string[]; purpose: string | null;