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/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/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 2b766bda5a3..52831cbcf3a 100644 --- a/apps/cli/src/commands/plugin.ts +++ b/apps/cli/src/commands/plugin.ts @@ -58,6 +58,7 @@ import { runPluginCliCommand } from "../plugin-cli-proxy.js"; import { resolveBbCliVersion } from "../version.js"; import { renderBorderlessTable } from "../table.js"; +import { sliceUtf16Head } from "@bb/text-utils"; interface NewPluginTarget { packageName: string; @@ -506,7 +507,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/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/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/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 d5bcc0ed22b..948eaf810fc 100644 --- a/apps/server/src/services/environments/environment-engine.ts +++ b/apps/server/src/services/environments/environment-engine.ts @@ -140,6 +140,7 @@ import { operationInProgress, } from "../lib/operation-response.js"; import { defineItemSweep, type ItemSweep } from "../system/item-sweep.js"; +import { sliceUtf16Head } from "@bb/text-utils"; type Deps = ThreadProvisioningDeps; @@ -296,9 +297,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 15a90f0cf0c..8d4c91138ba 100644 --- a/apps/server/src/services/machines/provider-orchestration.ts +++ b/apps/server/src/services/machines/provider-orchestration.ts @@ -64,6 +64,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; @@ -191,7 +192,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"]); }, @@ -199,9 +200,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"]); }, @@ -226,7 +228,7 @@ function lifecycleReporter( ) return; updateHost(deps.db, deps.hub, hostId, { - statusMessage: text.slice(0, 500), + statusMessage: sliceUtf16Head(text, 500), }); deps.hub.notifyHost(hostId, ["host-connected"]); }, 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 805108423e5..d146778d081 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/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/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/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/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/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/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/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/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 fe43762d2fe..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": { @@ -186,6 +186,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/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/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/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/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..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 @@ -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,27 @@ 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 { + const line = JSON.stringify(message); + return line.includes("\\ud") + ? JSON.stringify(message, wellFormedStrings) + : line; +} + +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 +348,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/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/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 9a88d4b2b4c..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, @@ -1451,7 +1452,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..dc1de125b68 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 = @@ -250,7 +256,7 @@ function installAgentAnnotations( tagName: element.tagName.toLowerCase().slice(0, 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), + comment: sliceUtf16Head(trimmed, 4000), url: location.href.slice(0, 4096), - title: document.title.slice(0, 1024), + 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/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 cb717b3d76e..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, @@ -43,7 +44,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/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 0f47c75131d..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, @@ -152,7 +153,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/browser-automation/app.tsx b/plugins/browser-automation/app.tsx index 099121aadcd..8280979475a 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 { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk/app"; 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..b5c6fd80d4a 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 { experimental_sliceUtf16Tail as sliceUtf16Tail } from "@get-bb/plugin-sdk/host"; 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/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 5bf6e223880..7070fabd0d1 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 { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk/host"; const messageSchema = z.object({ id: z.number().int().optional(), @@ -210,7 +211,7 @@ export function createPreview( ...latest, sequence: ++sequence, url: info.url.slice(0, 2_000), - title: info.title.slice(0, 300), + title: sliceUtf16Head(info.title, 300), }; for (const waiter of [...waiters]) waiter.check(); } @@ -255,7 +256,7 @@ export function createPreview( width: frame.metadata.deviceWidth, height: frame.metadata.deviceHeight, url: (target?.url ?? "").slice(0, 2_000), - title: (target?.title ?? "").slice(0, 300), + 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..76a898d0ad3 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 { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk/host"; 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/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 58685c434d7..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"; @@ -130,7 +131,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/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 52c92670fd0..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"; @@ -276,11 +277,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 +292,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 }; } @@ -317,12 +321,14 @@ function kebabCase(text: string): string { } 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/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 fe68c98debf..b7f739e94da 100644 --- a/plugins/github/server.ts +++ b/plugins/github/server.ts @@ -10,6 +10,7 @@ import { defineCli, type BbPluginApi, type PluginCliResult, + experimental_sliceUtf16Head as sliceUtf16Head, } from "@get-bb/plugin-sdk"; import { z } from "zod"; @@ -1009,7 +1010,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/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 b8954efd0be..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, @@ -68,7 +69,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/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 9bf2e76e96a..e685c1f7000 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 { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk/host"; 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..8e15a6ba93c 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 { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk/host"; 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-codex/src/ai/chatgpt-client.ts b/plugins/provider-codex/src/ai/chatgpt-client.ts index 84a4218135f..51d48725595 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 { experimental_sliceUtf16Head as sliceUtf16Head } from "@get-bb/plugin-sdk/host"; 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..64c7d2facb8 100644 --- a/plugins/provider-codex/src/bridge/app-server-connection.ts +++ b/plugins/provider-codex/src/bridge/app-server-connection.ts @@ -3,6 +3,7 @@ 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"; @@ -218,7 +219,7 @@ export function createCodexAppServerConnection( } return; } - stdin.write(JSON.stringify(message) + "\n"); + stdin.write(`${experimental_serializeJsonRpcLine(message)}\n`); } function finalizeExit(status: { 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..6de75c3419b 100644 --- a/plugins/push-notifications/notification-text.ts +++ b/plugins/push-notifications/notification-text.ts @@ -1,3 +1,4 @@ +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; @@ -10,7 +11,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/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 617219e5eda..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 { @@ -163,7 +164,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..45f41297c4f 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 @@ -2680,6 +2695,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 +2801,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 @@ -4116,6 +4137,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