strict-tool-schema.test.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. // ============================================================
  2. // Anthropic strict 工具 schema:资格判定 + 子集折叠
  3. // ============================================================
  4. import { describe, expect, it } from "vitest";
  5. import type { ModelToolContract } from "@zcode/contracts";
  6. import { toAiSdkTools } from "../src/model/index.js";
  7. import { isAnthropicFirstPartyModelId, toStrictToolSchema } from "../src/model/strict-tool-schema.js";
  8. /** dwf 合成器会发射的一份典型 mono 子代理 schema(外层 `{ result }` 由 contracts 包起来)。 */
  9. const REVIEW_SCHEMA = {
  10. type: "object",
  11. properties: {
  12. result: {
  13. type: "object",
  14. description: "The structured result for this ask.",
  15. properties: {
  16. findings: {
  17. type: "array",
  18. items: {
  19. type: "object",
  20. properties: {
  21. file: { type: "string", description: "Where it is." },
  22. line: { type: "number", minimum: 1 },
  23. severity: { enum: ["low", "high"] },
  24. evidence: { type: "string", minLength: 3, maxLength: 200 },
  25. },
  26. required: ["file", "line", "severity"],
  27. additionalProperties: false,
  28. },
  29. },
  30. adequate: { type: "boolean" },
  31. notes: { anyOf: [{ type: "null" }, { type: "string", pattern: "^[a-z]+$" }] },
  32. when: { type: "string", format: "date-time" },
  33. slug: { type: "string", format: "kebab-case" },
  34. },
  35. required: ["findings", "adequate", "notes"],
  36. additionalProperties: false,
  37. },
  38. },
  39. required: ["result"],
  40. additionalProperties: false,
  41. };
  42. function submitContract(inputSchema: Record<string, unknown>, strict = true): ModelToolContract {
  43. return {
  44. name: "submit_result",
  45. capability: "submit",
  46. description: "Submit the structured result for the current ask.",
  47. inputSchema,
  48. outputSchema: { type: "object" },
  49. ...(strict ? { strict: true } : {}),
  50. };
  51. }
  52. function schemaOf(toolValue: unknown): Record<string, unknown> {
  53. return (toolValue as { inputSchema: { jsonSchema: Record<string, unknown> } }).inputSchema
  54. .jsonSchema;
  55. }
  56. function at(schema: Record<string, unknown>, path: string[]): Record<string, unknown> {
  57. let node: Record<string, unknown> = schema;
  58. for (const segment of path) node = node[segment] as Record<string, unknown>;
  59. return node;
  60. }
  61. describe("toStrictToolSchema — folding", () => {
  62. it("removes the keywords strict cannot take and folds them into descriptions", () => {
  63. const strict = toStrictToolSchema(REVIEW_SCHEMA);
  64. expect(strict).toBeDefined();
  65. const finding = at(strict!, [
  66. "properties",
  67. "result",
  68. "properties",
  69. "findings",
  70. "items",
  71. "properties",
  72. ]);
  73. expect(finding.line).toEqual({ type: "number", description: "minimum 1" });
  74. expect(finding.evidence).toEqual({
  75. type: "string",
  76. description: "at least 3 characters; at most 200 characters",
  77. });
  78. // 既有 description 保留在前,折叠的约束跟在括号里。
  79. expect(finding.file).toEqual({ type: "string", description: "Where it is." });
  80. const result = at(strict!, ["properties", "result", "properties"]);
  81. expect((result.notes as { anyOf: unknown[] }).anyOf[1]).toEqual({
  82. type: "string",
  83. description: "must match /^[a-z]+$/",
  84. });
  85. // strict 认识的 format 保留;不认识的折进 description。
  86. expect(result.when).toEqual({ type: "string", format: "date-time" });
  87. expect(result.slug).toEqual({ type: "string", description: "format kebab-case" });
  88. });
  89. it("leaves an already-strict schema byte-identical and never mutates its input", () => {
  90. const input = {
  91. type: "object",
  92. properties: { ok: { type: "boolean" }, tags: { type: "array", items: { enum: ["a", "b"] } } },
  93. required: ["ok"],
  94. additionalProperties: false,
  95. };
  96. const snapshot = JSON.stringify(input);
  97. expect(toStrictToolSchema(input)).toEqual(input);
  98. expect(JSON.stringify(input)).toBe(snapshot);
  99. });
  100. it("closes objects that forgot additionalProperties and gives them an empty properties map", () => {
  101. expect(toStrictToolSchema({ type: "object", required: [] })).toEqual({
  102. type: "object",
  103. required: [],
  104. properties: {},
  105. additionalProperties: false,
  106. });
  107. });
  108. it("appends folded constraints to an existing description in parentheses", () => {
  109. expect(
  110. toStrictToolSchema({ type: "integer", description: "Age.", minimum: 0, maximum: 150 }),
  111. ).toEqual({
  112. type: "integer",
  113. description: "Age. (minimum 0; maximum 150)",
  114. });
  115. });
  116. });
  117. describe("toStrictToolSchema — ineligible shapes", () => {
  118. it.each([
  119. ["Record<string, T>", { type: "object", additionalProperties: { type: "string" } }],
  120. [
  121. "unknown ({})",
  122. { type: "object", properties: { any: {} }, required: ["any"], additionalProperties: false },
  123. ],
  124. [
  125. "recursive $ref",
  126. { type: "object", properties: { next: { $ref: "#/$defs/Node" } }, $defs: { Node: {} } },
  127. ],
  128. ["tuple", { type: "array", prefixItems: [{ type: "string" }], minItems: 1, maxItems: 1 }],
  129. [
  130. "nested Record inside anyOf",
  131. { anyOf: [{ type: "null" }, { type: "object", additionalProperties: { type: "number" } }] },
  132. ],
  133. ])("returns undefined for %s", (_label, schema) => {
  134. expect(toStrictToolSchema(schema as Record<string, unknown>)).toBeUndefined();
  135. });
  136. });
  137. describe("isAnthropicFirstPartyModelId", () => {
  138. it.each(["claude-opus-5", "claude-fable-5-1", "claude-sonnet-4-6"])("accepts %s", (id) => {
  139. expect(isAnthropicFirstPartyModelId(id)).toBe(true);
  140. });
  141. it.each(["glm-5.3", "gpt-5", "anthropic/claude-opus-5", undefined])("rejects %s", (id) => {
  142. expect(isAnthropicFirstPartyModelId(id)).toBe(false);
  143. });
  144. });
  145. describe("toAiSdkTools — strict forwarding", () => {
  146. it("forwards strict with the folded schema for an eligible contract on a first-party Claude model", () => {
  147. const tools = toAiSdkTools([submitContract(REVIEW_SCHEMA)], {
  148. providerKind: "anthropic",
  149. modelId: "claude-opus-5",
  150. });
  151. const tool = tools?.submit_result as { strict?: boolean } | undefined;
  152. expect(tool?.strict).toBe(true);
  153. const line = at(schemaOf(tool), [
  154. "properties",
  155. "result",
  156. "properties",
  157. "findings",
  158. "items",
  159. "properties",
  160. "line",
  161. ]);
  162. expect(line).toEqual({ type: "number", description: "minimum 1" });
  163. });
  164. it("sends the original schema without strict when the model is not first-party Claude", () => {
  165. const tools = toAiSdkTools([submitContract(REVIEW_SCHEMA)], {
  166. providerKind: "anthropic",
  167. modelId: "glm-5.3",
  168. });
  169. const tool = tools?.submit_result as { strict?: boolean } | undefined;
  170. expect(tool?.strict).toBeUndefined();
  171. expect(schemaOf(tool)).toEqual(REVIEW_SCHEMA);
  172. });
  173. it("sends the original schema without strict on non-Anthropic providers", () => {
  174. const tools = toAiSdkTools([submitContract(REVIEW_SCHEMA)], {
  175. providerKind: "openai-compatible",
  176. modelId: "claude-opus-5",
  177. });
  178. const tool = tools?.submit_result as { strict?: boolean } | undefined;
  179. expect(tool?.strict).toBeUndefined();
  180. expect(schemaOf(tool)).toEqual(REVIEW_SCHEMA);
  181. });
  182. it("ignores strict for a contract that never declared eligibility", () => {
  183. const tools = toAiSdkTools([submitContract(REVIEW_SCHEMA, false)], {
  184. providerKind: "anthropic",
  185. modelId: "claude-opus-5",
  186. });
  187. expect((tools?.submit_result as { strict?: boolean } | undefined)?.strict).toBeUndefined();
  188. });
  189. it("falls back to the full schema without strict when the shape is not expressible", () => {
  190. const recordSchema = {
  191. type: "object",
  192. properties: { result: { type: "object", additionalProperties: { type: "string" } } },
  193. required: ["result"],
  194. additionalProperties: false,
  195. };
  196. const tools = toAiSdkTools([submitContract(recordSchema)], {
  197. providerKind: "anthropic",
  198. modelId: "claude-opus-5",
  199. });
  200. const tool = tools?.submit_result as { strict?: boolean } | undefined;
  201. expect(tool?.strict).toBeUndefined();
  202. expect(schemaOf(tool)).toEqual(recordSchema);
  203. });
  204. });