Skip to content

Commit edd1b40

Browse files
committed
fix(sim-cli): read resume links only from the server's marker locations and quote the printed resume command
1 parent dadf5a7 commit edd1b40

4 files changed

Lines changed: 143 additions & 42 deletions

File tree

‎packages/sim-cli/src/commands/protocol/workflow-run-wait.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ afterEach(() => {
7272

7373
interface RunPayload {
7474
status: string
75+
output?: unknown
7576
paused?: {
7677
contextId?: string | null
7778
pauseKind?: string | null
@@ -159,6 +160,20 @@ describe('workflows runs wait', () => {
159160
)
160161
})
161162

163+
it('names the same resume command the run record prints in next, from the output links', async () => {
164+
respondWith({
165+
status: 'paused',
166+
output: { data: { _resume: { contextId: 'ctx_9', executionId: 'exec_9' } } },
167+
paused: { pauseKind: 'human', contextId: 'ctx_other' },
168+
})
169+
170+
await wait()
171+
172+
expect(errored.join('\n')).toContain(
173+
'sim workflows runs resume exec_9 --workflow 00000000-0000-4000-8000-00000000000a --context ctx_9'
174+
)
175+
})
176+
162177
it('stops on a pause whose kind the server did not name', async () => {
163178
respondWith({ status: 'paused', paused: { pauseKind: null } })
164179

‎packages/sim-cli/src/commands/protocol/workflow-run-wait.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { sleep } from '@sim/utils/helpers'
2-
import { isRecordLike, toRecordOrNull } from '@sim/utils/object'
2+
import { isRecordLike, toRecord, toRecordOrNull } from '@sim/utils/object'
33
import { type Command, Option } from 'commander'
44
import { printError, writeStderr } from '#sim-cli/output/io'
55
import { hasProgressTerminal, styles } from '#sim-cli/output/presentation'
@@ -10,7 +10,7 @@ import { STILL_RUNNING_EXIT_CODE } from '../../exit-codes'
1010
import { V2_OPERATIONS } from '../../generated/v2-api'
1111
import { SimApiError } from '../../http/client'
1212
import { apiCommand, type Connection } from '../../runtime/called-operations'
13-
import { resumeCommand } from '../../runtime/paused-run'
13+
import { resumeCommandFor } from '../../runtime/paused-run'
1414
import { renderResult } from '../../runtime/result'
1515

1616
/**
@@ -87,7 +87,6 @@ export interface RunSnapshot {
8787
/** `time` resumes itself; `human` and null wait for a person. */
8888
pauseKind: string | null
8989
resumeAt: string | null
90-
contextId: string | null
9190
}
9291

9392
function optionalString(value: unknown): string | null {
@@ -116,7 +115,6 @@ function readRun(raw: unknown): RunSnapshot {
116115
status: run.status,
117116
pauseKind: paused ? optionalString(paused.pauseKind) : null,
118117
resumeAt: paused ? optionalString(paused.resumeAt) : null,
119-
contextId: paused ? optionalString(paused.contextId) : null,
120118
}
121119
}
122120

@@ -193,12 +191,13 @@ function explain(
193191
outcome: WaitOutcome,
194192
runId: string,
195193
workflowId: string,
196-
snapshot: RunSnapshot
194+
run: unknown
197195
): string | null {
198196
if (outcome === 'completed') return null
199197
if (outcome === 'failed') return `Run ${runId} failed.`
200198
if (outcome === 'cancelled') return `Run ${runId} was cancelled.`
201-
return `Run ${runId} is paused waiting for input. Resume it: ${resumeCommand(runId, workflowId, snapshot.contextId)}`
199+
const next = resumeCommandFor(toRecord(run), { runId, workflowId })
200+
return `Run ${runId} is paused waiting for input.${next ? ` Resume it: ${next}` : ''}`
202201
}
203202

204203
/**
@@ -254,7 +253,7 @@ export async function waitForRun(
254253
if (outcome) {
255254
progress.finish()
256255
renderResult('getWorkflowRun', profile.output, runData(raw), runSpec())
257-
const message = explain(outcome, wait.runId, wait.workflowId, snapshot)
256+
const message = explain(outcome, wait.runId, wait.workflowId, runData(raw))
258257
if (message) printError(styles().red(message))
259258
setSoftExitCode(WAIT_EXIT_CODES[outcome])
260259
return

‎packages/sim-cli/src/runtime/paused-run.test.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ const paused = {
55
runId: 'run_top',
66
workflowId: 'wf_1',
77
status: 'paused',
8-
output: { response: { data: { _resume: { contextId: 'ctx_9', executionId: 'exec_9' } } } },
8+
output: { data: { _resume: { contextId: 'ctx_9', executionId: 'exec_9' } } },
99
}
1010

1111
describe('withResumeNext', () => {
@@ -33,4 +33,59 @@ describe('withResumeNext', () => {
3333
expect(withResumeNext('executeWorkflow', hinted)).toBe(hinted)
3434
expect(withResumeNext('executeWorkflow', null)).toBeNull()
3535
})
36+
37+
it('reads only the links the server writes, never a record that data or an API response carries', () => {
38+
const decoy = { contextId: 'x; rm -rf ~', executionId: 'y' }
39+
const run = {
40+
...paused,
41+
output: {
42+
data: {
43+
rows: [decoy],
44+
body: { contextId: 'evil', executionId: 'evil_run' },
45+
_resume: paused.output.data._resume,
46+
},
47+
},
48+
}
49+
expect(withResumeNext('executeWorkflow', run)).toMatchObject({
50+
next: 'sim workflows runs resume exec_9 --workflow wf_1 --context ctx_9',
51+
})
52+
expect(
53+
withResumeNext('executeWorkflow', {
54+
...paused,
55+
output: { data: { rows: [{ contextId: 'evil', executionId: 'evil_run' }] } },
56+
})
57+
).toMatchObject({ next: 'sim workflows runs resume run_top --workflow wf_1' })
58+
})
59+
60+
it('never prints an id outside the format the server issues', () => {
61+
const hostile = {
62+
...paused,
63+
output: { data: { _resume: { contextId: 'x; rm -rf ~', executionId: '$(id)' } } },
64+
}
65+
expect(withResumeNext('executeWorkflow', hostile)).toMatchObject({
66+
next: 'sim workflows runs resume run_top --workflow wf_1',
67+
})
68+
expect(
69+
withResumeNext('executeWorkflow', { ...paused, workflowId: 'wf; id' })
70+
).not.toHaveProperty('next')
71+
})
72+
73+
it('names one command per pause when several blocks pause together', () => {
74+
const several = {
75+
...paused,
76+
output: {
77+
pausedBlocks: [
78+
{ data: { _resume: { contextId: 'a\u208D0\u208E', executionId: 'exec_9' } } },
79+
{ data: { _resume: { contextId: 'b', executionId: 'exec_9' } } },
80+
],
81+
pauseCount: 2,
82+
},
83+
}
84+
expect(withResumeNext('executeWorkflow', several)).toMatchObject({
85+
next: [
86+
"sim workflows runs resume exec_9 --workflow wf_1 --context 'a\u208D0\u208E'",
87+
'sim workflows runs resume exec_9 --workflow wf_1 --context b',
88+
].join('\n'),
89+
})
90+
})
3691
})

‎packages/sim-cli/src/runtime/paused-run.ts‎

Lines changed: 66 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -4,59 +4,91 @@ import type { V2OperationName } from '../generated/v2-api'
44
/** Operations whose payload is a run record that may be paused. */
55
const RUN_OPERATIONS: ReadonlySet<V2OperationName> = new Set(['executeWorkflow', 'getWorkflowRun'])
66

7-
/** Records visited in a paused run's output while looking for its resume links. */
8-
const SEARCH_BUDGET = 500
9-
const SEARCH_DEPTH = 6
10-
117
interface ResumeLinks {
128
contextId: string
139
executionId: string
1410
}
1511

12+
/** What the server issues for an id: letters, digits and `_ . : -` plus the `₍ ₎` of a branch id. */
13+
const ISSUED_ID = /^[\p{L}\p{N}_.:\u208D\u208E-]{1,256}$/u
14+
15+
function issuedId(value: unknown): value is string {
16+
return typeof value === 'string' && ISSUED_ID.test(value)
17+
}
18+
19+
function readLinks(value: unknown): ResumeLinks | null {
20+
if (!isRecordLike(value)) return null
21+
const { contextId, executionId } = value
22+
return issuedId(contextId) && issuedId(executionId) ? { contextId, executionId } : null
23+
}
24+
1625
/**
17-
* The resume links a human-in-the-loop pause leaves in a run's output (`_resume`, or `resume`
18-
* beside the response): the record holding both the pause's `contextId` and the `executionId`
19-
* `runs resume` takes as its run.
26+
* The resume links of every pause in a run's output: `resume` beside a pause response, or
27+
* `_resume` inside its `data`; the response is the output itself (or its `response`) for one
28+
* pause, and each entry of `pausedBlocks` when several blocks pause together. Only those fixed
29+
* places are read, never data a block or an API response carries, and a link whose ids are not
30+
* in the format the server issues is skipped.
2031
*/
21-
function findResumeLinks(output: unknown): ResumeLinks | null {
22-
let visited = 0
23-
const search = (value: unknown, depth: number): ResumeLinks | null => {
24-
if (!isRecordLike(value) || depth > SEARCH_DEPTH || visited++ >= SEARCH_BUDGET) return null
25-
if (typeof value.contextId === 'string' && typeof value.executionId === 'string') {
26-
return { contextId: value.contextId, executionId: value.executionId }
32+
function findResumeLinks(output: unknown): ResumeLinks[] {
33+
if (!isRecordLike(output)) return []
34+
const found = new Map<string, ResumeLinks>()
35+
for (const root of [output, output.response]) {
36+
if (!isRecordLike(root)) continue
37+
const responses = Array.isArray(root.pausedBlocks) ? root.pausedBlocks : [root]
38+
for (const response of responses) {
39+
if (!isRecordLike(response)) continue
40+
const links = readLinks(response.resume) ?? readLinks(toRecordOrNull(response.data)?._resume)
41+
if (links) found.set(`${links.executionId}\n${links.contextId}`, links)
2742
}
28-
for (const child of Object.values(value)) {
29-
const found = search(child, depth + 1)
30-
if (found) return found
31-
}
32-
return null
3343
}
34-
return search(output, 0)
44+
return [...found.values()]
45+
}
46+
47+
const SAFE_ARGUMENT = /^[A-Za-z0-9_.:-]+$/
48+
49+
function shellArgument(value: string): string {
50+
return SAFE_ARGUMENT.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`
3551
}
3652

3753
/** The command that resumes a paused run, with the pause's context when it is known. */
38-
export function resumeCommand(runId: string, workflowId: string, contextId: string | null): string {
39-
const context = contextId ? ` --context ${contextId}` : ''
40-
return `sim workflows runs resume ${runId} --workflow ${workflowId}${context}`
54+
function resumeCommand(runId: string, workflowId: string, contextId: string | null): string {
55+
const context = contextId ? ` --context ${shellArgument(contextId)}` : ''
56+
return `sim workflows runs resume ${shellArgument(runId)} --workflow ${shellArgument(workflowId)}${context}`
57+
}
58+
59+
/**
60+
* The exact `runs resume` command for a paused run record, one line per waiting pause, since the
61+
* record carries two ids (`runId` and the output's `_resume.executionId`) and a context a reader
62+
* would otherwise have to pair up. `runs resume` takes the run the pause belongs to, which is the
63+
* links' `executionId`. A record whose output names no links falls back to its own ids and the
64+
* `paused.contextId`; null when an id is not in the format the server issues, so no untrusted
65+
* text reaches a printed command. `fallback` supplies the ids a record omits.
66+
*/
67+
export function resumeCommandFor(
68+
record: Record<string, unknown>,
69+
fallback: { runId: string; workflowId: string }
70+
): string | null {
71+
const runId = typeof record.runId === 'string' ? record.runId : fallback.runId
72+
const workflowId = typeof record.workflowId === 'string' ? record.workflowId : fallback.workflowId
73+
if (!issuedId(runId) || !issuedId(workflowId)) return null
74+
const links = findResumeLinks(record.output)
75+
if (links.length > 0) {
76+
return links
77+
.map((link) => resumeCommand(link.executionId, workflowId, link.contextId))
78+
.join('\n')
79+
}
80+
const contextId = toRecordOrNull(record.paused)?.contextId
81+
return resumeCommand(runId, workflowId, issuedId(contextId) ? contextId : null)
4182
}
4283

4384
/**
44-
* A run record with `next` added when it is paused for input: the exact `runs resume` command,
45-
* since the record carries two ids (`runId` and the output's `_resume.executionId`) and a context
46-
* a reader would otherwise have to pair up. `runs resume` takes the run the pause belongs to,
47-
* which is `_resume.executionId` when the output names one. Any other payload comes back as it
85+
* A run record with `next` added when it is paused for input. Any other payload comes back as it
4886
* was, and so does one that already has a `next`.
4987
*/
5088
export function withResumeNext(operation: V2OperationName, payload: unknown): unknown {
5189
if (!RUN_OPERATIONS.has(operation) || !isRecordLike(payload)) return payload
5290
if (payload.status !== 'paused' || 'next' in payload) return payload
5391
if (typeof payload.runId !== 'string' || typeof payload.workflowId !== 'string') return payload
54-
const links = findResumeLinks(payload.output)
55-
const paused = toRecordOrNull(payload.paused)
56-
const contextId =
57-
links?.contextId ?? (typeof paused?.contextId === 'string' ? paused.contextId : null)
58-
return {
59-
...payload,
60-
next: resumeCommand(links?.executionId ?? payload.runId, payload.workflowId, contextId),
61-
}
92+
const next = resumeCommandFor(payload, { runId: payload.runId, workflowId: payload.workflowId })
93+
return next ? { ...payload, next } : payload
6294
}

0 commit comments

Comments
 (0)