@fluidframework/tree-agent 2.63.0-359461 → 2.63.0-359962

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.
Files changed (63) hide show
  1. package/api-report/tree-agent.alpha.api.md +3 -24
  2. package/dist/agent.d.ts +0 -3
  3. package/dist/agent.d.ts.map +1 -1
  4. package/dist/agent.js +21 -49
  5. package/dist/agent.js.map +1 -1
  6. package/dist/alpha.d.ts +0 -2
  7. package/dist/api.d.ts +19 -7
  8. package/dist/api.d.ts.map +1 -1
  9. package/dist/api.js.map +1 -1
  10. package/dist/index.d.ts +0 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -4
  13. package/dist/index.js.map +1 -1
  14. package/dist/prompt.d.ts.map +1 -1
  15. package/dist/prompt.js +15 -17
  16. package/dist/prompt.js.map +1 -1
  17. package/dist/utils.d.ts +4 -0
  18. package/dist/utils.d.ts.map +1 -1
  19. package/dist/utils.js +16 -1
  20. package/dist/utils.js.map +1 -1
  21. package/lib/agent.d.ts +0 -3
  22. package/lib/agent.d.ts.map +1 -1
  23. package/lib/agent.js +22 -50
  24. package/lib/agent.js.map +1 -1
  25. package/lib/alpha.d.ts +0 -2
  26. package/lib/api.d.ts +19 -7
  27. package/lib/api.d.ts.map +1 -1
  28. package/lib/api.js.map +1 -1
  29. package/lib/index.d.ts +0 -1
  30. package/lib/index.d.ts.map +1 -1
  31. package/lib/index.js +0 -1
  32. package/lib/index.js.map +1 -1
  33. package/lib/prompt.d.ts.map +1 -1
  34. package/lib/prompt.js +15 -17
  35. package/lib/prompt.js.map +1 -1
  36. package/lib/utils.d.ts +4 -0
  37. package/lib/utils.d.ts.map +1 -1
  38. package/lib/utils.js +14 -0
  39. package/lib/utils.js.map +1 -1
  40. package/package.json +11 -12
  41. package/src/agent.ts +29 -61
  42. package/src/api.ts +20 -12
  43. package/src/index.ts +0 -1
  44. package/src/prompt.ts +15 -17
  45. package/src/utils.ts +14 -0
  46. package/dist/functionParsing.d.ts +0 -13
  47. package/dist/functionParsing.d.ts.map +0 -1
  48. package/dist/functionParsing.js +0 -215
  49. package/dist/functionParsing.js.map +0 -1
  50. package/dist/langchain.d.ts +0 -43
  51. package/dist/langchain.d.ts.map +0 -1
  52. package/dist/langchain.js +0 -90
  53. package/dist/langchain.js.map +0 -1
  54. package/lib/functionParsing.d.ts +0 -13
  55. package/lib/functionParsing.d.ts.map +0 -1
  56. package/lib/functionParsing.js +0 -210
  57. package/lib/functionParsing.js.map +0 -1
  58. package/lib/langchain.d.ts +0 -43
  59. package/lib/langchain.d.ts.map +0 -1
  60. package/lib/langchain.js +0 -84
  61. package/lib/langchain.js.map +0 -1
  62. package/src/functionParsing.ts +0 -268
  63. package/src/langchain.ts +0 -146
