@fluidframework/tree-agent 2.70.0-360753 → 2.70.0-361248
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 +2 -2
- package/dist/agent.d.ts +4 -4
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +25 -0
- package/dist/agent.js.map +1 -1
- package/dist/api.d.ts +66 -0
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js.map +1 -1
- package/dist/prompt.d.ts.map +1 -1
- package/dist/prompt.js +111 -17
- package/dist/prompt.js.map +1 -1
- package/lib/agent.d.ts +4 -4
- package/lib/agent.d.ts.map +1 -1
- package/lib/agent.js +26 -1
- package/lib/agent.js.map +1 -1
- package/lib/api.d.ts +66 -0
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js.map +1 -1
- package/lib/prompt.d.ts.map +1 -1
- package/lib/prompt.js +110 -16
- package/lib/prompt.js.map +1 -1
- package/package.json +12 -12
- package/src/agent.ts +34 -8
- package/src/api.ts +73 -0
- package/src/prompt.ts +118 -18
package/lib/prompt.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
|
|
3
3
|
* Licensed under the MIT License.
|
|
4
4
|
*/
|
|
5
|
+
import { oob } from "@fluidframework/core-utils/internal";
|
|
5
6
|
import { NodeKind, Tree, TreeNode } from "@fluidframework/tree";
|
|
6
7
|
import { getSimpleSchema } from "@fluidframework/tree/alpha";
|
|
7
8
|
import { normalizeFieldSchema } from "@fluidframework/tree/internal";
|
|
@@ -17,10 +18,19 @@ export function getPrompt(args) {
|
|
|
17
18
|
const mapInterfaceName = "TreeMap";
|
|
18
19
|
const simpleSchema = getSimpleSchema(schema);
|
|
19
20
|
// Inspect the schema to determine what kinds of nodes are possible - this will affect how much information we need to include in the prompt.
|
|
21
|
+
const rootTypes = [...normalizeFieldSchema(schema).allowedTypeSet];
|
|
22
|
+
const rootTypeUnion = `${rootTypes.map((t) => getFriendlyName(t)).join(" | ")}`;
|
|
23
|
+
let nodeTypeUnion;
|
|
20
24
|
let hasArrays = false;
|
|
21
25
|
let hasMaps = false;
|
|
22
26
|
let exampleObjectName;
|
|
23
27
|
for (const [definition, nodeSchema] of simpleSchema.definitions) {
|
|
28
|
+
if (nodeSchema.kind !== NodeKind.Leaf) {
|
|
29
|
+
nodeTypeUnion =
|
|
30
|
+
nodeTypeUnion === undefined
|
|
31
|
+
? unqualifySchema(definition)
|
|
32
|
+
: `${nodeTypeUnion} | ${unqualifySchema(definition)}`;
|
|
33
|
+
}
|
|
24
34
|
switch (nodeSchema.kind) {
|
|
25
35
|
case NodeKind.Array: {
|
|
26
36
|
hasArrays = true;
|
|
@@ -49,22 +59,103 @@ export function getPrompt(args) {
|
|
|
49
59
|
const stringified = stringifyTree(field);
|
|
50
60
|
const details = { hasHelperMethods: false };
|
|
51
61
|
const typescriptSchemaTypes = getZodSchemaAsTypeScript(domainTypes, details);
|
|
62
|
+
const exampleTypeName = nodeTypeUnion === undefined
|
|
63
|
+
? undefined
|
|
64
|
+
: nodeTypeUnion
|
|
65
|
+
.split("|")
|
|
66
|
+
.map((part) => part.trim())
|
|
67
|
+
.find((part) => part.length > 0);
|
|
68
|
+
const createDocs = exampleObjectName === undefined
|
|
69
|
+
? ""
|
|
70
|
+
: `\n /**
|
|
71
|
+
* A collection of builder functions for creating new tree nodes.
|
|
72
|
+
* @remarks
|
|
73
|
+
* Each property on this object is named after a type in the tree schema.
|
|
74
|
+
* Call the corresponding function to create a new node of that type.
|
|
75
|
+
* Always use these builder functions when creating new nodes rather than plain JavaScript objects.
|
|
76
|
+
*
|
|
77
|
+
* For example:
|
|
78
|
+
*
|
|
79
|
+
* \`\`\`javascript
|
|
80
|
+
* // This creates a new ${exampleObjectName} object:
|
|
81
|
+
* const ${communize(exampleObjectName)} = context.create.${exampleObjectName}({ ...properties });
|
|
82
|
+
* // Don't do this:
|
|
83
|
+
* // const ${communize(exampleObjectName)} = { ...properties };
|
|
84
|
+
* \`\`\`
|
|
85
|
+
*/
|
|
86
|
+
create: Record<string, <T extends TreeData>(input: T) => T>;\n`;
|
|
87
|
+
const isDocs = exampleTypeName === undefined
|
|
88
|
+
? ""
|
|
89
|
+
: `\n /**
|
|
90
|
+
* A collection of type-guard functions for data in the tree.
|
|
91
|
+
* @remarks
|
|
92
|
+
* Each property on this object is named after a type in the tree schema.
|
|
93
|
+
* Call the corresponding function to check if a node is of that specific type.
|
|
94
|
+
* This is useful when working with nodes that could be one of multiple types.
|
|
95
|
+
*
|
|
96
|
+
* ${`Example: Check if a node is a ${exampleTypeName} with \`if (context.is.${exampleTypeName}(node)) {}\``}
|
|
97
|
+
*/
|
|
98
|
+
is: Record<string, <T extends TreeData>(data: unknown) => data is T>;
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Checks if the provided data is an array.
|
|
102
|
+
* @remarks
|
|
103
|
+
* DO NOT use \`Array.isArray\` to check if tree data is an array - use this function instead.
|
|
104
|
+
*
|
|
105
|
+
* This function will also work for native JavaScript arrays.
|
|
106
|
+
*
|
|
107
|
+
* ${`Example: \`if (context.isArray(node)) {}\``}
|
|
108
|
+
*/
|
|
109
|
+
isArray(data: any): boolean;
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Checks if the provided data is a map.
|
|
113
|
+
* @remarks
|
|
114
|
+
* DO NOT use \`instanceof Map\` to check if tree data is a map - use this function instead.
|
|
115
|
+
*
|
|
116
|
+
* This function will also work for native JavaScript Map instances.
|
|
117
|
+
*
|
|
118
|
+
* ${`Example: \`if (context.isMap(node)) {}\``}
|
|
119
|
+
*/
|
|
120
|
+
isMap(data: any): boolean;\n`;
|
|
121
|
+
const context = `\`\`\`typescript
|
|
122
|
+
${nodeTypeUnion === undefined ? "" : `type TreeData = ${nodeTypeUnion};\n\n`} /**
|
|
123
|
+
* 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.
|
|
124
|
+
* @remarks This object is available as a variable named \`context\` in the scope of the generated JavaScript snippet.
|
|
125
|
+
*/
|
|
126
|
+
interface Context<TSchema extends ImplicitFieldSchema> {
|
|
127
|
+
/**
|
|
128
|
+
* The root of the tree that can be read or mutated.
|
|
129
|
+
* @remarks
|
|
130
|
+
* You can read properties and navigate through the tree starting from this root.
|
|
131
|
+
* 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.
|
|
132
|
+
*
|
|
133
|
+
* Example: Read the current root with \`const currentRoot = context.root;\`
|
|
134
|
+
*${rootTypes.length > 0 ? ` Example: Replace the entire root with \`context.root = context.create.${getFriendlyName(rootTypes[0] ?? oob())}({ });\`\n *` : ""}/
|
|
135
|
+
root: ReadableField<TSchema>;
|
|
136
|
+
${createDocs}
|
|
137
|
+
${isDocs}
|
|
138
|
+
/**
|
|
139
|
+
* Returns the parent object/array/map of the given object/array/map, if there is one.
|
|
140
|
+
* @returns The parent node, or \`undefined\` if the node is the root or is not in the tree.
|
|
141
|
+
* @remarks
|
|
142
|
+
* Example: Get the parent with \`const parent = context.parent(child);\`
|
|
143
|
+
*/
|
|
144
|
+
parent(child: TreeData): TreeData | undefined;
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Returns the property key or index of the given object/array/map within its parent.
|
|
148
|
+
* @returns A string key if the child is in an object or map, or a numeric index if the child is in an array.
|
|
149
|
+
*
|
|
150
|
+
* Example: \`const key = context.key(child);\`
|
|
151
|
+
*/
|
|
152
|
+
key(child: TreeData): string | number;
|
|
153
|
+
}
|
|
154
|
+
\`\`\``;
|
|
52
155
|
const helperMethodExplanation = details.hasHelperMethods
|
|
53
156
|
? `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.
|
|
54
157
|
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.`
|
|
55
158
|
: "";
|
|
56
|
-
const builderExplanation = exampleObjectName === undefined
|
|
57
|
-
? ""
|
|
58
|
-
: `When constructing new objects, you should wrap them in the appropriate builder function rather than simply making a javascript object.
|
|
59
|
-
The builders are available on the \`create\` property on the context object and are named according to the type that they create.
|
|
60
|
-
For example:
|
|
61
|
-
|
|
62
|
-
\`\`\`javascript
|
|
63
|
-
// This creates a new ${exampleObjectName} object:
|
|
64
|
-
const ${communize(exampleObjectName)} = context.create.${exampleObjectName}({ /* ...properties... */ });
|
|
65
|
-
// Don't do this:
|
|
66
|
-
// const ${communize(exampleObjectName)} = { /* ...properties... */ };
|
|
67
|
-
\`\`\`\n\n`;
|
|
68
159
|
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.
|
|
69
160
|
Instead, it must be deep cloned and recreated.
|
|
70
161
|
${exampleObjectName === undefined
|
|
@@ -129,7 +220,6 @@ ${getTreeMapNodeDocumentation(mapInterfaceName)}
|
|
|
129
220
|
\`\`\`
|
|
130
221
|
|
|
131
222
|
`;
|
|
132
|
-
const rootTypes = normalizeFieldSchema(schema).allowedTypeSet;
|
|
133
223
|
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.
|
|
134
224
|
You must use the "${editToolName}" tool to run the generated code.
|
|
135
225
|
After editing the tree, review the latest state of the tree to see if it satisfies the user's request.
|
|
@@ -142,14 +232,18 @@ If the user asks you to edit the document, you will write a snippet of JavaScrip
|
|
|
142
232
|
The snippet may be synchronous or asynchronous (i.e. it may \`await\` functions if necessary).
|
|
143
233
|
The snippet has a \`context\` variable in its scope.
|
|
144
234
|
This \`context\` variable holds the current state of the tree in the \`root\` property.
|
|
145
|
-
You may mutate any part of
|
|
146
|
-
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 (\`${
|
|
235
|
+
You may mutate any part of this tree as necessary, taking into account the caveats around${hasArrays ? ` arrays${hasMaps ? " and" : ""}` : ""}${hasMaps ? " maps" : ""} detailed below.
|
|
236
|
+
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}\`).
|
|
237
|
+
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.
|
|
238
|
+
There are other additional helper functions available on the \`context\` object to help you analyze the tree.
|
|
239
|
+
Here is the definition of the \`Context\` interface:
|
|
240
|
+
${context}
|
|
147
241
|
${helperMethodExplanation}
|
|
148
242
|
${hasArrays ? arrayEditing : ""}${hasMaps ? mapEditing : ""}#### Additional Notes
|
|
149
243
|
|
|
150
244
|
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.
|
|
151
245
|
|
|
152
|
-
${
|
|
246
|
+
${reinsertionExplanation}
|
|
153
247
|
|
|
154
248
|
Finally, double check that the edits would accomplish the user's request (if it is possible).
|
|
155
249
|
|
package/lib/prompt.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.js","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAGhE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAGrE,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EACN,eAAe,EACf,wBAAwB,EACxB,aAAa,EACb,SAAS,EACT,eAAe,GAEf,MAAM,YAAY,CAAC;AAEpB;;GAEG;AACH,MAAM,UAAU,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,MA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,CACP,IAAI,MAAM,CAAC,IAAI,iBAAiB,OAAO,EAAE,GAAG,CAAC,EAC7C,4HAA4H,CAC5H,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,6BAA6B,CAAC,QAAgB;IACtD,OAAO;mBACW,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qEA0E0C,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAiDhE,QAAQ;;EAEnB,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,SAAS,2BAA2B,CAAC,QAAgB;IACpD,OAAO;;;mBAGW,QAAQ;;;;;;;;kFAQuD,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyDxF,CAAC;AACH,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { NodeKind, Tree, TreeNode } from \"@fluidframework/tree\";\nimport type { ImplicitFieldSchema, TreeMapNode } from \"@fluidframework/tree\";\nimport type { ReadableField } from \"@fluidframework/tree/alpha\";\nimport { getSimpleSchema } from \"@fluidframework/tree/alpha\";\nimport { normalizeFieldSchema } from \"@fluidframework/tree/internal\";\n\nimport type { Subtree } from \"./subtree.js\";\nimport { generateEditTypesForPrompt } from \"./typeGeneration.js\";\nimport {\n\tgetFriendlyName,\n\tgetZodSchemaAsTypeScript,\n\tisNamedSchema,\n\tcommunize,\n\tunqualifySchema,\n\ttype SchemaDetails,\n} from \"./utils.js\";\n\n/**\n * Produces a \"system\" prompt for the tree agent, based on the provided subtree.\n */\nexport function getPrompt<TRoot extends ImplicitFieldSchema>(args: {\n\tsubtree: Subtree<TRoot>;\n\teditToolName: string | undefined;\n\tdomainHints?: string;\n}): string {\n\tconst { subtree, editToolName, domainHints } = args;\n\tconst { field, schema } = subtree;\n\tconst arrayInterfaceName = \"TreeArray\";\n\tconst mapInterfaceName = \"TreeMap\";\n\tconst simpleSchema = getSimpleSchema(schema);\n\t// Inspect the schema to determine what kinds of nodes are possible - this will affect how much information we need to include in the prompt.\n\tlet hasArrays = false;\n\tlet hasMaps = false;\n\tlet exampleObjectName: string | undefined;\n\tfor (const [definition, nodeSchema] of simpleSchema.definitions) {\n\t\tswitch (nodeSchema.kind) {\n\t\t\tcase NodeKind.Array: {\n\t\t\t\thasArrays = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Map: {\n\t\t\t\thasMaps = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Object: {\n\t\t\t\texampleObjectName ??= unqualifySchema(definition);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tconst { domainTypes } = generateEditTypesForPrompt(schema, simpleSchema);\n\tfor (const [key, value] of Object.entries(domainTypes)) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n\t\tdelete domainTypes[key];\n\t\tif (isNamedSchema(key)) {\n\t\t\tconst friendlyKey = unqualifySchema(key);\n\t\t\tdomainTypes[friendlyKey] = value;\n\t\t}\n\t}\n\n\tconst stringified = stringifyTree(field);\n\tconst details: SchemaDetails = { hasHelperMethods: false };\n\tconst typescriptSchemaTypes = getZodSchemaAsTypeScript(domainTypes, details);\n\tconst helperMethodExplanation = details.hasHelperMethods\n\t\t? `Manipulating the data using the APIs described below is allowed, but when possible ALWAYS prefer to use any application helper methods exposed on the schema TypeScript types if the goal can be accomplished that way.\nIt will often not be possible to fully accomplish the goal using those helpers. When this is the case, mutate the objects as normal, taking into account the following guidance.`\n\t\t: \"\";\n\n\tconst builderExplanation =\n\t\texampleObjectName === undefined\n\t\t\t? \"\"\n\t\t\t: `When constructing new objects, you should wrap them in the appropriate builder function rather than simply making a javascript object.\nThe builders are available on the \\`create\\` property on the context object and are named according to the type that they create.\nFor example:\n\n\\`\\`\\`javascript\n// This creates a new ${exampleObjectName} object:\nconst ${communize(exampleObjectName)} = context.create.${exampleObjectName}({ /* ...properties... */ });\n// Don't do this:\n// const ${communize(exampleObjectName)} = { /* ...properties... */ };\n\\`\\`\\`\\n\\n`;\n\n\tconst 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,\n\t\t\tkey: string,\n\t\t\tmap: ReadonlyMap<string, T>,\n\t\t) => void,\n\t\tthisArg?: any,\n\t): void;\n}`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"prompt.js","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,GAAG,EAAE,MAAM,qCAAqC,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAGhE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAGrE,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EACN,eAAe,EACf,wBAAwB,EACxB,aAAa,EACb,SAAS,EACT,eAAe,GAEf,MAAM,YAAY,CAAC;AAEpB;;GAEG;AACH,MAAM,UAAU,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,eAAe,CAAC,MAAM,CAAC,CAAC;IAC7C,6IAA6I;IAC7I,MAAM,SAAS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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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\tconst exampleTypeName =\n\t\tnodeTypeUnion === undefined\n\t\t\t? undefined\n\t\t\t: nodeTypeUnion\n\t\t\t\t\t.split(\"|\")\n\t\t\t\t\t.map((part) => part.trim())\n\t\t\t\t\t.find((part) => part.length > 0);\n\n\tconst createDocs =\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\texampleTypeName === 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 ${exampleTypeName} with \\`if (context.is.${exampleTypeName}(node)) {}\\``}\n\t */\n\tis: Record<string, <T extends TreeData>(data: unknown) => data is T>;\n\t\n\t/**\n\t * Checks if the provided data is an array.\n\t * @remarks\n\t * DO NOT use \\`Array.isArray\\` to check if tree data is an array - use this function instead.\n\t * \n\t * This function will also work for native JavaScript arrays.\n\t *\n\t * ${`Example: \\`if (context.isArray(node)) {}\\``}\n\t */\n\tisArray(data: any): boolean;\n\t\n\t/**\n\t * Checks if the provided data is a map.\n\t * @remarks\n\t * DO NOT use \\`instanceof Map\\` to check if tree data is a map - use this function instead.\n\t * \n\t * This function will also work for native JavaScript Map instances.\n\t *\n\t * ${`Example: \\`if (context.isMap(node)) {}\\``}\n\t */\n\tisMap(data: any): boolean;\\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${createDocs}\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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fluidframework/tree-agent",
|
|
3
|
-
"version": "2.70.0-
|
|
3
|
+
"version": "2.70.0-361248",
|
|
4
4
|
"description": "Experimental package to simplify integrating AI into Fluid-based applications",
|
|
5
5
|
"homepage": "https://fluidframework.com",
|
|
6
6
|
"repository": {
|
|
@@ -70,24 +70,24 @@
|
|
|
70
70
|
},
|
|
71
71
|
"dependencies": {
|
|
72
72
|
"@anthropic-ai/sdk": "^0.39.0",
|
|
73
|
-
"@fluidframework/core-utils": "2.70.0-
|
|
74
|
-
"@fluidframework/runtime-utils": "2.70.0-
|
|
75
|
-
"@fluidframework/telemetry-utils": "2.70.0-
|
|
76
|
-
"@fluidframework/tree": "2.70.0-
|
|
73
|
+
"@fluidframework/core-utils": "2.70.0-361248",
|
|
74
|
+
"@fluidframework/runtime-utils": "2.70.0-361248",
|
|
75
|
+
"@fluidframework/telemetry-utils": "2.70.0-361248",
|
|
76
|
+
"@fluidframework/tree": "2.70.0-361248",
|
|
77
77
|
"uuid": "^11.1.0",
|
|
78
78
|
"zod": "^3.25.32"
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
81
|
"@arethetypeswrong/cli": "^0.17.1",
|
|
82
82
|
"@biomejs/biome": "~1.9.3",
|
|
83
|
-
"@fluid-internal/mocha-test-setup": "2.70.0-
|
|
83
|
+
"@fluid-internal/mocha-test-setup": "2.70.0-361248",
|
|
84
84
|
"@fluid-tools/build-cli": "^0.58.3",
|
|
85
85
|
"@fluidframework/build-common": "^2.0.3",
|
|
86
86
|
"@fluidframework/build-tools": "^0.58.3",
|
|
87
|
-
"@fluidframework/eslint-config-fluid": "^6.
|
|
88
|
-
"@fluidframework/id-compressor": "2.70.0-
|
|
89
|
-
"@fluidframework/runtime-utils": "2.70.0-
|
|
90
|
-
"@fluidframework/test-runtime-utils": "2.70.0-
|
|
87
|
+
"@fluidframework/eslint-config-fluid": "^6.1.0",
|
|
88
|
+
"@fluidframework/id-compressor": "2.70.0-361248",
|
|
89
|
+
"@fluidframework/runtime-utils": "2.70.0-361248",
|
|
90
|
+
"@fluidframework/test-runtime-utils": "2.70.0-361248",
|
|
91
91
|
"@langchain/anthropic": "^0.3.24",
|
|
92
92
|
"@langchain/core": "^0.3.78",
|
|
93
93
|
"@langchain/google-genai": "^0.2.16",
|
|
@@ -100,8 +100,8 @@
|
|
|
100
100
|
"concurrently": "^8.2.1",
|
|
101
101
|
"copyfiles": "^2.4.1",
|
|
102
102
|
"cross-env": "^7.0.3",
|
|
103
|
-
"eslint": "~8.
|
|
104
|
-
"eslint-config-prettier": "~
|
|
103
|
+
"eslint": "~8.57.1",
|
|
104
|
+
"eslint-config-prettier": "~10.1.8",
|
|
105
105
|
"mocha": "^10.8.2",
|
|
106
106
|
"mocha-multi-reporters": "^1.5.1",
|
|
107
107
|
"prettier": "~3.0.3",
|
package/src/agent.ts
CHANGED
|
@@ -8,7 +8,7 @@ import type {
|
|
|
8
8
|
TreeFieldFromImplicitField,
|
|
9
9
|
TreeNodeSchema,
|
|
10
10
|
} from "@fluidframework/tree";
|
|
11
|
-
import { TreeNode } from "@fluidframework/tree";
|
|
11
|
+
import { NodeKind, TreeNode } from "@fluidframework/tree";
|
|
12
12
|
import type {
|
|
13
13
|
ReadableField,
|
|
14
14
|
FactoryContentObject,
|
|
@@ -24,6 +24,7 @@ import type {
|
|
|
24
24
|
Logger,
|
|
25
25
|
SynchronousEditor,
|
|
26
26
|
AsynchronousEditor,
|
|
27
|
+
Context,
|
|
27
28
|
} from "./api.js";
|
|
28
29
|
import { getPrompt, stringifyTree } from "./prompt.js";
|
|
29
30
|
import { Subtree } from "./subtree.js";
|
|
@@ -248,25 +249,25 @@ export const defaultEditor: AsynchronousEditor = async (context, code) => {
|
|
|
248
249
|
};
|
|
249
250
|
|
|
250
251
|
/**
|
|
251
|
-
* Binds the given {@link
|
|
252
|
+
* Binds the given {@link AsynchronousEditor | editor} to the given view or tree.
|
|
252
253
|
* @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.
|
|
253
254
|
* @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
|
|
254
255
|
* @alpha
|
|
255
256
|
*/
|
|
256
257
|
export function bindEditorImpl<TSchema extends ImplicitFieldSchema>(
|
|
257
258
|
tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),
|
|
258
|
-
editor:
|
|
259
|
-
): (code: string) => void
|
|
259
|
+
editor: AsynchronousEditor,
|
|
260
|
+
): (code: string) => Promise<void>;
|
|
260
261
|
/**
|
|
261
|
-
* Binds the given {@link
|
|
262
|
+
* Binds the given {@link SynchronousEditor | editor} to the given view or tree.
|
|
262
263
|
* @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.
|
|
263
264
|
* @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
|
|
264
265
|
* @alpha
|
|
265
266
|
*/
|
|
266
267
|
export function bindEditorImpl<TSchema extends ImplicitFieldSchema>(
|
|
267
268
|
tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),
|
|
268
|
-
editor:
|
|
269
|
-
): (code: string) =>
|
|
269
|
+
editor: SynchronousEditor,
|
|
270
|
+
): (code: string) => void;
|
|
270
271
|
/**
|
|
271
272
|
* Binds the given {@link SynchronousEditor | editor} or {@link AsynchronousEditor | editor} to the given view or tree.
|
|
272
273
|
* @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.
|
|
@@ -296,9 +297,11 @@ function bindEditorToSubtree<TSchema extends ImplicitFieldSchema>(
|
|
|
296
297
|
): (code: string) => void | Promise<void> {
|
|
297
298
|
// Stick the tree schema constructors on an object passed to the function so that the LLM can create new nodes.
|
|
298
299
|
const create: Record<string, (input: FactoryContentObject) => TreeNode> = {};
|
|
300
|
+
const is: Record<string, <T extends TreeNode>(input: unknown) => input is T> = {};
|
|
299
301
|
for (const schema of findNamedSchemas(tree.schema)) {
|
|
300
302
|
const name = getFriendlyName(schema);
|
|
301
303
|
create[name] = (input: FactoryContentObject) => constructTreeNode(schema, input);
|
|
304
|
+
is[name] = <T extends TreeNode>(input: unknown): input is T => Tree.is(input, schema);
|
|
302
305
|
}
|
|
303
306
|
|
|
304
307
|
const context = {
|
|
@@ -309,7 +312,30 @@ function bindEditorToSubtree<TSchema extends ImplicitFieldSchema>(
|
|
|
309
312
|
tree.field = value;
|
|
310
313
|
},
|
|
311
314
|
create,
|
|
312
|
-
|
|
315
|
+
is,
|
|
316
|
+
isArray(node) {
|
|
317
|
+
if (Array.isArray(node)) {
|
|
318
|
+
return true;
|
|
319
|
+
}
|
|
320
|
+
if (node instanceof TreeNode) {
|
|
321
|
+
const schema = Tree.schema(node);
|
|
322
|
+
return schema.kind === NodeKind.Array;
|
|
323
|
+
}
|
|
324
|
+
return false;
|
|
325
|
+
},
|
|
326
|
+
isMap(node) {
|
|
327
|
+
if (node instanceof Map) {
|
|
328
|
+
return true;
|
|
329
|
+
}
|
|
330
|
+
if (node instanceof TreeNode) {
|
|
331
|
+
const schema = Tree.schema(node);
|
|
332
|
+
return schema.kind === NodeKind.Map;
|
|
333
|
+
}
|
|
334
|
+
return false;
|
|
335
|
+
},
|
|
336
|
+
parent: (child: TreeNode): TreeNode | undefined => Tree.parent(child),
|
|
337
|
+
key: (child: TreeNode): string | number => Tree.key(child),
|
|
338
|
+
} satisfies Context<TSchema>;
|
|
313
339
|
|
|
314
340
|
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
315
341
|
return (code: string) => executeEdit(context, code);
|
package/src/api.ts
CHANGED
|
@@ -22,6 +22,79 @@ export interface Logger {
|
|
|
22
22
|
log(message: string): void;
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
/**
|
|
26
|
+
* The context object available to generated code when editing a tree.
|
|
27
|
+
* @remarks This object is provided to JavaScript code executed by the {@link SynchronousEditor | editor} as a variable named `context`.
|
|
28
|
+
* It contains the current state of the tree and utilities for creating and inspecting tree nodes.
|
|
29
|
+
* @alpha
|
|
30
|
+
*/
|
|
31
|
+
export interface Context<TSchema extends ImplicitFieldSchema> {
|
|
32
|
+
/**
|
|
33
|
+
* The root of the tree that can be read or modified.
|
|
34
|
+
* @remarks
|
|
35
|
+
* You can read properties and navigate through the tree starting from this root.
|
|
36
|
+
* 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.
|
|
37
|
+
*
|
|
38
|
+
* Example: Read the current root with `const currentRoot = context.root;`
|
|
39
|
+
*
|
|
40
|
+
* Example: Replace the entire root with `context.root = context.create.MyRootType({ });`
|
|
41
|
+
*/
|
|
42
|
+
root: ReadableField<TSchema>;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* A collection of builder functions for creating new tree nodes.
|
|
46
|
+
* @remarks
|
|
47
|
+
* Each property on this object is named after a type in the tree schema.
|
|
48
|
+
* Call the corresponding function to create a new node of that type.
|
|
49
|
+
* Always use these builder functions when creating new nodes rather than plain JavaScript objects.
|
|
50
|
+
*
|
|
51
|
+
* Example: Create a new Person node with `context.create.Person({ name: "Alice", age: 30 })`
|
|
52
|
+
*/
|
|
53
|
+
create: Record<string, (input: FactoryContentObject) => TreeNode>;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* A collection of type-checking functions for tree nodes.
|
|
57
|
+
* @remarks
|
|
58
|
+
* Each property on this object is named after a type in the tree schema.
|
|
59
|
+
* Call the corresponding function to check if a node is of that specific type.
|
|
60
|
+
* This is useful when working with nodes that could be one of multiple types.
|
|
61
|
+
*
|
|
62
|
+
* Example: Check if a node is a Person with `if (context.is.Person(node)) { console.log(node.name); }`
|
|
63
|
+
*/
|
|
64
|
+
is: Record<string, <T extends TreeNode>(input: T) => input is T>;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Checks if the given node is an array.
|
|
68
|
+
*/
|
|
69
|
+
isArray(value: unknown): boolean;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Checks if the given node is a map.
|
|
73
|
+
*/
|
|
74
|
+
isMap(value: unknown): boolean;
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Returns the parent node of the given child node.
|
|
78
|
+
* @param child - The node whose parent you want to find.
|
|
79
|
+
* @returns The parent node, or `undefined` if the node is the root or is not in the tree.
|
|
80
|
+
* @remarks
|
|
81
|
+
* Example: Get the parent with `const parent = context.parent(childNode);`
|
|
82
|
+
*/
|
|
83
|
+
parent(child: TreeNode): TreeNode | undefined;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Returns the key or index of the given node within its parent.
|
|
87
|
+
* @param child - The node whose key you want to find.
|
|
88
|
+
* @returns A string key if the node is in an object or map, or a numeric index if the node is in an array.
|
|
89
|
+
* @remarks
|
|
90
|
+
* For a node in an object, this might return a string like "firstName".
|
|
91
|
+
* For a node in an array, this might return a number like 0, 1, 2, etc.
|
|
92
|
+
*
|
|
93
|
+
* Example: `const key = context.key(childNode);`
|
|
94
|
+
*/
|
|
95
|
+
key(child: TreeNode): string | number;
|
|
96
|
+
}
|
|
97
|
+
|
|
25
98
|
/**
|
|
26
99
|
* A synchronous function that executes a string of JavaScript code to perform an edit within a {@link SharedTreeSemanticAgent}.
|
|
27
100
|
* @param context - An object that must be provided to the generated code as a variable named "context" in its top-level scope.
|