Skip to content

Commit 796c04a

Browse files
authored
fix(integrations): keep saved output references valid and encode firecrawl job ids (#10187)
* fix(integrations): keep saved output references valid and encode firecrawl job ids * fix(integrations): fail a firecrawl crawl or batch scrape that returned no job id * fix(integrations): keep open out of the public catalog and strip url control characters like the parser * fix(integrations): strip url control characters only where the id was sent raw
1 parent 99a6c76 commit 796c04a

31 files changed

Lines changed: 290 additions & 39 deletions

‎apps/docs/content/docs/integrations/kalshi.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -792,6 +792,7 @@ Cancel an existing order on Kalshi
792792
| --------- | ---- | -------- | ----------- |
793793
| `orderId` | string | Yes | Order ID to cancel \(e.g., "abc123-def456-ghi789"\) |
794794
| `ticker` | string | No | Market ticker of the order \(e.g., "KXBTC-24DEC31"\), so the cancel reaches the order's exchange shard. Leave empty to look it up from the order first |
795+
| `subaccount` | string | No | Subaccount the order belongs to \(0 for primary, 1-63 for numbered subaccounts\). Leave empty for the primary account |
795796

796797
#### Output
797798

@@ -858,6 +859,7 @@ Modify the price or quantity of an existing order on Kalshi
858859
| `yesPriceDollars` | string | No | Updated yes price in dollars \(e.g., "0.56"\) |
859860
| `noPriceDollars` | string | No | Updated no price in dollars \(e.g., "0.56"\) |
860861
| `countFp` | string | No | Count in fixed-point for fractional contracts |
862+
| `subaccount` | string | No | Subaccount the order belongs to \(0 for primary, 1-63 for numbered subaccounts\). Leave empty for the primary account |
861863

862864
#### Output
863865

‎apps/sim/lib/catalog/projection/tool.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { HostedApiKeySupport } from '@/tools/hosted-api-key'
33
import { getToolMetadata, type ToolMetadata } from '@/tools/metadata'
44
import { getToolOutputsMetadata } from '@/tools/metadata-outputs'
55
import { resolveToolId } from '@/tools/tool-ids'
6-
import type { ToolConfig } from '@/tools/types'
6+
import type { OutputProperty, ToolConfig } from '@/tools/types'
77

88
/**
99
* Surface-neutral projection of a built-in tool.
@@ -141,11 +141,27 @@ export function projectToolOutputs(
141141
const projected: Record<string, CatalogToolOutput> = {}
142142
for (const [id, output] of Object.entries(outputs ?? {})) {
143143
if (!output || isHiddenFromDisplay(output)) continue
144-
projected[id] = output as CatalogToolOutput
144+
projected[id] = publicOutput(output)
145145
}
146146
return projected
147147
}
148148

149+
/** A declared output in its public shape, without the internal `open` marker at any depth. */
150+
function publicOutput(output: OutputProperty): CatalogToolOutput {
151+
const { open, properties, items, ...rest } = output
152+
const projected: CatalogToolOutput = { ...rest }
153+
if (properties) projected.properties = publicOutputs(properties)
154+
if (items) {
155+
const { open: itemOpen, properties: itemProperties, ...item } = items
156+
projected.items = itemProperties ? { ...item, properties: publicOutputs(itemProperties) } : item
157+
}
158+
return projected
159+
}
160+
161+
function publicOutputs(outputs: Record<string, OutputProperty>): Record<string, CatalogToolOutput> {
162+
return Object.fromEntries(Object.entries(outputs).map(([id, node]) => [id, publicOutput(node)]))
163+
}
164+
149165
/**
150166
* Projects a tool to its full catalog entry, or `undefined` when no such tool
151167
* exists.

‎apps/sim/tools/arxiv/get_paper.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ function arxivPaperId(input: string): string {
1414
const linkPath = arxivLinkPath(
1515
SCHEMELESS_ARXIV_LINK.test(trimmed) ? `https://${trimmed}` : trimmed
1616
)
17-
const id = linkPath ?? trimmed.replace(/[?#].*$/, '')
17+
const id = linkPath ?? trimmed.split(/[?#]/, 1)[0]
1818
return id.replace(/\.pdf$/, '')
1919
}
2020

‎apps/sim/tools/firecrawl/agent.ts‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,10 @@ export const agentTool: ToolConfig<AgentParams, AgentResponse> = {
9898
transformResponse: async (response: Response) => {
9999
const data = await response.json()
100100

101+
if (!data.id) {
102+
throw new Error(data.error || 'Firecrawl did not return an agent job id to poll')
103+
}
104+
101105
return {
102106
success: true,
103107
output: {
@@ -123,14 +127,17 @@ export const agentTool: ToolConfig<AgentParams, AgentResponse> = {
123127
while (elapsedTime < MAX_POLL_TIME_MS) {
124128
try {
125129
signal?.throwIfAborted()
126-
const statusResponse = await outboundFetch(`https://api.firecrawl.dev/v2/agent/${jobId}`, {
127-
method: 'GET',
128-
headers: {
129-
Authorization: `Bearer ${params.apiKey}`,
130-
'Content-Type': 'application/json',
131-
},
132-
signal,
133-
})
130+
const statusResponse = await outboundFetch(
131+
`https://api.firecrawl.dev/v2/agent/${encodeURIComponent(jobId)}`,
132+
{
133+
method: 'GET',
134+
headers: {
135+
Authorization: `Bearer ${params.apiKey}`,
136+
'Content-Type': 'application/json',
137+
},
138+
signal,
139+
}
140+
)
134141

135142
if (!statusResponse.ok) {
136143
throw new Error(`Failed to get agent status: ${statusResponse.statusText}`)

‎apps/sim/tools/firecrawl/batch-scrape.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,13 @@ export const batchScrapeTool: ToolConfig<FirecrawlBatchScrapeParams, FirecrawlBa
192192
}
193193

194194
const jobId = result.output.jobId
195+
if (!jobId) {
196+
return {
197+
...result,
198+
success: false,
199+
error: 'Firecrawl did not return a batch scrape job ID to poll',
200+
}
201+
}
195202
const signal = context?.signal
196203
const invalidURLs = result.output.invalidURLs ?? []
197204
logger.info(`Firecrawl batch scrape job ${jobId} created, polling for completion...`)
@@ -202,7 +209,7 @@ export const batchScrapeTool: ToolConfig<FirecrawlBatchScrapeParams, FirecrawlBa
202209
try {
203210
signal?.throwIfAborted()
204211
const statusResponse = await outboundFetch(
205-
`https://api.firecrawl.dev/v2/batch/scrape/${jobId}`,
212+
`https://api.firecrawl.dev/v2/batch/scrape/${encodeURIComponent(jobId)}`,
206213
{
207214
method: 'GET',
208215
headers: {

‎apps/sim/tools/firecrawl/crawl.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,9 @@ export const crawlTool: ToolConfig<FirecrawlCrawlParams, FirecrawlCrawlResponse>
240240
}
241241

242242
const jobId = result.output.jobId
243+
if (!jobId) {
244+
return { ...result, success: false, error: 'Firecrawl did not return a crawl job ID to poll' }
245+
}
243246
const signal = context?.signal
244247
logger.info(`Firecrawl crawl job ${jobId} created, polling for completion...`)
245248

@@ -248,14 +251,17 @@ export const crawlTool: ToolConfig<FirecrawlCrawlParams, FirecrawlCrawlResponse>
248251
while (elapsedTime < MAX_POLL_TIME_MS) {
249252
try {
250253
signal?.throwIfAborted()
251-
const statusResponse = await outboundFetch(`https://api.firecrawl.dev/v2/crawl/${jobId}`, {
252-
method: 'GET',
253-
headers: {
254-
Authorization: `Bearer ${params.apiKey}`,
255-
'Content-Type': 'application/json',
256-
},
257-
signal,
258-
})
254+
const statusResponse = await outboundFetch(
255+
`https://api.firecrawl.dev/v2/crawl/${encodeURIComponent(jobId)}`,
256+
{
257+
method: 'GET',
258+
headers: {
259+
Authorization: `Bearer ${params.apiKey}`,
260+
'Content-Type': 'application/json',
261+
},
262+
signal,
263+
}
264+
)
259265

260266
if (!statusResponse.ok) {
261267
throw new Error(`Failed to get crawl status: ${statusResponse.statusText}`)

‎apps/sim/tools/firecrawl/extract.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,10 @@ export const extractTool: ToolConfig<ExtractParams, ExtractResponse> = {
153153
transformResponse: async (response: Response) => {
154154
const data = await response.json()
155155

156+
if (!data.id) {
157+
throw new Error(data.error || 'Firecrawl did not return an extract job id to poll')
158+
}
159+
156160
return {
157161
success: true,
158162
output: {
@@ -177,7 +181,7 @@ export const extractTool: ToolConfig<ExtractParams, ExtractResponse> = {
177181
try {
178182
signal?.throwIfAborted()
179183
const statusResponse = await outboundFetch(
180-
`https://api.firecrawl.dev/v2/extract/${jobId}`,
184+
`https://api.firecrawl.dev/v2/extract/${encodeURIComponent(jobId)}`,
181185
{
182186
method: 'GET',
183187
headers: {

‎apps/sim/tools/firecrawl/job-polling.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { jsonResponse } from '@sim/testing'
22
import { beforeEach, describe, expect, it, vi } from 'vitest'
3+
import { agentTool } from '@/tools/firecrawl/agent'
34
import { crawlTool } from '@/tools/firecrawl/crawl'
5+
import { extractTool } from '@/tools/firecrawl/extract'
46
import type { FirecrawlCrawlResponse } from '@/tools/firecrawl/types'
57

68
const fetchMock = vi.fn()
@@ -51,4 +53,33 @@ describe('Firecrawl crawl polling', () => {
5153
expect.objectContaining({ method: 'DELETE' })
5254
)
5355
})
56+
57+
it('fails at once instead of polling when Firecrawl returned no job ID', async () => {
58+
if (!crawlTool.postProcess) throw new Error('crawlTool has no postProcess')
59+
const result = await crawlTool.postProcess(
60+
{ success: true, output: { pages: [], total: 0 } },
61+
params,
62+
executeTool
63+
)
64+
65+
expect(result).toMatchObject({ success: false, error: expect.stringMatching(/job ID/) })
66+
expect(fetchMock).not.toHaveBeenCalled()
67+
})
68+
})
69+
70+
describe('Firecrawl agent and extract job start', () => {
71+
it.each([
72+
['agent', agentTool],
73+
['extract', extractTool],
74+
] as const)(
75+
'%s refuses a start response with no job id instead of polling it',
76+
async (_, tool) => {
77+
await expect(tool.transformResponse?.(jsonResponse({ success: true }))).rejects.toThrow(
78+
/did not return an? \w+ job id/
79+
)
80+
await expect(
81+
tool.transformResponse?.(jsonResponse({ success: false, error: 'Invalid schema' }))
82+
).rejects.toThrow('Invalid schema')
83+
}
84+
)
5485
})

‎apps/sim/tools/generated/tool-metadata.ts‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎apps/sim/tools/generated/tool-outputs.ts‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)