@fluidframework/tree-agent 2.70.0-360374 → 2.70.0-361092
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.
- package/api-report/tree-agent.alpha.api.md +20 -3
- package/dist/agent.d.ts +30 -1
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +57 -33
- package/dist/agent.js.map +1 -1
- package/dist/alpha.d.ts +5 -0
- package/dist/api.d.ts +84 -17
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/prompt.d.ts.map +1 -1
- package/dist/prompt.js +83 -17
- package/dist/prompt.js.map +1 -1
- package/lib/agent.d.ts +30 -1
- package/lib/agent.d.ts.map +1 -1
- package/lib/agent.js +54 -32
- package/lib/agent.js.map +1 -1
- package/lib/alpha.d.ts +5 -0
- package/lib/api.d.ts +84 -17
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js.map +1 -1
- package/lib/index.d.ts +2 -2
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/prompt.d.ts.map +1 -1
- package/lib/prompt.js +82 -16
- package/lib/prompt.js.map +1 -1
- package/package.json +13 -15
- package/src/agent.ts +94 -41
- package/src/api.ts +98 -24
- package/src/index.ts +8 -1
- package/src/prompt.ts +89 -18
package/dist/prompt.js
CHANGED
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
*/
|
|
6
6
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
7
|
exports.stringifyTree = exports.getPrompt = void 0;
|
|
8
|
+
const internal_1 = require("@fluidframework/core-utils/internal");
|
|
8
9
|
const tree_1 = require("@fluidframework/tree");
|
|
9
10
|
const alpha_1 = require("@fluidframework/tree/alpha");
|
|
10
|
-
const
|
|
11
|
+
const internal_2 = require("@fluidframework/tree/internal");
|
|
11
12
|
const typeGeneration_js_1 = require("./typeGeneration.js");
|
|
12
13
|
const utils_js_1 = require("./utils.js");
|
|
13
14
|
/**
|
|
@@ -20,10 +21,19 @@ function getPrompt(args) {
|
|
|
20
21
|
const mapInterfaceName = "TreeMap";
|
|
21
22
|
const simpleSchema = (0, alpha_1.getSimpleSchema)(schema);
|
|
22
23
|
// Inspect the schema to determine what kinds of nodes are possible - this will affect how much information we need to include in the prompt.
|
|
24
|
+
const rootTypes = [...(0, internal_2.normalizeFieldSchema)(schema).allowedTypeSet];
|
|
25
|
+
const rootTypeUnion = `${rootTypes.map((t) => (0, utils_js_1.getFriendlyName)(t)).join(" | ")}`;
|
|
26
|
+
let nodeTypeUnion;
|
|
23
27
|
let hasArrays = false;
|
|
24
28
|
let hasMaps = false;
|
|
25
29
|
let exampleObjectName;
|
|
26
30
|
for (const [definition, nodeSchema] of simpleSchema.definitions) {
|
|
31
|
+
if (nodeSchema.kind !== tree_1.NodeKind.Leaf) {
|
|
32
|
+
nodeTypeUnion =
|
|
33
|
+
nodeTypeUnion === undefined
|
|
34
|
+
? (0, utils_js_1.unqualifySchema)(definition)
|
|
35
|
+
: `${nodeTypeUnion} | ${(0, utils_js_1.unqualifySchema)(definition)}`;
|
|
36
|
+
}
|
|
27
37
|
switch (nodeSchema.kind) {
|
|
28
38
|
case tree_1.NodeKind.Array: {
|
|
29
39
|
hasArrays = true;
|
|
@@ -52,22 +62,75 @@ function getPrompt(args) {
|
|
|
52
62
|
const stringified = stringifyTree(field);
|
|
53
63
|
const details = { hasHelperMethods: false };
|
|
54
64
|
const typescriptSchemaTypes = (0, utils_js_1.getZodSchemaAsTypeScript)(domainTypes, details);
|
|
65
|
+
const create = exampleObjectName === undefined
|
|
66
|
+
? ""
|
|
67
|
+
: `\n /**
|
|
68
|
+
* A collection of builder functions for creating new tree nodes.
|
|
69
|
+
* @remarks
|
|
70
|
+
* Each property on this object is named after a type in the tree schema.
|
|
71
|
+
* Call the corresponding function to create a new node of that type.
|
|
72
|
+
* Always use these builder functions when creating new nodes rather than plain JavaScript objects.
|
|
73
|
+
*
|
|
74
|
+
* For example:
|
|
75
|
+
*
|
|
76
|
+
* \`\`\`javascript
|
|
77
|
+
* // This creates a new ${exampleObjectName} object:
|
|
78
|
+
* const ${(0, utils_js_1.communize)(exampleObjectName)} = context.create.${exampleObjectName}({ ...properties });
|
|
79
|
+
* // Don't do this:
|
|
80
|
+
* // const ${(0, utils_js_1.communize)(exampleObjectName)} = { ...properties };
|
|
81
|
+
* \`\`\`
|
|
82
|
+
*/
|
|
83
|
+
create: Record<string, <T extends TreeData>(input: T) => T>;\n`;
|
|
84
|
+
const isDocs = exampleObjectName === undefined
|
|
85
|
+
? ""
|
|
86
|
+
: `\n /**
|
|
87
|
+
* A collection of type-guard functions for data in the tree.
|
|
88
|
+
* @remarks
|
|
89
|
+
* Each property on this object is named after a type in the tree schema.
|
|
90
|
+
* Call the corresponding function to check if a node is of that specific type.
|
|
91
|
+
* This is useful when working with nodes that could be one of multiple types.
|
|
92
|
+
*
|
|
93
|
+
* ${`Example: Check if a node is a ${exampleObjectName} with \`if (context.is.${exampleObjectName}(node)) {}\``}
|
|
94
|
+
*/
|
|
95
|
+
is: Record<string, <T extends TreeData>(input: unknown) => input is T>;\n`;
|
|
96
|
+
const context = `\`\`\`typescript
|
|
97
|
+
${nodeTypeUnion === undefined ? "" : `type TreeData = ${nodeTypeUnion};\n\n`} /**
|
|
98
|
+
* An object available to generated code which provides read and write access to the tree as well as utilities for creating and inspecting data in the tree.
|
|
99
|
+
* @remarks This object is available as a variable named \`context\` in the scope of the generated JavaScript snippet.
|
|
100
|
+
*/
|
|
101
|
+
interface Context<TSchema extends ImplicitFieldSchema> {
|
|
102
|
+
/**
|
|
103
|
+
* The root of the tree that can be read or mutated.
|
|
104
|
+
* @remarks
|
|
105
|
+
* You can read properties and navigate through the tree starting from this root.
|
|
106
|
+
* You can also assign a new value to this property to replace the entire tree, as long as the new value is one of the types allowed at the root.
|
|
107
|
+
*
|
|
108
|
+
* Example: Read the current root with \`const currentRoot = context.root;\`
|
|
109
|
+
*${rootTypes.length > 0 ? ` Example: Replace the entire root with \`context.root = context.create.${(0, utils_js_1.getFriendlyName)(rootTypes[0] ?? (0, internal_1.oob)())}({ });\`\n *` : ""}/
|
|
110
|
+
root: ReadableField<TSchema>;
|
|
111
|
+
${create}
|
|
112
|
+
${isDocs}
|
|
113
|
+
/**
|
|
114
|
+
* Returns the parent object/array/map of the given object/array/map, if there is one.
|
|
115
|
+
* @returns The parent node, or \`undefined\` if the node is the root or is not in the tree.
|
|
116
|
+
* @remarks
|
|
117
|
+
* Example: Get the parent with \`const parent = context.parent(child);\`
|
|
118
|
+
*/
|
|
119
|
+
parent(child: TreeData): TreeData | undefined;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Returns the property key or index of the given object/array/map within its parent.
|
|
123
|
+
* @returns A string key if the child is in an object or map, or a numeric index if the child is in an array.
|
|
124
|
+
*
|
|
125
|
+
* Example: \`const key = context.key(child);\`
|
|
126
|
+
*/
|
|
127
|
+
key(child: TreeData): string | number;
|
|
128
|
+
}
|
|
129
|
+
\`\`\``;
|
|
55
130
|
const helperMethodExplanation = details.hasHelperMethods
|
|
56
131
|
? `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.
|
|
57
132
|
It 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.`
|
|
58
133
|
: "";
|
|
59
|
-
const builderExplanation = exampleObjectName === undefined
|
|
60
|
-
? ""
|
|
61
|
-
: `When constructing new objects, you should wrap them in the appropriate builder function rather than simply making a javascript object.
|
|
62
|
-
The builders are available on the \`create\` property on the context object and are named according to the type that they create.
|
|
63
|
-
For example:
|
|
64
|
-
|
|
65
|
-
\`\`\`javascript
|
|
66
|
-
// This creates a new ${exampleObjectName} object:
|
|
67
|
-
const ${(0, utils_js_1.communize)(exampleObjectName)} = context.create.${exampleObjectName}({ /* ...properties... */ });
|
|
68
|
-
// Don't do this:
|
|
69
|
-
// const ${(0, utils_js_1.communize)(exampleObjectName)} = { /* ...properties... */ };
|
|
70
|
-
\`\`\`\n\n`;
|
|
71
134
|
const reinsertionExplanation = `Once non-primitive 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.
|
|
72
135
|
Instead, it must be deep cloned and recreated.
|
|
73
136
|
${exampleObjectName === undefined
|
|
@@ -132,7 +195,6 @@ ${getTreeMapNodeDocumentation(mapInterfaceName)}
|
|
|
132
195
|
\`\`\`
|
|
133
196
|
|
|
134
197
|
`;
|
|
135
|
-
const rootTypes = (0, internal_1.normalizeFieldSchema)(schema).allowedTypeSet;
|
|
136
198
|
const 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.
|
|
137
199
|
You must use the "${editToolName}" tool to run the generated code.
|
|
138
200
|
After editing the tree, review the latest state of the tree to see if it satisfies the user's request.
|
|
@@ -145,14 +207,18 @@ If the user asks you to edit the document, you will write a snippet of JavaScrip
|
|
|
145
207
|
The snippet may be synchronous or asynchronous (i.e. it may \`await\` functions if necessary).
|
|
146
208
|
The snippet has a \`context\` variable in its scope.
|
|
147
209
|
This \`context\` variable holds the current state of the tree in the \`root\` property.
|
|
148
|
-
You may mutate any part of
|
|
149
|
-
You 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 (\`${
|
|
210
|
+
You may mutate any part of this tree as necessary, taking into account the caveats around${hasArrays ? ` arrays${hasMaps ? " and" : ""}` : ""}${hasMaps ? " maps" : ""} detailed below.
|
|
211
|
+
You 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 (\`${rootTypeUnion}\`).
|
|
212
|
+
You should also use the \`context\` object to create new data to insert into the tree, using the builder functions available on the \`create\` property.
|
|
213
|
+
There are other additional helper functions available on the \`context\` object to help you analyze the tree.
|
|
214
|
+
Here is the definition of the \`Context\` interface:
|
|
215
|
+
${context}
|
|
150
216
|
${helperMethodExplanation}
|
|
151
217
|
${hasArrays ? arrayEditing : ""}${hasMaps ? mapEditing : ""}#### Additional Notes
|
|
152
218
|
|
|
153
219
|
Before 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.
|
|
154
220
|
|
|
155
|
-
${
|
|
221
|
+
${reinsertionExplanation}
|
|
156
222
|
|
|
157
223
|
Finally, double check that the edits would accomplish the user's request (if it is possible).
|
|
158
224
|
|
package/dist/prompt.js.map
CHANGED
|
@@ -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,CAAC,KAAK,CAAC,CAAC,CAAC;gBACrB,SAAS,GAAG,IAAI,CAAC;gBACjB,MAAM;YACP,CAAC;YACD,KAAK,eAAQ,CAAC,GAAG,CAAC,CAA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;;;;;;;;;;;;;;;;;;;;;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 reinsertionExplanation = `Once non-primitive 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.\nInstead, it must be deep cloned and recreated.\n${\n\texampleObjectName === undefined\n\t\t? \"\"\n\t\t: `For example:\n\n\\`\\`\\`javascript\n// Data is removed from the tree:\nconst ${communize(exampleObjectName)} = parent.${communize(exampleObjectName)};\nparent.${communize(exampleObjectName)} = undefined;\n// \\`${communize(exampleObjectName)}\\` cannot be directly re-inserted into the tree - this will throw an error:\n// parent.${communize(exampleObjectName)} = ${communize(exampleObjectName)}; // ❌ A node may not be inserted into the tree more than once\n// Instead, it must be deep cloned and recreated before insertion:\nparent.${communize(exampleObjectName)} = context.create.${exampleObjectName}({ /*... deep clone all properties from \\`${communize(exampleObjectName)}\\` */ });\n\\`\\`\\`${\n\t\t\t\thasArrays\n\t\t\t\t\t? `\\n\\nThe same applies when using arrays:\\n\\`\\`\\`javascript\n// Data is removed from the tree:\nconst item = arrayOf${exampleObjectName}[0];\narrayOf${exampleObjectName}.removeAt(0);\n// \\`item\\` cannot be directly re-inserted into the tree - this will throw an error:\narrayOf${exampleObjectName}.insertAt(0, item); // ❌ A node may not be inserted into the tree more than once\n// Instead, it must be deep cloned and recreated before insertion:\narrayOf${exampleObjectName}.insertAt(0, context.create.${exampleObjectName}({ /*... deep clone all properties from \\`item\\` */ }));\n\\`\\`\\``\n\t\t\t\t\t: \"\"\n\t\t\t}${\n\t\t\t\thasMaps\n\t\t\t\t\t? `\\n\\nThe same applies when using maps:\n\\`\\`\\`javascript\n// Data is removed from the tree:\nconst value = mapOf${exampleObjectName}.get(\"someKey\");\nmapOf${exampleObjectName}.delete(\"someKey\");\n// \\`value\\` cannot be directly re-inserted into the tree - this will throw an error:\nmapOf${exampleObjectName}.set(\"someKey\", value); // ❌ A node may not be inserted into the tree more than once\n// Instead, it must be deep cloned and recreated before insertion:\nmapOf${exampleObjectName}.set(\"someKey\", context.create.${exampleObjectName}({ /*... deep clone all properties from \\`value\\` */ }));\n\\`\\`\\``\n\t\t\t\t\t: \"\"\n\t\t\t}`\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${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\n${builderExplanation}${reinsertionExplanation}\n\nFinally, 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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IACb,CAAC,EACD,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 { oob } from \"@fluidframework/core-utils/internal\";\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\tconst rootTypes = [...normalizeFieldSchema(schema).allowedTypeSet];\n\tconst rootTypeUnion = `${rootTypes.map((t) => getFriendlyName(t)).join(\" | \")}`;\n\tlet nodeTypeUnion: string | undefined;\n\tlet hasArrays = false;\n\tlet hasMaps = false;\n\tlet exampleObjectName: string | undefined;\n\tfor (const [definition, nodeSchema] of simpleSchema.definitions) {\n\t\tif (nodeSchema.kind !== NodeKind.Leaf) {\n\t\t\tnodeTypeUnion =\n\t\t\t\tnodeTypeUnion === undefined\n\t\t\t\t\t? unqualifySchema(definition)\n\t\t\t\t\t: `${nodeTypeUnion} | ${unqualifySchema(definition)}`;\n\t\t}\n\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\n\tconst create =\n\t\texampleObjectName === undefined\n\t\t\t? \"\"\n\t\t\t: `\\n\t/**\n\t * A collection of builder functions for creating new tree nodes.\n\t * @remarks\n\t * Each property on this object is named after a type in the tree schema.\n\t * Call the corresponding function to create a new node of that type.\n\t * Always use these builder functions when creating new nodes rather than plain JavaScript objects.\n\t *\n\t * For example:\n\t *\n\t * \\`\\`\\`javascript\n\t * // This creates a new ${exampleObjectName} object:\n\t * const ${communize(exampleObjectName)} = context.create.${exampleObjectName}({ ...properties });\n\t * // Don't do this:\n\t * // const ${communize(exampleObjectName)} = { ...properties };\n\t * \\`\\`\\`\n\t */\n\tcreate: Record<string, <T extends TreeData>(input: T) => T>;\\n`;\n\n\tconst isDocs =\n\t\texampleObjectName === undefined\n\t\t\t? \"\"\n\t\t\t: `\\n\t/**\n\t * A collection of type-guard functions for data in the tree.\n\t * @remarks\n\t * Each property on this object is named after a type in the tree schema.\n\t * Call the corresponding function to check if a node is of that specific type.\n\t * This is useful when working with nodes that could be one of multiple types.\n\t *\n\t * ${`Example: Check if a node is a ${exampleObjectName} with \\`if (context.is.${exampleObjectName}(node)) {}\\``}\n\t */\n\tis: Record<string, <T extends TreeData>(input: unknown) => input is T>;\\n`;\n\n\tconst context = `\\`\\`\\`typescript\n\t${nodeTypeUnion === undefined ? \"\" : `type TreeData = ${nodeTypeUnion};\\n\\n`}\t/**\n\t * An object available to generated code which provides read and write access to the tree as well as utilities for creating and inspecting data in the tree.\n\t * @remarks This object is available as a variable named \\`context\\` in the scope of the generated JavaScript snippet.\n\t */\n\tinterface Context<TSchema extends ImplicitFieldSchema> {\n\t/**\n\t * The root of the tree that can be read or mutated.\n\t * @remarks\n\t * You can read properties and navigate through the tree starting from this root.\n\t * You can also assign a new value to this property to replace the entire tree, as long as the new value is one of the types allowed at the root.\n\t *\n\t * Example: Read the current root with \\`const currentRoot = context.root;\\`\n\t *${rootTypes.length > 0 ? ` Example: Replace the entire root with \\`context.root = context.create.${getFriendlyName(rootTypes[0] ?? oob())}({ });\\`\\n\t *` : \"\"}/\n\troot: ReadableField<TSchema>;\n\t${create}\n\t${isDocs}\n\t/**\n\t * Returns the parent object/array/map of the given object/array/map, if there is one.\n\t * @returns The parent node, or \\`undefined\\` if the node is the root or is not in the tree.\n\t * @remarks\n\t * Example: Get the parent with \\`const parent = context.parent(child);\\`\n\t */\n\tparent(child: TreeData): TreeData | undefined;\n\n\t/**\n\t * Returns the property key or index of the given object/array/map within its parent.\n\t * @returns A string key if the child is in an object or map, or a numeric index if the child is in an array.\n\t *\n\t * Example: \\`const key = context.key(child);\\`\n\t */\n\tkey(child: TreeData): string | number;\n}\n\\`\\`\\``;\n\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 reinsertionExplanation = `Once non-primitive 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.\nInstead, it must be deep cloned and recreated.\n${\n\texampleObjectName === undefined\n\t\t? \"\"\n\t\t: `For example:\n\n\\`\\`\\`javascript\n// Data is removed from the tree:\nconst ${communize(exampleObjectName)} = parent.${communize(exampleObjectName)};\nparent.${communize(exampleObjectName)} = undefined;\n// \\`${communize(exampleObjectName)}\\` cannot be directly re-inserted into the tree - this will throw an error:\n// parent.${communize(exampleObjectName)} = ${communize(exampleObjectName)}; // ❌ A node may not be inserted into the tree more than once\n// Instead, it must be deep cloned and recreated before insertion:\nparent.${communize(exampleObjectName)} = context.create.${exampleObjectName}({ /*... deep clone all properties from \\`${communize(exampleObjectName)}\\` */ });\n\\`\\`\\`${\n\t\t\t\thasArrays\n\t\t\t\t\t? `\\n\\nThe same applies when using arrays:\\n\\`\\`\\`javascript\n// Data is removed from the tree:\nconst item = arrayOf${exampleObjectName}[0];\narrayOf${exampleObjectName}.removeAt(0);\n// \\`item\\` cannot be directly re-inserted into the tree - this will throw an error:\narrayOf${exampleObjectName}.insertAt(0, item); // ❌ A node may not be inserted into the tree more than once\n// Instead, it must be deep cloned and recreated before insertion:\narrayOf${exampleObjectName}.insertAt(0, context.create.${exampleObjectName}({ /*... deep clone all properties from \\`item\\` */ }));\n\\`\\`\\``\n\t\t\t\t\t: \"\"\n\t\t\t}${\n\t\t\t\thasMaps\n\t\t\t\t\t? `\\n\\nThe same applies when using maps:\n\\`\\`\\`javascript\n// Data is removed from the tree:\nconst value = mapOf${exampleObjectName}.get(\"someKey\");\nmapOf${exampleObjectName}.delete(\"someKey\");\n// \\`value\\` cannot be directly re-inserted into the tree - this will throw an error:\nmapOf${exampleObjectName}.set(\"someKey\", value); // ❌ A node may not be inserted into the tree more than once\n// Instead, it must be deep cloned and recreated before insertion:\nmapOf${exampleObjectName}.set(\"someKey\", context.create.${exampleObjectName}({ /*... deep clone all properties from \\`value\\` */ }));\n\\`\\`\\``\n\t\t\t\t\t: \"\"\n\t\t\t}`\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 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 this 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 (\\`${rootTypeUnion}\\`).\nYou should also use the \\`context\\` object to create new data to insert into the tree, using the builder functions available on the \\`create\\` property.\nThere are other additional helper functions available on the \\`context\\` object to help you analyze the tree.\nHere is the definition of the \\`Context\\` interface:\n${context}\n${helperMethodExplanation}\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\n${reinsertionExplanation}\n\nFinally, 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/lib/agent.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import type { ImplicitFieldSchema } from "@fluidframework/tree";
|
|
6
6
|
import { TreeNode } from "@fluidframework/tree";
|
|
7
7
|
import type { ReadableField } from "@fluidframework/tree/alpha";
|
|
8
|
-
import type { SharedTreeChatModel, SemanticAgentOptions } from "./api.js";
|
|
8
|
+
import type { SharedTreeChatModel, SemanticAgentOptions, SynchronousEditor, AsynchronousEditor } from "./api.js";
|
|
9
9
|
import { type TreeView } from "./utils.js";
|
|
10
10
|
/**
|
|
11
11
|
* An agent that uses a {@link SharedTreeChatModel} to interact with a SharedTree.
|
|
@@ -29,4 +29,33 @@ export declare class SharedTreeSemanticAgent<TSchema extends ImplicitFieldSchema
|
|
|
29
29
|
*/
|
|
30
30
|
query(userPrompt: string): Promise<string>;
|
|
31
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* The default {@link AsynchronousEditor | editor} implementation that simply uses `new Function` to run the provided code.
|
|
34
|
+
* @remarks This editor allows both synchronous and asynchronous code (i.e. the provided code may return a Promise).
|
|
35
|
+
* @example `await new Function("context", code)(context);`
|
|
36
|
+
* @alpha
|
|
37
|
+
*/
|
|
38
|
+
export declare const defaultEditor: AsynchronousEditor;
|
|
39
|
+
/**
|
|
40
|
+
* Binds the given {@link AsynchronousEditor | editor} to the given view or tree.
|
|
41
|
+
* @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.
|
|
42
|
+
* @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
|
|
43
|
+
* @alpha
|
|
44
|
+
*/
|
|
45
|
+
export declare function bindEditorImpl<TSchema extends ImplicitFieldSchema>(tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode), editor: AsynchronousEditor): (code: string) => Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Binds the given {@link SynchronousEditor | editor} to the given view or tree.
|
|
48
|
+
* @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.
|
|
49
|
+
* @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
|
|
50
|
+
* @alpha
|
|
51
|
+
*/
|
|
52
|
+
export declare function bindEditorImpl<TSchema extends ImplicitFieldSchema>(tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode), editor: SynchronousEditor): (code: string) => void;
|
|
53
|
+
/**
|
|
54
|
+
* Binds the given {@link SynchronousEditor | synchronous} or {@link AsynchronousEditor | asynchronous} editor to the given view or tree.
|
|
55
|
+
* @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor.
|
|
56
|
+
* @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
|
|
57
|
+
* @alpha
|
|
58
|
+
* @privateRemarks This exists (as opposed to just exporting bindEditorImpl directly) so that API documentation links work correctly.
|
|
59
|
+
*/
|
|
60
|
+
export declare const bindEditor: typeof bindEditorImpl;
|
|
32
61
|
//# sourceMappingURL=agent.d.ts.map
|
package/lib/agent.d.ts.map
CHANGED
|
@@ -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,
|
|
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,EAEnB,oBAAoB,EAEpB,iBAAiB,EACjB,kBAAkB,EAElB,MAAM,UAAU,CAAC;AA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The maximum number of edits (${maxEditCount}) for this query has been exceeded.`,
|
|
98
98
|
};
|
|
99
99
|
}
|
|
100
|
-
const editResult = await applyTreeFunction(queryTree, editCode, this.options?.
|
|
100
|
+
const editResult = await applyTreeFunction(queryTree, editCode, this.options?.editor ?? defaultEditor, this.options?.logger);
|
|
101
101
|
rollbackEdits = editResult.type !== "success";
|
|
102
102
|
return editResult;
|
|
103
103
|
};
|
|
@@ -147,46 +147,21 @@ function constructTreeNode(schema, value) {
|
|
|
147
147
|
/**
|
|
148
148
|
* Applies the given function (as a string of JavaScript code or an actual function) to the given tree.
|
|
149
149
|
*/
|
|
150
|
-
async function applyTreeFunction(tree, editCode,
|
|
150
|
+
async function applyTreeFunction(tree, editCode, editor, logger) {
|
|
151
151
|
logger?.log(`### Editing Tool Invoked\n\n`);
|
|
152
152
|
logger?.log(`#### Generated Code\n\n\`\`\`javascript\n${editCode}\n\`\`\`\n\n`);
|
|
153
|
-
try {
|
|
154
|
-
await validateEdit(editCode);
|
|
155
|
-
}
|
|
156
|
-
catch (error) {
|
|
157
|
-
logger?.log(`#### Code Validation Failed\n\n`);
|
|
158
|
-
logger?.log(`\`\`\`JSON\n${toErrorString(error)}\n\`\`\`\n\n`);
|
|
159
|
-
return {
|
|
160
|
-
type: "validationError",
|
|
161
|
-
message: `The generated code did not pass validation: ${toErrorString(error)}`,
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
// Stick the tree schema constructors on an object passed to the function so that the LLM can create new nodes.
|
|
165
|
-
const create = {};
|
|
166
|
-
for (const schema of findNamedSchemas(tree.schema)) {
|
|
167
|
-
const name = getFriendlyName(schema);
|
|
168
|
-
create[name] = (input) => constructTreeNode(schema, input);
|
|
169
|
-
}
|
|
170
153
|
// Fork a branch to edit. If the edit fails or produces an error, we discard this branch, otherwise we merge it.
|
|
171
154
|
const editTree = tree.fork();
|
|
172
|
-
const
|
|
173
|
-
get root() {
|
|
174
|
-
return editTree.field;
|
|
175
|
-
},
|
|
176
|
-
set root(value) {
|
|
177
|
-
editTree.field = value;
|
|
178
|
-
},
|
|
179
|
-
create,
|
|
180
|
-
};
|
|
155
|
+
const boundEditor = bindEditorToSubtree(editTree, editor);
|
|
181
156
|
try {
|
|
182
|
-
await
|
|
157
|
+
await boundEditor(editCode);
|
|
183
158
|
}
|
|
184
159
|
catch (error) {
|
|
185
160
|
logger?.log(`#### Error\n\n`);
|
|
186
161
|
logger?.log(`\`\`\`JSON\n${toErrorString(error)}\n\`\`\`\n\n`);
|
|
187
162
|
editTree.branch.dispose();
|
|
188
163
|
return {
|
|
189
|
-
type: "
|
|
164
|
+
type: "editingError",
|
|
190
165
|
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)}`,
|
|
191
166
|
};
|
|
192
167
|
}
|
|
@@ -198,10 +173,57 @@ async function applyTreeFunction(tree, editCode, validateEdit, executeEdit, logg
|
|
|
198
173
|
message: `After running the code, the new state of the tree is:\n\n\`\`\`JSON\n${stringifyTree(tree.field)}\n\`\`\``,
|
|
199
174
|
};
|
|
200
175
|
}
|
|
201
|
-
|
|
202
|
-
|
|
176
|
+
/**
|
|
177
|
+
* The default {@link AsynchronousEditor | editor} implementation that simply uses `new Function` to run the provided code.
|
|
178
|
+
* @remarks This editor allows both synchronous and asynchronous code (i.e. the provided code may return a Promise).
|
|
179
|
+
* @example `await new Function("context", code)(context);`
|
|
180
|
+
* @alpha
|
|
181
|
+
*/
|
|
182
|
+
export const defaultEditor = async (context, code) => {
|
|
203
183
|
// eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval
|
|
204
184
|
const fn = new Function("context", code);
|
|
205
185
|
await fn(context);
|
|
206
186
|
};
|
|
187
|
+
/**
|
|
188
|
+
* Binds the given {@link SynchronousEditor | editor} or {@link AsynchronousEditor | editor} to the given view or tree.
|
|
189
|
+
* @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.
|
|
190
|
+
* @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
|
|
191
|
+
* @alpha
|
|
192
|
+
*/
|
|
193
|
+
export function bindEditorImpl(tree, editor) {
|
|
194
|
+
const subtree = new Subtree(tree);
|
|
195
|
+
return bindEditorToSubtree(subtree, editor);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Binds the given {@link SynchronousEditor | synchronous} or {@link AsynchronousEditor | asynchronous} editor to the given view or tree.
|
|
199
|
+
* @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor.
|
|
200
|
+
* @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
|
|
201
|
+
* @alpha
|
|
202
|
+
* @privateRemarks This exists (as opposed to just exporting bindEditorImpl directly) so that API documentation links work correctly.
|
|
203
|
+
*/
|
|
204
|
+
export const bindEditor = bindEditorImpl;
|
|
205
|
+
function bindEditorToSubtree(tree, executeEdit) {
|
|
206
|
+
// Stick the tree schema constructors on an object passed to the function so that the LLM can create new nodes.
|
|
207
|
+
const create = {};
|
|
208
|
+
const is = {};
|
|
209
|
+
for (const schema of findNamedSchemas(tree.schema)) {
|
|
210
|
+
const name = getFriendlyName(schema);
|
|
211
|
+
create[name] = (input) => constructTreeNode(schema, input);
|
|
212
|
+
is[name] = (input) => Tree.is(input, schema);
|
|
213
|
+
}
|
|
214
|
+
const context = {
|
|
215
|
+
get root() {
|
|
216
|
+
return tree.field;
|
|
217
|
+
},
|
|
218
|
+
set root(value) {
|
|
219
|
+
tree.field = value;
|
|
220
|
+
},
|
|
221
|
+
create,
|
|
222
|
+
is,
|
|
223
|
+
parent: (child) => Tree.parent(child),
|
|
224
|
+
key: (child) => Tree.key(child),
|
|
225
|
+
};
|
|
226
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
227
|
+
return (code) => executeEdit(context, code);
|
|
228
|
+
}
|
|
207
229
|
//# sourceMappingURL=agent.js.map
|
package/lib/agent.js.map
CHANGED
|
@@ -1 +1 @@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nB,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 rollbackEdits = 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\trollbackEdits = 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\trollbackEdits = 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 (!rollbackEdits) {\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"]}
|
|
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;AAWpE,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,CAAC;AAErC;;;;GAIG;AACH,MAAM,OAAO,uBAAuB;IAQnC,YACkB,MAA2B,EAC5C,IAA6D,EAC5C,OAAwC;QAFxC,WAAM,GAAN,MAAM,CAAqB;QAE3B,YAAO,GAAP,OAAO,CAAiC;QAR1D;;WAEG;QACK,qBAAgB,GAAG,KAAK,CAAC;QAOhC,IAAI,IAAI,YAAY,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,aAAa,EAAE,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAC,CAAC;QACpE,CAAC;aAAM,CAAC;YACP,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAC,CAAC;QACjE,CAAC;QAED,IAAI,CAAC,SAAS,GAAG,IAAI,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qB,KAAc,EAAc,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACvF,CAAC;IAED,MAAM,OAAO,GAAG;QACf,IAAI,IAAI;YACP,OAAO,IAAI,CAAC,KAAK,CAAC;QACnB,CAAC;QACD,IAAI,IAAI,CAAC,KAAsD;YAC9D,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACpB,CAAC;QACD,MAAM;QACN,EAAE;QACF,MAAM,EAAE,CAAC,KAAe,EAAwB,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;QACrE,GAAG,EAAE,CAAC,KAAe,EAAmB,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC;KAC/B,CAAC;IAE7B,qEAAqE;IACrE,OAAO,CAAC,IAAY,EAAE,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AACrD,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 {\n\tSharedTreeChatModel,\n\tEditResult,\n\tSemanticAgentOptions,\n\tLogger,\n\tSynchronousEditor,\n\tAsynchronousEditor,\n\tContext,\n} 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 rollbackEdits = 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\trollbackEdits = 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?.editor ?? defaultEditor,\n\t\t\t\tthis.options?.logger,\n\t\t\t);\n\n\t\t\trollbackEdits = 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 (!rollbackEdits) {\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\teditor: Required<SemanticAgentOptions>[\"editor\"],\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\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 boundEditor = bindEditorToSubtree(editTree, editor);\n\ttry {\n\t\tawait boundEditor(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: \"editingError\",\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\n/**\n * The default {@link AsynchronousEditor | editor} implementation that simply uses `new Function` to run the provided code.\n * @remarks This editor allows both synchronous and asynchronous code (i.e. the provided code may return a Promise).\n * @example `await new Function(\"context\", code)(context);`\n * @alpha\n */\nexport const defaultEditor: AsynchronousEditor = async (context, code) => {\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\n/**\n * Binds the given {@link AsynchronousEditor | editor} to the given view or tree.\n * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.\n * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.\n * @alpha\n */\nexport function bindEditorImpl<TSchema extends ImplicitFieldSchema>(\n\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\teditor: AsynchronousEditor,\n): (code: string) => Promise<void>;\n/**\n * Binds the given {@link SynchronousEditor | editor} to the given view or tree.\n * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.\n * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.\n * @alpha\n */\nexport function bindEditorImpl<TSchema extends ImplicitFieldSchema>(\n\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\teditor: SynchronousEditor,\n): (code: string) => void;\n/**\n * Binds the given {@link SynchronousEditor | editor} or {@link AsynchronousEditor | editor} to the given view or tree.\n * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.\n * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.\n * @alpha\n */\nexport function bindEditorImpl<TSchema extends ImplicitFieldSchema>(\n\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\teditor: SynchronousEditor | AsynchronousEditor,\n): ((code: string) => void) | ((code: string) => Promise<void>) {\n\tconst subtree = new Subtree(tree);\n\treturn bindEditorToSubtree(subtree, editor);\n}\n\n/**\n * Binds the given {@link SynchronousEditor | synchronous} or {@link AsynchronousEditor | asynchronous} editor to the given view or tree.\n * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor.\n * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.\n * @alpha\n * @privateRemarks This exists (as opposed to just exporting bindEditorImpl directly) so that API documentation links work correctly.\n */\nexport const bindEditor = bindEditorImpl;\n\nfunction bindEditorToSubtree<TSchema extends ImplicitFieldSchema>(\n\ttree: Subtree<TSchema>,\n\texecuteEdit: SynchronousEditor | AsynchronousEditor,\n): (code: string) => void | Promise<void> {\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\tconst is: Record<string, <T extends TreeNode>(input: unknown) => input is T> = {};\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\tis[name] = <T extends TreeNode>(input: unknown): input is T => Tree.is(input, schema);\n\t}\n\n\tconst context = {\n\t\tget root(): ReadableField<TSchema> {\n\t\t\treturn tree.field;\n\t\t},\n\t\tset root(value: TreeFieldFromImplicitField<ReadSchema<TSchema>>) {\n\t\t\ttree.field = value;\n\t\t},\n\t\tcreate,\n\t\tis,\n\t\tparent: (child: TreeNode): TreeNode | undefined => Tree.parent(child),\n\t\tkey: (child: TreeNode): string | number => Tree.key(child),\n\t} satisfies Context<TSchema>;\n\n\t// eslint-disable-next-line @typescript-eslint/promise-function-async\n\treturn (code: string) => executeEdit(context, code);\n}\n"]}
|
package/lib/alpha.d.ts
CHANGED
|
@@ -18,6 +18,7 @@ export {
|
|
|
18
18
|
// #region @alpha APIs
|
|
19
19
|
Arg,
|
|
20
20
|
ArgsTuple,
|
|
21
|
+
AsynchronousEditor,
|
|
21
22
|
BindableSchema,
|
|
22
23
|
Ctor,
|
|
23
24
|
EditResult,
|
|
@@ -31,8 +32,12 @@ export {
|
|
|
31
32
|
SharedTreeChatModel,
|
|
32
33
|
SharedTreeChatQuery,
|
|
33
34
|
SharedTreeSemanticAgent,
|
|
35
|
+
SynchronousEditor,
|
|
34
36
|
TreeView,
|
|
37
|
+
bindEditor,
|
|
38
|
+
bindEditorImpl,
|
|
35
39
|
buildFunc,
|
|
40
|
+
defaultEditor,
|
|
36
41
|
exposeMethodsSymbol,
|
|
37
42
|
llmDefault
|
|
38
43
|
// #endregion
|