openapi.test.ts 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  1. import { describe, expect, test } from "bun:test"
  2. import { Effect, Layer, Option } from "effect"
  3. import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
  4. import { CodeMode, OpenAPI, Tool } from "../src/index.js"
  5. import { inputTypeScript, outputTypeScript } from "../src/tool-schema.js"
  6. const baseUrl = "http://localhost:4096"
  7. type Document = OpenAPI.Document
  8. type Recorded = {
  9. readonly method: string
  10. readonly url: string
  11. readonly headers: Record<string, string>
  12. readonly body: unknown
  13. }
  14. const opencodeSpec = async (): Promise<Document> => {
  15. return Bun.file(new URL("./fixtures/opencode-v2-openapi.json", import.meta.url)).json() as Promise<Document>
  16. }
  17. const happyPathSpec = async (): Promise<Document> => {
  18. return Bun.file(new URL("./fixtures/openapi-happy-path.json", import.meta.url)).json() as Promise<Document>
  19. }
  20. const isRecord = (value: unknown): value is Record<string, unknown> =>
  21. typeof value === "object" && value !== null && !Array.isArray(value)
  22. const toolAt = (tools: unknown, name: string) =>
  23. name.split(".").reduce<unknown>((current, segment) => (isRecord(current) ? current[segment] : undefined), tools)
  24. const recordingClient = (respond: (request: HttpClientRequest.HttpClientRequest) => Response) => {
  25. const requests: Array<Recorded> = []
  26. const layer = Layer.succeed(HttpClient.HttpClient)(
  27. HttpClient.make((request) =>
  28. Effect.gen(function* () {
  29. const body =
  30. request.body._tag === "Uint8Array" ? JSON.parse(new TextDecoder().decode(request.body.body)) : undefined
  31. const url = Option.map(HttpClientRequest.toUrl(request), (resolved) => resolved.toString())
  32. requests.push({
  33. method: request.method,
  34. url: Option.getOrElse(url, () => request.url),
  35. headers: { ...request.headers },
  36. body,
  37. })
  38. return HttpClientResponse.fromWeb(request, respond(request))
  39. }),
  40. ),
  41. )
  42. return { requests, layer }
  43. }
  44. const json = (value: unknown, status = 200) =>
  45. new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json" } })
  46. const singleOperation = (operation: Record<string, unknown>, method = "get"): Document => ({
  47. openapi: "3.1.0",
  48. paths: {
  49. "/test": { [method]: { operationId: "test", responses: { 200: { description: "Success" } }, ...operation } },
  50. },
  51. })
  52. const directionalSpec = (openapi: string): Document => ({
  53. openapi,
  54. paths: {
  55. "/users": {
  56. post: {
  57. operationId: "users.create",
  58. requestBody: {
  59. required: true,
  60. content: { "application/json": { schema: { $ref: "#/components/schemas/User" } } },
  61. },
  62. responses: {
  63. 200: {
  64. description: "Created",
  65. content: { "application/json": { schema: { $ref: "#/components/schemas/User" } } },
  66. },
  67. },
  68. },
  69. },
  70. },
  71. components: {
  72. schemas: {
  73. ReadOnlyID: { type: "string", readOnly: true },
  74. User: {
  75. type: "object",
  76. additionalProperties: false,
  77. required: ["id", "name", "password", "profile", "generated"],
  78. properties: {
  79. id: { type: "string", readOnly: true },
  80. name: { type: "string" },
  81. password: { type: "string", writeOnly: true },
  82. profile: {
  83. type: "object",
  84. additionalProperties: false,
  85. required: ["createdAt", "secret", "label"],
  86. properties: {
  87. createdAt: { type: "string", readOnly: true },
  88. secret: { type: "string", writeOnly: true },
  89. label: { type: "string" },
  90. },
  91. },
  92. generated: { $ref: "#/components/schemas/ReadOnlyID" },
  93. },
  94. },
  95. },
  96. },
  97. })
  98. describe("OpenAPI.fromSpec", () => {
  99. test("covers a representative API from generation through execution", async () => {
  100. const resolutions: Array<string> = []
  101. const client = recordingClient((request) => {
  102. const url = Option.getOrElse(HttpClientRequest.toUrl(request), () => new URL(request.url))
  103. if (request.method === "POST") {
  104. return new Response(
  105. JSON.stringify({ id: "user-2", name: "Grace", email: "grace@example.test", role: "admin" }),
  106. { status: 201, headers: { "content-type": "application/vnd.example+json" } },
  107. )
  108. }
  109. if (request.method === "DELETE") return new Response(null, { status: 204 })
  110. if (url.pathname === "/search") {
  111. return new Response("2 matches", { headers: { "content-type": "text/plain" } })
  112. }
  113. return json({ id: "user-1", name: "Ada", email: "ada@example.test", role: "member" })
  114. })
  115. const api = OpenAPI.fromSpec({
  116. spec: await happyPathSpec(),
  117. baseUrl,
  118. auth: {
  119. resolve: ({ name }) => {
  120. resolutions.push(name)
  121. return Effect.succeed(
  122. name === "BearerAuth"
  123. ? { type: "bearer", token: "bearer-secret" }
  124. : { type: "apiKey", value: "api-secret" },
  125. )
  126. },
  127. },
  128. })
  129. const get = toolAt(api.tools, "users.get")
  130. const create = toolAt(api.tools, "users.create")
  131. const search = toolAt(api.tools, "search.run")
  132. const remove = toolAt(api.tools, "users.remove")
  133. expect(api.skipped).toEqual([])
  134. if (!Tool.isTool(get) || !Tool.isTool(create) || !Tool.isTool(search) || !Tool.isTool(remove)) {
  135. throw new Error("happy-path fixture did not generate every operation")
  136. }
  137. expect(inputTypeScript(get)).toBe(
  138. '{ userId: string; include?: Array<string>; verbose?: boolean; "X-Trace-ID"?: string }',
  139. )
  140. expect(inputTypeScript(create)).toBe('{ name: string; email: string; role?: "admin" | "member" }')
  141. expect(inputTypeScript(search)).toBe("{ filter?: { query: string; page?: number }; tags?: Array<string> }")
  142. expect(inputTypeScript(remove)).toBe("{ userId: string }")
  143. expect(outputTypeScript(get)).toContain("id: string")
  144. expect(outputTypeScript(create)).toContain('role?: "admin" | "member"')
  145. expect(outputTypeScript(search)).toBe("string")
  146. expect(outputTypeScript(remove)).toBe("null")
  147. const result = await Effect.runPromise(
  148. CodeMode.make({ tools: { api: api.tools } })
  149. .execute(
  150. `
  151. const user = await tools.api.users.get({
  152. userId: "user-1",
  153. include: ["profile", "permissions"],
  154. verbose: true,
  155. "X-Trace-ID": "trace-1",
  156. })
  157. const created = await tools.api.users.create({
  158. name: "Grace",
  159. email: "grace@example.test",
  160. role: "admin",
  161. })
  162. const summary = await tools.api.search.run({
  163. filter: { query: "effect", page: 2 },
  164. tags: ["typescript", "runtime"],
  165. })
  166. const removed = await tools.api.users.remove({ userId: "user-1" })
  167. return { user, created, summary, removed }
  168. `,
  169. )
  170. .pipe(Effect.provide(client.layer)),
  171. )
  172. expect(result).toMatchObject({
  173. ok: true,
  174. value: {
  175. user: { id: "user-1", name: "Ada" },
  176. created: { id: "user-2", name: "Grace" },
  177. summary: "2 matches",
  178. removed: null,
  179. },
  180. })
  181. expect(resolutions).toEqual(["BearerAuth", "ApiKey", "BearerAuth"])
  182. expect(client.requests).toHaveLength(4)
  183. const getUrl = new URL(client.requests[0]!.url)
  184. expect(getUrl.pathname).toBe("/users/user-1")
  185. expect(getUrl.searchParams.get("include")).toBe("profile,permissions")
  186. expect(getUrl.searchParams.get("verbose")).toBe("true")
  187. expect(client.requests[0]!.headers["x-trace-id"]).toBe("trace-1")
  188. expect(client.requests[0]!.headers.authorization).toBe("Bearer bearer-secret")
  189. const createUrl = new URL(client.requests[1]!.url)
  190. expect(createUrl.searchParams.get("api_key")).toBe("api-secret")
  191. expect(client.requests[1]!.body).toEqual({ name: "Grace", email: "grace@example.test", role: "admin" })
  192. const searchUrl = new URL(client.requests[2]!.url)
  193. expect(searchUrl.searchParams.get("filter[query]")).toBe("effect")
  194. expect(searchUrl.searchParams.get("filter[page]")).toBe("2")
  195. expect(searchUrl.searchParams.getAll("tags")).toEqual(["typescript", "runtime"])
  196. expect(client.requests[2]!.headers.authorization).toBeUndefined()
  197. expect(new URL(client.requests[3]!.url).pathname).toBe("/users/user-1")
  198. expect(client.requests[3]!.headers.authorization).toBe("Bearer bearer-secret")
  199. })
  200. test("converts representative opencode operations into the expected tool shape", async () => {
  201. const spec = await opencodeSpec()
  202. const result = OpenAPI.fromSpec({ spec, baseUrl })
  203. expect(result.skipped).toHaveLength(4)
  204. expect(result.skipped).toContainEqual({
  205. method: "GET",
  206. path: "/api/pty/{ptyID}/connect",
  207. reason: "WebSocket operations are not supported",
  208. })
  209. expect(result.skipped.filter((item) => item.reason === "SSE operations are not supported")).toHaveLength(2)
  210. expect(result.skipped).toContainEqual({
  211. method: "GET",
  212. path: "/api/fs/read/*",
  213. reason: "binary responses are not supported",
  214. })
  215. expect(toolAt(result.tools, "v2.health.get")).not.toBeUndefined()
  216. expect(toolAt(result.tools, "v2.session.get")).not.toBeUndefined()
  217. expect(toolAt(result.tools, "v2.session.create")).not.toBeUndefined()
  218. const sessionGet = toolAt(result.tools, "v2.session.get")
  219. expect(Tool.isTool(sessionGet)).toBe(true)
  220. if (!Tool.isTool(sessionGet)) throw new Error("v2.session.get was not generated")
  221. expect(inputTypeScript(sessionGet)).toBe("{ sessionID: string }")
  222. expect(outputTypeScript(sessionGet)).toContain("id: string")
  223. expect(outputTypeScript(sessionGet)).toContain("additions: number")
  224. const switchAgent = toolAt(result.tools, "v2.session.switchAgent")
  225. expect(Tool.isTool(switchAgent)).toBe(true)
  226. if (!Tool.isTool(switchAgent)) throw new Error("v2.session.switchAgent was not generated")
  227. expect(inputTypeScript(switchAgent)).toBe("{ sessionID: string; agent: string }")
  228. const instructionPut = toolAt(result.tools, "v2.session.instructions.entry.put")
  229. expect(Tool.isTool(instructionPut)).toBe(true)
  230. if (!Tool.isTool(instructionPut)) throw new Error("v2.session.instructions.entry.put was not generated")
  231. expect(inputTypeScript(instructionPut)).toBe("{ sessionID: string; key: string; value: unknown }")
  232. expect(toolAt(result.tools, "v2_session_instructions_entry_put_2")).toBeUndefined()
  233. expect(Tool.isTool(toolAt(result.tools, "v2.pty.connect"))).toBe(false)
  234. expect(toolAt(result.tools, "v2.session.log")).toBeUndefined()
  235. expect(toolAt(result.tools, "v2.event.subscribe")).toBeUndefined()
  236. expect(toolAt(result.tools, "v2.fs.read")).toBeUndefined()
  237. expect(toolAt(result.tools, "v2.pty.connect.token")).not.toBeUndefined()
  238. })
  239. test("preserves operation path sanitization and collision handling", () => {
  240. const response = { responses: { 200: { description: "Success" } } }
  241. const result = OpenAPI.fromSpec({
  242. baseUrl,
  243. spec: {
  244. openapi: "3.1.0",
  245. paths: {
  246. "/first": { get: { ...response, operationId: "group.item" } },
  247. "/second": { get: { ...response, operationId: "group.item" } },
  248. "/third": { get: { ...response, operationId: "group..other" } },
  249. },
  250. },
  251. })
  252. expect(Tool.isTool(toolAt(result.tools, "group.item"))).toBe(true)
  253. expect(Tool.isTool(toolAt(result.tools, "group_item_2"))).toBe(true)
  254. expect(Tool.isTool(toolAt(result.tools, "group.operation.other"))).toBe(true)
  255. })
  256. test("synthesizes flat operation IDs from methods and paths", () => {
  257. const response = { responses: { 200: { description: "Success" } } }
  258. const tools = OpenAPI.fromSpec({
  259. baseUrl,
  260. spec: {
  261. openapi: "3.1.0",
  262. paths: {
  263. "/users": { get: response, post: response },
  264. "/users/{id}": { get: response, patch: response, delete: response },
  265. "/organizations/{organizationId}/users/{id}": { get: response },
  266. },
  267. },
  268. }).tools
  269. for (const path of [
  270. "getUsers",
  271. "postUsers",
  272. "getUsersById",
  273. "patchUsersById",
  274. "deleteUsersById",
  275. "getOrganizationsByOrganizationidUsersById",
  276. ]) {
  277. expect(Tool.isTool(toolAt(tools, path))).toBe(true)
  278. }
  279. })
  280. test("lets operation parameters override matching path parameters", () => {
  281. const tool = toolAt(
  282. OpenAPI.fromSpec({
  283. baseUrl,
  284. spec: {
  285. openapi: "3.1.0",
  286. paths: {
  287. "/test": {
  288. parameters: [{ name: "limit", in: "query", schema: { type: "string" } }],
  289. get: {
  290. operationId: "test",
  291. parameters: [{ name: "limit", in: "query", required: true, schema: { type: "number" } }],
  292. responses: { 200: { description: "Success" } },
  293. },
  294. },
  295. },
  296. },
  297. }).tools,
  298. "test",
  299. )
  300. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  301. expect(inputTypeScript(tool)).toBe("{ limit: number }")
  302. })
  303. test("normalizes OpenAPI 3.0 schemas with Effect", () => {
  304. const result = OpenAPI.fromSpec({
  305. baseUrl,
  306. spec: {
  307. openapi: "3.0.3",
  308. paths: {
  309. "/search": {
  310. get: {
  311. operationId: "search",
  312. parameters: [
  313. {
  314. in: "query",
  315. name: "value",
  316. schema: { type: "string", nullable: true, minLength: 2 },
  317. },
  318. ],
  319. responses: { 200: { description: "Success" } },
  320. },
  321. },
  322. },
  323. },
  324. })
  325. const search = toolAt(result.tools, "search")
  326. expect(Tool.isTool(search)).toBe(true)
  327. if (!Tool.isTool(search)) throw new Error("search was not generated")
  328. expect(inputTypeScript(search)).toBe("{ value?: string | null }")
  329. const schema: unknown = search.input
  330. const input = isRecord(schema) ? schema : {}
  331. const properties = isRecord(input.properties) ? input.properties : {}
  332. const value = isRecord(properties.value) ? properties.value : {}
  333. expect(value.minLength).toBe(2)
  334. })
  335. test("preserves schema-local definitions alongside component definitions", () => {
  336. const tool = toolAt(
  337. OpenAPI.fromSpec({
  338. baseUrl,
  339. spec: {
  340. openapi: "3.1.0",
  341. paths: {
  342. "/test": {
  343. get: {
  344. operationId: "test",
  345. responses: {
  346. 200: {
  347. description: "Success",
  348. content: {
  349. "application/json": {
  350. schema: { $ref: "#/$defs/Local", $defs: { Local: { type: "string" } } },
  351. },
  352. },
  353. },
  354. },
  355. },
  356. },
  357. },
  358. components: { schemas: { Global: { type: "number" } } },
  359. },
  360. }).tools,
  361. "test",
  362. )
  363. if (!Tool.isTool(tool) || !isRecord(tool.output)) throw new Error("test output was not generated")
  364. expect(tool.output.$defs).toMatchObject({ Local: { type: "string" }, Global: { type: "number" } })
  365. })
  366. test("projects read-only and write-only properties by schema direction", () => {
  367. for (const version of ["3.0.3", "3.1.0"]) {
  368. const tool = toolAt(OpenAPI.fromSpec({ baseUrl, spec: directionalSpec(version) }).tools, "users.create")
  369. if (!Tool.isTool(tool) || !isRecord(tool.input) || !isRecord(tool.output)) {
  370. throw new Error(`users.create was not generated for OpenAPI ${version}`)
  371. }
  372. expect(inputTypeScript(tool)).toBe(
  373. "{ name: string; password: string; profile: { secret: string; label: string } }",
  374. )
  375. expect(outputTypeScript(tool)).toBe(
  376. "{ id: string; name: string; profile: { createdAt: string; label: string }; generated: string }",
  377. )
  378. const requestDefinitions = isRecord(tool.input.$defs) ? tool.input.$defs : {}
  379. const responseDefinitions = isRecord(tool.output.$defs) ? tool.output.$defs : {}
  380. const requestUser = isRecord(requestDefinitions.User) ? requestDefinitions.User : {}
  381. const responseUser = isRecord(responseDefinitions.User) ? responseDefinitions.User : {}
  382. expect(Object.keys(isRecord(requestUser.properties) ? requestUser.properties : {})).toEqual([
  383. "name",
  384. "password",
  385. "profile",
  386. ])
  387. expect(requestUser.required).toEqual(["name", "password", "profile"])
  388. expect(Object.keys(isRecord(responseUser.properties) ? responseUser.properties : {})).toEqual([
  389. "id",
  390. "name",
  391. "profile",
  392. "generated",
  393. ])
  394. expect(responseUser.required).toEqual(["id", "name", "profile", "generated"])
  395. }
  396. })
  397. test("projects directional annotations through local refs and allOf composition", () => {
  398. const tool = toolAt(
  399. OpenAPI.fromSpec({
  400. baseUrl,
  401. spec: singleOperation(
  402. {
  403. requestBody: {
  404. required: true,
  405. content: {
  406. "application/json": {
  407. schema: {
  408. type: "object",
  409. additionalProperties: false,
  410. required: ["local", "composed", "name"],
  411. properties: {
  412. local: { $ref: "#/$defs/ReadOnlyValue" },
  413. composed: { allOf: [{ $ref: "#/$defs/ReadOnlyValue" }] },
  414. name: { type: "string" },
  415. },
  416. $defs: {
  417. ReadOnlyValue: { type: "string", readOnly: true },
  418. },
  419. },
  420. },
  421. },
  422. },
  423. },
  424. "post",
  425. ),
  426. }).tools,
  427. "test",
  428. )
  429. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  430. expect(inputTypeScript(tool)).toBe("{ name: string }")
  431. })
  432. test("honors declarations that are siblings of a $ref", () => {
  433. const tool = toolAt(
  434. OpenAPI.fromSpec({
  435. baseUrl,
  436. spec: {
  437. openapi: "3.1.0",
  438. paths: {
  439. "/test": {
  440. post: {
  441. operationId: "test",
  442. responses: { 200: { description: "Success" } },
  443. requestBody: {
  444. required: true,
  445. content: {
  446. "application/json": {
  447. schema: {
  448. type: "object",
  449. additionalProperties: false,
  450. required: ["record"],
  451. properties: {
  452. record: {
  453. $ref: "#/components/schemas/Base",
  454. properties: { extra: { type: "string", readOnly: true }, note: { type: "string" } },
  455. required: ["extra", "note", "id"],
  456. },
  457. },
  458. },
  459. },
  460. },
  461. },
  462. },
  463. },
  464. },
  465. components: {
  466. schemas: {
  467. Base: {
  468. type: "object",
  469. required: ["id", "name"],
  470. properties: { id: { type: "string", readOnly: true }, name: { type: "string" } },
  471. },
  472. },
  473. },
  474. },
  475. }).tools,
  476. "test",
  477. )
  478. if (!Tool.isTool(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
  479. const properties = isRecord(tool.input.properties) ? tool.input.properties : {}
  480. const record = isRecord(properties.record) ? properties.record : {}
  481. const definitions = isRecord(tool.input.$defs) ? tool.input.$defs : {}
  482. const base = isRecord(definitions.Base) ? definitions.Base : {}
  483. expect(Object.keys(isRecord(record.properties) ? record.properties : {})).toEqual(["note"])
  484. expect(record.required).toEqual(["note"])
  485. expect(Object.keys(isRecord(base.properties) ? base.properties : {})).toEqual(["name"])
  486. expect(base.required).toEqual(["name"])
  487. })
  488. test("honors directional declarations on intermediate reference hops", () => {
  489. const tool = toolAt(
  490. OpenAPI.fromSpec({
  491. baseUrl,
  492. spec: {
  493. ...singleOperation(
  494. {
  495. requestBody: {
  496. required: true,
  497. content: {
  498. "application/json": {
  499. schema: {
  500. type: "object",
  501. additionalProperties: false,
  502. required: ["secret", "name"],
  503. properties: {
  504. // Hidden only by the sibling declaration on the middle hop.
  505. secret: { $ref: "#/components/schemas/Middle" },
  506. name: { type: "string" },
  507. },
  508. },
  509. },
  510. },
  511. },
  512. },
  513. "post",
  514. ),
  515. components: {
  516. schemas: {
  517. Middle: { $ref: "#/components/schemas/Plain", readOnly: true },
  518. Plain: { type: "string" },
  519. },
  520. },
  521. },
  522. }).tools,
  523. "test",
  524. )
  525. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  526. expect(inputTypeScript(tool)).toBe("{ name: string }")
  527. })
  528. test("projects cyclic component references without hanging", () => {
  529. const tool = toolAt(
  530. OpenAPI.fromSpec({
  531. baseUrl,
  532. spec: {
  533. openapi: "3.1.0",
  534. paths: {
  535. "/test": {
  536. post: {
  537. operationId: "test",
  538. responses: { 200: { description: "Success" } },
  539. requestBody: {
  540. required: true,
  541. content: { "application/json": { schema: { $ref: "#/components/schemas/Node" } } },
  542. },
  543. },
  544. },
  545. },
  546. components: {
  547. schemas: {
  548. Node: {
  549. type: "object",
  550. required: ["id", "name", "child"],
  551. properties: {
  552. id: { type: "string", readOnly: true },
  553. name: { type: "string" },
  554. child: { $ref: "#/components/schemas/Node" },
  555. },
  556. },
  557. },
  558. },
  559. },
  560. }).tools,
  561. "test",
  562. )
  563. if (!Tool.isTool(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
  564. const definitions = isRecord(tool.input.$defs) ? tool.input.$defs : {}
  565. const node = isRecord(definitions.Node) ? definitions.Node : {}
  566. expect(Object.keys(isRecord(node.properties) ? node.properties : {})).toEqual(["name", "child"])
  567. expect(node.required).toEqual(["name", "child"])
  568. })
  569. test("projects diamond-shaped reference graphs in linear time", () => {
  570. // Each component references the next twice; without memoized hidden-ness this is 2^30 work.
  571. const depth = 30
  572. const schemas = Object.fromEntries(
  573. Array.from({ length: depth }, (_, index) => [
  574. `C${index}`,
  575. index === depth - 1
  576. ? { type: "object", properties: { id: { type: "string", readOnly: true }, name: { type: "string" } } }
  577. : { allOf: [{ $ref: `#/components/schemas/C${index + 1}` }, { $ref: `#/components/schemas/C${index + 1}` }] },
  578. ]),
  579. )
  580. const tool = toolAt(
  581. OpenAPI.fromSpec({
  582. baseUrl,
  583. spec: {
  584. openapi: "3.1.0",
  585. paths: {
  586. "/test": {
  587. post: {
  588. operationId: "test",
  589. responses: { 200: { description: "Success" } },
  590. requestBody: {
  591. required: true,
  592. content: { "application/json": { schema: { $ref: "#/components/schemas/C0" } } },
  593. },
  594. },
  595. },
  596. },
  597. components: { schemas },
  598. },
  599. }).tools,
  600. "test",
  601. )
  602. if (!Tool.isTool(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
  603. const definitions = isRecord(tool.input.$defs) ? tool.input.$defs : {}
  604. const leaf = isRecord(definitions[`C${depth - 1}`]) ? definitions[`C${depth - 1}`] : {}
  605. expect(Object.keys(isRecord(leaf.properties) ? leaf.properties : {})).toEqual(["name"])
  606. })
  607. test("resolves hiding through reference cycles regardless of evaluation order", () => {
  608. // `Wrap` is hidden only through the cycle member `Loop`; evaluating a property that
  609. // enters the cycle at `Loop` first must not freeze a provisional result for `Wrap`.
  610. const schemas = {
  611. Wrap: { allOf: [{ $ref: "#/components/schemas/Loop" }] },
  612. Loop: { allOf: [{ $ref: "#/components/schemas/Wrap" }, { readOnly: true }] },
  613. }
  614. const body = (properties: Record<string, unknown>) => ({
  615. required: true,
  616. content: {
  617. "application/json": {
  618. schema: {
  619. type: "object",
  620. additionalProperties: false,
  621. required: [...Object.keys(properties), "name"],
  622. properties: { ...properties, name: { type: "string" } },
  623. },
  624. },
  625. },
  626. })
  627. for (const properties of [
  628. { a: { $ref: "#/components/schemas/Loop" }, b: { $ref: "#/components/schemas/Wrap" } },
  629. { a: { $ref: "#/components/schemas/Wrap" }, b: { $ref: "#/components/schemas/Loop" } },
  630. ]) {
  631. const tool = toolAt(
  632. OpenAPI.fromSpec({
  633. baseUrl,
  634. spec: { ...singleOperation({ requestBody: body(properties) }, "post"), components: { schemas } },
  635. }).tools,
  636. "test",
  637. )
  638. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  639. expect(inputTypeScript(tool)).toBe("{ name: string }")
  640. }
  641. })
  642. test("keeps not, if, and contains subschemas unprojected", () => {
  643. const tool = toolAt(
  644. OpenAPI.fromSpec({
  645. baseUrl,
  646. spec: singleOperation(
  647. {
  648. requestBody: {
  649. required: true,
  650. content: {
  651. "application/json": {
  652. schema: {
  653. type: "object",
  654. additionalProperties: false,
  655. required: ["record"],
  656. properties: {
  657. record: {
  658. type: "object",
  659. // Removing `secret` here would turn `not` unsatisfiable and
  660. // flip which branch of `if` applies; both must pass through.
  661. not: { required: ["secret"], properties: { secret: { type: "string", readOnly: true } } },
  662. if: { required: ["kind"], properties: { kind: { type: "string", readOnly: true } } },
  663. },
  664. },
  665. },
  666. },
  667. },
  668. },
  669. },
  670. "post",
  671. ),
  672. }).tools,
  673. "test",
  674. )
  675. if (!Tool.isTool(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
  676. const properties = isRecord(tool.input.properties) ? tool.input.properties : {}
  677. const record: Record<string, unknown> = isRecord(properties.record) ? properties.record : {}
  678. expect(record.not).toEqual({ required: ["secret"], properties: { secret: { type: "string", readOnly: true } } })
  679. expect(record.if).toEqual({ required: ["kind"], properties: { kind: { type: "string", readOnly: true } } })
  680. })
  681. test("does not hide properties whose direction is declared only in anyOf or oneOf alternatives", () => {
  682. // Deliberate scope bound: alternatives may apply, so a directional declaration on
  683. // one alternative does not hide the property; the annotation is preserved as-is.
  684. const tool = toolAt(
  685. OpenAPI.fromSpec({
  686. baseUrl,
  687. spec: singleOperation(
  688. {
  689. requestBody: {
  690. required: true,
  691. content: {
  692. "application/json": {
  693. schema: {
  694. type: "object",
  695. additionalProperties: false,
  696. required: ["choice", "pick"],
  697. properties: {
  698. choice: { anyOf: [{ type: "string", readOnly: true }, { type: "number" }] },
  699. pick: { oneOf: [{ type: "string", readOnly: true }, { type: "number" }] },
  700. },
  701. },
  702. },
  703. },
  704. },
  705. },
  706. "post",
  707. ),
  708. }).tools,
  709. "test",
  710. )
  711. if (!Tool.isTool(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
  712. const properties = isRecord(tool.input.properties) ? tool.input.properties : {}
  713. const choice: Record<string, unknown> = isRecord(properties.choice) ? properties.choice : {}
  714. const pick: Record<string, unknown> = isRecord(properties.pick) ? properties.pick : {}
  715. expect(Object.keys(properties)).toEqual(["choice", "pick"])
  716. expect(choice.anyOf).toEqual([{ type: "string", readOnly: true }, { type: "number" }])
  717. expect(pick.oneOf).toEqual([{ type: "string", readOnly: true }, { type: "number" }])
  718. })
  719. test("does not misresolve shadowed local $defs when flattening body fields", () => {
  720. const tool = toolAt(
  721. OpenAPI.fromSpec({
  722. baseUrl,
  723. spec: singleOperation(
  724. {
  725. requestBody: {
  726. required: true,
  727. content: {
  728. "application/json": {
  729. schema: {
  730. type: "object",
  731. additionalProperties: false,
  732. required: ["record"],
  733. $defs: { Value: { type: "string" } },
  734. properties: {
  735. record: {
  736. type: "object",
  737. required: ["x"],
  738. properties: { x: { $ref: "#/$defs/Value" } },
  739. // Shadows the body-level Value; must not affect the body-rooted projection.
  740. $defs: { Value: { type: "string", readOnly: true } },
  741. },
  742. },
  743. },
  744. },
  745. },
  746. },
  747. },
  748. "post",
  749. ),
  750. }).tools,
  751. "test",
  752. )
  753. if (!Tool.isTool(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
  754. const properties = isRecord(tool.input.properties) ? tool.input.properties : {}
  755. const record = isRecord(properties.record) ? properties.record : {}
  756. expect(Object.keys(isRecord(record.properties) ? record.properties : {})).toEqual(["x"])
  757. expect(record.required).toEqual(["x"])
  758. })
  759. test("projects directional annotations inside parameter schemas", () => {
  760. const tool = toolAt(
  761. OpenAPI.fromSpec({
  762. baseUrl,
  763. spec: singleOperation({
  764. parameters: [
  765. {
  766. name: "filter",
  767. in: "query",
  768. required: true,
  769. schema: {
  770. type: "object",
  771. required: ["state", "id"],
  772. properties: { state: { type: "string" }, id: { type: "string", readOnly: true } },
  773. },
  774. },
  775. ],
  776. }),
  777. }).tools,
  778. "test",
  779. )
  780. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  781. expect(inputTypeScript(tool)).toBe("{ filter: { state: string } }")
  782. })
  783. test("ignores inherited directional annotations", () => {
  784. const inherited: Record<string, unknown> = { type: "string" }
  785. Object.setPrototypeOf(inherited, { readOnly: true })
  786. const tool = toolAt(
  787. OpenAPI.fromSpec({
  788. baseUrl,
  789. spec: singleOperation({
  790. parameters: [
  791. {
  792. name: "filter",
  793. in: "query",
  794. required: true,
  795. schema: {
  796. type: "object",
  797. // The own annotation on `id` keeps projection active for the document,
  798. // so `value` pins that prototype-inherited annotations are not read.
  799. properties: { value: inherited, id: { type: "string", readOnly: true } },
  800. required: ["value", "id"],
  801. },
  802. },
  803. ],
  804. }),
  805. }).tools,
  806. "test",
  807. )
  808. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  809. expect(inputTypeScript(tool)).toBe("{ filter: { value: string } }")
  810. })
  811. test("cleans required properties across allOf branches", () => {
  812. const tool = toolAt(
  813. OpenAPI.fromSpec({
  814. baseUrl,
  815. spec: singleOperation(
  816. {
  817. requestBody: {
  818. required: true,
  819. content: {
  820. "application/json": {
  821. schema: {
  822. type: "object",
  823. required: ["id", "name"],
  824. allOf: [
  825. {
  826. type: "object",
  827. required: ["id", "name"],
  828. properties: { id: { type: "string", readOnly: true }, name: { type: "string" } },
  829. },
  830. ],
  831. },
  832. },
  833. },
  834. },
  835. },
  836. "post",
  837. ),
  838. }).tools,
  839. "test",
  840. )
  841. if (!Tool.isTool(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
  842. const properties = isRecord(tool.input.properties) ? tool.input.properties : {}
  843. const body = isRecord(properties.body) ? properties.body : {}
  844. const allOf = Array.isArray(body.allOf) ? body.allOf : []
  845. const branch = isRecord(allOf[0]) ? allOf[0] : {}
  846. expect(body.required).toEqual(["name"])
  847. expect(branch.required).toEqual(["name"])
  848. expect(Object.keys(isRecord(branch.properties) ? branch.properties : {})).toEqual(["name"])
  849. })
  850. test("keeps directional schemas model-facing while preserving runtime pass-through", async () => {
  851. const client = recordingClient(() =>
  852. json({
  853. id: "server-id",
  854. name: "Ada",
  855. password: "returned-by-server",
  856. profile: { createdAt: "today", secret: "returned-secret", label: "primary" },
  857. generated: "generated-id",
  858. }),
  859. )
  860. const tool = toolAt(OpenAPI.fromSpec({ baseUrl, spec: directionalSpec("3.1.0") }).tools, "users.create")
  861. if (!Tool.isTool(tool)) throw new Error("users.create was not generated")
  862. const result = await Effect.runPromise(
  863. tool
  864. .execute({
  865. id: "ignored-top-level",
  866. generated: "ignored-generated",
  867. name: "Ada",
  868. password: "request-secret",
  869. profile: { createdAt: "sent-nested", secret: "nested-secret", label: "primary" },
  870. })
  871. .pipe(Effect.provide(client.layer)),
  872. )
  873. expect(client.requests[0]?.body).toEqual({
  874. name: "Ada",
  875. password: "request-secret",
  876. profile: { createdAt: "sent-nested", secret: "nested-secret", label: "primary" },
  877. })
  878. expect(result).toMatchObject({ password: "returned-by-server", profile: { secret: "returned-secret" } })
  879. })
  880. test("documents that the opencode fixture is unauthenticated", async () => {
  881. const spec = await opencodeSpec()
  882. const components = isRecord(spec.components) ? spec.components : {}
  883. const result = OpenAPI.fromSpec({ spec, baseUrl })
  884. expect(spec.security).toStrictEqual([])
  885. expect(isRecord(components.securitySchemes) ? Object.keys(components.securitySchemes) : []).toStrictEqual([])
  886. const health = toolAt(result.tools, "v2.health.get")
  887. const healthInput = isRecord(health) ? health.input : undefined
  888. expect(healthInput).toMatchObject({ type: "object", properties: {} })
  889. const input = isRecord(healthInput) ? healthInput : {}
  890. expect(Object.keys(isRecord(input.properties) ? input.properties : {})).toStrictEqual([])
  891. })
  892. test("exposes real opencode operations through CodeMode discovery", async () => {
  893. const { layer } = recordingClient(() => json({}))
  894. const runtime = CodeMode.make({
  895. tools: { opencode: OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools },
  896. })
  897. const result = await Effect.runPromise(
  898. runtime
  899. .execute(
  900. `
  901. return search({ query: "global health", namespace: "opencode", limit: 1 })
  902. `,
  903. )
  904. .pipe(Effect.provide(layer)),
  905. )
  906. expect(result).toMatchObject({ ok: true })
  907. if (!result.ok) return
  908. expect(result.value).toMatchObject({
  909. items: [
  910. {
  911. path: "tools.opencode.v2.health.get",
  912. description: "Check whether the API server is ready to accept requests.",
  913. },
  914. ],
  915. })
  916. expect(JSON.stringify(result.value)).toContain("healthy: true")
  917. })
  918. test("invokes real opencode path parameters and JSON request bodies", async () => {
  919. const { requests, layer } = recordingClient((request) => {
  920. if (request.method === "GET") return json({ id: "ses_123" })
  921. return json({ id: "ses_456" })
  922. })
  923. const runtime = CodeMode.make({
  924. tools: { opencode: OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools },
  925. })
  926. const result = await Effect.runPromise(
  927. runtime
  928. .execute(
  929. `
  930. const existing = await tools.opencode.v2.session.get({ sessionID: "ses_123" })
  931. const created = await tools.opencode.v2.session.create({ id: "ses_456" })
  932. return { existing, created }
  933. `,
  934. )
  935. .pipe(Effect.provide(layer)),
  936. )
  937. expect(result).toMatchObject({ ok: true })
  938. expect(requests).toHaveLength(2)
  939. expect(requests[0]).toMatchObject({ method: "GET", body: undefined })
  940. expect(new URL(requests[0]!.url).pathname).toBe("/api/session/ses_123")
  941. expect(requests[1]).toMatchObject({
  942. method: "POST",
  943. url: "http://localhost:4096/api/session",
  944. body: { id: "ses_456" },
  945. })
  946. })
  947. test("serializes deep-object query parameters from the opencode fixture", async () => {
  948. const client = recordingClient(() => json({ directory: "/tmp" }))
  949. const location = toolAt(OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools, "v2.location.get")
  950. if (!Tool.isTool(location)) throw new Error("v2.location.get was not generated")
  951. await Effect.runPromise(
  952. location
  953. .execute({ location: { directory: "/tmp", workspace: "workspace-1" } })
  954. .pipe(Effect.provide(client.layer)),
  955. )
  956. const url = new URL(client.requests[0]!.url)
  957. expect(url.searchParams.get("location[directory]")).toBe("/tmp")
  958. expect(url.searchParams.get("location[workspace]")).toBe("workspace-1")
  959. })
  960. test("serializes supported simple and form parameter shapes", async () => {
  961. const client = recordingClient(() => json({ ok: true }))
  962. const result = OpenAPI.fromSpec({
  963. baseUrl,
  964. spec: {
  965. openapi: "3.1.0",
  966. paths: {
  967. "/items/{keys}": {
  968. get: {
  969. operationId: "items",
  970. parameters: [
  971. { name: "keys", in: "path", required: true, schema: { type: "array", items: { type: "string" } } },
  972. { name: "tags", in: "query", style: "form", explode: false, schema: { type: "array" } },
  973. { name: "filter", in: "query", style: "form", explode: true, schema: { type: "object" } },
  974. { name: "nullable", in: "query", required: true, schema: { type: ["string", "null"] } },
  975. { name: "constructor", in: "query", schema: { type: "string" } },
  976. { name: "meta", in: "header", style: "simple", explode: true, schema: { type: "object" } },
  977. ],
  978. responses: { 200: { description: "Success" } },
  979. },
  980. },
  981. },
  982. },
  983. })
  984. const tool = toolAt(result.tools, "items")
  985. if (!Tool.isTool(tool)) throw new Error("items was not generated")
  986. await Effect.runPromise(
  987. tool
  988. .execute({
  989. keys: ["a!", "b*"],
  990. tags: ["x", "y"],
  991. filter: { state: "open", page: 2 },
  992. nullable: null,
  993. constructor_2: "safe",
  994. meta: { a: "b", c: "d" },
  995. })
  996. .pipe(Effect.provide(client.layer)),
  997. )
  998. const url = new URL(client.requests[0]!.url)
  999. expect(url.pathname).toBe("/items/a%21,b%2A")
  1000. expect(url.searchParams.get("tags")).toBe("x,y")
  1001. expect(url.searchParams.get("state")).toBe("open")
  1002. expect(url.searchParams.get("page")).toBe("2")
  1003. expect(url.searchParams.get("nullable")).toBe("null")
  1004. expect(url.searchParams.get("constructor")).toBe("safe")
  1005. expect(client.requests[0]!.headers.meta).toBe("a=b,c=d")
  1006. await expect(
  1007. Effect.runPromise(tool.execute({ keys: [undefined] }).pipe(Effect.provide(client.layer))),
  1008. ).rejects.toThrow("unsupported nested value")
  1009. })
  1010. test("preserves ordered exploded and deep-object query parameters", async () => {
  1011. const client = recordingClient(() => json({ ok: true }))
  1012. const tool = toolAt(
  1013. OpenAPI.fromSpec({
  1014. baseUrl,
  1015. spec: singleOperation({
  1016. parameters: [
  1017. { name: "tags", in: "query", style: "form", explode: true, schema: { type: "array" } },
  1018. { name: "filter", in: "query", style: "form", explode: true, schema: { type: "object" } },
  1019. { name: "location", in: "query", style: "deepObject", explode: true, schema: { type: "object" } },
  1020. ],
  1021. }),
  1022. }).tools,
  1023. "test",
  1024. )
  1025. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  1026. await Effect.runPromise(
  1027. tool
  1028. .execute({
  1029. tags: ["first value", "second&value"],
  1030. filter: { state: "open now", page: 2 },
  1031. location: { directory: "/tmp/a b", workspace: "work&1" },
  1032. })
  1033. .pipe(Effect.provide(client.layer)),
  1034. )
  1035. expect(client.requests[0]?.url).toBe(
  1036. `${baseUrl}/test?tags=first+value&tags=second%26value&state=open+now&page=2&location%5Bdirectory%5D=%2Ftmp%2Fa+b&location%5Bworkspace%5D=work%261`,
  1037. )
  1038. await expect(Effect.runPromise(tool.execute({ tags: [{}] }).pipe(Effect.provide(client.layer)))).rejects.toThrow(
  1039. "Parameter 'tags' contains an unsupported nested value.",
  1040. )
  1041. await expect(
  1042. Effect.runPromise(tool.execute({ filter: { state: {} } }).pipe(Effect.provide(client.layer))),
  1043. ).rejects.toThrow("Query parameter 'filter' contains an unsupported nested value.")
  1044. await expect(
  1045. Effect.runPromise(tool.execute({ location: { directory: [] } }).pipe(Effect.provide(client.layer))),
  1046. ).rejects.toThrow("Deep-object parameter 'location' contains an unsupported nested value.")
  1047. expect(client.requests).toHaveLength(1)
  1048. })
  1049. test("skips unsupported parameter encodings and malformed security", () => {
  1050. const result = OpenAPI.fromSpec({
  1051. baseUrl,
  1052. spec: {
  1053. openapi: "3.1.0",
  1054. security: [{ bearer: [] }],
  1055. paths: {
  1056. "/cookie": {
  1057. get: {
  1058. operationId: "cookie",
  1059. parameters: [{ name: "session", in: "cookie", schema: { type: "string" } }],
  1060. responses: { 200: { description: "Success" } },
  1061. },
  1062. },
  1063. "/reserved": {
  1064. get: {
  1065. operationId: "reserved",
  1066. parameters: [{ name: "query", in: "query", allowReserved: true, schema: { type: "string" } }],
  1067. responses: { 200: { description: "Success" } },
  1068. },
  1069. },
  1070. "/invalid-style": {
  1071. get: {
  1072. operationId: "invalidStyle",
  1073. parameters: [{ name: "query", in: "query", style: 42, schema: { type: "string" } }],
  1074. responses: { 200: { description: "Success" } },
  1075. },
  1076. },
  1077. "/security": {
  1078. get: { operationId: "security", security: null, responses: { 200: { description: "Success" } } },
  1079. },
  1080. },
  1081. },
  1082. })
  1083. expect(result.tools).toEqual({})
  1084. expect(result.skipped.map((item) => item.reason)).toEqual([
  1085. "cookie parameter 'session' is not supported",
  1086. "parameter 'query' uses unsupported allowReserved encoding",
  1087. "parameter 'query' has an invalid style",
  1088. "security declaration is not an array",
  1089. ])
  1090. })
  1091. test("fails closed on prototype-named missing security schemes", () => {
  1092. const result = OpenAPI.fromSpec({
  1093. baseUrl,
  1094. spec: singleOperation({ security: [JSON.parse('{"__proto__":[]}')] }),
  1095. })
  1096. expect(result.tools).toEqual({})
  1097. expect(result.skipped[0]?.reason).toBe("security requirement references missing or malformed scheme: __proto__")
  1098. })
  1099. test("resolves bearer authentication without exposing it as input", async () => {
  1100. const contexts: Array<Parameters<OpenAPI.AuthResolver>[0]> = []
  1101. const client = recordingClient(() => json({ ok: true }))
  1102. const spec = {
  1103. ...singleOperation({ operationId: undefined }),
  1104. security: [{ bearer: [] }],
  1105. components: { securitySchemes: { bearer: { type: "http", scheme: "bearer" } } },
  1106. } satisfies Document
  1107. const tool = toolAt(
  1108. OpenAPI.fromSpec({
  1109. baseUrl,
  1110. spec,
  1111. auth: {
  1112. resolve: (context) => {
  1113. contexts.push(context)
  1114. return Effect.succeed({ type: "bearer", token: "secret" })
  1115. },
  1116. },
  1117. }).tools,
  1118. "getTest",
  1119. )
  1120. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  1121. await Effect.runPromise(tool.execute({}).pipe(Effect.provide(client.layer)))
  1122. expect(inputTypeScript(tool)).toBe("{}")
  1123. expect(client.requests[0]!.headers.authorization).toBe("Bearer secret")
  1124. expect(contexts).toEqual([
  1125. {
  1126. name: "bearer",
  1127. definition: { type: "http", scheme: "bearer" },
  1128. scopes: [],
  1129. operation: {
  1130. operationId: undefined,
  1131. method: "GET",
  1132. path: "/test",
  1133. summary: undefined,
  1134. description: undefined,
  1135. },
  1136. },
  1137. ])
  1138. })
  1139. test("applies authentication carriers without prototype or collision loss", async () => {
  1140. const client = recordingClient(() => json({ ok: true }))
  1141. const authenticated = (
  1142. security: ReadonlyArray<Record<string, ReadonlyArray<string>>>,
  1143. schemes: Record<string, unknown>,
  1144. ) =>
  1145. OpenAPI.fromSpec({
  1146. baseUrl,
  1147. spec: { ...singleOperation({}), security, components: { securitySchemes: schemes } },
  1148. auth: { resolve: () => Effect.succeed({ type: "apiKey", value: "secret" }) },
  1149. })
  1150. const prototype = toolAt(
  1151. authenticated([{ key: [] }], { key: { type: "apiKey", in: "query", name: "__proto__" } }).tools,
  1152. "test",
  1153. )
  1154. if (!Tool.isTool(prototype)) throw new Error("prototype auth tool was not generated")
  1155. await Effect.runPromise(prototype.execute({}).pipe(Effect.provide(client.layer)))
  1156. expect(new URL(client.requests[0]!.url).searchParams.get("__proto__")).toBe("secret")
  1157. const duplicate = toolAt(
  1158. authenticated([{ first: [], second: [] }], {
  1159. first: { type: "apiKey", in: "header", name: "x-key" },
  1160. second: { type: "apiKey", in: "header", name: "x-key" },
  1161. }).tools,
  1162. "test",
  1163. )
  1164. if (!Tool.isTool(duplicate)) throw new Error("duplicate auth tool was not generated")
  1165. await expect(Effect.runPromise(duplicate.execute({}).pipe(Effect.provide(client.layer)))).rejects.toThrow(
  1166. "multiple credentials",
  1167. )
  1168. const cookie = authenticated([{ key: [] }], { key: { type: "apiKey", in: "cookie", name: "session" } })
  1169. expect(cookie.tools).toEqual({})
  1170. expect(cookie.skipped[0]?.reason).toBe("cookie authentication 'key' is not supported")
  1171. const alternative = OpenAPI.fromSpec({
  1172. baseUrl,
  1173. spec: {
  1174. ...singleOperation({}),
  1175. security: [{ cookie: [] }, { bearer: [] }],
  1176. components: {
  1177. securitySchemes: {
  1178. cookie: { type: "apiKey", in: "cookie", name: "session" },
  1179. bearer: { type: "http", scheme: "bearer" },
  1180. },
  1181. },
  1182. },
  1183. auth: {
  1184. resolve: ({ name }) => Effect.succeed(name === "bearer" ? { type: "bearer", token: "secret" } : undefined),
  1185. },
  1186. })
  1187. const alternativeTool = toolAt(alternative.tools, "test")
  1188. if (!Tool.isTool(alternativeTool)) throw new Error("supported auth alternative was not generated")
  1189. await Effect.runPromise(alternativeTool.execute({}).pipe(Effect.provide(client.layer)))
  1190. expect(client.requests.at(-1)?.headers.authorization).toBe("Bearer secret")
  1191. })
  1192. test("honors server precedence and rejects ambiguous base URLs", async () => {
  1193. const client = recordingClient(() => json({ ok: true }))
  1194. const spec = {
  1195. ...singleOperation({ servers: [{ url: "https://operation.example/v1" }] }),
  1196. servers: [{ url: "https://document.example" }],
  1197. } satisfies Document
  1198. const tool = toolAt(OpenAPI.fromSpec({ spec }).tools, "test")
  1199. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  1200. await Effect.runPromise(tool.execute({}).pipe(Effect.provide(client.layer)))
  1201. expect(client.requests[0]?.url).toBe("https://operation.example/v1/test")
  1202. const invalid = OpenAPI.fromSpec({ spec, baseUrl: "https://example.com/api?tenant=one" })
  1203. expect(invalid.tools).toEqual({})
  1204. expect(invalid.skipped[0]?.reason).toContain("unsupported query string or fragment")
  1205. const malformed = OpenAPI.fromSpec({ spec, baseUrl: "https:/example.com" })
  1206. expect(malformed.tools).toEqual({})
  1207. expect(malformed.skipped[0]?.reason).toContain("not an absolute HTTP(S) URL")
  1208. })
  1209. test("resolves chained response refs before detecting unsupported transports", () => {
  1210. const result = OpenAPI.fromSpec({
  1211. baseUrl,
  1212. spec: {
  1213. ...singleOperation({ responses: { 200: { $ref: "#/components/responses/First" } } }),
  1214. components: {
  1215. responses: {
  1216. First: { $ref: "#/components/responses/Stream" },
  1217. Stream: { content: { "text/event-stream": { schema: { type: "string" } } } },
  1218. },
  1219. },
  1220. },
  1221. })
  1222. expect(result.tools).toEqual({})
  1223. expect(result.skipped[0]?.reason).toBe("SSE operations are not supported")
  1224. })
  1225. test("resolves response schemas before detecting binary output", () => {
  1226. const result = OpenAPI.fromSpec({
  1227. baseUrl,
  1228. spec: {
  1229. ...singleOperation({
  1230. responses: {
  1231. 200: {
  1232. content: { "text/plain": { schema: { $ref: "#/components/schemas/File" } } },
  1233. },
  1234. },
  1235. }),
  1236. components: { schemas: { File: { type: "string", format: "binary" } } },
  1237. },
  1238. })
  1239. expect(result.tools).toEqual({})
  1240. expect(result.skipped[0]?.reason).toBe("binary responses are not supported")
  1241. })
  1242. test("validates composite parameters before resolving auth", async () => {
  1243. const resolutions: Array<string> = []
  1244. const client = recordingClient(() => json({ ok: true }))
  1245. const tool = toolAt(
  1246. OpenAPI.fromSpec({
  1247. baseUrl,
  1248. spec: {
  1249. ...singleOperation({
  1250. parameters: [{ name: "filter", in: "query", style: "form", explode: true, schema: { type: "object" } }],
  1251. }),
  1252. security: [{ bearer: [] }],
  1253. components: { securitySchemes: { bearer: { type: "http", scheme: "bearer" } } },
  1254. },
  1255. auth: {
  1256. resolve: ({ name }) => {
  1257. resolutions.push(name)
  1258. return Effect.succeed({ type: "bearer", token: "secret" })
  1259. },
  1260. },
  1261. }).tools,
  1262. "test",
  1263. )
  1264. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  1265. await expect(
  1266. Effect.runPromise(tool.execute({ filter: { value: undefined } }).pipe(Effect.provide(client.layer))),
  1267. ).rejects.toThrow("unsupported nested value")
  1268. expect(resolutions).toEqual([])
  1269. expect(client.requests).toEqual([])
  1270. })
  1271. test("preserves JSON media types and rejects unencodable bodies", async () => {
  1272. const client = recordingClient(() => json({ ok: true }))
  1273. const tool = toolAt(
  1274. OpenAPI.fromSpec({
  1275. baseUrl,
  1276. spec: singleOperation(
  1277. {
  1278. requestBody: {
  1279. required: true,
  1280. content: { "application/merge-patch+json": { schema: { type: "object" } } },
  1281. },
  1282. },
  1283. "post",
  1284. ),
  1285. }).tools,
  1286. "test",
  1287. )
  1288. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  1289. await Effect.runPromise(tool.execute({ body: { name: "updated" } }).pipe(Effect.provide(client.layer)))
  1290. expect(client.requests[0]!.headers["content-type"]).toBe("application/merge-patch+json")
  1291. const cyclic: Record<string, unknown> = {}
  1292. cyclic.self = cyclic
  1293. await expect(Effect.runPromise(tool.execute({ body: cyclic }).pipe(Effect.provide(client.layer)))).rejects.toThrow(
  1294. "Invalid JSON body",
  1295. )
  1296. })
  1297. test("rejects oversized and malformed JSON responses", async () => {
  1298. const tool = toolAt(OpenAPI.fromSpec({ baseUrl, spec: singleOperation({}) }).tools, "test")
  1299. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  1300. const oversized = recordingClient(
  1301. () => new Response(null, { headers: { "content-length": String(50 * 1024 * 1024 + 1) } }),
  1302. )
  1303. const malformed = recordingClient(() => new Response("{", { headers: { "content-type": "application/json" } }))
  1304. const chunked = recordingClient(() => new Response(new Uint8Array(50 * 1024 * 1024 + 1)))
  1305. await expect(Effect.runPromise(tool.execute({}).pipe(Effect.provide(oversized.layer)))).rejects.toThrow(
  1306. "response exceeds 50 MiB",
  1307. )
  1308. await expect(Effect.runPromise(tool.execute({}).pipe(Effect.provide(malformed.layer)))).rejects.toThrow(
  1309. "returned malformed JSON",
  1310. )
  1311. await expect(Effect.runPromise(tool.execute({}).pipe(Effect.provide(chunked.layer)))).rejects.toThrow(
  1312. "response exceeds 50 MiB",
  1313. )
  1314. })
  1315. test("keeps non-JSON responses raw and unions every success output", async () => {
  1316. const spec = singleOperation({
  1317. responses: {
  1318. 200: { description: "Text", content: { "text/plain": { schema: { type: "string" } } } },
  1319. 204: { description: "Empty" },
  1320. },
  1321. })
  1322. const tool = toolAt(OpenAPI.fromSpec({ baseUrl, spec }).tools, "test")
  1323. if (!Tool.isTool(tool)) throw new Error("test was not generated")
  1324. const client = recordingClient(() => new Response("123", { headers: { "content-type": "text/plain" } }))
  1325. expect(outputTypeScript(tool)).toBe("string | null")
  1326. await expect(Effect.runPromise(tool.execute({}).pipe(Effect.provide(client.layer)))).resolves.toBe("123")
  1327. })
  1328. test("fails missing required parameters before auth and network", async () => {
  1329. const { requests, layer } = recordingClient(() => json({}))
  1330. const runtime = CodeMode.make({
  1331. tools: { opencode: OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools },
  1332. })
  1333. const result = await Effect.runPromise(
  1334. runtime.execute("return await tools.opencode.v2.session.get({})").pipe(Effect.provide(layer)),
  1335. )
  1336. expect(result).toMatchObject({ ok: false })
  1337. expect(JSON.stringify(result)).toContain("Missing required path parameter 'sessionID'")
  1338. expect(requests).toHaveLength(0)
  1339. })
  1340. test("prefixes cross-location collisions and reconstructs the HTTP request", async () => {
  1341. const spec = {
  1342. openapi: "3.1.0",
  1343. info: { title: "collision", version: "1.0.0" },
  1344. paths: {
  1345. "/echo": {
  1346. post: {
  1347. operationId: "echo",
  1348. requestBody: {
  1349. required: true,
  1350. content: { "application/json": { schema: { type: "string" } } },
  1351. },
  1352. responses: { "204": { description: "Echoed" } },
  1353. },
  1354. },
  1355. "/things/{id}": {
  1356. post: {
  1357. operationId: "things.update",
  1358. parameters: [
  1359. { name: "id", in: "path", required: true, schema: { type: "string" } },
  1360. { name: "id", in: "query", required: true, schema: { type: "string" } },
  1361. { name: "path_id", in: "query", schema: { type: "string" } },
  1362. { name: "id", in: "header", required: true, schema: { type: "string" } },
  1363. ],
  1364. requestBody: {
  1365. required: true,
  1366. content: {
  1367. "application/json": {
  1368. schema: {
  1369. type: "object",
  1370. properties: { id: { type: "string" } },
  1371. required: ["id"],
  1372. additionalProperties: false,
  1373. },
  1374. },
  1375. },
  1376. },
  1377. responses: { "204": { description: "Updated" } },
  1378. },
  1379. },
  1380. },
  1381. } satisfies Document
  1382. const { requests, layer } = recordingClient(() => new Response(null, { status: 204 }))
  1383. const tools = OpenAPI.fromSpec({ spec, baseUrl }).tools
  1384. const update = toolAt(tools, "things.update")
  1385. const echo = toolAt(tools, "echo")
  1386. expect(Tool.isTool(update)).toBe(true)
  1387. if (!Tool.isTool(update)) throw new Error("things.update was not generated")
  1388. expect(inputTypeScript(update)).toBe(
  1389. "{ path_id: string; query_id: string; path_id_2?: string; header_id: string; body_id: string }",
  1390. )
  1391. expect(Tool.isTool(echo)).toBe(true)
  1392. if (!Tool.isTool(echo)) throw new Error("echo was not generated")
  1393. expect(inputTypeScript(echo)).toBe("{ body: string }")
  1394. const runtime = CodeMode.make({ tools })
  1395. const result = await Effect.runPromise(
  1396. runtime
  1397. .execute(
  1398. `
  1399. const updated = await tools.things.update({ path_id: "path", query_id: "query", path_id_2: "literal", header_id: "header", body_id: "body" })
  1400. const echoed = await tools.echo({ body: "hello" })
  1401. return { updated, echoed }
  1402. `,
  1403. )
  1404. .pipe(Effect.provide(layer)),
  1405. )
  1406. expect(result).toMatchObject({ ok: true })
  1407. expect(requests).toHaveLength(2)
  1408. expect(new URL(requests[0]!.url).pathname).toBe("/things/path")
  1409. expect(new URL(requests[0]!.url).searchParams.get("id")).toBe("query")
  1410. expect(new URL(requests[0]!.url).searchParams.get("path_id")).toBe("literal")
  1411. expect(requests[0]!.headers.id).toBe("header")
  1412. expect(requests[0]!.body).toStrictEqual({ id: "body" })
  1413. expect(requests[1]!.body).toBe("hello")
  1414. })
  1415. test("keeps bodies nested when flattening would lose schema semantics", () => {
  1416. const body = (schema: Record<string, unknown>, required = true) => ({
  1417. required,
  1418. content: { "application/json": { schema } },
  1419. })
  1420. const spec = {
  1421. openapi: "3.1.0",
  1422. info: { title: "bodies", version: "1.0.0" },
  1423. paths: Object.fromEntries(
  1424. [
  1425. [
  1426. "optional",
  1427. body(
  1428. {
  1429. type: "object",
  1430. properties: { name: { type: "string" } },
  1431. required: ["name"],
  1432. additionalProperties: false,
  1433. },
  1434. false,
  1435. ),
  1436. ],
  1437. ["dictionary", body({ type: "object", additionalProperties: { type: "string" } })],
  1438. [
  1439. "composed",
  1440. body({
  1441. type: "object",
  1442. allOf: [{ type: "object", properties: { name: { type: "string" } }, required: ["name"] }],
  1443. additionalProperties: false,
  1444. }),
  1445. ],
  1446. [
  1447. "nullable",
  1448. body({
  1449. type: ["object", "null"],
  1450. properties: { name: { type: "string" } },
  1451. additionalProperties: false,
  1452. }),
  1453. ],
  1454. ].map(([name, requestBody]) => [
  1455. `/body/${name}`,
  1456. {
  1457. post: {
  1458. operationId: `body.${name}`,
  1459. requestBody,
  1460. responses: { "204": { description: "Accepted" } },
  1461. },
  1462. },
  1463. ]),
  1464. ),
  1465. } satisfies Document
  1466. const tools = OpenAPI.fromSpec({ spec, baseUrl }).tools
  1467. for (const name of ["optional", "dictionary", "composed", "nullable"]) {
  1468. const tool = toolAt(tools, `body.${name}`)
  1469. expect(Tool.isTool(tool)).toBe(true)
  1470. if (!Tool.isTool(tool)) throw new Error(`body.${name} was not generated`)
  1471. const input = isRecord(tool.input) ? tool.input : {}
  1472. expect(Object.keys(isRecord(input.properties) ? input.properties : {})).toStrictEqual(["body"])
  1473. }
  1474. const optional = toolAt(tools, "body.optional")
  1475. if (!Tool.isTool(optional)) throw new Error("body.optional was not generated")
  1476. expect(inputTypeScript(optional)).toBe("{ body?: { name: string } }")
  1477. })
  1478. })