Skip to content

Commit a415745

Browse files
committed
fix(mothership): measure the run result window after secret projection and fit the preview
1 parent f8b4710 commit a415745

2 files changed

Lines changed: 109 additions & 22 deletions

File tree

‎apps/sim/lib/mothership/tools/handlers/workflow/run-workflow-result-budget.test.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,62 @@ describe('run_workflow model-facing result budget', () => {
179179
expect(presented[3]).toMatchObject({ success: false, error: 'SMTP refused' })
180180
})
181181

182+
/** A short secret under a long name grows when projected, so the window is measured after it. */
183+
it('fits the window as projected when short secrets expand into longer names', async () => {
184+
const password = 'pw-12345'
185+
const shortSecret = new ResolvedSecretTraceRegistry([
186+
{ name: 'DATABASE_PASSWORD', plaintext: password, encryptedValue: 'ciphertext' },
187+
])
188+
shortSecret.recordResolved('DATABASE_PASSWORD', password, { propagated: true })
189+
mocks.executeWorkflowUseCase.mockResolvedValue({
190+
success: true,
191+
output: { done: true },
192+
logs: [
193+
{
194+
blockId: 'echo',
195+
blockName: 'Echo',
196+
success: true,
197+
// About 14K characters raw, over 31K once each copy becomes {{DATABASE_PASSWORD}}.
198+
output: { tokens: Array.from({ length: 1_300 }, () => password) },
199+
},
200+
],
201+
metadata: { executionId: EXECUTION_ID },
202+
})
203+
204+
const settled = await executeRunWorkflow({ workflowId: 'wf-1' }, callContext(shortSecret))
205+
const projection = inspectToolResultForCopilot(settled, shortSecret, 'run_workflow')
206+
207+
expect(projection.safe).toBe(true)
208+
expect(JSON.stringify(projection.result.output).length).toBeLessThanOrEqual(16_000)
209+
const output = projection.result.output as { output: unknown; logs: Array<{ output: unknown }> }
210+
expect(output.output).toEqual({ done: true })
211+
expect(output.logs[0]?.output).toEqual(expect.stringContaining(`logs get ${EXECUTION_ID}`))
212+
})
213+
214+
/** Many small block entries leave less room than a full preview, so the preview shrinks to fit. */
215+
it('shrinks the final output preview to the room the block entries leave', async () => {
216+
const logs = Array.from({ length: 150 }, (_, index) => ({
217+
blockId: `step-${index}`,
218+
blockName: `Step ${index} of the nightly import`,
219+
success: true,
220+
output: { ok: true },
221+
}))
222+
mocks.executeWorkflowUseCase.mockResolvedValue({
223+
success: true,
224+
output: { report: 'z'.repeat(50_000) },
225+
logs,
226+
metadata: { executionId: EXECUTION_ID },
227+
})
228+
const inactive = secretRegistry({ active: false })
229+
230+
const settled = await executeRunWorkflow({ workflowId: 'wf-1' }, callContext(inactive))
231+
const output = settled.output as { output: unknown; logs: unknown[] }
232+
233+
expect(JSON.stringify({ output }).length).toBeLessThanOrEqual(16_000)
234+
expect(output.logs).toEqual(logs)
235+
expect(output.output).toEqual(expect.stringMatching(/^\{"report":"z+ …\[final output cut at/))
236+
})
237+
182238
/** Narrow rows reach the traversal cap while staying far under every byte budget. */
183239
it('bounds narrow row outputs by value count alone', async () => {
184240
const logs = Array.from({ length: 6 }, (_, index) => ({

‎apps/sim/lib/mothership/tools/workflow-output.ts‎

Lines changed: 53 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
MAX_CONTENT_NODES,
55
MAX_MODEL_CONTENT_BYTES,
66
measureModelContent,
7+
projectResolvedSecretModelContent,
78
} from '@/executor/utils/resolved-secret-content-projection'
89
import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
910

@@ -195,14 +196,16 @@ function compactBlockLogOutputs(logs: unknown, executionId: string | undefined):
195196
}
196197

197198
/**
198-
* The most serialized characters a run result carries to the agent. The agent holds a workflow
199-
* tool result inline up to twice its 12K-character output window and stores a larger one behind a
200-
* paged read, which costs the agent a round to learn whether the run passed. This leaves room for
201-
* the envelope and the secret projection's placeholders.
199+
* The most serialized characters a run result carries to the agent, measured after secret
200+
* projection. The agent holds a workflow tool result inline up to twice its 12K-character output
201+
* window and stores a larger one behind a paged read, which costs the agent a round to learn
202+
* whether the run passed. This leaves room for the envelope.
202203
*/
203204
const MODEL_RUN_RESULT_MAX_CHARS = 16_000
204-
/** How much of an oversized final output stays inline, as serialized JSON, when no secret is active. */
205+
/** The most of an oversized final output that stays inline, as serialized JSON, when no secret is active. */
205206
const FINAL_OUTPUT_PREVIEW_CHARS = 4_000
207+
/** A preview shorter than this says too little to be worth more than a pointer. */
208+
const FINAL_OUTPUT_PREVIEW_MIN_CHARS = 200
206209

207210
/** `value` serialized the way the agent receives it; undefined for a value JSON cannot encode. */
208211
function serialize(value: unknown): string | undefined {
@@ -218,8 +221,12 @@ function serialize(value: unknown): string | undefined {
218221
* active: a kept prefix could otherwise cut through a secret and leave a fragment no whole-literal
219222
* redaction matches.
220223
*/
221-
function finalOutputPreview(serialized: string, executionId: string | undefined): string {
222-
let end = FINAL_OUTPUT_PREVIEW_CHARS
224+
function finalOutputPreview(
225+
serialized: string,
226+
chars: number,
227+
executionId: string | undefined
228+
): string {
229+
let end = chars
223230
const last = serialized.charCodeAt(end - 1)
224231
if (last >= 0xd800 && last <= 0xdbff) end -= 1
225232
return `${serialized.slice(0, end)} …[final output cut at ${end} of ${serialized.length} chars; inspect with logs get ${executionId ?? '<executionId>'} --trace]`
@@ -229,17 +236,33 @@ function finalOutputPreview(serialized: string, executionId: string | undefined)
229236
* Holds a run result to {@link MODEL_RUN_RESULT_MAX_CHARS} so the agent reads pass/fail, the
230237
* failing block's error, and each block's status inline. Echoed block inputs and outputs are
231238
* replaced with pointers, largest first, until the result fits; the per-block entries keep their
232-
* name, id, status, and error. If that is not enough, the final output is cut to a preview, or to a
233-
* pointer when `walksContent` (a secret is active). Values a caller named with `select` are kept.
239+
* name, id, status, and error. If that is not enough, the final output is cut to a preview that
240+
* fits what is left, or to a pointer when a secret is active. Values a caller named with `select`
241+
* are kept. A result that still does not fit is returned as far as it was reduced.
242+
*
243+
* While `registry` makes the projection walk the result, its size is measured as projected:
244+
* replacing many short secrets with their longer names can grow it. Raw sizes rank the parts and
245+
* skip the projection while the raw result is plainly over.
234246
*/
235247
function fitRunResultToWindow(
236248
data: Record<string, unknown>,
237249
error: string | undefined,
238250
executionId: string | undefined,
251+
registry: ResolvedSecretTraceRegistry | undefined,
239252
walksContent: boolean
240253
): Record<string, unknown> {
241-
let total = serialize(error === undefined ? { output: data } : { output: data, error })?.length
242-
if (total === undefined || total <= MODEL_RUN_RESULT_MAX_CHARS) return data
254+
const envelope = (candidate: Record<string, unknown>) =>
255+
error === undefined ? { output: candidate } : { output: candidate, error }
256+
const fits = (candidate: Record<string, unknown>, rawChars: number): boolean => {
257+
if (rawChars > MODEL_RUN_RESULT_MAX_CHARS) return false
258+
if (!walksContent) return true
259+
const projection = projectResolvedSecretModelContent(envelope(candidate), registry)
260+
const projected = projection.safe ? serialize(projection.value)?.length : undefined
261+
return (projected ?? rawChars) <= MODEL_RUN_RESULT_MAX_CHARS
262+
}
263+
264+
let raw = serialize(envelope(data))?.length
265+
if (raw === undefined || fits(data, raw)) return data
243266

244267
let fitted = data
245268
if (Array.isArray(data.logs)) {
@@ -255,7 +278,6 @@ function fitRunResultToWindow(
255278
parts.sort((left, right) => right.size - left.size)
256279
const logs = [...data.logs]
257280
for (const part of parts) {
258-
if (total <= MODEL_RUN_RESULT_MAX_CHARS) break
259281
const entry = logs[part.index] as Record<string, unknown>
260282
const pointer =
261283
part.field === 'input'
@@ -267,22 +289,31 @@ function fitRunResultToWindow(
267289
const saved = part.size - JSON.stringify(pointer).length
268290
if (saved <= 0) continue
269291
logs[part.index] = { ...entry, [part.field]: pointer }
270-
total -= saved
292+
raw -= saved
293+
fitted = { ...data, logs }
294+
if (fits(fitted, raw)) return fitted
271295
}
272-
fitted = { ...data, logs }
273296
}
274-
if (total <= MODEL_RUN_RESULT_MAX_CHARS || !Object.hasOwn(fitted, 'output')) return fitted
297+
if (!Object.hasOwn(fitted, 'output')) return fitted
275298

299+
// A final output no longer than a preview is what the run was for; it stays whole.
276300
const serialized = serialize(fitted.output)
277301
if (serialized === undefined || serialized.length <= FINAL_OUTPUT_PREVIEW_CHARS) return fitted
278302
const label = sizeBlockOutput(fitted.output)?.label
279-
if (walksContent && !label) return fitted
280-
return {
281-
...fitted,
282-
output: walksContent
283-
? blockOutputPointer(label ?? 'output omitted', executionId)
284-
: finalOutputPreview(serialized, executionId),
303+
if (!label) return fitted
304+
const pointed = { ...fitted, output: blockOutputPointer(label, executionId) }
305+
if (walksContent) return pointed
306+
307+
const rest = serialize(envelope(pointed))?.length ?? Number.POSITIVE_INFINITY
308+
let chars = Math.min(FINAL_OUTPUT_PREVIEW_CHARS, MODEL_RUN_RESULT_MAX_CHARS - rest)
309+
while (chars >= FINAL_OUTPUT_PREVIEW_MIN_CHARS && chars < serialized.length) {
310+
const previewed = { ...fitted, output: finalOutputPreview(serialized, chars, executionId) }
311+
const previewedChars = serialize(envelope(previewed))?.length ?? Number.POSITIVE_INFINITY
312+
if (previewedChars <= MODEL_RUN_RESULT_MAX_CHARS) return previewed
313+
// JSON escapes inside the preview grow it once it is embedded as a string.
314+
chars -= previewedChars - MODEL_RUN_RESULT_MAX_CHARS
285315
}
316+
return pointed
286317
}
287318

288319
/**
@@ -303,7 +334,7 @@ export function boundRunResultForModel(
303334
): Record<string, unknown> {
304335
const walksContent = copilotProjectionWalksContent(registry)
305336
const capped = walksContent ? boundToProjectionCaps(data, error, executionId) : data
306-
return fitRunResultToWindow(capped, error, executionId, walksContent)
337+
return fitRunResultToWindow(capped, error, executionId, registry, walksContent)
307338
}
308339

309340
function boundToProjectionCaps(

0 commit comments

Comments
 (0)