@@ -1 +1 @@
1
- {"version":3,"file":"prompt.js","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+CAAgE;AAGhE,sDAA6D;AAC7D,4DAAqE;AAGrE,2DAAiE;AACjE,yCAOoB;AAEpB;;GAEG;AACH,SAAgB,SAAS,CAAoC,IAI5D;IACA,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IACpD,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAClC,MAAM,kBAAkB,GAAG,WAAW,CAAC;IACvC,MAAM,gBAAgB,GAAG,SAAS,CAAC;IACnC,MAAM,YAAY,GAAG,IAAA,uBAAe,EAAC,MAAM,CAAC,CAAC;IAC7C,6IAA6I;IAC7I,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,IAAI,iBAAqC,CAAC;IAC1C,KAAK,MAAM,CAAC,UAAU,EAAE,UAAU,CAAC,IAAI,YAAY,CAAC,WAAW,EAAE,CAAC;QACjE,QAAQ,UAAU,CAAC,IAAI,EAAE,CAAC;YACzB,KAAK,eAAQ,C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CAAC,IAAI,MAAM,CAAC,IAAI,mBAAmB,IAAI,EAAE,GAAG,CAAC,EAAE,WAAW,CAAC;SAClE,OAAO,CACP,IAAI,MAAM,CAAC,IAAI,iBAAiB,OAAO,EAAE,GAAG,CAAC,EAC7C,4HAA4H,CAC5H,CAAC;AACJ,CAAC;AA9CD,sCA8CC;AAED;;;;GAIG;AACH,SAAS,6BAA6B,CAAC,QAAgB;IACtD,OAAO;mBACW,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qEA0E0C,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAiDhE,QAAQ;;EAEnB,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,SAAS,2BAA2B,CAAC,QAAgB;IACpD,OAAO;;;mBAGW,QAAQ;;;;;;;;kFAQuD,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyDxF,CAAC;AACH,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { NodeKind, Tree, TreeNode } from \"@fluidframework/tree\";\nimport type { ImplicitFieldSchema, TreeMapNode } from \"@fluidframework/tree\";\nimport type { ReadableField } from \"@fluidframework/tree/alpha\";\nimport { getSimpleSchema } from \"@fluidframework/tree/alpha\";\nimport { normalizeFieldSchema } from \"@fluidframework/tree/internal\";\n\nimport type { Subtree } from \"./subtree.js\";\nimport { generateEditTypesForPrompt } from \"./typeGeneration.js\";\nimport {\n\tgetFriendlyName,\n\tgetZodSchemaAsTypeScript,\n\tisNamedSchema,\n\tcommunize,\n\tunqualifySchema,\n\ttype SchemaDetails,\n} from \"./utils.js\";\n\n/**\n * Produces a \"system\" prompt for the tree agent, based on the provided subtree.\n */\nexport function getPrompt<TRoot extends ImplicitFieldSchema>(args: {\n\tsubtree: Subtree<TRoot>;\n\teditToolName: string | undefined;\n\tdomainHints?: string;\n}): string {\n\tconst { subtree, editToolName, domainHints } = args;\n\tconst { field, schema } = subtree;\n\tconst arrayInterfaceName = \"TreeArray\";\n\tconst mapInterfaceName = \"TreeMap\";\n\tconst simpleSchema = getSimpleSchema(schema);\n\t// Inspect the schema to determine what kinds of nodes are possible - this will affect how much information we need to include in the prompt.\n\tlet hasArrays = false;\n\tlet hasMaps = false;\n\tlet exampleObjectName: string | undefined;\n\tfor (const [definition, nodeSchema] of simpleSchema.definitions) {\n\t\tswitch (nodeSchema.kind) {\n\t\t\tcase NodeKind.Array: {\n\t\t\t\thasArrays = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Map: {\n\t\t\t\thasMaps = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Object: {\n\t\t\t\texampleObjectName ??= unqualifySchema(definition);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tconst { domainTypes } = generateEditTypesForPrompt(schema, simpleSchema);\n\tfor (const [key, value] of Object.entries(domainTypes)) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n\t\tdelete domainTypes[key];\n\t\tif (isNamedSchema(key)) {\n\t\t\tconst friendlyKey = unqualifySchema(key);\n\t\t\tdomainTypes[friendlyKey] = value;\n\t\t}\n\t}\n\n\tconst stringified = stringifyTree(field);\n\tconst details: SchemaDetails = { hasHelperMethods: false };\n\tconst typescriptSchemaTypes = getZodSchemaAsTypeScript(domainTypes, details);\n\tconst helperMethodExplanation = details.hasHelperMethods\n\t\t? `Manipulating the data using the APIs described below is allowed, but when possible ALWAYS prefer to use the application helper methods exposed on the schema TypeScript types if the goal can be accomplished that way.\nIt will often not be possible to fully accomplish the goal using those helpers. When this is the case, mutate the objects as normal, taking into account the following guidance.`\n\t\t: \"\";\n\n\tconst builderExplanation =\n\t\texampleObjectName === undefined\n\t\t\t? \"\"\n\t\t\t: `When constructing new objects, you should wrap them in the appropriate builder function rather than simply making a javascript object.\nThe builders are available on the \"create\" property on the first argument of the edit function and are named according to the type that they create.\nFor example:\n\n\\`\\`\\`javascript\nfunction editTree({ root, create }) {\n\t// This creates a new ${exampleObjectName} object:\n\tconst ${communize(exampleObjectName)} = create.${exampleObjectName}({ /* ...properties... */ });\n\t// Don't do this:\n\t// const ${communize(exampleObjectName)} = { /* ...properties... */ };\n}\n\\`\\`\\`\\n\\n`;\n\n\tconst arrayEditing = `#### Editing Arrays\n\nThe arrays in the tree are somewhat different than normal JavaScript \\`Array\\`s.\nRead-only operations are generally the same - you can create them, read via index, and call non-mutating methods like \\`concat\\`, \\`map\\`, \\`filter\\`, \\`find\\`, \\`forEach\\`, \\`indexOf\\`, \\`slice\\`, \\`join\\`, etc.\nHowever, write operations (e.g. index assignment, \\`push\\`, \\`pop\\`, \\`splice\\`, etc.) are not supported.\nInstead, you must use the methods on the following interface to mutate the array:\n\n\\`\\`\\`typescript\n${getTreeArrayNodeDocumentation(arrayInterfaceName)}\n\\`\\`\\`\n\nWhen possible, ensure that the edits preserve the identity of objects already in the tree.\nFor example, prefer \\`array.moveToIndex\\` over \\`array.removeAt\\` + \\`array.insertAt\\` and prefer \\`array.moveRangeToIndex\\` over \\`array.removeRange\\` + \\`array.insertAt\\`.\n\n`;\n\n\tconst mapEditing = `#### Editing Maps\n\nThe maps in the tree are somewhat different than normal JavaScript \\`Map\\`s.\nMap keys are always strings.\nRead-only operations are generally the same - you can create them, read via \\`get\\`, and call non-mutating methods like \\`has\\`, \\`forEach\\`, \\`entries\\`, \\`keys\\`, \\`values\\`, etc. (note the subtle differences around return values and iteration order).\nHowever, write operations (e.g. \\`set\\`, \\`delete\\`, etc.) are not supported.\nInstead, you must use the methods on the following interface to mutate the map:\n\n\\`\\`\\`typescript\n${getTreeMapNodeDocumentation(mapInterfaceName)}\n\\`\\`\\`\n\n`;\n\n\tconst rootTypes = normalizeFieldSchema(schema).allowedTypeSet;\n\tconst editing = `If the user asks you to edit the tree, you should author a JavaScript function to accomplish the user-specified goal, following the instructions for editing detailed below.\nYou must use the \"${editToolName}\" tool to perform the edit.\nAfter editing the tree, review the latest state of the tree to see if it satisfies the user's request.\nIf it does not, or if you receive an error, you may try again with a different approach.\nOnce the tree is in the desired state, you should inform the user that the request has been completed.\n\n### Editing\n\nIf the user asks you to edit the document, you will write a JavaScript function that mutates the data in-place to achieve the user's goal.\nThe edit function may be synchronous or asynchronous.\nThe edit function must have a first parameter which has a \\`root\\` property.\nThis \\`root\\` property holds the current state of the tree as shown above.\nYou may mutate any part of the tree as necessary, taking into account the caveats around arrays and maps detailed below.\nYou may also set the \\`root\\` property to be an entirely new value as long as it is one of the types allowed at the root of the tree (\\`${Array.from(rootTypes.values(), (t) => getFriendlyName(t)).join(\" | \")}\\`).\n${helperMethodExplanation}\n\n${hasArrays ? arrayEditing : \"\"}${hasMaps ? mapEditing : \"\"}#### Additional Notes\n\nBefore outputting the edit function, you should check that it is valid according to both the application tree's schema and any restrictions of the editing APIs described above.\n\nOnce data has been removed from the tree (e.g. replaced via assignment, or removed from an array), that data cannot be re-inserted into the tree - instead, it must be deep cloned and recreated.\n\n${builderExplanation}Finally, double check that the edits would accomplish the user's request (if it is possible).\n\n`;\n\n\tconst prompt = `You are a helpful assistant collaborating with the user on a document. The document state is a JSON tree, and you are able to analyze and edit it.\nThe JSON tree adheres to the following Typescript schema:\n\n\\`\\`\\`typescript\n${typescriptSchemaTypes}\n\\`\\`\\`\n\nIf the user asks you a question about the tree, you should inspect the state of the tree and answer the question.\nWhen answering such a question, DO NOT answer with information that is not part of the document unless requested to do so.\n\n${editToolName === undefined ? \"\" : editing}### Application data\n\n${\n\tdomainHints === undefined\n\t\t? \"\"\n\t\t: `\\nThe application supplied the following additional instructions: ${domainHints}`\n}\nThe current state of the application tree (a \\`${field === undefined ? \"undefined\" : getFriendlyName(Tree.schema(field))}\\`) is:\n\n\\`\\`\\`JSON\n${stringified}\n\\`\\`\\``;\n\treturn prompt;\n}\n\n/**\n * Serializes tree data e.g. to include in a prompt or message.\n * @remarks This includes some extra metadata to make it easier to understand the structure of the tree.\n */\nexport function stringifyTree(tree: ReadableField<ImplicitFieldSchema>): string {\n\tconst typeReplacementKey = \"_e944da5a5fd04ea2b8b2eb6109e089ed\";\n\tconst indexReplacementKey = \"_27bb216b474d45e6aaee14d1ec267b96\";\n\tconst mapReplacementKey = \"_a0d98d22a1c644539f07828d3f064d71\";\n\tconst stringified = JSON.stringify(\n\t\ttree,\n\t\t(_, node: unknown) => {\n\t\t\tif (node instanceof TreeNode) {\n\t\t\t\tconst key = Tree.key(node);\n\t\t\t\tconst index = typeof key === \"number\" ? key : undefined;\n\t\t\t\tconst schema = Tree.schema(node);\n\t\t\t\tswitch (schema.kind) {\n\t\t\t\t\tcase NodeKind.Object: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[typeReplacementKey]: getFriendlyName(schema),\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t...node,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tcase NodeKind.Map: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t[mapReplacementKey]: \"\",\n\t\t\t\t\t\t\t...Object.fromEntries(node as TreeMapNode),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t...node,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn node;\n\t\t},\n\t\t2,\n\t);\n\n\treturn stringified\n\t\t.replace(new RegExp(`\"${typeReplacementKey}\":`, \"g\"), `// Type:`)\n\t\t.replace(new RegExp(`\"${indexReplacementKey}\":`, \"g\"), `// Index:`)\n\t\t.replace(\n\t\t\tnew RegExp(`\"${mapReplacementKey}\": \"\"`, \"g\"),\n\t\t\t`// Note: This is a map that has been serialized to JSON. It is not a key-value object/record but is being printed as such.`,\n\t\t);\n}\n\n/**\n * Retrieves the documentation for the `TreeArrayNode` interface to feed to the LLM.\n * @remarks The documentation has been simplified in various ways to make it easier for the LLM to understand.\n * @privateRemarks TODO: How do we keep this in sync with the actual `TreeArrayNode` docs if/when those docs change?\n */\nfunction getTreeArrayNodeDocumentation(typeName: string): string {\n\treturn `/** A special type of array which implements 'readonly T[]' (i.e. it supports all read-only JS array methods) and provides custom array mutation APIs. */\nexport interface ${typeName}<T> extends ReadonlyArray<T> {\n\t/**\n\t * Inserts new item(s) at a specified location.\n\t * @param index - The index at which to insert \\`value\\`.\n\t * @param value - The content to insert.\n\t * @throws Throws if \\`index\\` is not in the range [0, \\`array.length\\`).\n\t */\n\tinsertAt(index: number, ...value: readonly T[]): void;\n\n\t/**\n\t * Removes the item at the specified location.\n\t * @param index - The index at which to remove the item.\n\t * @throws Throws if \\`index\\` is not in the range [0, \\`array.length\\`).\n\t */\n\tremoveAt(index: number): void;\n\n\t/**\n\t * Removes all items between the specified indices.\n\t * @param start - The starting index of the range to remove (inclusive). Defaults to the start of the array.\n\t * @param end - The ending index of the range to remove (exclusive). Defaults to \\`array.length\\`.\n\t * @throws Throws if \\`start\\` is not in the range [0, \\`array.length\\`].\n\t * @throws Throws if \\`end\\` is less than \\`start\\`.\n\t * If \\`end\\` is not supplied or is greater than the length of the array, all items after \\`start\\` are removed.\n\t *\n\t * @remarks\n\t * The default values for start and end are computed when this is called,\n\t * and thus the behavior is the same as providing them explicitly, even with respect to merge resolution with concurrent edits.\n\t * For example, two concurrent transactions both emptying the array with \\`node.removeRange()\\` then inserting an item,\n\t * will merge to result in the array having both inserted items.\n\t */\n\tremoveRange(start?: number, end?: number): void;\n\n\t/**\n\t * Moves the specified item to the desired location in the array.\n\t *\n\t * WARNING - This API is easily misused.\n\t * Please read the documentation for the \\`destinationGap\\` parameter carefully.\n\t *\n\t * @param destinationGap - The location *between* existing items that the moved item should be moved to.\n\t *\n\t * WARNING - \\`destinationGap\\` describes a location between existing items *prior to applying the move operation*.\n\t *\n\t * For example, if the array contains items \\`[A, B, C]\\` before the move, the \\`destinationGap\\` must be one of the following:\n\t *\n\t * - \\`0\\` (between the start of the array and \\`A\\`'s original position)\n\t * - \\`1\\` (between \\`A\\`'s original position and \\`B\\`'s original position)\n\t * - \\`2\\` (between \\`B\\`'s original position and \\`C\\`'s original position)\n\t * - \\`3\\` (between \\`C\\`'s original position and the end of the array)\n\t *\n\t * So moving \\`A\\` between \\`B\\` and \\`C\\` would require \\`destinationGap\\` to be \\`2\\`.\n\t *\n\t * This interpretation of \\`destinationGap\\` makes it easy to specify the desired destination relative to a sibling item that is not being moved,\n\t * or relative to the start or end of the array:\n\t *\n\t * - Move to the start of the array: \\`array.moveToIndex(0, ...)\\` (see also \\`moveToStart\\`)\n\t * - Move to before some item X: \\`array.moveToIndex(indexOfX, ...)\\`\n\t * - Move to after some item X: \\`array.moveToIndex(indexOfX + 1\\`, ...)\n\t * - Move to the end of the array: \\`array.moveToIndex(array.length, ...)\\` (see also \\`moveToEnd\\`)\n\t *\n\t * This interpretation of \\`destinationGap\\` does however make it less obvious how to move an item relative to its current position:\n\t *\n\t * - Move item B before its predecessor: \\`array.moveToIndex(indexOfB - 1, ...)\\`\n\t * - Move item B after its successor: \\`array.moveToIndex(indexOfB + 2, ...)\\`\n\t *\n\t * Notice the asymmetry between \\`-1\\` and \\`+2\\` in the above examples.\n\t * In such scenarios, it can often be easier to approach such edits by swapping adjacent items:\n\t * If items A and B are adjacent, such that A precedes B,\n\t * then they can be swapped with \\`array.moveToIndex(indexOfA, indexOfB)\\`.\n\t *\n\t * @param sourceIndex - The index of the item to move.\n\t * @param source - The optional source array to move the item out of (defaults to this array).\n\t * @throws Throws if any of the source index is not in the range [0, \\`array.length\\`),\n\t * or if the index is not in the range [0, \\`array.length\\`].\n\t */\n\tmoveToIndex(destinationGap: number, sourceIndex: number, source?: ${typeName}<T>): void;\n\n\t/**\n\t * Moves the specified items to the desired location within the array.\n\t *\n\t * WARNING - This API is easily misused.\n\t * Please read the documentation for the \\`destinationGap\\` parameter carefully.\n\t *\n\t * @param destinationGap - The location *between* existing items that the moved item should be moved to.\n\t *\n\t * WARNING - \\`destinationGap\\` describes a location between existing items *prior to applying the move operation*.\n\t *\n\t * For example, if the array contains items \\`[A, B, C]\\` before the move, the \\`destinationGap\\` must be one of the following:\n\t *\n\t * - \\`0\\` (between the start of the array and \\`A\\`'s original position)\n\t * - \\`1\\` (between \\`A\\`'s original position and \\`B\\`'s original position)\n\t * - \\`2\\` (between \\`B\\`'s original position and \\`C\\`'s original position)\n\t * - \\`3\\` (between \\`C\\`'s original position and the end of the array)\n\t *\n\t * So moving \\`A\\` between \\`B\\` and \\`C\\` would require \\`destinationGap\\` to be \\`2\\`.\n\t *\n\t * This interpretation of \\`destinationGap\\` makes it easy to specify the desired destination relative to a sibling item that is not being moved,\n\t * or relative to the start or end of the array:\n\t *\n\t * - Move to the start of the array: \\`array.moveToIndex(0, ...)\\` (see also \\`moveToStart\\`)\n\t * - Move to before some item X: \\`array.moveToIndex(indexOfX, ...)\\`\n\t * - Move to after some item X: \\`array.moveToIndex(indexOfX + 1\\`, ...)\n\t * - Move to the end of the array: \\`array.moveToIndex(array.length, ...)\\` (see also \\`moveToEnd\\`)\n\t *\n\t * This interpretation of \\`destinationGap\\` does however make it less obvious how to move an item relative to its current position:\n\t *\n\t * - Move item B before its predecessor: \\`array.moveToIndex(indexOfB - 1, ...)\\`\n\t * - Move item B after its successor: \\`array.moveToIndex(indexOfB + 2, ...)\\`\n\t *\n\t * Notice the asymmetry between \\`-1\\` and \\`+2\\` in the above examples.\n\t * In such scenarios, it can often be easier to approach such edits by swapping adjacent items:\n\t * If items A and B are adjacent, such that A precedes B,\n\t * then they can be swapped with \\`array.moveToIndex(indexOfA, indexOfB)\\`.\n\t *\n\t * @param sourceStart - The starting index of the range to move (inclusive).\n\t * @param sourceEnd - The ending index of the range to move (exclusive)\n\t * @param source - The optional source array to move items out of (defaults to this array).\n\t * @throws Throws if the types of any of the items being moved are not allowed in the destination array,\n\t * if any of the input indices are not in the range [0, \\`array.length\\`], or if \\`sourceStart\\` is greater than \\`sourceEnd\\`.\n\t */\n\tmoveRangeToIndex(\n\t\tdestinationGap: number,\n\t\tsourceStart: number,\n\t\tsourceEnd: number,\n\t\tsource?: ${typeName}<T>,\n\t): void;\n}`;\n}\n\n/**\n * Retrieves the documentation for the `TreeMapNode` interface to feed to the LLM.\n * @remarks The documentation has been simplified in various ways to make it easier for the LLM to understand.\n * @privateRemarks TODO: How do we keep this in sync with the actual `TreeMapNode` docs if/when those docs change?\n */\nfunction getTreeMapNodeDocumentation(typeName: string): string {\n\treturn `/**\n * A map of string keys to tree objects.\n */\nexport interface ${typeName}<T> extends ReadonlyMap<string, T> {\n\t/**\n\t * Adds or updates an entry in the map with a specified \\`key\\` and a \\`value\\`.\n\t *\n\t * @param key - The key of the element to add to the map.\n\t * @param value - The value of the element to add to the map.\n\t *\n\t * @remarks\n\t * Setting the value at a key to \\`undefined\\` is equivalent to calling {@link ${typeName}.delete} with that key.\n\t */\n\tset(key: string, value: T | undefined): void;\n\n\t/**\n\t * Removes the specified element from this map by its \\`key\\`.\n\t *\n\t * @remarks\n\t * Note: unlike JavaScript's Map API, this method does not return a flag indicating whether or not the value was\n\t * deleted.\n\t *\n\t * @param key - The key of the element to remove from the map.\n\t */\n\tdelete(key: string): void;\n\n\t/**\n\t * Returns an iterable of keys in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the keys returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tkeys(): IterableIterator<string>;\n\n\t/**\n\t * Returns an iterable of values in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the values returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tvalues(): IterableIterator<T>;\n\n\t/**\n\t * Returns an iterable of key/value pairs for every entry in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the entries returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tentries(): IterableIterator<[string, T]>;\n\n\t/**\n\t * Executes the provided function once per each key/value pair in this map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order in which the function is called with respect to the map's entries.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tforEach(\n\t\tcallbackfn: (\n\t\t\tvalue: T,\n\t\t\tkey: string,\n\t\t\tmap: ReadonlyMap<string, T>,\n\t\t) => void,\n\t\tthisArg?: any,\n\t): void;\n}`;\n}\n"]}
1
+ {"version":3,"file":"prompt.js","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+CAAgE;AAGhE,sDAA6D;AAC7D,4DAAqE;AAGrE,2DAAiE;AACjE,yCAOoB;AAEpB;;GAEG;AACH,SAAgB,SAAS,CAAoC,IAI5D;IACA,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IACpD,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAClC,MAAM,kBAAkB,GAAG,WAAW,CAAC;IACvC,MAAM,gBAAgB,GAAG,SAAS,CAAC;IACnC,MAAM,YAAY,GAAG,IAAA,uBAAe,EAAC,MAAM,CAAC,CAAC;IAC7C,6IAA6I;IAC7I,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,IAAI,iBAAqC,CAAC;IAC1C,KAAK,MAAM,CAAC,UAAU,EAAE,UAAU,CAAC,IAAI,YAAY,CAAC,WAAW,EAAE,CAAC;QACjE,QAAQ,UAAU,CAAC,IAAI,EAAE,CAAC;YACzB,KAAK,eAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;gBACrB,SAAS,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CAAC,CACD,CAAC;IAEF,OAAO,WAAW;SAChB,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,kBAAkB,IAAI,EAAE,GAAG,CAAC,EAAE,UAAU,CAAC;SAChE,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,mBAAmB,IAAI,EAAE,GAAG,CAAC,EAAE,WAAW,CAAC;SAClE,OAAO,CACP,IAAI,MAAM,CAAC,IAAI,iBAAiB,OAAO,EAAE,GAAG,CAAC,EAC7C,4HAA4H,CAC5H,CAAC;AACJ,CAAC;AA9CD,sCA8CC;AAED;;;;GAIG;AACH,SAAS,6BAA6B,CAAC,QAAgB;IACtD,OAAO;mBACW,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qEA0E0C,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAiDhE,QAAQ;;EAEnB,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,SAAS,2BAA2B,CAAC,QAAgB;IACpD,OAAO;;;mBAGW,QAAQ;;;;;;;;kFAQuD,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyDxF,CAAC;AACH,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { NodeKind, Tree, TreeNode } from \"@fluidframework/tree\";\nimport type { ImplicitFieldSchema, TreeMapNode } from \"@fluidframework/tree\";\nimport type { ReadableField } from \"@fluidframework/tree/alpha\";\nimport { getSimpleSchema } from \"@fluidframework/tree/alpha\";\nimport { normalizeFieldSchema } from \"@fluidframework/tree/internal\";\n\nimport type { Subtree } from \"./subtree.js\";\nimport { generateEditTypesForPrompt } from \"./typeGeneration.js\";\nimport {\n\tgetFriendlyName,\n\tgetZodSchemaAsTypeScript,\n\tisNamedSchema,\n\tcommunize,\n\tunqualifySchema,\n\ttype SchemaDetails,\n} from \"./utils.js\";\n\n/**\n * Produces a \"system\" prompt for the tree agent, based on the provided subtree.\n */\nexport function getPrompt<TRoot extends ImplicitFieldSchema>(args: {\n\tsubtree: Subtree<TRoot>;\n\teditToolName: string | undefined;\n\tdomainHints?: string;\n}): string {\n\tconst { subtree, editToolName, domainHints } = args;\n\tconst { field, schema } = subtree;\n\tconst arrayInterfaceName = \"TreeArray\";\n\tconst mapInterfaceName = \"TreeMap\";\n\tconst simpleSchema = getSimpleSchema(schema);\n\t// Inspect the schema to determine what kinds of nodes are possible - this will affect how much information we need to include in the prompt.\n\tlet hasArrays = false;\n\tlet hasMaps = false;\n\tlet exampleObjectName: string | undefined;\n\tfor (const [definition, nodeSchema] of simpleSchema.definitions) {\n\t\tswitch (nodeSchema.kind) {\n\t\t\tcase NodeKind.Array: {\n\t\t\t\thasArrays = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Map: {\n\t\t\t\thasMaps = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Object: {\n\t\t\t\texampleObjectName ??= unqualifySchema(definition);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tconst { domainTypes } = generateEditTypesForPrompt(schema, simpleSchema);\n\tfor (const [key, value] of Object.entries(domainTypes)) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n\t\tdelete domainTypes[key];\n\t\tif (isNamedSchema(key)) {\n\t\t\tconst friendlyKey = unqualifySchema(key);\n\t\t\tdomainTypes[friendlyKey] = value;\n\t\t}\n\t}\n\n\tconst stringified = stringifyTree(field);\n\tconst details: SchemaDetails = { hasHelperMethods: false };\n\tconst typescriptSchemaTypes = getZodSchemaAsTypeScript(domainTypes, details);\n\tconst helperMethodExplanation = details.hasHelperMethods\n\t\t? `Manipulating the data using the APIs described below is allowed, but when possible ALWAYS prefer to use any application helper methods exposed on the schema TypeScript types if the goal can be accomplished that way.\nIt will often not be possible to fully accomplish the goal using those helpers. When this is the case, mutate the objects as normal, taking into account the following guidance.`\n\t\t: \"\";\n\n\tconst builderExplanation =\n\t\texampleObjectName === undefined\n\t\t\t? \"\"\n\t\t\t: `When constructing new objects, you should wrap them in the appropriate builder function rather than simply making a javascript object.\nThe builders are available on the \\`create\\` property on the context object and are named according to the type that they create.\nFor example:\n\n\\`\\`\\`javascript\n// This creates a new ${exampleObjectName} object:\nconst ${communize(exampleObjectName)} = context.create.${exampleObjectName}({ /* ...properties... */ });\n// Don't do this:\n// const ${communize(exampleObjectName)} = { /* ...properties... */ };\n\\`\\`\\`\\n\\n`;\n\n\tconst arrayEditing = `#### Editing Arrays\n\nThe arrays in the tree are somewhat different than normal JavaScript \\`Array\\`s.\nRead-only operations are generally the same - you can create them, read via index, and call non-mutating methods like \\`concat\\`, \\`map\\`, \\`filter\\`, \\`find\\`, \\`forEach\\`, \\`indexOf\\`, \\`slice\\`, \\`join\\`, etc.\nHowever, write operations (e.g. index assignment, \\`push\\`, \\`pop\\`, \\`splice\\`, etc.) are not supported.\nInstead, you must use the methods on the following interface to mutate the array:\n\n\\`\\`\\`typescript\n${getTreeArrayNodeDocumentation(arrayInterfaceName)}\n\\`\\`\\`\n\nWhen possible, ensure that the edits preserve the identity of objects already in the tree.\nFor example, prefer \\`array.moveToIndex\\` over \\`array.removeAt\\` + \\`array.insertAt\\` and prefer \\`array.moveRangeToIndex\\` over \\`array.removeRange\\` + \\`array.insertAt\\`.\n\n`;\n\n\tconst mapEditing = `#### Editing Maps\n\nThe maps in the tree are somewhat different than normal JavaScript \\`Map\\`s.\nMap keys are always strings.\nRead-only operations are generally the same - you can create them, read via \\`get\\`, and call non-mutating methods like \\`has\\`, \\`forEach\\`, \\`entries\\`, \\`keys\\`, \\`values\\`, etc. (note the subtle differences around return values and iteration order).\nHowever, write operations (e.g. \\`set\\`, \\`delete\\`, etc.) are not supported.\nInstead, you must use the methods on the following interface to mutate the map:\n\n\\`\\`\\`typescript\n${getTreeMapNodeDocumentation(mapInterfaceName)}\n\\`\\`\\`\n\n`;\n\n\tconst rootTypes = normalizeFieldSchema(schema).allowedTypeSet;\n\tconst editing = `If the user asks you to edit the tree, you should author a snippet of JavaScript code to accomplish the user-specified goal, following the instructions for editing detailed below.\nYou must use the \"${editToolName}\" tool to run the generated code.\nAfter editing the tree, review the latest state of the tree to see if it satisfies the user's request.\nIf it does not, or if you receive an error, you may try again with a different approach.\nOnce the tree is in the desired state, you should inform the user that the request has been completed.\n\n### Editing\n\nIf the user asks you to edit the document, you will write a snippet of JavaScript code that mutates the data in-place to achieve the user's goal.\nThe snippet may be synchronous or asynchronous (i.e. it may \\`await\\` functions if necessary).\nThe snippet has a \\`context\\` variable in its scope.\nThis \\`context\\` variable holds the current state of the tree in the \\`root\\` property.\nYou may mutate any part of the root tree as necessary, taking into account the caveats around${hasArrays ? ` arrays${hasMaps ? \" and\" : \"\"}` : \"\"}${hasMaps ? \" maps\" : \"\"} detailed below.\nYou may also set the \\`root\\` property of the context to be an entirely new value as long as it is one of the types allowed at the root of the tree (\\`${Array.from(rootTypes.values(), (t) => getFriendlyName(t)).join(\" | \")}\\`).\n${helperMethodExplanation}\n\n${hasArrays ? arrayEditing : \"\"}${hasMaps ? mapEditing : \"\"}#### Additional Notes\n\nBefore outputting the edit function, you should check that it is valid according to both the application tree's schema and any restrictions of the editing APIs described above.\n\nOnce data has been removed from the tree (e.g. replaced via assignment, or removed from an array), that data cannot be re-inserted into the tree - instead, it must be deep cloned and recreated.\n\n${builderExplanation}Finally, double check that the edits would accomplish the user's request (if it is possible).\n\n`;\n\n\tconst prompt = `You are a helpful assistant collaborating with the user on a document. The document state is a JSON tree, and you are able to analyze and edit it.\nThe JSON tree adheres to the following Typescript schema:\n\n\\`\\`\\`typescript\n${typescriptSchemaTypes}\n\\`\\`\\`\n\nIf the user asks you a question about the tree, you should inspect the state of the tree and answer the question.\nWhen answering such a question, DO NOT answer with information that is not part of the document unless requested to do so.\n\n${editToolName === undefined ? \"\" : editing}### Application data\n\n${\n\tdomainHints === undefined\n\t\t? \"\"\n\t\t: `\\nThe application supplied the following additional instructions: ${domainHints}`\n}\nThe current state of \\`context.root\\` (a \\`${field === undefined ? \"undefined\" : getFriendlyName(Tree.schema(field))}\\`) is:\n\n\\`\\`\\`JSON\n${stringified}\n\\`\\`\\``;\n\treturn prompt;\n}\n\n/**\n * Serializes tree data e.g. to include in a prompt or message.\n * @remarks This includes some extra metadata to make it easier to understand the structure of the tree.\n */\nexport function stringifyTree(tree: ReadableField<ImplicitFieldSchema>): string {\n\tconst typeReplacementKey = \"_e944da5a5fd04ea2b8b2eb6109e089ed\";\n\tconst indexReplacementKey = \"_27bb216b474d45e6aaee14d1ec267b96\";\n\tconst mapReplacementKey = \"_a0d98d22a1c644539f07828d3f064d71\";\n\tconst stringified = JSON.stringify(\n\t\ttree,\n\t\t(_, node: unknown) => {\n\t\t\tif (node instanceof TreeNode) {\n\t\t\t\tconst key = Tree.key(node);\n\t\t\t\tconst index = typeof key === \"number\" ? key : undefined;\n\t\t\t\tconst schema = Tree.schema(node);\n\t\t\t\tswitch (schema.kind) {\n\t\t\t\t\tcase NodeKind.Object: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[typeReplacementKey]: getFriendlyName(schema),\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t...node,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tcase NodeKind.Map: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t[mapReplacementKey]: \"\",\n\t\t\t\t\t\t\t...Object.fromEntries(node as TreeMapNode),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t...node,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn node;\n\t\t},\n\t\t2,\n\t);\n\n\treturn stringified\n\t\t.replace(new RegExp(`\"${typeReplacementKey}\":`, \"g\"), `// Type:`)\n\t\t.replace(new RegExp(`\"${indexReplacementKey}\":`, \"g\"), `// Index:`)\n\t\t.replace(\n\t\t\tnew RegExp(`\"${mapReplacementKey}\": \"\"`, \"g\"),\n\t\t\t`// Note: This is a map that has been serialized to JSON. It is not a key-value object/record but is being printed as such.`,\n\t\t);\n}\n\n/**\n * Retrieves the documentation for the `TreeArrayNode` interface to feed to the LLM.\n * @remarks The documentation has been simplified in various ways to make it easier for the LLM to understand.\n * @privateRemarks TODO: How do we keep this in sync with the actual `TreeArrayNode` docs if/when those docs change?\n */\nfunction getTreeArrayNodeDocumentation(typeName: string): string {\n\treturn `/** A special type of array which implements 'readonly T[]' (i.e. it supports all read-only JS array methods) and provides custom array mutation APIs. */\nexport interface ${typeName}<T> extends ReadonlyArray<T> {\n\t/**\n\t * Inserts new item(s) at a specified location.\n\t * @param index - The index at which to insert \\`value\\`.\n\t * @param value - The content to insert.\n\t * @throws Throws if \\`index\\` is not in the range [0, \\`array.length\\`).\n\t */\n\tinsertAt(index: number, ...value: readonly T[]): void;\n\n\t/**\n\t * Removes the item at the specified location.\n\t * @param index - The index at which to remove the item.\n\t * @throws Throws if \\`index\\` is not in the range [0, \\`array.length\\`).\n\t */\n\tremoveAt(index: number): void;\n\n\t/**\n\t * Removes all items between the specified indices.\n\t * @param start - The starting index of the range to remove (inclusive). Defaults to the start of the array.\n\t * @param end - The ending index of the range to remove (exclusive). Defaults to \\`array.length\\`.\n\t * @throws Throws if \\`start\\` is not in the range [0, \\`array.length\\`].\n\t * @throws Throws if \\`end\\` is less than \\`start\\`.\n\t * If \\`end\\` is not supplied or is greater than the length of the array, all items after \\`start\\` are removed.\n\t *\n\t * @remarks\n\t * The default values for start and end are computed when this is called,\n\t * and thus the behavior is the same as providing them explicitly, even with respect to merge resolution with concurrent edits.\n\t * For example, two concurrent transactions both emptying the array with \\`node.removeRange()\\` then inserting an item,\n\t * will merge to result in the array having both inserted items.\n\t */\n\tremoveRange(start?: number, end?: number): void;\n\n\t/**\n\t * Moves the specified item to the desired location in the array.\n\t *\n\t * WARNING - This API is easily misused.\n\t * Please read the documentation for the \\`destinationGap\\` parameter carefully.\n\t *\n\t * @param destinationGap - The location *between* existing items that the moved item should be moved to.\n\t *\n\t * WARNING - \\`destinationGap\\` describes a location between existing items *prior to applying the move operation*.\n\t *\n\t * For example, if the array contains items \\`[A, B, C]\\` before the move, the \\`destinationGap\\` must be one of the following:\n\t *\n\t * - \\`0\\` (between the start of the array and \\`A\\`'s original position)\n\t * - \\`1\\` (between \\`A\\`'s original position and \\`B\\`'s original position)\n\t * - \\`2\\` (between \\`B\\`'s original position and \\`C\\`'s original position)\n\t * - \\`3\\` (between \\`C\\`'s original position and the end of the array)\n\t *\n\t * So moving \\`A\\` between \\`B\\` and \\`C\\` would require \\`destinationGap\\` to be \\`2\\`.\n\t *\n\t * This interpretation of \\`destinationGap\\` makes it easy to specify the desired destination relative to a sibling item that is not being moved,\n\t * or relative to the start or end of the array:\n\t *\n\t * - Move to the start of the array: \\`array.moveToIndex(0, ...)\\` (see also \\`moveToStart\\`)\n\t * - Move to before some item X: \\`array.moveToIndex(indexOfX, ...)\\`\n\t * - Move to after some item X: \\`array.moveToIndex(indexOfX + 1\\`, ...)\n\t * - Move to the end of the array: \\`array.moveToIndex(array.length, ...)\\` (see also \\`moveToEnd\\`)\n\t *\n\t * This interpretation of \\`destinationGap\\` does however make it less obvious how to move an item relative to its current position:\n\t *\n\t * - Move item B before its predecessor: \\`array.moveToIndex(indexOfB - 1, ...)\\`\n\t * - Move item B after its successor: \\`array.moveToIndex(indexOfB + 2, ...)\\`\n\t *\n\t * Notice the asymmetry between \\`-1\\` and \\`+2\\` in the above examples.\n\t * In such scenarios, it can often be easier to approach such edits by swapping adjacent items:\n\t * If items A and B are adjacent, such that A precedes B,\n\t * then they can be swapped with \\`array.moveToIndex(indexOfA, indexOfB)\\`.\n\t *\n\t * @param sourceIndex - The index of the item to move.\n\t * @param source - The optional source array to move the item out of (defaults to this array).\n\t * @throws Throws if any of the source index is not in the range [0, \\`array.length\\`),\n\t * or if the index is not in the range [0, \\`array.length\\`].\n\t */\n\tmoveToIndex(destinationGap: number, sourceIndex: number, source?: ${typeName}<T>): void;\n\n\t/**\n\t * Moves the specified items to the desired location within the array.\n\t *\n\t * WARNING - This API is easily misused.\n\t * Please read the documentation for the \\`destinationGap\\` parameter carefully.\n\t *\n\t * @param destinationGap - The location *between* existing items that the moved item should be moved to.\n\t *\n\t * WARNING - \\`destinationGap\\` describes a location between existing items *prior to applying the move operation*.\n\t *\n\t * For example, if the array contains items \\`[A, B, C]\\` before the move, the \\`destinationGap\\` must be one of the following:\n\t *\n\t * - \\`0\\` (between the start of the array and \\`A\\`'s original position)\n\t * - \\`1\\` (between \\`A\\`'s original position and \\`B\\`'s original position)\n\t * - \\`2\\` (between \\`B\\`'s original position and \\`C\\`'s original position)\n\t * - \\`3\\` (between \\`C\\`'s original position and the end of the array)\n\t *\n\t * So moving \\`A\\` between \\`B\\` and \\`C\\` would require \\`destinationGap\\` to be \\`2\\`.\n\t *\n\t * This interpretation of \\`destinationGap\\` makes it easy to specify the desired destination relative to a sibling item that is not being moved,\n\t * or relative to the start or end of the array:\n\t *\n\t * - Move to the start of the array: \\`array.moveToIndex(0, ...)\\` (see also \\`moveToStart\\`)\n\t * - Move to before some item X: \\`array.moveToIndex(indexOfX, ...)\\`\n\t * - Move to after some item X: \\`array.moveToIndex(indexOfX + 1\\`, ...)\n\t * - Move to the end of the array: \\`array.moveToIndex(array.length, ...)\\` (see also \\`moveToEnd\\`)\n\t *\n\t * This interpretation of \\`destinationGap\\` does however make it less obvious how to move an item relative to its current position:\n\t *\n\t * - Move item B before its predecessor: \\`array.moveToIndex(indexOfB - 1, ...)\\`\n\t * - Move item B after its successor: \\`array.moveToIndex(indexOfB + 2, ...)\\`\n\t *\n\t * Notice the asymmetry between \\`-1\\` and \\`+2\\` in the above examples.\n\t * In such scenarios, it can often be easier to approach such edits by swapping adjacent items:\n\t * If items A and B are adjacent, such that A precedes B,\n\t * then they can be swapped with \\`array.moveToIndex(indexOfA, indexOfB)\\`.\n\t *\n\t * @param sourceStart - The starting index of the range to move (inclusive).\n\t * @param sourceEnd - The ending index of the range to move (exclusive)\n\t * @param source - The optional source array to move items out of (defaults to this array).\n\t * @throws Throws if the types of any of the items being moved are not allowed in the destination array,\n\t * if any of the input indices are not in the range [0, \\`array.length\\`], or if \\`sourceStart\\` is greater than \\`sourceEnd\\`.\n\t */\n\tmoveRangeToIndex(\n\t\tdestinationGap: number,\n\t\tsourceStart: number,\n\t\tsourceEnd: number,\n\t\tsource?: ${typeName}<T>,\n\t): void;\n}`;\n}\n\n/**\n * Retrieves the documentation for the `TreeMapNode` interface to feed to the LLM.\n * @remarks The documentation has been simplified in various ways to make it easier for the LLM to understand.\n * @privateRemarks TODO: How do we keep this in sync with the actual `TreeMapNode` docs if/when those docs change?\n */\nfunction getTreeMapNodeDocumentation(typeName: string): string {\n\treturn `/**\n * A map of string keys to tree objects.\n */\nexport interface ${typeName}<T> extends ReadonlyMap<string, T> {\n\t/**\n\t * Adds or updates an entry in the map with a specified \\`key\\` and a \\`value\\`.\n\t *\n\t * @param key - The key of the element to add to the map.\n\t * @param value - The value of the element to add to the map.\n\t *\n\t * @remarks\n\t * Setting the value at a key to \\`undefined\\` is equivalent to calling {@link ${typeName}.delete} with that key.\n\t */\n\tset(key: string, value: T | undefined): void;\n\n\t/**\n\t * Removes the specified element from this map by its \\`key\\`.\n\t *\n\t * @remarks\n\t * Note: unlike JavaScript's Map API, this method does not return a flag indicating whether or not the value was\n\t * deleted.\n\t *\n\t * @param key - The key of the element to remove from the map.\n\t */\n\tdelete(key: string): void;\n\n\t/**\n\t * Returns an iterable of keys in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the keys returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tkeys(): IterableIterator<string>;\n\n\t/**\n\t * Returns an iterable of values in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the values returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tvalues(): IterableIterator<T>;\n\n\t/**\n\t * Returns an iterable of key/value pairs for every entry in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the entries returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tentries(): IterableIterator<[string, T]>;\n\n\t/**\n\t * Executes the provided function once per each key/value pair in this map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order in which the function is called with respect to the map's entries.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tforEach(\n\t\tcallbackfn: (\n\t\t\tvalue: T,\n\t\t\tkey: string,\n\t\t\tmap: ReadonlyMap<string, T>,\n\t\t) => void,\n\t\tthisArg?: any,\n\t): void;\n}`;\n}\n"]}
package/dist/utils.d.ts CHANGED
@@ -124,4 +124,8 @@ export declare function findNamedSchemas(schema: ImplicitFieldSchema, schemas?:
124
124
  * De-capitalize (the first letter of) a string.
125
125
  */
126
126
  export declare function communize(str: string): string;
127
+ /**
128
+ * Stringify an unknown error value
129
+ */
130
+ export declare function toErrorString(error: unknown): string;
127
131
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAQH,OAAO,KAAK,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AACrF,OAAO,KAAK,EACX,iBAAiB,EACjB,UAAU,EACV,QAAQ,EACR,cAAc,EACd,aAAa,EACb,mBAAmB,EACnB,MAAM,4BAA4B,CAAC;AASpC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CA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AAG,MAAM,CAE7C;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CASpD"}
package/dist/utils.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * Licensed under the MIT License.
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.communize = exports.findNamedSchemas = exports.instanceOf = exports.getZodSchemaAsTypeScript = exports.unqualifySchema = exports.isNamedSchema = exports.getFriendlyName = exports.constructNode = exports.failUsage = exports.llmDefault = exports.hasAtLeastTwo = exports.tryGetSingleton = exports.getOrCreate = exports.mapIterable = exports.fail = void 0;
7
+ exports.toErrorString = exports.communize = exports.findNamedSchemas = exports.instanceOf = exports.getZodSchemaAsTypeScript = exports.unqualifySchema = exports.isNamedSchema = exports.getFriendlyName = exports.constructNode = exports.failUsage = exports.llmDefault = exports.hasAtLeastTwo = exports.tryGetSingleton = exports.getOrCreate = exports.mapIterable = exports.fail = void 0;
8
8
  /* eslint-disable @typescript-eslint/no-unsafe-argument */
9
9
  /* eslint-disable @typescript-eslint/explicit-function-return-type */
10
10
  const internal_1 = require("@fluidframework/core-utils/internal");
@@ -518,4 +518,19 @@ function communize(str) {
518
518
  return str.charAt(0).toLowerCase() + str.slice(1);
519
519
  }
520
520
  exports.communize = communize;
521
+ /**
522
+ * Stringify an unknown error value
523
+ */
524
+ function toErrorString(error) {
525
+ if (error instanceof Error) {
526
+ return error.message;
527
+ }
528
+ try {
529
+ return JSON.stringify(error);
530
+ }
531
+ catch {
532
+ return String(error);
533
+ }
534
+ }
535
+ exports.toErrorString = toErrorString;
521
536
  //# sourceMappingURL=utils.js.map
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,0DAA0D;AAC1D,qEAAqE;AAErE,kEAA6D;AAC7D,iEAA8D;AAC9D,uEAAsE;AAUtE,sDAMoC;AACpC,4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c,EAAE,CAAC;QACtE,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YAC1B,IAAI,aAAa,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;gBAC1C,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YACrB,CAAC;YACD,gBAAgB,CAAC,CAAC,GAAG,UAAU,CAAC,UAAU,CAAC,EAAE,GAAG,CAAC,CAAC;QACnD,CAAC;IACF,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC;AAdD,4CAcC;AAED;;GAEG;AACH,SAAgB,SAAS,CAAC,GAAW;IACpC,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnD,CAAC;AAFD,8BAEC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/* eslint-disable @typescript-eslint/no-unsafe-argument */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n\nimport { assert } from \"@fluidframework/core-utils/internal\";\nimport { isFluidHandle } from \"@fluidframework/runtime-utils\";\nimport { UsageError } from \"@fluidframework/telemetry-utils/internal\";\nimport type { ImplicitFieldSchema, TreeNodeSchemaClass } from \"@fluidframework/tree\";\nimport type {\n\tInsertableContent,\n\tTreeBranch,\n\tTreeNode,\n\tTreeNodeSchema,\n\tTreeViewAlpha,\n\tUnsafeUnknownSchema,\n} from \"@fluidframework/tree/alpha\";\nimport {\n\tArrayNodeSchema,\n\tMapNodeSchema,\n\tObjectNodeSchema,\n\tRecordNodeSchema,\n\tTreeAlpha,\n} from \"@fluidframework/tree/alpha\";\nimport { NodeKind, normalizeFieldSchema } from \"@fluidframework/tree/internal\";\nimport { z } from \"zod\";\n\nimport { FunctionWrapper } from \"./methodBinding.js\";\n\n/**\n * Subset of Map interface.\n *\n * @remarks originally from tree/src/util/utils.ts\n */\nexport interface MapGetSet<K, V> {\n\tget(key: K): V | undefined;\n\tset(key: K, value: V): void;\n}\n\n/**\n * TBD\n */\nexport function fail(message: string): never {\n\tthrow new Error(message);\n}\n\n/**\n * Map one iterable to another by transforming each element one at a time\n * @param iterable - the iterable to transform\n * @param map - the transformation function to run on each element of the iterable\n * @returns a new iterable of elements which have been transformed by the `map` function\n *\n * @remarks originally from tree/src/util/utils.ts\n */\nexport function* mapIterable<T, U>(\n\titerable: Iterable<T>,\n\tmap: (t: T) => U,\n): IterableIterator<U> {\n\tfor (const t of iterable) {\n\t\tyield map(t);\n\t}\n}\n\n/**\n * Retrieve a value from a map with the given key, or create a new entry if the key is not in the map.\n * @param map - The map to query/update\n * @param key - The key to lookup in the map\n * @param defaultValue - a function which returns a default value. This is called and used to set an initial value for the given key in the map if none exists\n * @returns either the existing value for the given key, or the newly-created value (the result of `defaultValue`)\n *\n * @remarks originally from tree/src/util/utils.ts\n */\nexport function getOrCreate<K, V>(\n\tmap: MapGetSet<K, V>,\n\tkey: K,\n\tdefaultValue: (key: K) => V,\n): V {\n\tlet value = map.get(key);\n\tif (value === undefined) {\n\t\tvalue = defaultValue(key);\n\t\tmap.set(key, value);\n\t}\n\treturn value;\n}\n\n/**\n * TODO\n * @alpha\n * @privateRemarks This is a subset of the TreeViewAlpha functionality because if take it wholesale, it causes problems with invariance of the generic parameters.\n */\nexport type TreeView<TRoot extends ImplicitFieldSchema | UnsafeUnknownSchema> = Pick<\n\tTreeViewAlpha<TRoot>,\n\t\"root\" | \"fork\" | \"merge\" | \"rebaseOnto\" | \"schema\" | \"events\"\n> &\n\tTreeBranch;\n\n/**\n * TODO\n */\nexport function tryGetSingleton<T>(set: ReadonlySet<T>): T | undefined {\n\tif (set.size === 1) {\n\t\tfor (const item of set) {\n\t\t\treturn item;\n\t\t}\n\t}\n}\n\n/**\n * Does it have at least two elements?\n */\nexport function hasAtLeastTwo<T>(array: T[]): array is [T, T, ...T[]] {\n\treturn array.length >= 2;\n}\n\n/**\n * Include this property in a field's schema metadata to indicate that the field's value should be generated via a provided function rather than by the LLM.\n * @example\n * ```ts\n * class Object extends schemaFactory.object(\"Object\", {\n * created: sf.required(sf.number, {\n * custom: {\n * // The LLM will ignore this field, and instead it will be populated with the result of the function\n * [llmDefault]: () => Date.now(),\n * },\n * }),\n * }) {};\n * ```\n * @alpha\n */\nexport const llmDefault = Symbol(\"tree-agent/llmDefault\");\n// TODO: make this a wrapper function instead, and hide the symbol.\n// function llmDefault<T extends FieldSchemaMetadata>(metadata: T): T { ... }\n\n/**\n * Usage fail\n */\nexport function failUsage(message: string): never {\n\tthrow new UsageError(message);\n}\n\n/**\n * Construct an object node from a schema and value.\n */\nexport function constructNode(schema: TreeNodeSchema, value: InsertableContent): TreeNode {\n\tconst node = TreeAlpha.create<UnsafeUnknownSchema>(schema, value);\n\tassert(\n\t\tnode !== undefined && node !== null && typeof node === \"object\" && !isFluidHandle(node),\n\t\t0xc1e /* Expected a constructed node to be an object */,\n\t);\n\treturn node;\n}\n\n/**\n * Returns the unqualified name of a tree value's schema (e.g. a node with schema identifier `\"my.scope.MyNode\"` returns `\"MyNode\"`).\n * @remarks If the schema is an inlined array, map, or record type, then it has no name and this function will return a string representation of the type (e.g., `\"MyNode[]\"` or `\"Map<string, MyNode>\"`).\n */\nexport function getFriendlyName(schema: TreeNodeSchema): string {\n\tif (schema.kind === NodeKind.Leaf || isNamedSchema(schema.identifier)) {\n\t\treturn unqualifySchema(schema.identifier);\n\t}\n\n\tconst childNames = Array.from(schema.childTypes, (t) => getFriendlyName(t));\n\tif (schema instanceof ArrayNodeSchema) {\n\t\treturn childNames.length > 1 ? `(${childNames.join(\" | \")})[]` : `${childNames[0]}[]`;\n\t}\n\tif (schema instanceof MapNodeSchema) {\n\t\treturn childNames.length > 1\n\t\t\t? `Map<string, (${childNames.join(\" | \")})>`\n\t\t\t: `Map<string, ${childNames[0]}>`;\n\t}\n\tif (schema instanceof RecordNodeSchema) {\n\t\treturn childNames.length > 1\n\t\t\t? `Record<string, (${childNames.join(\" | \")})>`\n\t\t\t: `Record<string, ${childNames[0]}>`;\n\t}\n\tfail(\"Unexpected node schema\");\n}\n\n/**\n * Returns true if the schema identifier represents a named schema (object, named array, named map, or named record).\n * @remarks This does not include primitive schemas or inlined array/map/record schemas.\n */\nexport function isNamedSchema(schemaIdentifier: string): boolean {\n\tif (\n\t\t[\"string\", \"number\", \"boolean\", \"null\", \"handle\"].includes(\n\t\t\tunqualifySchema(schemaIdentifier),\n\t\t)\n\t) {\n\t\treturn false;\n\t}\n\n\treturn schemaIdentifier.match(/(?:Array|Map|Record)<\\[\"(.*)\"]>/) === null;\n}\n\n/**\n * Returns the unqualified name of a schema (e.g. `\"my.scope.MyNode\"` returns `\"MyNode\"`).\n * @remarks This works by removing all characters before the last dot in the schema name.\n * If there is a dot in a user's schema name, this might produce unexpected results.\n */\nexport function unqualifySchema(schemaIdentifier: string): string {\n\t// Get the unqualified name by removing the scope (everything before the last dot).\n\tconst matches = schemaIdentifier.match(/[^.]+$/);\n\tif (matches === null) {\n\t\treturn schemaIdentifier; // Return the original name if it is unscoped.\n\t}\n\treturn matches[0];\n}\n\n/**\n * Details about the properties of a TypeScript schema represented as Zod.\n */\nexport interface SchemaDetails {\n\thasHelperMethods: boolean;\n}\n\n// TODO: yuck, this entire file has too many statics. we should rewrite it as a generic zod schema walk.\nlet detailsI: SchemaDetails = {\n\thasHelperMethods: false,\n};\n\n/**\n * Returns the TypeScript source code corresponding to a Zod schema. The schema is supplied as an object where each\n * property provides a name for an associated Zod type. The return value is a string containing the TypeScript source\n * code corresponding to the schema. Each property of the schema object is emitted as a named `interface` or `type`\n * declaration for the associated type and is referenced by that name in the emitted type declarations. Other types\n * referenced in the schema are emitted in their structural form.\n * @param schema - A schema object where each property provides a name for an associated Zod type.\n * @param details - Optional details about the schema. The fields will be set according to the details in the given schema.\n * @returns The TypeScript source code corresponding to the schema.\n */\nexport function getZodSchemaAsTypeScript(\n\tschema: Record<string, z.ZodType>,\n\tdetails?: SchemaDetails,\n): string {\n\tdetailsI = details ?? { hasHelperMethods: false };\n\tlet result = \"\";\n\tlet startOfLine = true;\n\tlet indent = 0;\n\tconst entries = [...Object.entries(schema)];\n\tconst namedTypes = new Map<object, string>(\n\t\tentries.map(([name, type]) => [getTypeIdentity(type), name]),\n\t);\n\tfor (const [name, type] of entries) {\n\t\tif (result) {\n\t\t\tappendNewLine();\n\t\t}\n\t\tconst description = type._def.description;\n\t\tif (description !== undefined && description !== \"\") {\n\t\t\tfor (const comment of description.split(\"\\n\")) {\n\t\t\t\tappend(`// ${comment}`);\n\t\t\t\tappendNewLine();\n\t\t\t}\n\t\t}\n\t\tif (getTypeKind(type) === z.ZodFirstPartyTypeKind.ZodObject) {\n\t\t\tappend(`interface ${name} `);\n\t\t\tappendObjectType(type as z.ZodObject<z.ZodRawShape>);\n\t\t} else {\n\t\t\tappend(`type ${name} = `);\n\t\t\tappendTypeDefinition(type);\n\t\t\tappend(\";\");\n\t\t}\n\t\tappendNewLine();\n\t}\n\treturn result;\n\n\tfunction append(s: string) {\n\t\tif (startOfLine) {\n\t\t\tresult += \" \".repeat(indent);\n\t\t\tstartOfLine = false;\n\t\t}\n\t\tresult += s;\n\t}\n\n\tfunction appendNewLine() {\n\t\tappend(\"\\n\");\n\t\tstartOfLine = true;\n\t}\n\n\tfunction appendType(type: z.ZodType, minPrecedence = TypePrecedence.Object) {\n\t\tconst name = namedTypes.get(getTypeIdentity(type));\n\t\tif (name === undefined) {\n\t\t\tconst parenthesize = getTypePrecendece(type) < minPrecedence;\n\t\t\tif (parenthesize) append(\"(\");\n\t\t\tappendTypeDefinition(type);\n\t\t\tif (parenthesize) append(\")\");\n\t\t} else {\n\t\t\tappend(name);\n\t\t}\n\t}\n\n\tfunction appendTypeDefinition(type: z.ZodType) {\n\t\tswitch (getTypeKind(type)) {\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodString: {\n\t\t\t\treturn append(\"string\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodNumber: {\n\t\t\t\treturn append(\"number\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodBoolean: {\n\t\t\t\treturn append(\"boolean\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodDate: {\n\t\t\t\treturn append(\"Date\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodUndefined: {\n\t\t\t\treturn append(\"undefined\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodNull: {\n\t\t\t\treturn append(\"null\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodUnknown: {\n\t\t\t\treturn append(\"unknown\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodArray: {\n\t\t\t\treturn appendArrayType(type);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodObject: {\n\t\t\t\treturn appendObjectType(type);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodUnion: {\n\t\t\t\treturn appendUnionOrIntersectionTypes(\n\t\t\t\t\t(type._def as z.ZodUnionDef).options,\n\t\t\t\t\tTypePrecedence.Union,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: {\n\t\t\t\treturn appendUnionOrIntersectionTypes(\n\t\t\t\t\t[...(type._def as z.ZodDiscriminatedUnionDef<string>).options.values()],\n\t\t\t\t\tTypePrecedence.Union,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodIntersection: {\n\t\t\t\treturn appendUnionOrIntersectionTypes(\n\t\t\t\t\t[\n\t\t\t\t\t\t(type._def as z.ZodIntersectionDef).left,\n\t\t\t\t\t\t(type._def as z.ZodIntersectionDef).right,\n\t\t\t\t\t],\n\t\t\t\t\tTypePrecedence.Intersection,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodTuple: {\n\t\t\t\treturn appendTupleType(type);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodRecord: {\n\t\t\t\treturn appendRecordType(type);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodMap: {\n\t\t\t\treturn appendMapType(type);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodLiteral: {\n\t\t\t\treturn appendLiteral((type._def as z.ZodLiteralDef).value);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodEnum: {\n\t\t\t\treturn append(\n\t\t\t\t\t(type._def as z.ZodEnumDef).values.map((value) => JSON.stringify(value)).join(\" | \"),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodOptional: {\n\t\t\t\treturn appendUnionOrIntersectionTypes(\n\t\t\t\t\t[(type._def as z.ZodOptionalDef).innerType, z.undefined()],\n\t\t\t\t\tTypePrecedence.Union,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodReadonly: {\n\t\t\t\treturn appendReadonlyType(type);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodEffects: {\n\t\t\t\t// Currently, this only handles schema class instances, but there are other cases in which a ZodEffects could theoretically be used.\n\t\t\t\tif (instanceOfs.has(type)) {\n\t\t\t\t\tconst objectNodeSchema = instanceOfs.get(type);\n\t\t\t\t\tif (objectNodeSchema === undefined) {\n\t\t\t\t\t\tthrow new UsageError(\n\t\t\t\t\t\t\t`Unsupported zod effects type when transforming class method: ${getTypeKind(type)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn append(getFriendlyName(objectNodeSchema));\n\t\t\t\t}\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Unsupported zod effects type. Did you use z.instanceOf? Use ExposedMethods.instanceOf function to reference schema classes in methods.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodVoid: {\n\t\t\t\treturn append(\"void\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodLazy: {\n\t\t\t\treturn appendType((type._def as z.ZodLazyDef).getter());\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tthrow new UsageError(\n\t\t\t\t\t`Unsupported type when transforming class method: ${getTypeKind(type)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction appendBoundMethods(boundType: z.ZodType): void {\n\t\t// eslint-disable-next-line prefer-const\n\t\tfor (let [name, type] of Object.entries((boundType._def as z.ZodObjectDef).shape())) {\n\t\t\t// Special handling of methods on objects\n\t\t\tconst method = (type as unknown as { method: object | undefined }).method;\n\t\t\tif (method !== undefined && method instanceof FunctionWrapper) {\n\t\t\t\tdetailsI.hasHelperMethods = true;\n\t\t\t\tappend(name);\n\t\t\t\tappend(\"(\");\n\t\t\t\tlet first = true;\n\t\t\t\tfor (const [argName, argType] of method.args) {\n\t\t\t\t\tif (!first) append(\", \");\n\t\t\t\t\tif (getTypeKind(argType) === z.ZodFirstPartyTypeKind.ZodOptional) {\n\t\t\t\t\t\tappend(`${argName}?: `);\n\t\t\t\t\t\tappendType((argType._def as z.ZodOptionalDef).innerType, TypePrecedence.Object);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tappend(`${argName}: `);\n\t\t\t\t\t\tappendType(argType);\n\t\t\t\t\t}\n\t\t\t\t\tfirst = false;\n\t\t\t\t}\n\t\t\t\tif (method.rest !== null) {\n\t\t\t\t\tif (!first) append(\", \");\n\t\t\t\t\tappend(\"...rest: \");\n\t\t\t\t\tappendType(method.rest, TypePrecedence.Object);\n\t\t\t\t\tappend(\"[]\");\n\t\t\t\t}\n\t\t\t\tappend(`): `);\n\t\t\t\tappendType(method.returns, TypePrecedence.Object);\n\t\t\t\tappend(\";\");\n\t\t\t\tif (method.description !== undefined) {\n\t\t\t\t\tappend(` // ${method.description}`);\n\t\t\t\t}\n\t\t\t\tappendNewLine();\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction appendArrayType(arrayType: z.ZodType) {\n\t\tappendType((arrayType._def as z.ZodArrayDef).type, TypePrecedence.Object);\n\t\tappend(\"[]\");\n\t}\n\n\tfunction appendObjectType(objectType: z.ZodType) {\n\t\tappend(\"{\");\n\t\tappendNewLine();\n\t\tindent++;\n\t\t// eslint-disable-next-line prefer-const\n\t\tfor (let [name, type] of Object.entries((objectType._def as z.ZodObjectDef).shape())) {\n\t\t\tconst method = (type as unknown as { method: object | undefined }).method;\n\t\t\tif (method === undefined || !(method instanceof FunctionWrapper)) {\n\t\t\t\tappend(name);\n\t\t\t\tif (getTypeKind(type) === z.ZodFirstPartyTypeKind.ZodOptional) {\n\t\t\t\t\tappend(\"?\");\n\t\t\t\t\ttype = (type._def as z.ZodOptionalDef).innerType;\n\t\t\t\t}\n\t\t\t\tappend(\": \");\n\t\t\t\tappendType(type);\n\t\t\t\tappend(\";\");\n\t\t\t\tconst comment = type.description;\n\t\t\t\tif (comment !== undefined && comment !== \"\") append(` // ${comment}`);\n\t\t\t\tappendNewLine();\n\t\t\t}\n\t\t}\n\t\tappendBoundMethods(objectType);\n\t\tindent--;\n\t\tappend(\"}\");\n\t}\n\n\tfunction appendUnionOrIntersectionTypes(\n\t\ttypes: readonly z.ZodType[],\n\t\tminPrecedence: TypePrecedence,\n\t) {\n\t\tlet first = true;\n\t\tfor (const type of types) {\n\t\t\tif (!first) append(minPrecedence === TypePrecedence.Intersection ? \" & \" : \" | \");\n\t\t\tappendType(type, minPrecedence);\n\t\t\tfirst = false;\n\t\t}\n\t}\n\n\tfunction appendTupleType(tupleType: z.ZodType) {\n\t\tappend(\"[\");\n\t\tlet first = true;\n\t\tfor (const type of (tupleType._def as z.ZodTupleDef<z.ZodTupleItems, z.ZodType>).items) {\n\t\t\tif (!first) append(\", \");\n\t\t\tif (getTypeKind(type) === z.ZodFirstPartyTypeKind.ZodOptional) {\n\t\t\t\tappendType((type._def as z.ZodOptionalDef).innerType, TypePrecedence.Object);\n\t\t\t\tappend(\"?\");\n\t\t\t} else {\n\t\t\t\tappendType(type);\n\t\t\t}\n\t\t\tfirst = false;\n\t\t}\n\t\tconst rest = (tupleType._def as z.ZodTupleDef<z.ZodTupleItems, z.ZodType | null>).rest;\n\t\tif (rest !== null) {\n\t\t\tif (!first) append(\", \");\n\t\t\tappend(\"...\");\n\t\t\tappendType(rest, TypePrecedence.Object);\n\t\t\tappend(\"[]\");\n\t\t}\n\t\tappend(\"]\");\n\t}\n\n\tfunction appendRecordType(recordType: z.ZodType) {\n\t\tappend(\"Record<\");\n\t\tappendType((recordType._def as z.ZodRecordDef).keyType);\n\t\tappend(\", \");\n\t\tappendType((recordType._def as z.ZodRecordDef).valueType);\n\t\tappend(\">\");\n\t}\n\n\tfunction appendMapType(mapType: z.ZodType) {\n\t\tappend(\"Map<\");\n\t\tappendType((mapType._def as z.ZodMapDef).keyType);\n\t\tappend(\", \");\n\t\tappendType((mapType._def as z.ZodMapDef).valueType);\n\t\tappend(\">\");\n\t}\n\n\tfunction appendLiteral(value: unknown) {\n\t\tappend(\n\t\t\ttypeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\"\n\t\t\t\t? JSON.stringify(value)\n\t\t\t\t: \"any\",\n\t\t);\n\t}\n\n\tfunction appendReadonlyType(readonlyType: z.ZodType) {\n\t\tappend(\"Readonly<\");\n\t\tappendType((readonlyType._def as z.ZodReadonlyDef).innerType);\n\t\tappend(\">\");\n\t}\n}\n\nfunction getTypeKind(type: z.ZodType): z.ZodFirstPartyTypeKind {\n\treturn (type._def as z.ZodTypeDef & { typeName: z.ZodFirstPartyTypeKind }).typeName;\n}\n\nfunction getTypeIdentity(type: z.ZodType): object {\n\tswitch (getTypeKind(type)) {\n\t\tcase z.ZodFirstPartyTypeKind.ZodObject: {\n\t\t\treturn (type._def as z.ZodObjectDef).shape();\n\t\t}\n\t\tcase z.ZodFirstPartyTypeKind.ZodEnum: {\n\t\t\treturn (type._def as z.ZodEnumDef).values;\n\t\t}\n\t\tcase z.ZodFirstPartyTypeKind.ZodUnion: {\n\t\t\treturn (type._def as z.ZodUnionDef).options;\n\t\t}\n\t\tdefault: {\n\t\t\treturn type;\n\t\t}\n\t}\n}\n\nconst enum TypePrecedence {\n\tUnion = 0,\n\tIntersection = 1,\n\tObject = 2,\n}\n\nfunction getTypePrecendece(type: z.ZodType): TypePrecedence {\n\tswitch (getTypeKind(type)) {\n\t\tcase z.ZodFirstPartyTypeKind.ZodEnum:\n\t\tcase z.ZodFirstPartyTypeKind.ZodUnion:\n\t\tcase z.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: {\n\t\t\treturn TypePrecedence.Union;\n\t\t}\n\t\tcase z.ZodFirstPartyTypeKind.ZodIntersection: {\n\t\t\treturn TypePrecedence.Intersection;\n\t\t}\n\t\tdefault: {\n\t\t\treturn TypePrecedence.Object;\n\t\t}\n\t}\n}\n\n/**\n * Create a Zod schema for a SharedTree schema class.\n * @alpha\n */\nexport function instanceOf<T extends TreeNodeSchemaClass>(\n\tschema: T,\n): z.ZodType<InstanceType<T>, z.ZodTypeDef, InstanceType<T>> {\n\tif (!(schema instanceof ObjectNodeSchema)) {\n\t\tthrow new UsageError(`${schema.identifier} must be an instance of ObjectNodeSchema.`);\n\t}\n\tconst effect = z.instanceof(schema);\n\tinstanceOfs.set(effect, schema);\n\treturn effect;\n}\n\nconst instanceOfs = new WeakMap<z.ZodTypeAny, ObjectNodeSchema>();\n\n/**\n * Adds all named object, map, array, and record schemas reachable from the given schema to the given set.\n * @remarks This includes transitive child/descendant schemas.\n * It does not include primitive schemas or inlined array/map/record schemas.\n * @returns The set of named schemas added (same as the `schemas` parameter, if supplied).\n */\nexport function findNamedSchemas(\n\tschema: ImplicitFieldSchema,\n\tschemas = new Set<TreeNodeSchema>(),\n): Set<TreeNodeSchema> {\n\tconst set = schemas ?? new Set();\n\tfor (const nodeSchema of normalizeFieldSchema(schema).allowedTypeSet) {\n\t\tif (!set.has(nodeSchema)) {\n\t\t\tif (isNamedSchema(nodeSchema.identifier)) {\n\t\t\t\tset.add(nodeSchema);\n\t\t\t}\n\t\t\tfindNamedSchemas([...nodeSchema.childTypes], set);\n\t\t}\n\t}\n\treturn set;\n}\n\n/**\n * De-capitalize (the first letter of) a string.\n */\nexport function communize(str: string): string {\n\treturn str.charAt(0).toLowerCase() + str.slice(1);\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,0DAA0D;AAC1D,qEAAqE;AAErE,kEAA6D;AAC7D,iEAA8D;AAC9D,uEAAsE;AAUtE,sDAMoC;AACpC,4DAA+E;AAC/E,6BAAwB;AAExB,yDAAqD;AAYrD;;GAEG;AACH,SAAgB,IAAI,CAAC,OAAe;IACnC,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;AAC1B,CAAC;AAFD,oBAEC;AAED;;;;;;;GAOG;AACH,QAAe,CAAC,CAAC,WAAW,CAC3B,QAAqB,EACrB,GAAgB;IAEhB,KAAK,MAAM,CAAC,IAAI,QAAQ,EAAE,CAAC;QAC1B,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;IACd,CAAC;AACF,CAAC;AAPD,kCAOC;AAED;;;;;;;;GAQG;AACH,SAAgB,WAAW,CAC1B,GAAoB,EACpB,GAAM,EACN,YAA2B;IAE3B,IAAI,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACzB,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACzB,KAAK,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC;QAC1B,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACrB,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC;AAXD,kCAWC;AAaD;;GAEG;AACH,SAAgB,eAAe,CAAI,GAAmB;IACrD,IAAI,GAAG,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;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C;IACtB,CAAC;AACF,CAAC;AATD,sCASC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/* eslint-disable @typescript-eslint/no-unsafe-argument */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n\nimport { assert } from \"@fluidframework/core-utils/internal\";\nimport { isFluidHandle } from \"@fluidframework/runtime-utils\";\nimport { UsageError } from \"@fluidframework/telemetry-utils/internal\";\nimport type { ImplicitFieldSchema, TreeNodeSchemaClass } from \"@fluidframework/tree\";\nimport type {\n\tInsertableContent,\n\tTreeBranch,\n\tTreeNode,\n\tTreeNodeSchema,\n\tTreeViewAlpha,\n\tUnsafeUnknownSchema,\n} from \"@fluidframework/tree/alpha\";\nimport {\n\tArrayNodeSchema,\n\tMapNodeSchema,\n\tObjectNodeSchema,\n\tRecordNodeSchema,\n\tTreeAlpha,\n} from \"@fluidframework/tree/alpha\";\nimport { NodeKind, normalizeFieldSchema } from \"@fluidframework/tree/internal\";\nimport { z } from \"zod\";\n\nimport { FunctionWrapper } from \"./methodBinding.js\";\n\n/**\n * Subset of Map interface.\n *\n * @remarks originally from tree/src/util/utils.ts\n */\nexport interface MapGetSet<K, V> {\n\tget(key: K): V | undefined;\n\tset(key: K, value: V): void;\n}\n\n/**\n * TBD\n */\nexport function fail(message: string): never {\n\tthrow new Error(message);\n}\n\n/**\n * Map one iterable to another by transforming each element one at a time\n * @param iterable - the iterable to transform\n * @param map - the transformation function to run on each element of the iterable\n * @returns a new iterable of elements which have been transformed by the `map` function\n *\n * @remarks originally from tree/src/util/utils.ts\n */\nexport function* mapIterable<T, U>(\n\titerable: Iterable<T>,\n\tmap: (t: T) => U,\n): IterableIterator<U> {\n\tfor (const t of iterable) {\n\t\tyield map(t);\n\t}\n}\n\n/**\n * Retrieve a value from a map with the given key, or create a new entry if the key is not in the map.\n * @param map - The map to query/update\n * @param key - The key to lookup in the map\n * @param defaultValue - a function which returns a default value. This is called and used to set an initial value for the given key in the map if none exists\n * @returns either the existing value for the given key, or the newly-created value (the result of `defaultValue`)\n *\n * @remarks originally from tree/src/util/utils.ts\n */\nexport function getOrCreate<K, V>(\n\tmap: MapGetSet<K, V>,\n\tkey: K,\n\tdefaultValue: (key: K) => V,\n): V {\n\tlet value = map.get(key);\n\tif (value === undefined) {\n\t\tvalue = defaultValue(key);\n\t\tmap.set(key, value);\n\t}\n\treturn value;\n}\n\n/**\n * TODO\n * @alpha\n * @privateRemarks This is a subset of the TreeViewAlpha functionality because if take it wholesale, it causes problems with invariance of the generic parameters.\n */\nexport type TreeView<TRoot extends ImplicitFieldSchema | UnsafeUnknownSchema> = Pick<\n\tTreeViewAlpha<TRoot>,\n\t\"root\" | \"fork\" | \"merge\" | \"rebaseOnto\" | \"schema\" | \"events\"\n> &\n\tTreeBranch;\n\n/**\n * TODO\n */\nexport function tryGetSingleton<T>(set: ReadonlySet<T>): T | undefined {\n\tif (set.size === 1) {\n\t\tfor (const item of set) {\n\t\t\treturn item;\n\t\t}\n\t}\n}\n\n/**\n * Does it have at least two elements?\n */\nexport function hasAtLeastTwo<T>(array: T[]): array is [T, T, ...T[]] {\n\treturn array.length >= 2;\n}\n\n/**\n * Include this property in a field's schema metadata to indicate that the field's value should be generated via a provided function rather than by the LLM.\n * @example\n * ```ts\n * class Object extends schemaFactory.object(\"Object\", {\n * created: sf.required(sf.number, {\n * custom: {\n * // The LLM will ignore this field, and instead it will be populated with the result of the function\n * [llmDefault]: () => Date.now(),\n * },\n * }),\n * }) {};\n * ```\n * @alpha\n */\nexport const llmDefault = Symbol(\"tree-agent/llmDefault\");\n// TODO: make this a wrapper function instead, and hide the symbol.\n// function llmDefault<T extends FieldSchemaMetadata>(metadata: T): T { ... }\n\n/**\n * Usage fail\n */\nexport function failUsage(message: string): never {\n\tthrow new UsageError(message);\n}\n\n/**\n * Construct an object node from a schema and value.\n */\nexport function constructNode(schema: TreeNodeSchema, value: InsertableContent): TreeNode {\n\tconst node = TreeAlpha.create<UnsafeUnknownSchema>(schema, value);\n\tassert(\n\t\tnode !== undefined && node !== null && typeof node === \"object\" && !isFluidHandle(node),\n\t\t0xc1e /* Expected a constructed node to be an object */,\n\t);\n\treturn node;\n}\n\n/**\n * Returns the unqualified name of a tree value's schema (e.g. a node with schema identifier `\"my.scope.MyNode\"` returns `\"MyNode\"`).\n * @remarks If the schema is an inlined array, map, or record type, then it has no name and this function will return a string representation of the type (e.g., `\"MyNode[]\"` or `\"Map<string, MyNode>\"`).\n */\nexport function getFriendlyName(schema: TreeNodeSchema): string {\n\tif (schema.kind === NodeKind.Leaf || isNamedSchema(schema.identifier)) {\n\t\treturn unqualifySchema(schema.identifier);\n\t}\n\n\tconst childNames = Array.from(schema.childTypes, (t) => getFriendlyName(t));\n\tif (schema instanceof ArrayNodeSchema) {\n\t\treturn childNames.length > 1 ? `(${childNames.join(\" | \")})[]` : `${childNames[0]}[]`;\n\t}\n\tif (schema instanceof MapNodeSchema) {\n\t\treturn childNames.length > 1\n\t\t\t? `Map<string, (${childNames.join(\" | \")})>`\n\t\t\t: `Map<string, ${childNames[0]}>`;\n\t}\n\tif (schema instanceof RecordNodeSchema) {\n\t\treturn childNames.length > 1\n\t\t\t? `Record<string, (${childNames.join(\" | \")})>`\n\t\t\t: `Record<string, ${childNames[0]}>`;\n\t}\n\tfail(\"Unexpected node schema\");\n}\n\n/**\n * Returns true if the schema identifier represents a named schema (object, named array, named map, or named record).\n * @remarks This does not include primitive schemas or inlined array/map/record schemas.\n */\nexport function isNamedSchema(schemaIdentifier: string): boolean {\n\tif (\n\t\t[\"string\", \"number\", \"boolean\", \"null\", \"handle\"].includes(\n\t\t\tunqualifySchema(schemaIdentifier),\n\t\t)\n\t) {\n\t\treturn false;\n\t}\n\n\treturn schemaIdentifier.match(/(?:Array|Map|Record)<\\[\"(.*)\"]>/) === null;\n}\n\n/**\n * Returns the unqualified name of a schema (e.g. `\"my.scope.MyNode\"` returns `\"MyNode\"`).\n * @remarks This works by removing all characters before the last dot in the schema name.\n * If there is a dot in a user's schema name, this might produce unexpected results.\n */\nexport function unqualifySchema(schemaIdentifier: string): string {\n\t// Get the unqualified name by removing the scope (everything before the last dot).\n\tconst matches = schemaIdentifier.match(/[^.]+$/);\n\tif (matches === null) {\n\t\treturn schemaIdentifier; // Return the original name if it is unscoped.\n\t}\n\treturn matches[0];\n}\n\n/**\n * Details about the properties of a TypeScript schema represented as Zod.\n */\nexport interface SchemaDetails {\n\thasHelperMethods: boolean;\n}\n\n// TODO: yuck, this entire file has too many statics. we should rewrite it as a generic zod schema walk.\nlet detailsI: SchemaDetails = {\n\thasHelperMethods: false,\n};\n\n/**\n * Returns the TypeScript source code corresponding to a Zod schema. The schema is supplied as an object where each\n * property provides a name for an associated Zod type. The return value is a string containing the TypeScript source\n * code corresponding to the schema. Each property of the schema object is emitted as a named `interface` or `type`\n * declaration for the associated type and is referenced by that name in the emitted type declarations. Other types\n * referenced in the schema are emitted in their structural form.\n * @param schema - A schema object where each property provides a name for an associated Zod type.\n * @param details - Optional details about the schema. The fields will be set according to the details in the given schema.\n * @returns The TypeScript source code corresponding to the schema.\n */\nexport function getZodSchemaAsTypeScript(\n\tschema: Record<string, z.ZodType>,\n\tdetails?: SchemaDetails,\n): string {\n\tdetailsI = details ?? { hasHelperMethods: false };\n\tlet result = \"\";\n\tlet startOfLine = true;\n\tlet indent = 0;\n\tconst entries = [...Object.entries(schema)];\n\tconst namedTypes = new Map<object, string>(\n\t\tentries.map(([name, type]) => [getTypeIdentity(type), name]),\n\t);\n\tfor (const [name, type] of entries) {\n\t\tif (result) {\n\t\t\tappendNewLine();\n\t\t}\n\t\tconst description = type._def.description;\n\t\tif (description !== undefined && description !== \"\") {\n\t\t\tfor (const comment of description.split(\"\\n\")) {\n\t\t\t\tappend(`// ${comment}`);\n\t\t\t\tappendNewLine();\n\t\t\t}\n\t\t}\n\t\tif (getTypeKind(type) === z.ZodFirstPartyTypeKind.ZodObject) {\n\t\t\tappend(`interface ${name} `);\n\t\t\tappendObjectType(type as z.ZodObject<z.ZodRawShape>);\n\t\t} else {\n\t\t\tappend(`type ${name} = `);\n\t\t\tappendTypeDefinition(type);\n\t\t\tappend(\";\");\n\t\t}\n\t\tappendNewLine();\n\t}\n\treturn result;\n\n\tfunction append(s: string) {\n\t\tif (startOfLine) {\n\t\t\tresult += \" \".repeat(indent);\n\t\t\tstartOfLine = false;\n\t\t}\n\t\tresult += s;\n\t}\n\n\tfunction appendNewLine() {\n\t\tappend(\"\\n\");\n\t\tstartOfLine = true;\n\t}\n\n\tfunction appendType(type: z.ZodType, minPrecedence = TypePrecedence.Object) {\n\t\tconst name = namedTypes.get(getTypeIdentity(type));\n\t\tif (name === undefined) {\n\t\t\tconst parenthesize = getTypePrecendece(type) < minPrecedence;\n\t\t\tif (parenthesize) append(\"(\");\n\t\t\tappendTypeDefinition(type);\n\t\t\tif (parenthesize) append(\")\");\n\t\t} else {\n\t\t\tappend(name);\n\t\t}\n\t}\n\n\tfunction appendTypeDefinition(type: z.ZodType) {\n\t\tswitch (getTypeKind(type)) {\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodString: {\n\t\t\t\treturn append(\"string\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodNumber: {\n\t\t\t\treturn append(\"number\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodBoolean: {\n\t\t\t\treturn append(\"boolean\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodDate: {\n\t\t\t\treturn append(\"Date\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodUndefined: {\n\t\t\t\treturn append(\"undefined\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodNull: {\n\t\t\t\treturn append(\"null\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodUnknown: {\n\t\t\t\treturn append(\"unknown\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodArray: {\n\t\t\t\treturn appendArrayType(type);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodObject: {\n\t\t\t\treturn appendObjectType(type);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodUnion: {\n\t\t\t\treturn appendUnionOrIntersectionTypes(\n\t\t\t\t\t(type._def as z.ZodUnionDef).options,\n\t\t\t\t\tTypePrecedence.Union,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: {\n\t\t\t\treturn appendUnionOrIntersectionTypes(\n\t\t\t\t\t[...(type._def as z.ZodDiscriminatedUnionDef<string>).options.values()],\n\t\t\t\t\tTypePrecedence.Union,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodIntersection: {\n\t\t\t\treturn appendUnionOrIntersectionTypes(\n\t\t\t\t\t[\n\t\t\t\t\t\t(type._def as z.ZodIntersectionDef).left,\n\t\t\t\t\t\t(type._def as z.ZodIntersectionDef).right,\n\t\t\t\t\t],\n\t\t\t\t\tTypePrecedence.Intersection,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodTuple: {\n\t\t\t\treturn appendTupleType(type);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodRecord: {\n\t\t\t\treturn appendRecordType(type);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodMap: {\n\t\t\t\treturn appendMapType(type);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodLiteral: {\n\t\t\t\treturn appendLiteral((type._def as z.ZodLiteralDef).value);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodEnum: {\n\t\t\t\treturn append(\n\t\t\t\t\t(type._def as z.ZodEnumDef).values.map((value) => JSON.stringify(value)).join(\" | \"),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodOptional: {\n\t\t\t\treturn appendUnionOrIntersectionTypes(\n\t\t\t\t\t[(type._def as z.ZodOptionalDef).innerType, z.undefined()],\n\t\t\t\t\tTypePrecedence.Union,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodReadonly: {\n\t\t\t\treturn appendReadonlyType(type);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodEffects: {\n\t\t\t\t// Currently, this only handles schema class instances, but there are other cases in which a ZodEffects could theoretically be used.\n\t\t\t\tif (instanceOfs.has(type)) {\n\t\t\t\t\tconst objectNodeSchema = instanceOfs.get(type);\n\t\t\t\t\tif (objectNodeSchema === undefined) {\n\t\t\t\t\t\tthrow new UsageError(\n\t\t\t\t\t\t\t`Unsupported zod effects type when transforming class method: ${getTypeKind(type)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn append(getFriendlyName(objectNodeSchema));\n\t\t\t\t}\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Unsupported zod effects type. Did you use z.instanceOf? Use ExposedMethods.instanceOf function to reference schema classes in methods.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodVoid: {\n\t\t\t\treturn append(\"void\");\n\t\t\t}\n\t\t\tcase z.ZodFirstPartyTypeKind.ZodLazy: {\n\t\t\t\treturn appendType((type._def as z.ZodLazyDef).getter());\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tthrow new UsageError(\n\t\t\t\t\t`Unsupported type when transforming class method: ${getTypeKind(type)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction appendBoundMethods(boundType: z.ZodType): void {\n\t\t// eslint-disable-next-line prefer-const\n\t\tfor (let [name, type] of Object.entries((boundType._def as z.ZodObjectDef).shape())) {\n\t\t\t// Special handling of methods on objects\n\t\t\tconst method = (type as unknown as { method: object | undefined }).method;\n\t\t\tif (method !== undefined && method instanceof FunctionWrapper) {\n\t\t\t\tdetailsI.hasHelperMethods = true;\n\t\t\t\tappend(name);\n\t\t\t\tappend(\"(\");\n\t\t\t\tlet first = true;\n\t\t\t\tfor (const [argName, argType] of method.args) {\n\t\t\t\t\tif (!first) append(\", \");\n\t\t\t\t\tif (getTypeKind(argType) === z.ZodFirstPartyTypeKind.ZodOptional) {\n\t\t\t\t\t\tappend(`${argName}?: `);\n\t\t\t\t\t\tappendType((argType._def as z.ZodOptionalDef).innerType, TypePrecedence.Object);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tappend(`${argName}: `);\n\t\t\t\t\t\tappendType(argType);\n\t\t\t\t\t}\n\t\t\t\t\tfirst = false;\n\t\t\t\t}\n\t\t\t\tif (method.rest !== null) {\n\t\t\t\t\tif (!first) append(\", \");\n\t\t\t\t\tappend(\"...rest: \");\n\t\t\t\t\tappendType(method.rest, TypePrecedence.Object);\n\t\t\t\t\tappend(\"[]\");\n\t\t\t\t}\n\t\t\t\tappend(`): `);\n\t\t\t\tappendType(method.returns, TypePrecedence.Object);\n\t\t\t\tappend(\";\");\n\t\t\t\tif (method.description !== undefined) {\n\t\t\t\t\tappend(` // ${method.description}`);\n\t\t\t\t}\n\t\t\t\tappendNewLine();\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction appendArrayType(arrayType: z.ZodType) {\n\t\tappendType((arrayType._def as z.ZodArrayDef).type, TypePrecedence.Object);\n\t\tappend(\"[]\");\n\t}\n\n\tfunction appendObjectType(objectType: z.ZodType) {\n\t\tappend(\"{\");\n\t\tappendNewLine();\n\t\tindent++;\n\t\t// eslint-disable-next-line prefer-const\n\t\tfor (let [name, type] of Object.entries((objectType._def as z.ZodObjectDef).shape())) {\n\t\t\tconst method = (type as unknown as { method: object | undefined }).method;\n\t\t\tif (method === undefined || !(method instanceof FunctionWrapper)) {\n\t\t\t\tappend(name);\n\t\t\t\tif (getTypeKind(type) === z.ZodFirstPartyTypeKind.ZodOptional) {\n\t\t\t\t\tappend(\"?\");\n\t\t\t\t\ttype = (type._def as z.ZodOptionalDef).innerType;\n\t\t\t\t}\n\t\t\t\tappend(\": \");\n\t\t\t\tappendType(type);\n\t\t\t\tappend(\";\");\n\t\t\t\tconst comment = type.description;\n\t\t\t\tif (comment !== undefined && comment !== \"\") append(` // ${comment}`);\n\t\t\t\tappendNewLine();\n\t\t\t}\n\t\t}\n\t\tappendBoundMethods(objectType);\n\t\tindent--;\n\t\tappend(\"}\");\n\t}\n\n\tfunction appendUnionOrIntersectionTypes(\n\t\ttypes: readonly z.ZodType[],\n\t\tminPrecedence: TypePrecedence,\n\t) {\n\t\tlet first = true;\n\t\tfor (const type of types) {\n\t\t\tif (!first) append(minPrecedence === TypePrecedence.Intersection ? \" & \" : \" | \");\n\t\t\tappendType(type, minPrecedence);\n\t\t\tfirst = false;\n\t\t}\n\t}\n\n\tfunction appendTupleType(tupleType: z.ZodType) {\n\t\tappend(\"[\");\n\t\tlet first = true;\n\t\tfor (const type of (tupleType._def as z.ZodTupleDef<z.ZodTupleItems, z.ZodType>).items) {\n\t\t\tif (!first) append(\", \");\n\t\t\tif (getTypeKind(type) === z.ZodFirstPartyTypeKind.ZodOptional) {\n\t\t\t\tappendType((type._def as z.ZodOptionalDef).innerType, TypePrecedence.Object);\n\t\t\t\tappend(\"?\");\n\t\t\t} else {\n\t\t\t\tappendType(type);\n\t\t\t}\n\t\t\tfirst = false;\n\t\t}\n\t\tconst rest = (tupleType._def as z.ZodTupleDef<z.ZodTupleItems, z.ZodType | null>).rest;\n\t\tif (rest !== null) {\n\t\t\tif (!first) append(\", \");\n\t\t\tappend(\"...\");\n\t\t\tappendType(rest, TypePrecedence.Object);\n\t\t\tappend(\"[]\");\n\t\t}\n\t\tappend(\"]\");\n\t}\n\n\tfunction appendRecordType(recordType: z.ZodType) {\n\t\tappend(\"Record<\");\n\t\tappendType((recordType._def as z.ZodRecordDef).keyType);\n\t\tappend(\", \");\n\t\tappendType((recordType._def as z.ZodRecordDef).valueType);\n\t\tappend(\">\");\n\t}\n\n\tfunction appendMapType(mapType: z.ZodType) {\n\t\tappend(\"Map<\");\n\t\tappendType((mapType._def as z.ZodMapDef).keyType);\n\t\tappend(\", \");\n\t\tappendType((mapType._def as z.ZodMapDef).valueType);\n\t\tappend(\">\");\n\t}\n\n\tfunction appendLiteral(value: unknown) {\n\t\tappend(\n\t\t\ttypeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\"\n\t\t\t\t? JSON.stringify(value)\n\t\t\t\t: \"any\",\n\t\t);\n\t}\n\n\tfunction appendReadonlyType(readonlyType: z.ZodType) {\n\t\tappend(\"Readonly<\");\n\t\tappendType((readonlyType._def as z.ZodReadonlyDef).innerType);\n\t\tappend(\">\");\n\t}\n}\n\nfunction getTypeKind(type: z.ZodType): z.ZodFirstPartyTypeKind {\n\treturn (type._def as z.ZodTypeDef & { typeName: z.ZodFirstPartyTypeKind }).typeName;\n}\n\nfunction getTypeIdentity(type: z.ZodType): object {\n\tswitch (getTypeKind(type)) {\n\t\tcase z.ZodFirstPartyTypeKind.ZodObject: {\n\t\t\treturn (type._def as z.ZodObjectDef).shape();\n\t\t}\n\t\tcase z.ZodFirstPartyTypeKind.ZodEnum: {\n\t\t\treturn (type._def as z.ZodEnumDef).values;\n\t\t}\n\t\tcase z.ZodFirstPartyTypeKind.ZodUnion: {\n\t\t\treturn (type._def as z.ZodUnionDef).options;\n\t\t}\n\t\tdefault: {\n\t\t\treturn type;\n\t\t}\n\t}\n}\n\nconst enum TypePrecedence {\n\tUnion = 0,\n\tIntersection = 1,\n\tObject = 2,\n}\n\nfunction getTypePrecendece(type: z.ZodType): TypePrecedence {\n\tswitch (getTypeKind(type)) {\n\t\tcase z.ZodFirstPartyTypeKind.ZodEnum:\n\t\tcase z.ZodFirstPartyTypeKind.ZodUnion:\n\t\tcase z.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: {\n\t\t\treturn TypePrecedence.Union;\n\t\t}\n\t\tcase z.ZodFirstPartyTypeKind.ZodIntersection: {\n\t\t\treturn TypePrecedence.Intersection;\n\t\t}\n\t\tdefault: {\n\t\t\treturn TypePrecedence.Object;\n\t\t}\n\t}\n}\n\n/**\n * Create a Zod schema for a SharedTree schema class.\n * @alpha\n */\nexport function instanceOf<T extends TreeNodeSchemaClass>(\n\tschema: T,\n): z.ZodType<InstanceType<T>, z.ZodTypeDef, InstanceType<T>> {\n\tif (!(schema instanceof ObjectNodeSchema)) {\n\t\tthrow new UsageError(`${schema.identifier} must be an instance of ObjectNodeSchema.`);\n\t}\n\tconst effect = z.instanceof(schema);\n\tinstanceOfs.set(effect, schema);\n\treturn effect;\n}\n\nconst instanceOfs = new WeakMap<z.ZodTypeAny, ObjectNodeSchema>();\n\n/**\n * Adds all named object, map, array, and record schemas reachable from the given schema to the given set.\n * @remarks This includes transitive child/descendant schemas.\n * It does not include primitive schemas or inlined array/map/record schemas.\n * @returns The set of named schemas added (same as the `schemas` parameter, if supplied).\n */\nexport function findNamedSchemas(\n\tschema: ImplicitFieldSchema,\n\tschemas = new Set<TreeNodeSchema>(),\n): Set<TreeNodeSchema> {\n\tconst set = schemas ?? new Set();\n\tfor (const nodeSchema of normalizeFieldSchema(schema).allowedTypeSet) {\n\t\tif (!set.has(nodeSchema)) {\n\t\t\tif (isNamedSchema(nodeSchema.identifier)) {\n\t\t\t\tset.add(nodeSchema);\n\t\t\t}\n\t\t\tfindNamedSchemas([...nodeSchema.childTypes], set);\n\t\t}\n\t}\n\treturn set;\n}\n\n/**\n * De-capitalize (the first letter of) a string.\n */\nexport function communize(str: string): string {\n\treturn str.charAt(0).toLowerCase() + str.slice(1);\n}\n\n/**\n * Stringify an unknown error value\n */\nexport function toErrorString(error: unknown): string {\n\tif (error instanceof Error) {\n\t\treturn error.message;\n\t}\n\ttry {\n\t\treturn JSON.stringify(error);\n\t} catch {\n\t\treturn String(error);\n\t}\n}\n"]}
package/lib/agent.d.ts CHANGED
@@ -29,7 +29,4 @@ export declare class SharedTreeSemanticAgent<TSchema extends ImplicitFieldSchema
29
29
  */
