enumeration.test.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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 supplied tools), 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. execute: ({ 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(
  35. await value(`
  36. const namespaces = Object.keys(tools)
  37. return { namespaces, count: namespaces.length }
  38. `),
  39. ).toEqual({ namespaces: ["github", "memory", "playwright"], count: 3 })
  40. })
  41. test("enumerates tool names at a nested namespace", async () => {
  42. expect(await value(`return Object.keys(tools.github)`)).toEqual(["list_issues", "get_issue"])
  43. })
  44. test("a callable tool is a leaf and enumerates as []", async () => {
  45. expect(await value(`return Object.keys(tools.github.list_issues)`)).toEqual([])
  46. })
  47. test("search is a global built-in function", async () => {
  48. expect(await value(`return typeof search`)).toBe("function")
  49. })
  50. test("an unknown namespace is an UnknownTool error", async () => {
  51. const failure = await error(`return Object.keys(tools.nonexistent)`)
  52. expect(failure.kind).toBe("UnknownTool")
  53. expect(failure.message).toContain("Unknown tool namespace 'nonexistent'")
  54. })
  55. test("Object.values/entries on a tool reference explain the working idioms", async () => {
  56. for (const method of ["values", "entries"] as const) {
  57. const failure = await error(`return Object.${method}(tools)`)
  58. expect(failure.kind).toBe("InvalidDataValue")
  59. expect(failure.message).toContain(
  60. `Object.${method}(...) cannot read tool references: they are not plain data. Use Object.keys(tools) for names, or search({ query }) for signatures.`,
  61. )
  62. }
  63. const nested = await error(`return Object.entries(tools.github)`)
  64. expect(nested.message).toContain("Use Object.keys(tools) for names")
  65. })
  66. })
  67. describe("Object.keys over arrays", () => {
  68. test("returns index strings, like JS", async () => {
  69. expect(await value(`return Object.keys(["a", "b", "c"])`)).toEqual(["0", "1", "2"])
  70. expect(await value(`return Object.keys([])`)).toEqual([])
  71. })
  72. test("objects keep their own enumerable keys", async () => {
  73. expect(await value(`return Object.keys({ a: 1, b: 2 })`)).toEqual(["a", "b"])
  74. })
  75. test("non-object inputs still fail clearly", async () => {
  76. const failure = await error(`return Object.keys("nope")`)
  77. expect(failure.message).toContain("Object.keys expects a data object or array")
  78. })
  79. })
  80. describe("for...in", () => {
  81. test("iterates own enumerable keys of a plain object with break/continue", async () => {
  82. expect(
  83. await value(`
  84. const seen = []
  85. for (const key in { a: 1, b: 2, c: 3, d: 4 }) {
  86. if (key === "b") continue
  87. if (key === "d") break
  88. seen.push(key)
  89. }
  90. return seen
  91. `),
  92. ).toEqual(["a", "c"])
  93. })
  94. test("iterates index strings over arrays", async () => {
  95. expect(
  96. await value(`
  97. const indexes = []
  98. for (const i in ["x", "y", "z"]) {
  99. if (i === "2") break
  100. indexes.push(i)
  101. }
  102. return indexes
  103. `),
  104. ).toEqual(["0", "1"])
  105. })
  106. test("supports let declarations and bare identifiers", async () => {
  107. expect(
  108. await value(`
  109. let last = ""
  110. for (let key in { a: 1, b: 2 }) last = key
  111. return last
  112. `),
  113. ).toBe("b")
  114. expect(
  115. await value(`
  116. let key = "before"
  117. for (key in { only: 1 }) {}
  118. return key
  119. `),
  120. ).toBe("only")
  121. })
  122. test("enumerates namespaces and tools from the supplied tools", async () => {
  123. expect(
  124. await value(`
  125. const names = []
  126. for (const ns in tools) {
  127. for (const name in tools[ns]) names.push(ns + "." + name)
  128. }
  129. return names
  130. `),
  131. ).toEqual(["github.list_issues", "github.get_issue", "memory.search", "playwright.navigate"])
  132. })
  133. test("unsupported values fail with a hint at for...of and Object.keys", async () => {
  134. for (const expression of [`"text"`, "new Map([[1, 2]])", "new Set([1])", "42", "null"]) {
  135. const failure = await error(`for (const key in ${expression}) {}; return "no"`)
  136. expect(failure.message).toContain("for...in requires a plain object, array, or tools reference")
  137. expect(failure.message).toContain("Use for...of for arrays/strings/Maps/Sets, or Object.keys(value)")
  138. }
  139. })
  140. })