From 87a7312cfd23983537c91dba2b01a347134cb7e8 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 8 Oct 2026 09:34:37 -0500 Subject: [PATCH] refactor(server): extract heartbeat run-log formatting (#15573) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Heartbeat orchestration records agent output and run events. > - The heartbeat service still contains more than 30,000 lines after the first extraction. > - Log formatting has fixed limits and does not write run state. > - These helpers form a small next step toward a more manageable heartbeat service. > - This PR moves them into the heartbeat folder without changing their function bodies. > - Direct boundary tests and existing caller tests check the output. ## Linked Issues or Issue Description Refs: #15568. **What existing behavior does this improve?** This improves the structure and test coverage of heartbeat run-log formatting. **Subsystem affected** server/ — orchestration services. **Current behavior** `heartbeat.ts` contains excerpt handling, payload size limits, and log chunk formatting beside run orchestration. **Proposed behavior** Move these helpers and their constants into `server/src/services/heartbeat/run-log.ts`. Keep the same function bodies, output, limits, and public exports. **Reason and benefit** Run-log formatting has its own small module and focused tests. This keeps the second extraction small enough to review on its own. **Breaking changes** None. The existing public import path and persisted output stay the same. Related run-log PRs: Refs: #6373, Refs: #8841. Those PRs change redaction behavior. This PR only moves existing formatting code. ## What Changed - Move 109 lines of helper functions and six constants into `heartbeat/run-log.ts`. - Move `appendExcerpt` and retain the existing public exports for `boundHeartbeatRunEventPayloadForStorage` and `compactRunLogChunk` in `heartbeat.ts`. - Add 17 direct regression cases for size and depth limits, cycles, shared references, immutable input, image omission, redaction order, excerpt tails, and UTF-8 boundaries. - Document both heartbeat extractions in `doc/DEVELOPING.md`. ## Verification - Before extraction, four focused files passed with 55 tests. - After extraction and the two new excerpt tests, the same four files passed with 57 tests. - Run `pnpm exec vitest run server/src/services/heartbeat/run-log.test.ts server/src/__tests__/heartbeat-run-log.test.ts server/src/__tests__/heartbeat-list.test.ts server/src/__tests__/redaction.test.ts`. - The original and extracted function blocks match byte for byte after adding the export keyword to `appendExcerpt`. - Existing tests still import the public helpers from `heartbeat.ts`. - `node scripts/check-module-boundaries.mjs` and `git diff --check` passed. - `pnpm -r typecheck` passed. - `pnpm build` passed. - The full suite passed in CI. The duplicate local `pnpm test:run` was stopped after CI passed; it did not complete locally. - All CI gates passed on commit `4e65c666e3b5b46162b3a528b37fba8902a1d200`: 54 passing checks, two skipped Storybook checks. - Fresh Greptile review of the same commit: 5/5, no actionable or inline findings. The PR has no merge conflicts. ## Risks - Low risk. Moving code can cause an import or build error. - The same redaction and adapter utility modules remain in use. - Database writes, current-user redaction, live event delivery, and run state remain in `heartbeat.ts`. - The event schema and payload output do not change. - No database, API, Telemetry, Observability, or UI contract changes are required. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI GPT-6 via Codex. The exact serving model ID and context window were not exposed in this session. Used reasoning, repository inspection, shell tools, and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- doc/DEVELOPING.md | 12 +- server/src/services/heartbeat.ts | 127 +------------ server/src/services/heartbeat/run-log.test.ts | 175 ++++++++++++++++++ server/src/services/heartbeat/run-log.ts | 120 ++++++++++++ 4 files changed, 314 insertions(+), 120 deletions(-) create mode 100644 server/src/services/heartbeat/run-log.test.ts create mode 100644 server/src/services/heartbeat/run-log.ts diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 3ef4c6b62eb..1809c2fc165 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -1204,12 +1204,20 @@ In Vite middleware mode, Paperclip gives HMR a dedicated HTTP server bound to th When a workspace service runs Paperclip for browser OAuth QA, configure its `expose.urlTemplate` with the canonical URL the browser can reach. Paperclip preserves explicit `PAPERCLIP_PUBLIC_URL` or `BETTER_AUTH_URL` settings; otherwise it uses a valid exposed HTTPS origin (or loopback HTTP) as the managed runtime fallback for Better Auth and `/api/tools/oauth/callback`. Internal service names such as `http://paperclip-dev:` are rejected unless that hostname is genuinely the browser route. Use a unique origin per isolated worktree. See [Execution Workspaces And Runtime Services](../docs/guides/board-operator/execution-workspaces-and-runtime-services.md#browser-reachable-origins-for-oauth-qa) for configuration and verification. -## Wake Context Delivery +## Heartbeat Service Extractions + +Keep relevant heartbeat extractions and their focused tests in `server/src/services/heartbeat/`. Task assignment Markdown is rendered by `server/src/services/heartbeat/task-markdown.ts`. `heartbeat.ts` calls the renderer and re-exports it for existing callers. Keep prompt formatting changes in the renderer and its tests, separate from run orchestration. -Keep relevant heartbeat extractions and their focused tests in `server/src/services/heartbeat/`. + +Run-log formatting is in `server/src/services/heartbeat/run-log.ts`. It bounds +stored event payloads, redacts and shortens log chunks, and caps stdout/stderr +excerpts. `heartbeat.ts` keeps event writes, current-user redaction, and live +event delivery. Existing public helpers remain available from `heartbeat.ts`. + +## Wake Context Delivery Built-in adapters deliver wake context through the run prompt, including structured execution-continuation data. They do not export `PAPERCLIP_WAKE_PAYLOAD_JSON`. A diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 68dd8bbec29..0e9118c75fe 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -1,3 +1,12 @@ +import { + appendExcerpt, + boundHeartbeatRunEventPayloadForStorage, + compactRunLogChunk, +} from "./heartbeat/run-log.js"; +export { + boundHeartbeatRunEventPayloadForStorage, + compactRunLogChunk, +} from "./heartbeat/run-log.js"; import { buildPaperclipTaskMarkdown } from "./heartbeat/task-markdown.js"; export { buildPaperclipTaskMarkdown } from "./heartbeat/task-markdown.js"; import { preserveWorkspaceRestoreRecoveryMetadataSql } from "./legacy-workspace-restore-recovery.js"; @@ -327,8 +336,6 @@ import { parseObject, asBoolean, asNumber, - appendWithByteCap, - MAX_EXCERPT_BYTES, } from "../adapters/utils.js"; import { authorizeChatConversationForBoundRun, @@ -672,9 +679,6 @@ import type { PluginWorkerManager } from "./plugin-worker-manager.js"; import { serverVersion } from "../version.js"; const MAX_LIVE_LOG_CHUNK_BYTES = 8 * 1024; -const MAX_PERSISTED_LOG_CHUNK_CHARS = 64 * 1024; -const MAX_RUN_EVENT_PAYLOAD_STRING_CHARS = 16 * 1024; -const MAX_RUN_EVENT_PAYLOAD_ARRAY_ITEMS = 50; export function redactDetectedSuccessfulRunProgressSummaryForBoard( summary: string, @@ -697,8 +701,6 @@ export function redactSuccessfulRunHandoffEvidence( ); } -const MAX_RUN_EVENT_PAYLOAD_OBJECT_KEYS = 100; -const MAX_RUN_EVENT_PAYLOAD_DEPTH = 6; const HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT = AGENT_DEFAULT_MAX_CONCURRENT_RUNS; const HEARTBEAT_MAX_CONCURRENT_RUNS_MIN = 1; const HEARTBEAT_MAX_CONCURRENT_RUNS_MAX = 50; @@ -1433,8 +1435,6 @@ export function getTaskDrainStatus(): { }; } -const INLINE_BASE64_IMAGE_DATA_RE = - /("type":"image","source":\{"type":"base64","data":")([A-Za-z0-9+/=]{1024,})(")/g; type RuntimeConfigSecretResolver = Pick< ReturnType, | "resolveAdapterConfigForRuntime" @@ -3722,115 +3722,6 @@ const heartbeatRunIssueSummaryColumns = { issueId: heartbeatRuns.issueId, } as const; -function appendExcerpt(prev: string, chunk: string) { - return appendWithByteCap(prev, chunk, MAX_EXCERPT_BYTES); -} - -function truncateRunEventString(value: string) { - if (value.length <= MAX_RUN_EVENT_PAYLOAD_STRING_CHARS) return value; - const omittedChars = value.length - MAX_RUN_EVENT_PAYLOAD_STRING_CHARS; - return `${value.slice(0, MAX_RUN_EVENT_PAYLOAD_STRING_CHARS)}\n[truncated ${omittedChars} chars]`; -} - -function boundRunEventValue( - value: unknown, - depth: number, - seen: WeakSet, -): unknown { - if (typeof value === "string") { - return truncateRunEventString(value); - } - if ( - value === null || - typeof value === "number" || - typeof value === "boolean" - ) { - return value; - } - if (value instanceof Date) { - return value.toISOString(); - } - if (Array.isArray(value)) { - if (depth >= MAX_RUN_EVENT_PAYLOAD_DEPTH) { - return { - _truncated: true, - type: "array", - originalLength: value.length, - }; - } - const bounded = value - .slice(0, MAX_RUN_EVENT_PAYLOAD_ARRAY_ITEMS) - .map((entry) => boundRunEventValue(entry, depth + 1, seen)); - if (value.length > MAX_RUN_EVENT_PAYLOAD_ARRAY_ITEMS) { - bounded.push({ - _truncated: true, - omittedItems: value.length - MAX_RUN_EVENT_PAYLOAD_ARRAY_ITEMS, - }); - } - return bounded; - } - if (typeof value !== "object" || value === undefined) { - return null; - } - if (seen.has(value)) { - return "[Circular]"; - } - seen.add(value); - const entries = Object.entries(value as Record); - if (depth >= MAX_RUN_EVENT_PAYLOAD_DEPTH) { - const bounded = { - _truncated: true, - type: "object", - keys: entries.map(([key]) => key).slice(0, 20), - }; - seen.delete(value); - return bounded; - } - - const out: Record = {}; - for (const [key, entryValue] of entries.slice( - 0, - MAX_RUN_EVENT_PAYLOAD_OBJECT_KEYS, - )) { - out[key] = boundRunEventValue(entryValue, depth + 1, seen); - } - if (entries.length > MAX_RUN_EVENT_PAYLOAD_OBJECT_KEYS) { - out._truncated = true; - out._omittedKeys = entries.length - MAX_RUN_EVENT_PAYLOAD_OBJECT_KEYS; - } - seen.delete(value); - return out; -} - -export function boundHeartbeatRunEventPayloadForStorage( - payload: Record, -): Record { - const bounded = boundRunEventValue(payload, 0, new WeakSet()); - return parseObject(bounded) ?? { _truncated: true }; -} - -function redactInlineBase64ImageData(chunk: string) { - return chunk.replace( - INLINE_BASE64_IMAGE_DATA_RE, - (_match, prefix: string, data: string, suffix: string) => - `${prefix}[omitted base64 image data: ${data.length} chars]${suffix}`, - ); -} - -export function compactRunLogChunk( - chunk: string, - maxChars = MAX_PERSISTED_LOG_CHUNK_CHARS, -) { - const normalized = redactSensitiveText(redactInlineBase64ImageData(chunk)); - if (normalized.length <= maxChars) return normalized; - - const headChars = Math.max(0, Math.floor(maxChars * 0.6)); - const tailChars = Math.max(0, Math.floor(maxChars * 0.25)); - const omittedChars = Math.max(0, normalized.length - headChars - tailChars); - const marker = `\n[paperclip truncated run log chunk: omitted ${omittedChars} chars]\n`; - return `${normalized.slice(0, headChars)}${marker}${normalized.slice(normalized.length - tailChars)}`; -} - function normalizeMaxConcurrentRuns(value: unknown) { const parsed = Math.floor( asNumber(value, HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT), diff --git a/server/src/services/heartbeat/run-log.test.ts b/server/src/services/heartbeat/run-log.test.ts new file mode 100644 index 00000000000..87fa5cf9439 --- /dev/null +++ b/server/src/services/heartbeat/run-log.test.ts @@ -0,0 +1,175 @@ +import { describe, expect, it } from "vitest"; +import { + appendExcerpt, + boundHeartbeatRunEventPayloadForStorage, + compactRunLogChunk, +} from "./run-log.js"; + +describe("heartbeat run-log excerpts", () => { + it("appends chunks while preserving the most recent 32 KiB of output", () => { + const prefix = "x".repeat(32 * 1024); + expect(appendExcerpt("ready", "\nnext")).toBe("ready\nnext"); + const full = appendExcerpt(prefix, "tail"); + expect(full).toBe(`${"x".repeat(32 * 1024 - 4)}tail`); + expect(appendExcerpt(full, "next")).toBe(`${"x".repeat(32 * 1024 - 8)}tailnext`); + }); + + it("respects the byte limit without splitting a multibyte character", () => { + const suffix = "x".repeat(32 * 1024 - 4); + const excerpt = appendExcerpt(`🙂${suffix}`, "y"); + expect(excerpt).toBe(`${suffix}y`); + expect(Buffer.byteLength(excerpt)).toBeLessThanOrEqual(32 * 1024); + }); +}); + +describe("heartbeat run-log payload formatting", () => { + it("preserves ordinary values, serializes dates, and replaces unsupported values", () => { + expect(boundHeartbeatRunEventPayloadForStorage({ + text: "ready", + count: 2, + flag: false, + empty: null, + at: new Date("2026-10-08T12:00:00Z"), + missing: undefined, + callback: () => "unused", + symbol: Symbol("unused"), + bigint: 1n, + })).toEqual({ + text: "ready", + count: 2, + flag: false, + empty: null, + at: "2026-10-08T12:00:00.000Z", + missing: null, + callback: null, + symbol: null, + bigint: null, + }); + }); + + it("keeps strings at the limit and reports the exact number of omitted characters", () => { + const limit = "x".repeat(16 * 1024); + expect(boundHeartbeatRunEventPayloadForStorage({ + exact: limit, + oversized: `${limit}end`, + })).toEqual({ + exact: limit, + oversized: `${limit}\n[truncated 3 chars]`, + }); + }); + + it("keeps the first 50 array entries and reports omitted items", () => { + const exact = Array.from({ length: 50 }, (_, index) => index); + expect(boundHeartbeatRunEventPayloadForStorage({ exact, oversized: [...exact, 50, 51] })) + .toEqual({ exact, oversized: [...exact, { _truncated: true, omittedItems: 2 }] }); + }); + + it("keeps the first 100 object keys and reports omitted keys", () => { + const exact = Object.fromEntries(Array.from({ length: 100 }, (_, index) => [`key${index}`, index])); + expect(boundHeartbeatRunEventPayloadForStorage({ + exact, + oversized: { ...exact, extra1: 1, extra2: 2 }, + })).toEqual({ + exact, + oversized: { ...exact, _truncated: true, _omittedKeys: 2 }, + }); + }); + + it("replaces objects at the depth limit with at most 20 key names", () => { + const leaf = Object.fromEntries(Array.from({ length: 25 }, (_, index) => [`key${index}`, "hidden"])); + const payload = { one: { two: { three: { four: { five: { six: leaf } } } } } }; + expect(boundHeartbeatRunEventPayloadForStorage(payload)).toEqual({ + one: { two: { three: { four: { five: { six: { + _truncated: true, + type: "object", + keys: Object.keys(leaf).slice(0, 20), + } } } } } }, + }); + }); + + it("replaces arrays at the depth limit with their original length", () => { + const payload = { one: { two: { three: { four: { five: { six: [1, 2, 3] } } } } } }; + expect(boundHeartbeatRunEventPayloadForStorage(payload)).toEqual({ + one: { two: { three: { four: { five: { six: { + _truncated: true, + type: "array", + originalLength: 3, + } } } } } }, + }); + }); + + it("marks object cycles while preserving repeated references in separate branches", () => { + const shared = { text: "same value" }; + const payload: Record = { first: shared, second: shared }; + payload.self = payload; + expect(boundHeartbeatRunEventPayloadForStorage(payload)).toEqual({ + first: { text: "same value" }, + second: { text: "same value" }, + self: "[Circular]", + }); + }); + + it("bounds a self-referencing array without changing it", () => { + const entries: unknown[] = []; + entries.push(entries); + const result = boundHeartbeatRunEventPayloadForStorage({ entries }); + expect(JSON.stringify(result)).toBe('{"entries":[[[[[{"_truncated":true,"type":"array","originalLength":1}]]]]]}'); + expect(entries[0]).toBe(entries); + }); + + it("leaves frozen input values unchanged and creates independent output", () => { + const nested = Object.freeze({ text: "x".repeat(20_000) }); + const entries = Object.freeze([nested]); + const payload = Object.freeze({ nested, entries }); + const first = boundHeartbeatRunEventPayloadForStorage(payload); + const second = boundHeartbeatRunEventPayloadForStorage(payload); + expect(first).toEqual(second); + expect(first.nested).not.toBe(nested); + expect(first.entries).not.toBe(entries); + expect(nested.text).toHaveLength(20_000); + expect(entries[0]).toBe(nested); + }); +}); + +describe("heartbeat run-log chunk formatting", () => { + it("preserves ordinary chunks through the default 64 KiB character limit", () => { + const chunk = "x".repeat(64 * 1024); + expect(compactRunLogChunk("")).toBe(""); + expect(compactRunLogChunk("ready\n")).toBe("ready\n"); + expect(compactRunLogChunk(chunk)).toBe(chunk); + }); + + it("keeps the existing head, tail, and omission count for a custom limit", () => { + expect(compactRunLogChunk(`${"x".repeat(95)}tail!`, 20)).toBe( + `${"x".repeat(12)}\n[paperclip truncated run log chunk: omitted 83 chars]\ntail!`, + ); + }); + + it.each([1023, 1024])("preserves the image omission threshold at %i characters", (length) => { + const data = "A".repeat(length); + const chunk = `{"type":"image","source":{"type":"base64","data":"${data}"}}`; + expect(compactRunLogChunk(chunk)).toBe(length < 1024 + ? chunk + : chunk.replace(data, `[omitted base64 image data: ${length} chars]`)); + }); + + it("omits every large image consistently across repeated calls", () => { + const chunk = [1024, 2048].map((length) => + `{"type":"image","source":{"type":"base64","data":"${"A".repeat(length)}"}}`, + ).join("\n"); + const expected = [1024, 2048].map((length) => + `{"type":"image","source":{"type":"base64","data":"[omitted base64 image data: ${length} chars]"}}`, + ).join("\n"); + expect(compactRunLogChunk(chunk)).toBe(expected); + expect(compactRunLogChunk(chunk)).toBe(expected); + }); + + it("redacts credentials and image data before deciding whether a chunk needs truncation", () => { + const chunk = `Authorization: Bearer fixture-secret-token\n{"type":"image","source":{"type":"base64","data":"${"A".repeat(70_000)}"}}`; + const compacted = compactRunLogChunk(chunk, 512); + expect(compacted).toContain("***REDACTED***"); + expect(compacted).not.toContain("fixture-secret-token"); + expect(compacted).toContain("[omitted base64 image data: 70000 chars]"); + expect(compacted).not.toContain("[paperclip truncated"); + }); +}); diff --git a/server/src/services/heartbeat/run-log.ts b/server/src/services/heartbeat/run-log.ts new file mode 100644 index 00000000000..cbdd54e074b --- /dev/null +++ b/server/src/services/heartbeat/run-log.ts @@ -0,0 +1,120 @@ +import { appendWithByteCap, MAX_EXCERPT_BYTES, parseObject } from "../../adapters/utils.js"; +import { redactSensitiveText } from "../../redaction.js"; + +const MAX_PERSISTED_LOG_CHUNK_CHARS = 64 * 1024; +const MAX_RUN_EVENT_PAYLOAD_STRING_CHARS = 16 * 1024; +const MAX_RUN_EVENT_PAYLOAD_ARRAY_ITEMS = 50; +const MAX_RUN_EVENT_PAYLOAD_OBJECT_KEYS = 100; +const MAX_RUN_EVENT_PAYLOAD_DEPTH = 6; +const INLINE_BASE64_IMAGE_DATA_RE = + /("type":"image","source":\{"type":"base64","data":")([A-Za-z0-9+/=]{1024,})(")/g; + +export function appendExcerpt(prev: string, chunk: string) { + return appendWithByteCap(prev, chunk, MAX_EXCERPT_BYTES); +} + +function truncateRunEventString(value: string) { + if (value.length <= MAX_RUN_EVENT_PAYLOAD_STRING_CHARS) return value; + const omittedChars = value.length - MAX_RUN_EVENT_PAYLOAD_STRING_CHARS; + return `${value.slice(0, MAX_RUN_EVENT_PAYLOAD_STRING_CHARS)}\n[truncated ${omittedChars} chars]`; +} + +function boundRunEventValue( + value: unknown, + depth: number, + seen: WeakSet, +): unknown { + if (typeof value === "string") { + return truncateRunEventString(value); + } + if ( + value === null || + typeof value === "number" || + typeof value === "boolean" + ) { + return value; + } + if (value instanceof Date) { + return value.toISOString(); + } + if (Array.isArray(value)) { + if (depth >= MAX_RUN_EVENT_PAYLOAD_DEPTH) { + return { + _truncated: true, + type: "array", + originalLength: value.length, + }; + } + const bounded = value + .slice(0, MAX_RUN_EVENT_PAYLOAD_ARRAY_ITEMS) + .map((entry) => boundRunEventValue(entry, depth + 1, seen)); + if (value.length > MAX_RUN_EVENT_PAYLOAD_ARRAY_ITEMS) { + bounded.push({ + _truncated: true, + omittedItems: value.length - MAX_RUN_EVENT_PAYLOAD_ARRAY_ITEMS, + }); + } + return bounded; + } + if (typeof value !== "object" || value === undefined) { + return null; + } + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + const entries = Object.entries(value as Record); + if (depth >= MAX_RUN_EVENT_PAYLOAD_DEPTH) { + const bounded = { + _truncated: true, + type: "object", + keys: entries.map(([key]) => key).slice(0, 20), + }; + seen.delete(value); + return bounded; + } + + const out: Record = {}; + for (const [key, entryValue] of entries.slice( + 0, + MAX_RUN_EVENT_PAYLOAD_OBJECT_KEYS, + )) { + out[key] = boundRunEventValue(entryValue, depth + 1, seen); + } + if (entries.length > MAX_RUN_EVENT_PAYLOAD_OBJECT_KEYS) { + out._truncated = true; + out._omittedKeys = entries.length - MAX_RUN_EVENT_PAYLOAD_OBJECT_KEYS; + } + seen.delete(value); + return out; +} + +export function boundHeartbeatRunEventPayloadForStorage( + payload: Record, +): Record { + const bounded = boundRunEventValue(payload, 0, new WeakSet()); + return parseObject(bounded) ?? { _truncated: true }; +} + +function redactInlineBase64ImageData(chunk: string) { + return chunk.replace( + INLINE_BASE64_IMAGE_DATA_RE, + (_match, prefix: string, data: string, suffix: string) => + `${prefix}[omitted base64 image data: ${data.length} chars]${suffix}`, + ); +} + +export function compactRunLogChunk( + chunk: string, + maxChars = MAX_PERSISTED_LOG_CHUNK_CHARS, +) { + const normalized = redactSensitiveText(redactInlineBase64ImageData(chunk)); + if (normalized.length <= maxChars) return normalized; + + const headChars = Math.max(0, Math.floor(maxChars * 0.6)); + const tailChars = Math.max(0, Math.floor(maxChars * 0.25)); + const omittedChars = Math.max(0, normalized.length - headChars - tailChars); + const marker = `\n[paperclip truncated run log chunk: omitted ${omittedChars} chars]\n`; + return `${normalized.slice(0, headChars)}${marker}${normalized.slice(normalized.length - tailChars)}`; +} +