30
30
  query(userPrompt: string): Promise<string>;
31
31
  }
32
- /**
33
- * Finds the name of the first invocable function in the given code.
34
- */
35
32
  //# sourceMappingURL=agent.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EACX,mBAAmB,EAGnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,KAAK,EACX,aAAa,EAIb,MAAM,4BAA4B,CAAC;AAGpC,OAAO,KAAK,EACX,mBAAmB,EAGnB,oBAAoB,EAEpB,MAAM,UAAU,CAAC;AAIlB,OAAO,EAIN,KAAK,QAAQ,EAEb,MAAM,YAAY,CAAC;AAapB;;;;GAIG;AACH,qBAAa,uBAAuB,CAAC,OAAO,SAAS,mBAAmB;IAStE,OAAO,CAAC,QAAQ,CAAC,MAAM;IAEvB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;IAT1B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAmB;IAC7C;;OAEG;IACH,OAAO,CAAC,gBAAgB,CAAS;gBAGf,MAAM,EAAE,mBAAmB,EAC5C,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,QAAQ,CAAC,EAC5C,OAAO,CAAC,4CAAgC;IAiC1D;;;;;OAKG;IACU,KAAK,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAqEvD;AA8HD;;GAEG"}
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EACX,mBAAmB,EAGnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,KAAK,EACX,aAAa,EAIb,MAAM,4BAA4B,CAAC;AAGpC,OAAO,KAAK,EAAE,mBAAmB,EAAc,oBAAoB,EAAU,MAAM,UAAU,CAAC;AAG9F,OAAO,EAIN,KAAK,QAAQ,EAGb,MAAM,YAAY,CAAC;AAQpB;;;;GAIG;AACH,qBAAa,uBAAuB,CAAC,OAAO,SAAS,mBAAmB;IAStE,OAAO,CAAC,QAAQ,CAAC,MAAM;IAEvB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;IAT1B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAmB;IAC7C;;OAEG;IACH,OAAO,CAAC,gBAAgB,CAAS;gBAGf,MAAM,EAAE,mBAAmB,EAC5C,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,QAAQ,CAAC,EAC5C,OAAO,CAAC,4CAAgC;IAiC1D;;;;;OAKG;IACU,KAAK,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAsEvD"}
package/lib/agent.js CHANGED
@@ -4,19 +4,14 @@
4
4
  */
