@neurocode-ai/codemode 1.18.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,449 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { Effect, Schema } from "effect"
3
+ import { CodeMode, Tool } from "../src/index.js"
4
+ import { inputTypeScript, jsonSchemaToTypeScript, outputTypeScript } from "../src/tool-schema.js"
5
+
6
+ // A raw JSON Schema tool in the shape an MCP adapter produces: render-only input schema
7
+ // whose property descriptions and constraints must surface as JSDoc in pretty signatures.
8
+ const listIssues = Tool.make({
9
+ description: "List issues in a repository",
10
+ input: {
11
+ type: "object",
12
+ properties: {
13
+ owner: { type: "string", description: "Repository owner" },
14
+ after: { type: "string", description: "Cursor from the previous response's pageInfo" },
15
+ perPage: { type: "number", description: "Results per page", default: 30 },
16
+ labels: { type: "array", items: { type: "string" }, description: "Filter by labels", minItems: 1, maxItems: 10 },
17
+ state: { type: "string", enum: ["open", "closed"] },
18
+ },
19
+ required: ["owner"],
20
+ },
21
+ run: () => Effect.succeed("[]"),
22
+ })
23
+
24
+ // An Effect Schema tool whose field annotations must flow through the emitted JSON Schema.
25
+ const lookupOrder = Tool.make({
26
+ description: "Look up an order",
27
+ input: Schema.Struct({
28
+ id: Schema.String.annotate({ description: "Order identifier" }),
29
+ verbose: Schema.optionalKey(Schema.Boolean),
30
+ }),
31
+ output: Schema.Struct({
32
+ status: Schema.String.annotate({ description: "Current order status" }),
33
+ }),
34
+ run: () => Effect.succeed({ status: "open" }),
35
+ })
36
+
37
+ describe("pretty signature rendering", () => {
38
+ test("described fields get JSDoc comments; undescribed and untagged fields get none", () => {
39
+ expect(inputTypeScript(listIssues, true)).toBe(
40
+ [
41
+ "{",
42
+ " /** Repository owner */",
43
+ " owner: string,",
44
+ " /** Cursor from the previous response's pageInfo */",
45
+ " after?: string,",
46
+ " /**",
47
+ " * Results per page",
48
+ " * @default 30",
49
+ " */",
50
+ " perPage?: number,",
51
+ " /**",
52
+ " * Filter by labels",
53
+ " * @minItems 1",
54
+ " * @maxItems 10",
55
+ " */",
56
+ " labels?: Array<string>,",
57
+ ' state?: "open" | "closed",',
58
+ "}",
59
+ ].join("\n"),
60
+ )
61
+ })
62
+
63
+ test("compact mode output is unchanged by the pretty machinery", () => {
64
+ expect(inputTypeScript(listIssues)).toBe(
65
+ '{ owner: string; after?: string; perPage?: number; labels?: Array<string>; state?: "open" | "closed" }',
66
+ )
67
+ expect(inputTypeScript(lookupOrder)).toBe("{ id: string; verbose?: boolean }")
68
+ expect(outputTypeScript(lookupOrder)).toBe("{ status: string }")
69
+ })
70
+
71
+ test("nested objects recurse with increasing indent and their own JSDoc", () => {
72
+ const pretty = jsonSchemaToTypeScript(
73
+ {
74
+ type: "object",
75
+ properties: {
76
+ filter: {
77
+ type: "object",
78
+ description: "Search filter",
79
+ properties: { state: { type: "string", description: "Issue state" } },
80
+ },
81
+ },
82
+ },
83
+ true,
84
+ )
85
+ expect(pretty).toBe(
86
+ [
87
+ "{",
88
+ " /** Search filter */",
89
+ " filter?: {",
90
+ " /** Issue state */",
91
+ " state?: string,",
92
+ " },",
93
+ "}",
94
+ ].join("\n"),
95
+ )
96
+ })
97
+
98
+ test("Effect Schema annotations become JSDoc on input and output fields", () => {
99
+ expect(inputTypeScript(lookupOrder, true)).toBe(
100
+ ["{", " /** Order identifier */", " id: string,", " verbose?: boolean,", "}"].join("\n"),
101
+ )
102
+ expect(outputTypeScript(lookupOrder, true)).toBe(
103
+ ["{", " /** Current order status */", " status: string,", "}"].join("\n"),
104
+ )
105
+ })
106
+
107
+ test("constraints TypeScript cannot express surface as JSDoc tags", () => {
108
+ const pretty = jsonSchemaToTypeScript(
109
+ {
110
+ type: "object",
111
+ properties: {
112
+ legacy: { type: "string", deprecated: true },
113
+ homepage: { type: "string", format: "uri" },
114
+ tags: { type: "array", items: { type: "string" }, minItems: 2, maxItems: 5, default: ["a", "b"] },
115
+ },
116
+ },
117
+ true,
118
+ )
119
+ expect(pretty).toContain(" /** @deprecated */\n legacy?: string")
120
+ expect(pretty).toContain(" /** @format uri */\n homepage?: string")
121
+ expect(pretty).toContain(
122
+ [
123
+ " /**",
124
+ ' * @default ["a","b"]',
125
+ " * @minItems 2",
126
+ " * @maxItems 5",
127
+ " */",
128
+ " tags?: Array<string>",
129
+ ].join("\n"),
130
+ )
131
+ })
132
+
133
+ test("skips an unserializable default rather than emitting a broken tag", () => {
134
+ const pretty = jsonSchemaToTypeScript(
135
+ { type: "object", properties: { size: { type: "number", default: 1n } } },
136
+ true,
137
+ )
138
+ expect(pretty).toBe(["{", " size?: number,", "}"].join("\n"))
139
+ })
140
+
141
+ test("neutralizes */ inside descriptions so nothing closes the comment early", () => {
142
+ const pretty = jsonSchemaToTypeScript(
143
+ { type: "object", properties: { note: { type: "string", description: "Ends */ early" } } },
144
+ true,
145
+ )
146
+ expect(pretty).toContain(" /** Ends * / early */")
147
+ expect(pretty).not.toContain("Ends */")
148
+ })
149
+
150
+ test("multiline descriptions become *-prefixed blocks with blank edges trimmed", () => {
151
+ const pretty = jsonSchemaToTypeScript(
152
+ {
153
+ type: "object",
154
+ properties: { query: { type: "string", description: "\nFirst line\n\nSecond line\n" } },
155
+ },
156
+ true,
157
+ )
158
+ expect(pretty).toBe(
159
+ ["{", " /**", " * First line", " *", " * Second line", " */", " query?: string,", "}"].join("\n"),
160
+ )
161
+ })
162
+
163
+ test("stays total on cyclic $refs and pathological nesting in both modes", () => {
164
+ const cyclic = {
165
+ $ref: "#/$defs/Node",
166
+ $defs: { Node: { type: "object", properties: { child: { $ref: "#/$defs/Node" }, name: { type: "string" } } } },
167
+ } as const
168
+ expect(jsonSchemaToTypeScript(cyclic)).toBe("{ child?: unknown; name?: string }")
169
+ expect(jsonSchemaToTypeScript(cyclic, true)).toContain("child?: unknown")
170
+
171
+ let deep: Record<string, unknown> = { type: "string" }
172
+ for (let level = 0; level < 12; level += 1) deep = { type: "object", properties: { next: deep } }
173
+ for (const pretty of [false, true]) {
174
+ const rendered = jsonSchemaToTypeScript(deep, pretty)
175
+ expect(rendered).toContain("unknown")
176
+ expect(rendered).toContain("next?:")
177
+ }
178
+ })
179
+
180
+ test("intersects ref and union siblings instead of discarding them", () => {
181
+ expect(
182
+ jsonSchemaToTypeScript({
183
+ $ref: "#/$defs/User",
184
+ properties: { active: { type: "boolean" } },
185
+ required: ["active"],
186
+ $defs: {
187
+ User: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
188
+ },
189
+ }),
190
+ ).toBe("{ id: string } & { active: boolean }")
191
+ expect(
192
+ jsonSchemaToTypeScript({
193
+ type: "object",
194
+ properties: { common: { type: "boolean" } },
195
+ required: ["common"],
196
+ anyOf: [
197
+ { type: "object", properties: { name: { type: "string" } }, required: ["name"] },
198
+ { type: "object", properties: { count: { type: "number" } }, required: ["count"] },
199
+ ],
200
+ }),
201
+ ).toBe("({ name: string } | { count: number }) & { common: boolean }")
202
+ expect(jsonSchemaToTypeScript({ $ref: "https://example.com/schema.json" })).toBe("unknown")
203
+ expect(
204
+ jsonSchemaToTypeScript({
205
+ $ref: "#/$defs/User/properties/id",
206
+ $defs: { User: { type: "object" }, id: { type: "string" } },
207
+ }),
208
+ ).toBe("unknown")
209
+ expect(
210
+ jsonSchemaToTypeScript({
211
+ type: ["object", "null"],
212
+ properties: { name: { type: "string" } },
213
+ }),
214
+ ).toBe("{ name?: string } | null")
215
+ })
216
+ })
217
+
218
+ describe("non-identifier property names render as quoted keys", () => {
219
+ // MCP-style schemas routinely carry property names that are not bare TS identifiers
220
+ // (`foo-bar`, `@type`, dotted names); the rendered signature must quote them so the
221
+ // model sees a valid TypeScript object type. Bare identifiers stay unquoted.
222
+ const rawSchema = {
223
+ type: "object",
224
+ properties: {
225
+ "foo-bar": { type: "string" },
226
+ "@type": { type: "string" },
227
+ "x.y": { type: "number", description: "Dotted name" },
228
+ "123": { type: "number" },
229
+ plain: { type: "boolean" },
230
+ },
231
+ required: ["@type"],
232
+ } as const
233
+
234
+ test("compact rendering quotes non-identifier keys and leaves identifiers bare", () => {
235
+ expect(jsonSchemaToTypeScript(rawSchema)).toBe(
236
+ '{ "123"?: number; "foo-bar"?: string; "@type": string; "x.y"?: number; plain?: boolean }',
237
+ )
238
+ })
239
+
240
+ test("pretty rendering quotes non-identifier keys and keeps their JSDoc", () => {
241
+ expect(jsonSchemaToTypeScript(rawSchema, true)).toBe(
242
+ [
243
+ "{",
244
+ ' "123"?: number,',
245
+ ' "foo-bar"?: string,',
246
+ ' "@type": string,',
247
+ " /** Dotted name */",
248
+ ' "x.y"?: number,',
249
+ " plain?: boolean,",
250
+ "}",
251
+ ].join("\n"),
252
+ )
253
+ })
254
+
255
+ test("JSON Schema input and output signatures of a tool both quote", () => {
256
+ const tool = Tool.make({
257
+ description: "Adapter tool with awkward field names",
258
+ input: rawSchema,
259
+ output: {
260
+ type: "object",
261
+ properties: { "content-type": { type: "string" } },
262
+ required: ["content-type"],
263
+ } as const,
264
+ run: () => Effect.succeed({ "content-type": "text/plain" }),
265
+ })
266
+ expect(inputTypeScript(tool)).toContain('"foo-bar"?: string')
267
+ expect(outputTypeScript(tool)).toBe('{ "content-type": string }')
268
+ expect(outputTypeScript(tool, true)).toBe(["{", ' "content-type": string,', "}"].join("\n"))
269
+ })
270
+
271
+ test("Effect Schema structs with non-identifier field names quote too", () => {
272
+ const tool = Tool.make({
273
+ description: "Schema tool with awkward field names",
274
+ input: Schema.Struct({ "foo-bar": Schema.String, plain: Schema.optionalKey(Schema.Number) }),
275
+ run: () => Effect.succeed(null),
276
+ })
277
+ expect(inputTypeScript(tool)).toBe('{ "foo-bar": string; plain?: number }')
278
+ expect(inputTypeScript(tool, true)).toBe(["{", ' "foo-bar": string,', " plain?: number,", "}"].join("\n"))
279
+ })
280
+ })
281
+
282
+ describe("union schemas render every alternative", () => {
283
+ test("anyOf with a number branch keeps sibling alternatives", () => {
284
+ const schema = {
285
+ anyOf: [{ type: "string" }, { type: "number" }],
286
+ } as const
287
+ expect(jsonSchemaToTypeScript(schema)).toBe("string | number")
288
+ expect(jsonSchemaToTypeScript(schema, true)).toBe("string | number")
289
+ })
290
+
291
+ test("nullable numeric unions keep null", () => {
292
+ const schema = {
293
+ oneOf: [{ type: "number" }, { type: "null" }],
294
+ } as const
295
+ expect(jsonSchemaToTypeScript(schema)).toBe("number | null")
296
+ expect(jsonSchemaToTypeScript(schema, true)).toBe("number | null")
297
+ })
298
+
299
+ test("tool input and output signatures preserve numeric unions", () => {
300
+ const tool = Tool.make({
301
+ description: "Tool with numeric unions",
302
+ input: {
303
+ type: "object",
304
+ properties: {
305
+ value: { anyOf: [{ type: "string" }, { type: "number" }] },
306
+ },
307
+ } as const,
308
+ output: { anyOf: [{ type: "number" }, { type: "boolean" }] } as const,
309
+ run: () => Effect.succeed(1),
310
+ })
311
+ expect(inputTypeScript(tool)).toBe("{ value?: string | number }")
312
+ expect(outputTypeScript(tool)).toBe("number | boolean")
313
+ })
314
+
315
+ test("allOf renders intersections with parenthesized union members", () => {
316
+ const schema = {
317
+ allOf: [{ type: "object", properties: { id: { type: "string" } } }, { type: ["string", "null"] }],
318
+ } as const
319
+ expect(jsonSchemaToTypeScript(schema)).toBe("{ id?: string } & (string | null)")
320
+ })
321
+
322
+ test("allOf does not discard an unresolved constraint", () => {
323
+ expect(jsonSchemaToTypeScript({ allOf: [{ type: "string" }, { $ref: "https://example.com/external.json" }] })).toBe(
324
+ "unknown",
325
+ )
326
+ expect(
327
+ jsonSchemaToTypeScript({
328
+ allOf: [{ type: "string" }, { allOf: [{ $ref: "https://example.com/external.json" }] }],
329
+ }),
330
+ ).toBe("unknown")
331
+ expect(
332
+ jsonSchemaToTypeScript({
333
+ type: "string",
334
+ allOf: [{ $ref: "#/$defs/Constraint" }],
335
+ $defs: { Constraint: { description: "TypeScript-neutral constraint" } },
336
+ }),
337
+ ).toBe("string")
338
+ })
339
+ })
340
+
341
+ describe("JSDoc signatures in catalogs and search results", () => {
342
+ const runtime = CodeMode.make({ tools: { github: { list_issues: listIssues }, orders: { lookup: lookupOrder } } })
343
+
344
+ const search = async (query: string) => {
345
+ const result = await Effect.runPromise(
346
+ runtime.execute(`return await tools.$codemode.search({ query: ${JSON.stringify(query)} })`),
347
+ )
348
+ expect(result.ok).toBe(true)
349
+ if (!result.ok) throw new Error("search failed")
350
+ return result.value as { items: Array<{ path: string; signature: string }>; remaining: number }
351
+ }
352
+
353
+ test("a raw JSON Schema (MCP-style) tool's result signature carries field JSDoc and tags", async () => {
354
+ const { items } = await search("list issues repository")
355
+ const item = items.find(({ path }) => path === "tools.github.list_issues")!
356
+ expect(item.signature).toBe(
357
+ [
358
+ "tools.github.list_issues(input: {",
359
+ " /** Repository owner */",
360
+ " owner: string,",
361
+ " /** Cursor from the previous response's pageInfo */",
362
+ " after?: string,",
363
+ " /**",
364
+ " * Results per page",
365
+ " * @default 30",
366
+ " */",
367
+ " perPage?: number,",
368
+ " /**",
369
+ " * Filter by labels",
370
+ " * @minItems 1",
371
+ " * @maxItems 10",
372
+ " */",
373
+ " labels?: Array<string>,",
374
+ ' state?: "open" | "closed",',
375
+ "}): Promise<unknown>",
376
+ ].join("\n"),
377
+ )
378
+ })
379
+
380
+ test("an annotated Effect Schema tool's result signature carries field JSDoc (exact-path lookup too)", async () => {
381
+ for (const query of ["look up order", "tools.orders.lookup"]) {
382
+ const { items } = await search(query)
383
+ const item = items.find(({ path }) => path === "tools.orders.lookup")!
384
+ expect(item.signature).toBe(
385
+ [
386
+ "tools.orders.lookup(input: {",
387
+ " /** Order identifier */",
388
+ " id: string,",
389
+ " verbose?: boolean,",
390
+ "}): Promise<{",
391
+ " /** Current order status */",
392
+ " status: string,",
393
+ "}>",
394
+ ].join("\n"),
395
+ )
396
+ }
397
+ })
398
+
399
+ test("the inline catalog uses the same JSDoc signatures", async () => {
400
+ const instructions = runtime.instructions()
401
+ const github = (await search("list issues repository")).items.find(
402
+ ({ path }) => path === "tools.github.list_issues",
403
+ )!
404
+ const orders = (await search("look up order")).items.find(({ path }) => path === "tools.orders.lookup")!
405
+ expect(instructions).toContain(` - ${github.signature} // List issues in a repository`)
406
+ expect(instructions).toContain(` - ${orders.signature} // Look up an order`)
407
+ expect(instructions).toContain("/** Repository owner */")
408
+ })
409
+ })
410
+
411
+ describe("non-identifier tool paths", () => {
412
+ const resolveLibrary = Tool.make({
413
+ description: "Resolve a Context7 library ID",
414
+ input: {
415
+ type: "object",
416
+ properties: {
417
+ query: { type: "string" },
418
+ libraryName: { type: "string" },
419
+ },
420
+ required: ["query", "libraryName"],
421
+ } as const,
422
+ run: () => Effect.succeed("/reactjs/react.dev"),
423
+ })
424
+ const runtime = CodeMode.make({ tools: { context7: { "resolve-library-id": resolveLibrary } } })
425
+
426
+ test("inline catalog uses bracket notation for dashed tool names", () => {
427
+ const instructions = runtime.instructions()
428
+
429
+ expect(instructions).toContain(
430
+ 'tools.context7["resolve-library-id"](input: {\n query: string,\n libraryName: string,\n}): Promise<unknown>',
431
+ )
432
+ expect(instructions).toContain("Do not infer or normalize tool names")
433
+ expect(instructions).toContain("bracket notation and quotes are part of the path")
434
+ expect(instructions).not.toContain("tools.context7.resolve-library-id")
435
+ expect(instructions).not.toContain("tools.context7.resolve_library_id")
436
+ })
437
+
438
+ test("search results return callable bracket-notation paths and signatures", async () => {
439
+ const result = await Effect.runPromise(
440
+ runtime.execute(`return await tools.$codemode.search({ query: "resolve library" })`),
441
+ )
442
+ expect(result.ok).toBe(true)
443
+ if (!result.ok) throw new Error("search failed")
444
+
445
+ const value = result.value as { items: Array<{ path: string; signature: string }> }
446
+ expect(value.items[0]?.path).toBe('tools.context7["resolve-library-id"]')
447
+ expect(value.items[0]?.signature).toContain('tools.context7["resolve-library-id"](input: {')
448
+ })
449
+ })