Skip to content

Commit dadf5a7

Browse files
committed
improvement(workflow-code): remove agent traps from table keys, Function results, resume ids and builder names
1 parent 05c8216 commit dadf5a7

23 files changed

Lines changed: 531 additions & 55 deletions

‎apps/docs/content/docs/workflows/code/syntax.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ A secret is never printed. A literal value in a password field prints as `stored
196196

197197
### JSON fields
198198

199-
A field that holds JSON text, such as `responseFormat`, a table row's `data` or a response body, takes an object or array literal and stores it as formatted JSON. Each bare reference inside is quoted when the output is a string and left bare otherwise, because the run splices a string raw and any other value as JSON. A field of a Function's `result` has the type its JavaScript certainly returns there (a string literal, `String(…)`, `.toISOString().slice(…)` and the like are text; arithmetic, comparisons and literals are not). A reference no output type is known for is stored bare with `W_JSON_REF_UNTYPED`. A template is a JSON string, which is how a value becomes text on purpose. A resource helper inside the literal is `E_UNSUPPORTED_SYNTAX`.
199+
A field that holds JSON text, such as `responseFormat`, a table row's `data` or a response body, takes an object or array literal and stores it as formatted JSON. Each bare reference inside is quoted when the output is a string and left bare otherwise, because the run splices a string raw and any other value as JSON. A Function's `result`, or a field of it, has the type its JavaScript certainly returns there (a string literal, `String(…)`, `.toISOString().slice(…)` and the like are text; arithmetic, comparisons and literals are not); a Function `result` or an API `data` whose code or response may be text is untyped unless the code says. A reference no output type is known for is stored bare with `W_JSON_REF_UNTYPED`. A template is a JSON string, which is how a value becomes text on purpose. A resource helper inside the literal is `E_UNSUPPORTED_SYNTAX`.
200200

201201
### Input formats and tools
202202

‎apps/sim/lib/workflows/application/apply-workflow-source.skills.integration.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,7 @@ check(
297297
const written = edit(
298298
edit(source.files, 'skills: []', "skills: [skill('listed-only')]"),
299299
'tools: []',
300-
"tools: [customTool('listed-lookup')]"
300+
"tools: [customTool('listed_lookup')]"
301301
)
302302
written['workflow.ts'] = written['workflow.ts'].replace(
303303
/^import \{ /m,
@@ -313,7 +313,7 @@ check(
313313
])
314314
expect(manifest.skills).toContainEqual({ key: 'listed-only', id: skillId, name: 'Listed only' })
315315
expect(manifest.customTools).toContainEqual({
316-
key: 'listed-lookup',
316+
key: 'listed_lookup',
317317
id: toolId,
318318
name: 'listed_lookup',
319319
})

‎apps/sim/lib/workflows/application/read-source-resources.integration.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ describe('source resources manifest', () => {
401401
{ key: 'tone', id: ids.laterSkill, name: 'Tone' },
402402
])
403403
expect(manifest.customTools).toEqual([
404-
{ key: 'lookup-order', id: ids.customTool, name: 'lookup_order' },
404+
{ key: 'lookup_order', id: ids.customTool, name: 'lookup_order' },
405405
])
406406
})
407407

‎apps/sim/lib/workspaces/resource-keys.integration.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,35 @@ describe('workspace resource keys against PostgreSQL', () => {
181181
expect(new Set(keys)).toEqual(new Set(['invoices', 'invoices-2', 'invoices-3']))
182182
})
183183

184+
it('keys a name with underscores by its own spelling, apart from the hyphenated one', async () => {
185+
const underscored = generateId()
186+
const hyphenated = generateId()
187+
await insertTable(underscored, workspaceId, 'daily_totals', at(40))
188+
await insertTable(hyphenated, workspaceId, 'daily-totals', at(41))
189+
190+
expect(await keyOf('table', hyphenated)).toBe('daily-totals')
191+
expect(await keyOf('table', underscored)).toBe('daily_totals')
192+
expect(await idOf('table', 'daily_totals')).toBe(underscored)
193+
})
194+
195+
it('suffixes an underscored name whose key is taken, and leaves a persisted hyphen key alone', async () => {
196+
const legacy = generateId()
197+
const first = generateId()
198+
const second = generateId()
199+
await insertTable(legacy, workspaceId, 'weekly-totals', at(42))
200+
expect(await keyOf('table', legacy)).toBe('weekly-totals')
201+
await db
202+
.update(userTableDefinitions)
203+
.set({ name: 'weekly_totals' })
204+
.where(eq(userTableDefinitions.id, legacy))
205+
await insertTable(first, workspaceId, 'monthly_totals', at(43))
206+
await insertTable(second, workspaceId, 'Monthly_Totals!', at(44))
207+
208+
expect(await keyOf('table', legacy)).toBe('weekly-totals')
209+
expect(await keyOf('table', first)).toBe('monthly_totals')
210+
expect(await keyOf('table', second)).toBe('monthly_totals-2')
211+
})
212+
184213
it('keeps every kind’s key through a rename', async () => {
185214
const ids = {
186215
table: generateId(),

‎apps/sim/lib/workspaces/resource-keys.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,12 @@ describe('resourceKeyBase', () => {
88
expect(resourceKeyBase('table', 'Leads (EU)!')).toBe('leads-eu')
99
})
1010

11+
it('keeps the underscores of a name, the spelling its author types', () => {
12+
expect(resourceKeyBase('table', 'daily_totals')).toBe('daily_totals')
13+
expect(resourceKeyBase('table', 'Daily_Totals (v2)')).toBe('daily_totals-v2')
14+
expect(resourceKeyBase('table', '_scratch_')).toBe('scratch')
15+
})
16+
1117
it('keys a name with no slug characters by its kind', () => {
1218
expect(resourceKeyBase('knowledge-base', '***')).toBe('knowledge-base')
1319
expect(resourceKeyBase('credential', '')).toBe('credential')

‎apps/sim/lib/workspaces/resource-keys.ts‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
} from '@sim/db/schema'
1414
import { createLogger } from '@sim/logger'
1515
import { generateId } from '@sim/utils/id'
16-
import { compareStrings, slugify } from '@sim/utils/string'
16+
import { compareStrings, escapeLikePattern } from '@sim/utils/string'
1717
import type { ResourceKind } from '@sim/workflow-code'
1818
import { and, asc, eq, inArray, isNull, like, or } from 'drizzle-orm'
1919
import { OrchestrationError } from '@/lib/core/orchestration/types'
@@ -203,12 +203,24 @@ function trimKey(value: string, maxLength: number): string {
203203
}
204204

205205
/**
206-
* The key a resource is first offered: its name's slug, or the kind when the name has no slug
207-
* characters; prefixed with the kind when the slug starts with a digit, and cut to the key
208-
* length. Always matches the stored key format `^[a-z][a-z0-9_-]{0,63}$`.
206+
* A name's key characters: lowercased, with every run of other characters one hyphen and no
207+
* leading or trailing separator. Underscores stay, so a table named `daily_totals` is keyed
208+
* `daily_totals`, the spelling its author will type.
209+
*/
210+
function keySlug(name: string): string {
211+
return name
212+
.toLowerCase()
213+
.replace(/[^a-z0-9_]+/g, '-')
214+
.replace(/^[-_]+|[-_]+$/g, '')
215+
}
216+
217+
/**
218+
* The key a resource is first offered: its name's slug (underscores kept), or the kind when the
219+
* name has no slug characters; prefixed with the kind when the slug starts with a digit, and cut
220+
* to the key length. Always matches the stored key format `^[a-z][a-z0-9_-]{0,63}$`.
209221
*/
210222
export function resourceKeyBase(kind: ResourceKind, name: string): string {
211-
const slug = slugify(name)
223+
const slug = keySlug(name)
212224
const base = slug === '' ? kind : /^[a-z]/.test(slug) ? slug : `${kind}-${slug}`
213225
return trimKey(base, MAX_KEY_LENGTH)
214226
}
@@ -309,7 +321,11 @@ async function readTakenKeys(
309321
and(
310322
eq(workspaceResourceKey.workspaceId, workspaceId),
311323
eq(workspaceResourceKey.kind, kind),
312-
or(...prefixes.map((prefix) => like(workspaceResourceKey.key, `${prefix}%`)))
324+
or(
325+
...prefixes.map((prefix) =>
326+
like(workspaceResourceKey.key, `${escapeLikePattern(prefix)}%`)
327+
)
328+
)
313329
)
314330
)
315331
return new Set(rows.map((row) => row.key))

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,23 @@ describe('sim workflows runs get --select-output', () => {
112112
expect(request.mock.calls.map(([path]) => path)).toEqual([STATE_PATH])
113113
})
114114
})
115+
116+
describe('sim workflows runs get on a paused run', () => {
117+
it('prints the exact resume command beside the run, additively', async () => {
118+
const run = {
119+
runId: RUN_ID,
120+
workflowId: WORKFLOW_ID,
121+
status: 'paused',
122+
paused: { contextId: 'ctx_1', pauseKind: 'human' },
123+
}
124+
answer({ data: run })
125+
const out = stdout()
126+
127+
await get()
128+
129+
expect(JSON.parse(out())).toEqual({
130+
...run,
131+
next: `sim workflows runs resume ${RUN_ID} --workflow ${WORKFLOW_ID} --context ctx_1`,
132+
})
133+
})
134+
})

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +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'
1314
import { renderResult } from '../../runtime/result'
1415

1516
/**
@@ -197,8 +198,7 @@ function explain(
197198
if (outcome === 'completed') return null
198199
if (outcome === 'failed') return `Run ${runId} failed.`
199200
if (outcome === 'cancelled') return `Run ${runId} was cancelled.`
200-
const context = snapshot.contextId ? ` --context ${snapshot.contextId}` : ''
201-
return `Run ${runId} is paused waiting for input. Resume it: sim workflows runs resume ${runId} --workflow ${workflowId}${context}`
201+
return `Run ${runId} is paused waiting for input. Resume it: ${resumeCommand(runId, workflowId, snapshot.contextId)}`
202202
}
203203

204204
/**

‎packages/sim-cli/src/contract/commands.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2459,6 +2459,7 @@ To read what a block is set to, use \`sim workflows outline\` or \`sim workflows
24592459
{ header: 'resume at', path: 'paused.resumeAt', format: 'timestamp' },
24602460
{ header: 'blocked on', path: 'paused.blockedOnBlockId' },
24612461
{ header: 'pause points', path: 'paused.pausePointCount' },
2462+
{ header: 'next', path: 'next' },
24622463
{ header: 'error', path: 'error.message' },
24632464
],
24642465
},
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { withResumeNext } from './paused-run'
3+
4+
const paused = {
5+
runId: 'run_top',
6+
workflowId: 'wf_1',
7+
status: 'paused',
8+
output: { response: { data: { _resume: { contextId: 'ctx_9', executionId: 'exec_9' } } } },
9+
}
10+
11+
describe('withResumeNext', () => {
12+
it('names the exact resume command, with the pause context and the execution its links name', () => {
13+
expect(withResumeNext('executeWorkflow', paused)).toEqual({
14+
...paused,
15+
next: 'sim workflows runs resume exec_9 --workflow wf_1 --context ctx_9',
16+
})
17+
})
18+
19+
it('falls back to the run id, and to the paused record context, when the output names none', () => {
20+
expect(withResumeNext('executeWorkflow', { ...paused, output: null })).toMatchObject({
21+
next: 'sim workflows runs resume run_top --workflow wf_1',
22+
})
23+
expect(
24+
withResumeNext('getWorkflowRun', { ...paused, output: undefined, paused: { contextId: 'c' } })
25+
).toMatchObject({ next: 'sim workflows runs resume run_top --workflow wf_1 --context c' })
26+
})
27+
28+
it('leaves a run that is not paused, another operation and an existing next as they were', () => {
29+
const done = { ...paused, status: 'completed' }
30+
expect(withResumeNext('executeWorkflow', done)).toBe(done)
31+
expect(withResumeNext('listWorkflowRuns', paused)).toBe(paused)
32+
const hinted = { ...paused, next: 'x' }
33+
expect(withResumeNext('executeWorkflow', hinted)).toBe(hinted)
34+
expect(withResumeNext('executeWorkflow', null)).toBeNull()
35+
})
36+
})

0 commit comments

Comments
 (0)