5
5
  import { TreeNode } from "@fluidframework/tree";
6
6
  import { ObjectNodeSchema, Tree } from "@fluidframework/tree/alpha";
7
- import { findInvocableFunctionName, stripExportSyntax } from "./functionParsing.js";
8
7
  import { getPrompt, stringifyTree } from "./prompt.js";
9
8
  import { Subtree } from "./subtree.js";
10
- import { constructNode, getFriendlyName, llmDefault, findNamedSchemas, } from "./utils.js";
9
+ import { constructNode, getFriendlyName, llmDefault, findNamedSchemas, toErrorString, } from "./utils.js";
11
10
  /**
12
11
  * The default maximum number of sequential edits the LLM can make before we assume it's stuck in a loop.
13
12
  * @remarks This can be overridden by passing {@link SemanticAgentOptions.maximumSequentialEdits | maximumSequentialEdits} to {@link createSemanticAgent}.
14
13
  */
15
14
  const defaultMaxSequentialEdits = 20;
16
- /**
17
- * The name of the parameter passed to the edit function.
18
- */
19
- const paramsName = "params";
20
15
  /**
21
16
  * An agent that uses a {@link SharedTreeChatModel} to interact with a SharedTree.
22
17
  * @remarks This class forwards user queries to the chat model, and handles the application of any edits to the tree that the model requests.
@@ -82,7 +77,7 @@ export class SharedTreeSemanticAgent {
82
77
  let editCount = 0;
83
78
  let editFailed = false;
84
79
  const { editToolName } = this.client;
85
- const edit = async (js) => {
80
+ const edit = async (editCode) => {
86
81
  if (editToolName === undefined) {
87
82
  return {
88
83
  type: "disabledError",
@@ -102,7 +97,7 @@ export class SharedTreeSemanticAgent {
102
97
  message: `The maximum number of edits (${maxEditCount}) for this query has been exceeded.`,
103
98
  };
104
99
  }
105
- const editResult = await applyTreeFunction(queryTree, js, this.options?.validator, this.options?.logger);
100
+ const editResult = await applyTreeFunction(queryTree, editCode, this.options?.validateEdit ?? defaultValidateEdit, this.options?.executeEdit ?? defaultExecuteEdit, this.options?.logger);
106
101
  editFailed ||= editResult.type !== "success";
107
102
  return editResult;
108
103
  };
@@ -152,14 +147,18 @@ function constructTreeNode(schema, value) {
152
147
  /**
153
148
  * Applies the given function (as a string of JavaScript code or an actual function) to the given tree.
154
149
  */
