enumeration.test.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import { describe, expect, test } from "bun:test"
  2. import { Effect, Schema } from "effect"
  3. import { CodeMode, Tool } from "../src/index.js"
  4. // Key enumeration: Object.keys and for...in share one surface over plain objects, arrays
  5. // (index strings), and tool references (namespace/tool names from the host tool tree), so a
  6. // model can discover what it may call instead of guessing names from the instructions. The
  7. // motivating transcript: `Object.keys(tools)` failed with the generic plain-objects-only
  8. // message and `for (const key in tools)` was unsupported syntax, forcing blind guesses.
  9. const echo = (description: string) =>
  10. Tool.make({
  11. description,
  12. input: Schema.Struct({ value: Schema.String }),
  13. output: Schema.String,
  14. run: ({ value }) => Effect.succeed(value),
  15. })
  16. const tools = {
  17. github: { list_issues: echo("List issues"), get_issue: echo("Get one issue") },
  18. memory: { search: echo("Search memory") },
  19. playwright: { navigate: echo("Navigate somewhere") },
  20. }
  21. const run = (code: string) => Effect.runPromise(CodeMode.execute({ tools, code }))
  22. const value = async (code: string) => {
  23. const result = await run(code)
  24. if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`)
  25. return result.value
  26. }
  27. const error = async (code: string) => {
  28. const result = await run(code)
  29. if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`)
  30. return result.error
  31. }
  32. describe("Object.keys over tool references", () => {
  33. test("enumerates top-level namespaces (the transcript program)", async () => {
  34. expect(await value(`
  35. const namespaces = Object.keys(tools)
  36. return { namespaces, count: namespaces.length }
  37. `)).toEqual({ namespaces: ["github", "memory", "playwright"], count: 3 })
  38. })
  39. test("enumerates tool names at a nested namespace", async () => {
  40. expect(await value(`return Object.keys(tools.github)`)).toEqual(["list_issues", "get_issue"])
  41. })
  42. test("a callable tool is a leaf and enumerates as []", async () => {
  43. expect(await value(`return Object.keys(tools.github.list_issues)`)).toEqual([])
  44. })
  45. test("the virtual discovery namespace enumerates its callable surface", async () => {
  46. expect(await value(`return Object.keys(tools.$codemode)`)).toEqual(["search"])
  47. })
  48. test("an unknown namespace is an UnknownTool error pointing at the discovery idioms", async () => {
  49. const failure = await error(`return Object.keys(tools.nonexistent)`)
  50. expect(failure.kind).toBe("UnknownTool")
  51. expect(failure.message).toContain("Unknown tool namespace 'nonexistent'")
  52. expect(failure.suggestions?.join(" ")).toContain("Object.keys(tools)")
  53. })
  54. test("Object.values/entries on a tool reference explain the working idioms", async () => {
  55. for (const method of ["values", "entries"] as const) {
  56. const failure = await error(`return Object.${method}(tools)`)
  57. expect(failure.kind).toBe("InvalidDataValue")
  58. expect(failure.message).toContain(
  59. `Object.${method}(...) cannot read tool references: they are not plain data. Use Object.keys(tools) for names, or tools.$codemode.search({ query }) for signatures.`,
  60. )
  61. }
  62. const nested = await error(`return Object.entries(tools.github)`)
  63. expect(nested.message).toContain("Use Object.keys(tools) for names")
  64. })
  65. })
  66. describe("Object.keys over arrays", () => {
  67. test("returns index strings, like JS", async () => {
  68. expect(await value(`return Object.keys(["a", "b", "c"])`)).toEqual(["0", "1", "2"])
  69. expect(await value(`return Object.keys([])`)).toEqual([])
  70. })
  71. test("objects keep their own enumerable keys", async () => {
  72. expect(await value(`return Object.keys({ a: 1, b: 2 })`)).toEqual(["a", "b"])
  73. })
  74. test("non-object inputs still fail clearly", async () => {
  75. const failure = await error(`return Object.keys("nope")`)
  76. expect(failure.message).toContain("Object.keys expects a data object or array")
  77. })
  78. })
  79. describe("for...in", () => {
  80. test("iterates own enumerable keys of a plain object with break/continue", async () => {
  81. expect(await value(`
  82. const seen = []
  83. for (const key in { a: 1, b: 2, c: 3, d: 4 }) {
  84. if (key === "b") continue
  85. if (key === "d") break
  86. seen.push(key)
  87. }
  88. return seen
  89. `)).toEqual(["a", "c"])
  90. })
  91. test("iterates index strings over arrays", async () => {
  92. expect(await value(`
  93. const indexes = []
  94. for (const i in ["x", "y", "z"]) {
  95. if (i === "2") break
  96. indexes.push(i)
  97. }
  98. return indexes
  99. `)).toEqual(["0", "1"])
  100. })
  101. test("supports let declarations and bare identifiers", async () => {
  102. expect(await value(`
  103. let last = ""
  104. for (let key in { a: 1, b: 2 }) last = key
  105. return last
  106. `)).toBe("b")
  107. expect(await value(`
  108. let key = "before"
  109. for (key in { only: 1 }) {}
  110. return key
  111. `)).toBe("only")
  112. })
  113. test("enumerates namespaces and tools from the host tool tree", async () => {
  114. expect(await value(`
  115. const names = []
  116. for (const ns in tools) {
  117. for (const name in tools[ns]) names.push(ns + "." + name)
  118. }
  119. return names
  120. `)).toEqual(["github.list_issues", "github.get_issue", "memory.search", "playwright.navigate"])
  121. })
  122. test("unsupported values fail with a hint at for...of and Object.keys", async () => {
  123. for (const expression of [`"text"`, "new Map([[1, 2]])", "new Set([1])", "42", "null"]) {
  124. const failure = await error(`for (const key in ${expression}) {}; return "no"`)
  125. expect(failure.message).toContain("for...in requires a plain object, array, or tools reference")
  126. expect(failure.message).toContain("Use for...of for arrays/strings/Maps/Sets, or Object.keys(value)")
  127. }
  128. })
  129. })