Skip to content

Commit f8b4710

Browse files
committed
improvement(mothership): keep workflow test-run results inside the agent window
1 parent 6ee1d0d commit f8b4710

5 files changed

Lines changed: 174 additions & 65 deletions

File tree

‎apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,10 @@ describe('POST /api/v2/workflows/[workflowId]/execute', () => {
482482
blockName: 'Send Email',
483483
blockType: 'gmail',
484484
})
485+
// An agent reads the head of an oversized run, so the error precedes the unbounded output.
486+
const keys = Object.keys(body.data)
487+
expect(keys.indexOf('error')).toBeLessThan(keys.indexOf('output'))
488+
expect(keys.indexOf('durationMs')).toBeLessThan(keys.indexOf('output'))
485489
})
486490

487491
it('queues async runs and returns a 202 receipt with the v2 runs statusUrl', async () => {

‎apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,18 +123,23 @@ function encodeNdjson(value: unknown): Uint8Array {
123123
return ndjsonEncoder.encode(`${JSON.stringify(value)}\n`)
124124
}
125125

126+
/**
127+
* The run resource, its bounded fields ahead of `output` and `blockOutputs`: a reader that keeps
128+
* only the head of an oversized response (an agent's output window) still sees the status, the
129+
* failing block and its error, and the duration.
130+
*/
126131
function presentRun(result: ExecuteWorkflowServiceRun) {
127132
return {
128133
runId: result.executionId,
129134
workflowId: result.workflowId,
130135
status: result.status,
131-
output: result.output ?? null,
132-
blockOutputs: result.blockOutputs ?? null,
133136
error: result.error,
134137
startedAt: result.startedAt,
135138
endedAt: result.endedAt,
136139
durationMs: result.durationMs,
137140
executionTimeoutSeconds: executionTimeoutSeconds(result.executionTimeoutMs),
141+
output: result.output ?? null,
142+
blockOutputs: result.blockOutputs ?? null,
138143
}
139144
}
140145

‎apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -111,13 +111,13 @@ export const POST = withRouteHandler(
111111
runId: result.executionId,
112112
workflowId,
113113
status: result.status as 'completed' | 'failed' | 'paused' | 'cancelled',
114-
output: result.output ?? null,
115-
// Resume has no request body to name selectors in, so selection never applies here.
116-
blockOutputs: null,
117114
error: result.structuredError,
118115
startedAt: result.metadata?.startTime,
119116
endedAt: result.metadata?.endTime,
120117
durationMs: result.metadata?.duration,
118+
output: result.output ?? null,
119+
// Resume has no request body to name selectors in, so selection never applies here.
120+
blockOutputs: null,
121121
},
122122
{ headers }
123123
)

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

Lines changed: 49 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -148,21 +148,35 @@ describe('run_workflow model-facing result budget', () => {
148148
expect(presented.find((log) => log.blockName === 'Query 1')?.output).toEqual(logs[1].output)
149149
})
150150

151-
/** The final output is what the run was for, so it is never compacted and needs the headroom. */
152-
it('leaves room for a large final output beside the bounded logs', async () => {
153-
const finalOutput = { rows: tableRows(4_800, 3_200_000) }
151+
/**
152+
* The agent stores a result past its window behind a paged read, which costs it a round to learn
153+
* whether the run passed. Block outputs give way first, so the verdict, the failing block, and a
154+
* final output that fits all arrive inline.
155+
*/
156+
it('fits a failed run with bulky block outputs inside the agent window', async () => {
157+
const logs = [
158+
...traceShapedLogs().slice(0, 3),
159+
{ blockId: 'send', blockName: 'Send', success: false, error: 'SMTP refused', output: {} },
160+
]
161+
const finalOutput = { summary: 'partial report', rowCount: 1_882 }
154162
mocks.executeWorkflowUseCase.mockResolvedValue({
155-
success: true,
163+
success: false,
156164
output: finalOutput,
157-
logs: traceShapedLogs(),
165+
logs,
158166
metadata: { executionId: EXECUTION_ID },
159167
})
160168

161169
const settled = await executeRunWorkflow({ workflowId: 'wf-1' }, context)
162170
const projection = inspectToolResultForCopilot(settled, registry, 'run_workflow')
163171

164172
expect(projection.safe).toBe(true)
165-
expect((projection.result.output as Record<string, unknown>).output).toEqual(finalOutput)
173+
expect(JSON.stringify(projection.result).length).toBeLessThanOrEqual(24_000)
174+
expect(projection.result.error).toBe('Send: SMTP refused')
175+
const output = projection.result.output as Record<string, unknown>
176+
expect(output.output).toEqual(finalOutput)
177+
const presented = output.logs as Array<Record<string, unknown>>
178+
expect(presented.map((log) => log.blockName)).toEqual(logs.map((log) => log.blockName))
179+
expect(presented[3]).toMatchObject({ success: false, error: 'SMTP refused' })
166180
})
167181

168182
/** Narrow rows reach the traversal cap while staying far under every byte budget. */
@@ -186,7 +200,9 @@ describe('run_workflow model-facing result budget', () => {
186200
const projection = inspectToolResultForCopilot(settled, registry, 'run_workflow')
187201

188202
expect(projection.safe).toBe(true)
189-
expect((projection.result.output as Record<string, unknown>).output).toEqual(finalOutput)
203+
expect((projection.result.output as Record<string, unknown>).output).toEqual(
204+
expect.stringContaining(`logs get ${EXECUTION_ID} --trace`)
205+
)
190206
})
191207

192208
it('returns selected values in full, bypassing the log budget', async () => {
@@ -343,11 +359,10 @@ describe('run_workflow model-facing result budget', () => {
343359
})
344360

345361
/**
346-
* Without an active secret the projection passes JSON through under its byte cap alone, so
347-
* nothing is bounded: a lifted output is the whole point of run_block and reaches the worker in
348-
* full, which spills an oversized one to storage for the model to read.
362+
* Without an active secret a cut cannot strand a secret fragment, so an oversized lifted output
363+
* keeps its head inline as a preview and names where the rest is.
349364
*/
350-
it('returns a large lifted output and its logs in full when no secret is active', async () => {
365+
it('previews an oversized lifted output when no secret is active', async () => {
351366
const rows = wideRows()
352367
mocks.executeWorkflowUseCase.mockResolvedValue({
353368
success: true,
@@ -368,52 +383,35 @@ describe('run_workflow model-facing result budget', () => {
368383

369384
expect(projection.safe).toBe(true)
370385
const output = projection.result.output as Record<string, unknown>
371-
expect(output.output).toEqual({ rows })
372-
expect((output.logs as Array<Record<string, unknown>>)[1]?.output).toEqual({ rows })
386+
expect(JSON.stringify(output).length).toBeLessThanOrEqual(16_000)
387+
expect(output.output).toEqual(expect.stringMatching(/^\{"rows":\[\{"c0":"r0"/))
388+
expect(output.output).toEqual(expect.stringContaining(`logs get ${EXECUTION_ID} --trace`))
389+
expect(output.outputFrom).toEqual({ blockId: 'query', blockName: 'Query' })
390+
expect((output.logs as Array<Record<string, unknown>>)[0]?.output).toEqual({ ok: true })
373391
})
374392

375393
/**
376-
* Nothing is bounded while the whole result fits the projection's caps, so a result that crossed
377-
* in full before still does: a lifted output and its log copy of about 27.5k values each, or one
378-
* 4.5 MB block output.
394+
* A preview keeps a prefix that can cut through a secret, so with one active an oversized final
395+
* output becomes a pointer whose text does not depend on the secret.
379396
*/
380-
it('returns a result that fits the caps in full while a secret is active', async () => {
381-
const rows = wideRows()
382-
mocks.executeWorkflowUseCase.mockResolvedValue({
383-
success: true,
384-
output: {},
385-
logs: [{ blockId: 'query', blockName: 'Query', success: true, output: { rows } }],
386-
metadata: { executionId: EXECUTION_ID },
387-
})
388-
const lifted = inspectToolResultForCopilot(
389-
await executeRunWorkflowUntilBlock(
390-
{ workflowId: 'wf-1', stopAfterBlockId: 'query' },
391-
context
392-
),
393-
registry,
394-
'run_workflow'
395-
)
396-
expect(lifted.safe).toBe(true)
397-
const liftedOutput = lifted.result.output as Record<string, unknown>
398-
expect(liftedOutput.output).toEqual({ rows })
399-
expect((liftedOutput.logs as Array<Record<string, unknown>>)[0]?.output).toEqual({ rows })
397+
it('replaces an oversized final output with a pointer, never a preview, while a secret is active', async () => {
398+
async function finalOutputFor(secret: string) {
399+
mocks.executeWorkflowUseCase.mockResolvedValue({
400+
success: true,
401+
output: { report: `${'r'.repeat(20_000)}${secret}`, token: secret },
402+
logs: [{ blockId: 'small', blockName: 'Small', success: true, output: { ok: true } }],
403+
metadata: { executionId: EXECUTION_ID },
404+
})
405+
const settled = await executeRunWorkflow({ workflowId: 'wf-1' }, context)
406+
expect(inspectToolResultForCopilot(settled, registry, 'run_workflow').safe).toBe(true)
407+
return (settled.output as Record<string, unknown>).output
408+
}
400409

401-
const text = { text: 'y'.repeat(4_500_000) }
402-
mocks.executeWorkflowUseCase.mockResolvedValue({
403-
success: true,
404-
output: { done: true },
405-
logs: [{ blockId: 'big', blockName: 'Big', success: true, output: text }],
406-
metadata: { executionId: EXECUTION_ID },
407-
})
408-
const wide = inspectToolResultForCopilot(
409-
await executeRunWorkflow({ workflowId: 'wf-1' }, context),
410-
registry,
411-
'run_workflow'
412-
)
413-
expect(wide.safe).toBe(true)
414-
expect((wide.result.output as { logs: Array<{ output: unknown }> }).logs[0]?.output).toEqual(
415-
text
410+
const short = await finalOutputFor(SECRET)
411+
expect(short).toEqual(
412+
expect.stringMatching(/^…\[output omitted: \d+ values; inspect with logs get /)
416413
)
414+
expect(await finalOutputFor(`${SECRET}-but-considerably-longer`)).toBe(short)
417415
})
418416

419417
/**

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

Lines changed: 111 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ function presentWorkflowLogs(logs: unknown, select?: string[]): Record<string, u
1919
* resolves against the full logs and replaces them. Otherwise, when `registry` makes the projection
2020
* walk the result, long echoed inputs get a marker that keeps nothing of the raw input. Without an
2121
* active secret the logs cross as they always have: the server handler previews long inputs
22-
* (`previewLongInputs`) and the browser-run path leaves them untouched. Outputs are bounded by
23-
* {@link boundRunResultForModel}, only when the whole result would pass a projection cap.
22+
* (`previewLongInputs`) and the browser-run path leaves them untouched. Outputs, and any input
23+
* still too long for the agent's window, are bounded by {@link boundRunResultForModel}.
2424
*/
2525
export function presentWorkflowLogsForModel(
2626
logs: unknown,
@@ -195,20 +195,122 @@ function compactBlockLogOutputs(logs: unknown, executionId: string | undefined):
195195
}
196196

197197
/**
198-
* Bounds a run's whole model-facing result before secret projection. When `registry` makes the
199-
* projection walk the result, one past any of its caps is withheld entirely. So a result that
200-
* would pass a cap first has its bulkiest block-log outputs replaced with pointers, down to their
201-
* budget, and if it still would, its final output too. The result is measured whole, envelope and
202-
* error included, and a result that fits is returned untouched. A block output that run_block or
203-
* run_workflow_until_block lifted into `output` is the run's final output here too.
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.
202+
*/
203+
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+
const FINAL_OUTPUT_PREVIEW_CHARS = 4_000
206+
207+
/** `value` serialized the way the agent receives it; undefined for a value JSON cannot encode. */
208+
function serialize(value: unknown): string | undefined {
209+
try {
210+
return JSON.stringify(value) ?? ''
211+
} catch {
212+
return undefined
213+
}
214+
}
215+
216+
/**
217+
* The head of an oversized final output and where the rest is. Only used when no secret is
218+
* active: a kept prefix could otherwise cut through a secret and leave a fragment no whole-literal
219+
* redaction matches.
220+
*/
221+
function finalOutputPreview(serialized: string, executionId: string | undefined): string {
222+
let end = FINAL_OUTPUT_PREVIEW_CHARS
223+
const last = serialized.charCodeAt(end - 1)
224+
if (last >= 0xd800 && last <= 0xdbff) end -= 1
225+
return `${serialized.slice(0, end)} …[final output cut at ${end} of ${serialized.length} chars; inspect with logs get ${executionId ?? '<executionId>'} --trace]`
226+
}
227+
228+
/**
229+
* Holds a run result to {@link MODEL_RUN_RESULT_MAX_CHARS} so the agent reads pass/fail, the
230+
* failing block's error, and each block's status inline. Echoed block inputs and outputs are
231+
* 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.
234+
*/
235+
function fitRunResultToWindow(
236+
data: Record<string, unknown>,
237+
error: string | undefined,
238+
executionId: string | undefined,
239+
walksContent: boolean
240+
): 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
243+
244+
let fitted = data
245+
if (Array.isArray(data.logs)) {
246+
const parts: Array<{ index: number; field: 'input' | 'output'; size: number }> = []
247+
for (const [index, entry] of data.logs.entries()) {
248+
if (!isPlainRecord(entry)) continue
249+
for (const field of ['input', 'output'] as const) {
250+
if (entry[field] === undefined) continue
251+
const size = serialize(entry[field])?.length
252+
if (size !== undefined) parts.push({ index, field, size })
253+
}
254+
}
255+
parts.sort((left, right) => right.size - left.size)
256+
const logs = [...data.logs]
257+
for (const part of parts) {
258+
if (total <= MODEL_RUN_RESULT_MAX_CHARS) break
259+
const entry = logs[part.index] as Record<string, unknown>
260+
const pointer =
261+
part.field === 'input'
262+
? omittedInputMarker('', executionId ?? '<executionId>')
263+
: blockOutputPointer(
264+
sizeBlockOutput(entry.output)?.label ?? 'output omitted',
265+
executionId
266+
)
267+
const saved = part.size - JSON.stringify(pointer).length
268+
if (saved <= 0) continue
269+
logs[part.index] = { ...entry, [part.field]: pointer }
270+
total -= saved
271+
}
272+
fitted = { ...data, logs }
273+
}
274+
if (total <= MODEL_RUN_RESULT_MAX_CHARS || !Object.hasOwn(fitted, 'output')) return fitted
275+
276+
const serialized = serialize(fitted.output)
277+
if (serialized === undefined || serialized.length <= FINAL_OUTPUT_PREVIEW_CHARS) return fitted
278+
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),
285+
}
286+
}
287+
288+
/**
289+
* Bounds a run's whole model-facing result before secret projection, in two steps. First, when
290+
* `registry` makes the projection walk the result, one past any of its caps is withheld entirely.
291+
* So a result that would pass a cap first has its bulkiest block-log outputs replaced with
292+
* pointers, down to their budget, and if it still would, its final output too. The result is
293+
* measured whole, envelope and error included. A block output that run_block or
294+
* run_workflow_until_block lifted into `output` is the run's final output here too. Then every
295+
* result, secret or not, is held to the agent's inline window ({@link fitRunResultToWindow}). A
296+
* result that fits both is returned untouched.
204297
*/
205298
export function boundRunResultForModel(
206299
data: Record<string, unknown>,
207300
error: string | undefined,
208301
executionId: string | undefined,
209302
registry: ResolvedSecretTraceRegistry | undefined
210303
): Record<string, unknown> {
211-
if (!copilotProjectionWalksContent(registry)) return data
304+
const walksContent = copilotProjectionWalksContent(registry)
305+
const capped = walksContent ? boundToProjectionCaps(data, error, executionId) : data
306+
return fitRunResultToWindow(capped, error, executionId, walksContent)
307+
}
308+
309+
function boundToProjectionCaps(
310+
data: Record<string, unknown>,
311+
error: string | undefined,
312+
executionId: string | undefined
313+
): Record<string, unknown> {
212314
// A result JSON cannot encode is refused whatever its size, so only one past a cap is bounded.
213315
const passesCap = (candidate: Record<string, unknown>): boolean =>
214316
measureModelContent(error === undefined ? { output: candidate } : { output: candidate, error })

0 commit comments

Comments
 (0)