155
- async function applyTreeFunction(tree, fn, validator, logger) {
150
+ async function applyTreeFunction(tree, editCode, validateEdit, executeEdit, logger) {
156
151
  logger?.log(`### Editing Tool Invoked\n\n`);
157
- logger?.log(`#### Generated Code\n\n\`\`\`javascript\n${fn}\n\`\`\`\n\n`);
158
- if (validator?.(fn.toString()) === false) {
152
+ logger?.log(`#### Generated Code\n\n\`\`\`javascript\n${editCode}\n\`\`\`\n\n`);
153
+ try {
154
+ await validateEdit(editCode);
155
+ }
156
+ catch (error) {
159
157
  logger?.log(`#### Code Validation Failed\n\n`);
158
+ logger?.log(`\`\`\`JSON\n${toErrorString(error)}\n\`\`\`\n\n`);
160
159
  return {
161
160
  type: "validationError",
162
- message: "The generated code did not pass validation. Please try again.",
161
+ message: `The generated code did not pass validation: ${toErrorString(error)}`,
163
162
  };
164
163
  }
165
164
  // Stick the tree schema constructors on an object passed to the function so that the LLM can create new nodes.
@@ -170,7 +169,7 @@ async function applyTreeFunction(tree, fn, validator, logger) {
170
169
  }
171
170
  // Fork a branch to edit. If the edit fails or produces an error, we discard this branch, otherwise we merge it.
172
171
  const editTree = tree.fork();
173
- const params = {
172
+ const context = {
174
173
  get root() {
175
174
  return editTree.field;
176
175
  },
@@ -179,36 +178,16 @@ async function applyTreeFunction(tree, fn, validator, logger) {
179
178
  },
180
179
  create,
181
180
  };
182
- let editFunction;
183
- if (typeof fn === "string") {
184
- try {
185
- editFunction = processLlmCode(fn);
186
- }
187
- catch (error) {
188
- logger?.log(`#### Error\n\n`);
189
- const errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
190
- logger?.log(`\`\`\`JSON\n${errorMessage}\n\`\`\`\n\n`);
191
- editTree.branch.dispose();
192
- return {
193
- type: "compileError",
194
- message: `The supplied JavaScript function is not valid: ${errorMessage}`,
195
- };
196
- }
197
- }
198
- else {
199
- editFunction = fn;
200
- }
201
181
  try {
202
- await editFunction(params);
182
+ await executeEdit(context, editCode);
203
183
  }
204
184
  catch (error) {
205
185
  logger?.log(`#### Error\n\n`);
206
- const errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
207
- logger?.log(`\`\`\`JSON\n${errorMessage}\n\`\`\`\n\n`);
186
+ logger?.log(`\`\`\`JSON\n${toErrorString(error)}\n\`\`\`\n\n`);
208
187
  editTree.branch.dispose();
209
188
  return {
210
- type: "runtimeError",
211
- message: `Running the function produced an error. The state of the tree will be reset to its previous state as it was before the function ran. Please try again. Here is the error: ${errorMessage}`,
189
+ type: "executionError",
190
+ message: `Running the generated code produced an error. The state of the tree will be reset to its previous state as it was before the code ran. Please try again. Here is the error: ${toErrorString(error)}`,
212
191
  };
213
192
  }
214
193
  tree.branch.merge(editTree.branch);
@@ -216,20 +195,13 @@ async function applyTreeFunction(tree, fn, validator, logger) {
216
195
  logger?.log(`${`\`\`\`JSON\n${stringifyTree(tree.field)}\n\`\`\``}\n\n`);
217
196
  return {
218
197
  type: "success",
219
- message: `After running the function, the new state of the tree is:\n\n\`\`\`JSON\n${stringifyTree(tree.field)}\n\`\`\``,
198
+ message: `After running the code, the new state of the tree is:\n\n\`\`\`JSON\n${stringifyTree(tree.field)}\n\`\`\``,
220
199
  };
221
200
  }
222
- function processLlmCode(code) {
223
- const functionName = findInvocableFunctionName(code);
224
- if (functionName === undefined) {
225
- throw new Error("Generated code does not contain an invokable function");
226
- }
227
- const executionCode = `${stripExportSyntax(code)}\n\nreturn ${functionName}(${paramsName});`;
201
+ const defaultValidateEdit = () => { };
202
+ const defaultExecuteEdit = async (context, code) => {
228
203
  // eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval
229
- const fn = new Function(paramsName, executionCode);
230
- return fn;
231
- }
232
- /**
233
- * Finds the name of the first invocable function in the given code.
234
- */
204
+ const fn = new Function("context", code);
205
+ await fn(context);
206
+ };
235
207
  //# sourceMappingURL=agent.js.map
package/lib/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAOhD,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,4BAA4B,CAAC;AASpE,OAAO,EAAE,yBAAyB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACpF,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EACN,aAAa,EACb,eAAe,EACf,UAAU,EAEV,gBAAgB,GAChB,MAAM,YAAY,CAAC;AAEpB;;;GAGG;AACH,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAErC;;GAEG;AACH,MAAM,UAAU,GAAG,QAAQ,CAAC;AAE5B;;;;GAIG;AACH,MAAM,OAAO,uBAAuB;IAQnC,YACkB,MAA2B,EAC5C,IAA6D,EAC5C,OAAwC;QAFxC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C3E,MAAM,EAAE,GAAG,IAAI,QAAQ,CAAC,UAAU,EAAE,aAAa,CAAC,CAAC;IACnD,OAAO,EAA2B,CAAC;AACpC,CAAC;AAED;;GAEG","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type {\n\tImplicitFieldSchema,\n\tTreeFieldFromImplicitField,\n\tTreeNodeSchema,\n} from \"@fluidframework/tree\";\nimport { TreeNode } from \"@fluidframework/tree\";\nimport type {\n\tReadableField,\n\tFactoryContentObject,\n\tInsertableContent,\n\tReadSchema,\n} from \"@fluidframework/tree/alpha\";\nimport { ObjectNodeSchema, Tree } from \"@fluidframework/tree/alpha\";\n\nimport type {\n\tSharedTreeChatModel,\n\tEditFunction,\n\tEditResult,\n\tSemanticAgentOptions,\n\tLogger,\n} from \"./api.js\";\nimport { findInvocableFunctionName, stripExportSyntax } from \"./functionParsing.js\";\nimport { getPrompt, stringifyTree } from \"./prompt.js\";\nimport { Subtree } from \"./subtree.js\";\nimport {\n\tconstructNode,\n\tgetFriendlyName,\n\tllmDefault,\n\ttype TreeView,\n\tfindNamedSchemas,\n} from \"./utils.js\";\n\n/**\n * The default maximum number of sequential edits the LLM can make before we assume it's stuck in a loop.\n * @remarks This can be overridden by passing {@link SemanticAgentOptions.maximumSequentialEdits | maximumSequentialEdits} to {@link createSemanticAgent}.\n */\nconst defaultMaxSequentialEdits = 20;\n\n/**\n * The name of the parameter passed to the edit function.\n */\nconst paramsName = \"params\";\n\n/**\n * An agent that uses a {@link SharedTreeChatModel} to interact with a SharedTree.\n * @remarks This class forwards user queries to the chat model, and handles the application of any edits to the tree that the model requests.\n * @alpha @sealed\n */\nexport class SharedTreeSemanticAgent<TSchema extends ImplicitFieldSchema> {\n\t// Converted from ECMAScript private fields (#name) to TypeScript private members for easier debugger inspection.\n\tprivate readonly outerTree: Subtree<TSchema>;\n\t/**\n\t * Whether or not the outer tree has changed since the last query finished.\n\t */\n\tprivate outerTreeIsDirty = false;\n\n\tpublic constructor(\n\t\tprivate readonly client: SharedTreeChatModel,\n\t\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\t\tprivate readonly options?: Readonly<SemanticAgentOptions>,\n\t) {\n\t\tif (tree instanceof TreeNode) {\n\t\t\tTree.on(tree, \"treeChanged\", () => (this.outerTreeIsDirty = true));\n\t\t} else {\n\t\t\ttree.events.on(\"changed\", () => (this.outerTreeIsDirty = true));\n\t\t}\n\n\t\tthis.outerTree = new Subtree(tree);\n\t\tconst prompt = getPrompt({\n\t\t\tsubtree: this.outerTree,\n\t\t\teditToolName: this.client.editToolName,\n\t\t\tdomainHints: this.options?.domainHints,\n\t\t});\n\t\tthis.options?.logger?.log(`# Fluid Framework SharedTree AI Agent Log\\n\\n`);\n\t\tconst now = new Date();\n\t\tconst formattedDate = now.toLocaleString(undefined, {\n\t\t\tweekday: \"long\",\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"long\",\n\t\t\tday: \"numeric\",\n\t\t\thour: \"numeric\",\n\t\t\tminute: \"2-digit\",\n\t\t\tsecond: \"2-digit\",\n\t\t});\n\t\tthis.options?.logger?.log(`Agent created: **${formattedDate}**\\n\\n`);\n\t\tif (this.client.name !== undefined) {\n\t\t\tthis.options?.logger?.log(`Model: **${this.client.name}**\\n\\n`);\n\t\t}\n\t\tthis.client.appendContext?.(prompt);\n\t\tthis.options?.logger?.log(`## System Prompt\\n\\n${prompt}\\n\\n`);\n\t}\n\n\t/**\n\t * Given a user prompt, return a response.\n\t *\n\t * @param userPrompt - The prompt to send to the agent.\n\t * @returns The agent's response.\n\t */\n\tpublic async query(userPrompt: string): Promise<string> {\n\t\tthis.options?.logger?.log(`## User Query\\n\\n${userPrompt}\\n\\n`);\n\n\t\t// Notify the llm if the tree has changed since the last query, and if so, provide the new state of the tree.\n\t\tif (this.outerTreeIsDirty) {\n\t\t\tconst stringified = stringifyTree(this.outerTree.field);\n\t\t\tthis.client.appendContext?.(\n\t\t\t\t`The tree has changed since the last query. The new state of the tree is: \\n\\n\\`\\`\\`JSON\\n${stringified}\\n\\`\\`\\``,\n\t\t\t);\n\t\t\tthis.options?.logger?.log(\n\t\t\t\t`### Latest Tree State\\n\\nThe Tree was edited by a local or remote user since the previous query. The latest state is:\\n\\n\\`\\`\\`JSON\\n${stringified}\\n\\`\\`\\`\\n\\n`,\n\t\t\t);\n\t\t}\n\n\t\t// Fork a branch that will live for the lifetime of this query (which can be multiple LLM calls if the there are errors or the LLM decides to take multiple steps to accomplish a task).\n\t\t// The branch will be merged back into the outer branch if and only if the query succeeds.\n\t\tconst queryTree = this.outerTree.fork();\n\t\tconst maxEditCount = this.options?.maximumSequentialEdits ?? defaultMaxSequentialEdits;\n\t\tlet active = true;\n\t\tlet editCount = 0;\n\t\tlet editFailed = false;\n\t\tconst { editToolName } = this.client;\n\t\tconst edit = async (js: string): Promise<EditResult> => {\n\t\t\tif (editToolName === undefined) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"disabledError\",\n\t\t\t\t\tmessage: \"Editing is not enabled for this model.\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!active) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"expiredError\",\n\t\t\t\t\tmessage: `The query has already completed. Further edits are not allowed.`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (++editCount > maxEditCount) {\n\t\t\t\teditFailed = true;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"tooManyEditsError\",\n\t\t\t\t\tmessage: `The maximum number of edits (${maxEditCount}) for this query has been exceeded.`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst editResult = await applyTreeFunction(\n\t\t\t\tqueryTree,\n\t\t\t\tjs,\n\t\t\t\tthis.options?.validator,\n\t\t\t\tthis.options?.logger,\n\t\t\t);\n\n\t\t\teditFailed ||= editResult.type !== \"success\";\n\t\t\treturn editResult;\n\t\t};\n\n\t\tconst responseMessage = await this.client.query({\n\t\t\ttext: userPrompt,\n\t\t\tedit,\n\t\t});\n\t\tactive = false;\n\n\t\tif (!editFailed) {\n\t\t\tthis.outerTree.branch.merge(queryTree.branch);\n\t\t\tthis.outerTreeIsDirty = false;\n\t\t}\n\t\tthis.options?.logger?.log(`## Response\\n\\n`);\n\t\tthis.options?.logger?.log(`${responseMessage}\\n\\n`);\n\t\treturn responseMessage;\n\t}\n}\n\n/**\n * Creates an unhydrated node of the given schema with the given value.\n * @remarks If the schema is an object with {@link llmDefault | default values}, this function populates the node with those defaults.\n */\nfunction constructTreeNode(schema: TreeNodeSchema, value: FactoryContentObject): TreeNode {\n\tif (schema instanceof ObjectNodeSchema) {\n\t\tconst inputWithDefaults: Record<string, InsertableContent | undefined> = {};\n\t\tfor (const [key, field] of schema.fields) {\n\t\t\tif (value[key] === undefined) {\n\t\t\t\tif (\n\t\t\t\t\ttypeof field.metadata.custom === \"object\" &&\n\t\t\t\t\tfield.metadata.custom !== null &&\n\t\t\t\t\tllmDefault in field.metadata.custom\n\t\t\t\t) {\n\t\t\t\t\tconst defaulter = field.metadata.custom[llmDefault];\n\t\t\t\t\tif (typeof defaulter === \"function\") {\n\t\t\t\t\t\tconst defaultValue: unknown = defaulter();\n\t\t\t\t\t\tif (defaultValue !== undefined) {\n\t\t\t\t\t\t\tinputWithDefaults[key] = defaultValue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tinputWithDefaults[key] = value[key];\n\t\t\t}\n\t\t}\n\t\treturn constructNode(schema, inputWithDefaults);\n\t}\n\treturn constructNode(schema, value);\n}\n\n/**\n * Applies the given function (as a string of JavaScript code or an actual function) to the given tree.\n */\nasync function applyTreeFunction<TSchema extends ImplicitFieldSchema>(\n\ttree: Subtree<TSchema>,\n\tfn: string | EditFunction<TSchema>,\n\tvalidator: ((js: string) => boolean) | undefined,\n\tlogger: Logger | undefined,\n): Promise<EditResult> {\n\tlogger?.log(`### Editing Tool Invoked\\n\\n`);\n\tlogger?.log(`#### Generated Code\\n\\n\\`\\`\\`javascript\\n${fn}\\n\\`\\`\\`\\n\\n`);\n\n\tif (validator?.(fn.toString()) === false) {\n\t\tlogger?.log(`#### Code Validation Failed\\n\\n`);\n\t\treturn {\n\t\t\ttype: \"validationError\",\n\t\t\tmessage: \"The generated code did not pass validation. Please try again.\",\n\t\t};\n\t}\n\n\t// Stick the tree schema constructors on an object passed to the function so that the LLM can create new nodes.\n\tconst create: Record<string, (input: FactoryContentObject) => TreeNode> = {};\n\tfor (const schema of findNamedSchemas(tree.schema)) {\n\t\tconst name = getFriendlyName(schema);\n\t\tcreate[name] = (input: FactoryContentObject) => constructTreeNode(schema, input);\n\t}\n\n\t// Fork a branch to edit. If the edit fails or produces an error, we discard this branch, otherwise we merge it.\n\tconst editTree = tree.fork();\n\tconst params = {\n\t\tget root(): ReadableField<TSchema> {\n\t\t\treturn editTree.field;\n\t\t},\n\t\tset root(value: TreeFieldFromImplicitField<ReadSchema<TSchema>>) {\n\t\t\teditTree.field = value;\n\t\t},\n\t\tcreate,\n\t};\n\n\tlet editFunction: EditFunction<TSchema>;\n\tif (typeof fn === \"string\") {\n\t\ttry {\n\t\t\teditFunction = processLlmCode(fn);\n\t\t} catch (error) {\n\t\t\tlogger?.log(`#### Error\\n\\n`);\n\t\t\tconst errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\t\tlogger?.log(`\\`\\`\\`JSON\\n${errorMessage}\\n\\`\\`\\`\\n\\n`);\n\t\t\teditTree.branch.dispose();\n\t\t\treturn {\n\t\t\t\ttype: \"compileError\",\n\t\t\t\tmessage: `The supplied JavaScript function is not valid: ${errorMessage}`,\n\t\t\t};\n\t\t}\n\t} else {\n\t\teditFunction = fn;\n\t}\n\n\ttry {\n\t\tawait editFunction(params);\n\t} catch (error: unknown) {\n\t\tlogger?.log(`#### Error\\n\\n`);\n\t\tconst errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\tlogger?.log(`\\`\\`\\`JSON\\n${errorMessage}\\n\\`\\`\\`\\n\\n`);\n\t\teditTree.branch.dispose();\n\t\treturn {\n\t\t\ttype: \"runtimeError\",\n\t\t\tmessage: `Running the function produced an error. The state of the tree will be reset to its previous state as it was before the function ran. Please try again. Here is the error: ${errorMessage}`,\n\t\t};\n\t}\n\n\ttree.branch.merge(editTree.branch);\n\tlogger?.log(`#### New Tree State\\n\\n`);\n\tlogger?.log(`${`\\`\\`\\`JSON\\n${stringifyTree(tree.field)}\\n\\`\\`\\``}\\n\\n`);\n\treturn {\n\t\ttype: \"success\",\n\t\tmessage: `After running the function, the new state of the tree is:\\n\\n\\`\\`\\`JSON\\n${stringifyTree(tree.field)}\\n\\`\\`\\``,\n\t};\n}\n\nfunction processLlmCode<TSchema extends ImplicitFieldSchema>(\n\tcode: string,\n): EditFunction<TSchema> {\n\tconst functionName = findInvocableFunctionName(code);\n\tif (functionName === undefined) {\n\t\tthrow new Error(\"Generated code does not contain an invokable function\");\n\t}\n\n\tconst executionCode = `${stripExportSyntax(code)}\\n\\nreturn ${functionName}(${paramsName});`;\n\t// eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval\n\tconst fn = new Function(paramsName, executionCode);\n\treturn fn as EditFunction<TSchema>;\n}\n\n/**\n * Finds the name of the first invocable function in the given code.\n */\n"]}
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAOhD,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,4BAA4B,CAAC;AAGpE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EACN,aAAa,EACb,eAAe,EACf,UAAU,EAEV,gBAAgB,EAChB,aAAa,GACb,MAAM,YAAY,CAAC;AAEpB;;;GAGG;AACH,MAAM,yBAAyB,GAAG,EAAE,C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D,QAAQ,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QAC1B,OAAO;YACN,IAAI,EAAE,gBAAgB;YACtB,OAAO,EAAE,+KAA+K,aAAa,CAAC,KAAK,CAAC,EAAE;SAC9M,CAAC;IACH,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACnC,MAAM,EAAE,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,MAAM,EAAE,GAAG,CAAC,GAAG,eAAe,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,MAAM,CAAC,CAAC;IACzE,OAAO;QACN,IAAI,EAAE,SAAS;QACf,OAAO,EAAE,wEAAwE,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU;KACpH,CAAC;AACH,CAAC;AAED,MAAM,mBAAmB,GAAmD,GAAG,EAAE,GAAE,CAAC,CAAC;AAErF,MAAM,kBAAkB,GAAkD,KAAK,EAC9E,OAAO,EACP,IAAI,EACH,EAAE;IACH,2EAA2E;IAC3E,MAAM,EAAE,GAAG,IAAI,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IACzC,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC;AACnB,CAAC,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type {\n\tImplicitFieldSchema,\n\tTreeFieldFromImplicitField,\n\tTreeNodeSchema,\n} from \"@fluidframework/tree\";\nimport { TreeNode } from \"@fluidframework/tree\";\nimport type {\n\tReadableField,\n\tFactoryContentObject,\n\tInsertableContent,\n\tReadSchema,\n} from \"@fluidframework/tree/alpha\";\nimport { ObjectNodeSchema, Tree } from \"@fluidframework/tree/alpha\";\n\nimport type { SharedTreeChatModel, EditResult, SemanticAgentOptions, Logger } from \"./api.js\";\nimport { getPrompt, stringifyTree } from \"./prompt.js\";\nimport { Subtree } from \"./subtree.js\";\nimport {\n\tconstructNode,\n\tgetFriendlyName,\n\tllmDefault,\n\ttype TreeView,\n\tfindNamedSchemas,\n\ttoErrorString,\n} from \"./utils.js\";\n\n/**\n * The default maximum number of sequential edits the LLM can make before we assume it's stuck in a loop.\n * @remarks This can be overridden by passing {@link SemanticAgentOptions.maximumSequentialEdits | maximumSequentialEdits} to {@link createSemanticAgent}.\n */\nconst defaultMaxSequentialEdits = 20;\n\n/**\n * An agent that uses a {@link SharedTreeChatModel} to interact with a SharedTree.\n * @remarks This class forwards user queries to the chat model, and handles the application of any edits to the tree that the model requests.\n * @alpha @sealed\n */\nexport class SharedTreeSemanticAgent<TSchema extends ImplicitFieldSchema> {\n\t// Converted from ECMAScript private fields (#name) to TypeScript private members for easier debugger inspection.\n\tprivate readonly outerTree: Subtree<TSchema>;\n\t/**\n\t * Whether or not the outer tree has changed since the last query finished.\n\t */\n\tprivate outerTreeIsDirty = false;\n\n\tpublic constructor(\n\t\tprivate readonly client: SharedTreeChatModel,\n\t\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\t\tprivate readonly options?: Readonly<SemanticAgentOptions>,\n\t) {\n\t\tif (tree instanceof TreeNode) {\n\t\t\tTree.on(tree, \"treeChanged\", () => (this.outerTreeIsDirty = true));\n\t\t} else {\n\t\t\ttree.events.on(\"changed\", () => (this.outerTreeIsDirty = true));\n\t\t}\n\n\t\tthis.outerTree = new Subtree(tree);\n\t\tconst prompt = getPrompt({\n\t\t\tsubtree: this.outerTree,\n\t\t\teditToolName: this.client.editToolName,\n\t\t\tdomainHints: this.options?.domainHints,\n\t\t});\n\t\tthis.options?.logger?.log(`# Fluid Framework SharedTree AI Agent Log\\n\\n`);\n\t\tconst now = new Date();\n\t\tconst formattedDate = now.toLocaleString(undefined, {\n\t\t\tweekday: \"long\",\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"long\",\n\t\t\tday: \"numeric\",\n\t\t\thour: \"numeric\",\n\t\t\tminute: \"2-digit\",\n\t\t\tsecond: \"2-digit\",\n\t\t});\n\t\tthis.options?.logger?.log(`Agent created: **${formattedDate}**\\n\\n`);\n\t\tif (this.client.name !== undefined) {\n\t\t\tthis.options?.logger?.log(`Model: **${this.client.name}**\\n\\n`);\n\t\t}\n\t\tthis.client.appendContext?.(prompt);\n\t\tthis.options?.logger?.log(`## System Prompt\\n\\n${prompt}\\n\\n`);\n\t}\n\n\t/**\n\t * Given a user prompt, return a response.\n\t *\n\t * @param userPrompt - The prompt to send to the agent.\n\t * @returns The agent's response.\n\t */\n\tpublic async query(userPrompt: string): Promise<string> {\n\t\tthis.options?.logger?.log(`## User Query\\n\\n${userPrompt}\\n\\n`);\n\n\t\t// Notify the llm if the tree has changed since the last query, and if so, provide the new state of the tree.\n\t\tif (this.outerTreeIsDirty) {\n\t\t\tconst stringified = stringifyTree(this.outerTree.field);\n\t\t\tthis.client.appendContext?.(\n\t\t\t\t`The tree has changed since the last query. The new state of the tree is: \\n\\n\\`\\`\\`JSON\\n${stringified}\\n\\`\\`\\``,\n\t\t\t);\n\t\t\tthis.options?.logger?.log(\n\t\t\t\t`### Latest Tree State\\n\\nThe Tree was edited by a local or remote user since the previous query. The latest state is:\\n\\n\\`\\`\\`JSON\\n${stringified}\\n\\`\\`\\`\\n\\n`,\n\t\t\t);\n\t\t}\n\n\t\t// Fork a branch that will live for the lifetime of this query (which can be multiple LLM calls if the there are errors or the LLM decides to take multiple steps to accomplish a task).\n\t\t// The branch will be merged back into the outer branch if and only if the query succeeds.\n\t\tconst queryTree = this.outerTree.fork();\n\t\tconst maxEditCount = this.options?.maximumSequentialEdits ?? defaultMaxSequentialEdits;\n\t\tlet active = true;\n\t\tlet editCount = 0;\n\t\tlet editFailed = false;\n\t\tconst { editToolName } = this.client;\n\t\tconst edit = async (editCode: string): Promise<EditResult> => {\n\t\t\tif (editToolName === undefined) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"disabledError\",\n\t\t\t\t\tmessage: \"Editing is not enabled for this model.\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!active) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"expiredError\",\n\t\t\t\t\tmessage: `The query has already completed. Further edits are not allowed.`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (++editCount > maxEditCount) {\n\t\t\t\teditFailed = true;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"tooManyEditsError\",\n\t\t\t\t\tmessage: `The maximum number of edits (${maxEditCount}) for this query has been exceeded.`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst editResult = await applyTreeFunction(\n\t\t\t\tqueryTree,\n\t\t\t\teditCode,\n\t\t\t\tthis.options?.validateEdit ?? defaultValidateEdit,\n\t\t\t\tthis.options?.executeEdit ?? defaultExecuteEdit,\n\t\t\t\tthis.options?.logger,\n\t\t\t);\n\n\t\t\teditFailed ||= editResult.type !== \"success\";\n\t\t\treturn editResult;\n\t\t};\n\n\t\tconst responseMessage = await this.client.query({\n\t\t\ttext: userPrompt,\n\t\t\tedit,\n\t\t});\n\t\tactive = false;\n\n\t\tif (!editFailed) {\n\t\t\tthis.outerTree.branch.merge(queryTree.branch);\n\t\t\tthis.outerTreeIsDirty = false;\n\t\t}\n\t\tthis.options?.logger?.log(`## Response\\n\\n`);\n\t\tthis.options?.logger?.log(`${responseMessage}\\n\\n`);\n\t\treturn responseMessage;\n\t}\n}\n\n/**\n * Creates an unhydrated node of the given schema with the given value.\n * @remarks If the schema is an object with {@link llmDefault | default values}, this function populates the node with those defaults.\n */\nfunction constructTreeNode(schema: TreeNodeSchema, value: FactoryContentObject): TreeNode {\n\tif (schema instanceof ObjectNodeSchema) {\n\t\tconst inputWithDefaults: Record<string, InsertableContent | undefined> = {};\n\t\tfor (const [key, field] of schema.fields) {\n\t\t\tif (value[key] === undefined) {\n\t\t\t\tif (\n\t\t\t\t\ttypeof field.metadata.custom === \"object\" &&\n\t\t\t\t\tfield.metadata.custom !== null &&\n\t\t\t\t\tllmDefault in field.metadata.custom\n\t\t\t\t) {\n\t\t\t\t\tconst defaulter = field.metadata.custom[llmDefault];\n\t\t\t\t\tif (typeof defaulter === \"function\") {\n\t\t\t\t\t\tconst defaultValue: unknown = defaulter();\n\t\t\t\t\t\tif (defaultValue !== undefined) {\n\t\t\t\t\t\t\tinputWithDefaults[key] = defaultValue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tinputWithDefaults[key] = value[key];\n\t\t\t}\n\t\t}\n\t\treturn constructNode(schema, inputWithDefaults);\n\t}\n\treturn constructNode(schema, value);\n}\n\n/**\n * Applies the given function (as a string of JavaScript code or an actual function) to the given tree.\n */\nasync function applyTreeFunction<TSchema extends ImplicitFieldSchema>(\n\ttree: Subtree<TSchema>,\n\teditCode: string,\n\tvalidateEdit: Required<SemanticAgentOptions>[\"validateEdit\"],\n\texecuteEdit: Required<SemanticAgentOptions>[\"executeEdit\"],\n\tlogger: Logger | undefined,\n): Promise<EditResult> {\n\tlogger?.log(`### Editing Tool Invoked\\n\\n`);\n\tlogger?.log(`#### Generated Code\\n\\n\\`\\`\\`javascript\\n${editCode}\\n\\`\\`\\`\\n\\n`);\n\n\ttry {\n\t\tawait validateEdit(editCode);\n\t} catch (error: unknown) {\n\t\tlogger?.log(`#### Code Validation Failed\\n\\n`);\n\t\tlogger?.log(`\\`\\`\\`JSON\\n${toErrorString(error)}\\n\\`\\`\\`\\n\\n`);\n\t\treturn {\n\t\t\ttype: \"validationError\",\n\t\t\tmessage: `The generated code did not pass validation: ${toErrorString(error)}`,\n\t\t};\n\t}\n\n\t// Stick the tree schema constructors on an object passed to the function so that the LLM can create new nodes.\n\tconst create: Record<string, (input: FactoryContentObject) => TreeNode> = {};\n\tfor (const schema of findNamedSchemas(tree.schema)) {\n\t\tconst name = getFriendlyName(schema);\n\t\tcreate[name] = (input: FactoryContentObject) => constructTreeNode(schema, input);\n\t}\n\n\t// Fork a branch to edit. If the edit fails or produces an error, we discard this branch, otherwise we merge it.\n\tconst editTree = tree.fork();\n\tconst context = {\n\t\tget root(): ReadableField<TSchema> {\n\t\t\treturn editTree.field;\n\t\t},\n\t\tset root(value: TreeFieldFromImplicitField<ReadSchema<TSchema>>) {\n\t\t\teditTree.field = value;\n\t\t},\n\t\tcreate,\n\t};\n\n\ttry {\n\t\tawait executeEdit(context, editCode);\n\t} catch (error: unknown) {\n\t\tlogger?.log(`#### Error\\n\\n`);\n\t\tlogger?.log(`\\`\\`\\`JSON\\n${toErrorString(error)}\\n\\`\\`\\`\\n\\n`);\n\t\teditTree.branch.dispose();\n\t\treturn {\n\t\t\ttype: \"executionError\",\n\t\t\tmessage: `Running the generated code produced an error. The state of the tree will be reset to its previous state as it was before the code ran. Please try again. Here is the error: ${toErrorString(error)}`,\n\t\t};\n\t}\n\n\ttree.branch.merge(editTree.branch);\n\tlogger?.log(`#### New Tree State\\n\\n`);\n\tlogger?.log(`${`\\`\\`\\`JSON\\n${stringifyTree(tree.field)}\\n\\`\\`\\``}\\n\\n`);\n\treturn {\n\t\ttype: \"success\",\n\t\tmessage: `After running the code, the new state of the tree is:\\n\\n\\`\\`\\`JSON\\n${stringifyTree(tree.field)}\\n\\`\\`\\``,\n\t};\n}\n\nconst defaultValidateEdit: Required<SemanticAgentOptions>[\"validateEdit\"] = () => {};\n\nconst defaultExecuteEdit: Required<SemanticAgentOptions>[\"executeEdit\"] = async (\n\tcontext,\n\tcode,\n) => {\n\t// eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval\n\tconst fn = new Function(\"context\", code);\n\tawait fn(context);\n};\n"]}
package/lib/alpha.d.ts CHANGED
@@ -25,7 +25,6 @@ export {
25
25
  FunctionDef,
26
26
  IExposedMethods,
27
27
  Infer,
28
- LangchainChatModel,
29
28
  Logger,
30
29
  MethodKeys,
31
30
  SemanticAgentOptions,
@@ -34,7 +33,6 @@ export {
34
33
  SharedTreeSemanticAgent,
35
34
  TreeView,
36
35
  buildFunc,
37
- createSemanticAgent,
38
36
  exposeMethodsSymbol,
39
37
  llmDefault
40
38
  // #endregion