@fluidframework/tree-agent 2.63.0 → 2.70.0-360753

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/lib/api.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAgFH;;GAEG;AACH,MAAM,UAAU,YAAY,CAAC,KAAc;IAC1C,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACjD,OAAO,KAAK,CAAC;IACd,CAAC;IACD,OAAO,CACN,OAAQ,KAAoB,CAAC,IAAI,KAAK,QAAQ;QAC9C,OAAQ,KAAoB,CAAC,OAAO,KAAK,QAAQ,CACjD,CAAC;AACH,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type { ImplicitFieldSchema, TreeNode } from \"@fluidframework/tree\";\n// This is used for doc links\nimport type { FactoryContentObject, ReadableField } from \"@fluidframework/tree/alpha\";\n\n/**\n * Logger interface for logging events from a {@link SharedTreeSemanticAgent}.\n * @alpha\n */\nexport interface Logger {\n\t/**\n\t * Log a message.\n\t */\n\tlog(message: string): void;\n}\n\n/**\n * Options used to parameterize the creation of a {@link SharedTreeSemanticAgent}.\n * @alpha\n */\nexport interface SemanticAgentOptions {\n\t/**\n\t * Additional information about the application domain that will be included in the context provided to the {@link SharedTreeChatModel | model}.\n\t */\n\tdomainHints?: string;\n\t/**\n\t * Validates any generated JavaScript created by the {@link SharedTreeChatModel.editToolName | model's editing tool}.\n\t * @remarks This happens before the code is executed - execution can be intercepted by using the {@link SemanticAgentOptions.executeEdit | executeEdit} callback.\n\t * @param code - The generated JavaScript code as a string.\n\t * @throws If the code is invalid, this function should throw an error with a human-readable message describing why it is invalid.\n\t */\n\tvalidateEdit?: (code: string) => void | Promise<void>;\n\t/**\n\t * Evaluates/runs any generated JavaScript created by the {@link SharedTreeChatModel.editToolName | model's editing tool}.\n\t * @remarks This happens only after the code has been successfully validated by the optional {@link SemanticAgentOptions.validateEdit | validateEdit} function.\n\t * @param context - An object that must be provided to the generated code as a variable named \"context\" in its top-level scope.\n\t * @param code - The generated JavaScript code as a string.\n\t * @throws If an error is thrown while executing the code, it will be caught and the message will be forwarded to the model for debugging.\n\t * @remarks If this function is not provided, the generated code will be executed using a simple `eval` call, which may not provide sufficient security guarantees for some environments.\n\t * Use a library such as SES to provide a more secure implementation - see `@fluidframework/tree-agent-ses` for a drop-in implementation.\n\t */\n\texecuteEdit?: (context: Record<string, unknown>, code: string) => void | Promise<void>;\n\t/**\n\t * The maximum number of sequential edits the LLM can make before we assume it's stuck in a loop.\n\t */\n\tmaximumSequentialEdits?: number;\n\t/**\n\t * If supplied, generates human-readable markdown text describing the actions taken by the {@link SharedTreeSemanticAgent | agent} as it performs queries.\n\t */\n\tlogger?: Logger;\n}\n\n/**\n * A result from an edit attempt via the {@link SharedTreeChatQuery.edit} function.\n * @remarks\n * - `success`: The edit was successfully applied.\n * - `disabledError`: The model is not allowed to edit the tree (i.e. {@link SharedTreeChatModel.editToolName} was not provided).\n * - `validationError`: The provided JavaScript did not pass the optional {@link SemanticAgentOptions.validateEdit} function.\n * - `executionError`: An error was thrown while parsing or executing the provided JavaScript.\n * - `tooManyEditsError`: The {@link SharedTreeChatQuery.edit} function has been called more than the number of times specified by {@link SemanticAgentOptions.maximumSequentialEdits} for the same message.\n * - `expiredError`: The {@link SharedTreeChatQuery.edit} function was called after the issuing query has already completed.\n * @alpha\n */\nexport interface EditResult {\n\ttype:\n\t\t| \"success\"\n\t\t| \"disabledError\"\n\t\t| \"validationError\"\n\t\t| \"executionError\"\n\t\t| \"tooManyEditsError\"\n\t\t| \"expiredError\";\n\n\t/**\n\t * A human-readable message describing the result of the edit attempt.\n\t * @remarks In the case of an error, this message is appropriate to include in a model's chat history.\n\t */\n\tmessage: string;\n}\n\n/**\n * Type guard for {@link EditResult}.\n */\nexport function isEditResult(value: unknown): value is EditResult {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn false;\n\t}\n\treturn (\n\t\ttypeof (value as EditResult).type === \"string\" &&\n\t\ttypeof (value as EditResult).message === \"string\"\n\t);\n}\n\n/**\n * A query from a user to a {@link SharedTreeSemanticAgent}.\n * @remarks Processing a query may involve editing the SharedTree via the provided {@link SharedTreeChatQuery.edit} function.\n * @alpha\n */\nexport interface SharedTreeChatQuery {\n\t/**\n\t * The user's query.\n\t */\n\ttext: string;\n\t/**\n\t * Edit the tree with the provided JavaScript function code.\n\t * @remarks Attempting an edit may fail for a variety of reasons which are captured in the {@link EditResult | returned object}.\n\t */\n\tedit(js: string): Promise<EditResult>;\n}\n\n/**\n * A plugin interface that handles queries from a {@link SharedTreeSemanticAgent}.\n * @remarks This wraps an underlying communication with an LLM and receives all necessary {@link SharedTreeChatModel.appendContext | context} from the {@link SharedTreeSemanticAgent | agent} for the LLM to properly analyze and edit the tree.\n * See `@fluidframework/tree-agent-langchain` for a drop-in implementation based on the LangChain library.\n * @alpha\n */\nexport interface SharedTreeChatModel {\n\t/**\n\t * A optional name of this chat model.\n\t * @remarks If supplied, this may be used in logging or debugging information.\n\t * @example \"gpt-5\"\n\t */\n\tname?: string;\n\t/**\n\t * The name of the tool that the model should use to edit the tree.\n\t * @remarks If supplied, this will be mentioned in the context provided to the model so that the underlying LLM will be encouraged to use it when a user query requires an edit.\n\t * The model should \"implement\" the tool by registering it with the underlying LLM API.\n\t * The tool should take an LLM-generated JavaScript function as input and supply it to the {@link SharedTreeChatQuery.edit | edit} function.\n\t * Instructions for generating the proper function signature and implementation will be provided by the {@link SharedTreeSemanticAgent | agent} via {@link SharedTreeChatModel.appendContext | context}.\n\t * If not supplied, the model will not be able to edit the tree (running the {@link SharedTreeChatQuery.edit | edit} function will fail).\n\t */\n\teditToolName?: string;\n\t/**\n\t * Add contextual information to the model that may be relevant to future queries.\n\t * @remarks In practice, this may be implemented by e.g. appending a \"system\" message to an LLM's chat/message history.\n\t * This context must be present in the context window of every {@link SharedTreeChatModel.query | query} for e.g. {@link SharedTreeChatModel.editToolName | editing} to work.\n\t * @param text - The message or context to append.\n\t */\n\tappendContext?(text: string): void;\n\t/**\n\t * Queries the chat model with a request from the user.\n\t * @remarks This model may simply return a text response to the query, or it may first call the {@link SharedTreeChatQuery.edit} function (potentially multiple times) to modify the tree in response to the query.\n\t */\n\tquery(message: SharedTreeChatQuery): Promise<string>;\n}\n\n/**\n * A function that edits a SharedTree.\n */\nexport type EditFunction<TSchema extends ImplicitFieldSchema> = ({\n\troot,\n\tcreate,\n}: {\n\troot: ReadableField<TSchema>;\n\tcreate: Record<string, (input: FactoryContentObject) => TreeNode>;\n}) => void | Promise<void>;\n"]}
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA4FH;;GAEG;AACH,MAAM,UAAU,YAAY,CAAC,KAAc;IAC1C,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACjD,OAAO,KAAK,CAAC;IACd,CAAC;IACD,OAAO,CACN,OAAQ,KAAoB,CAAC,IAAI,KAAK,QAAQ;QAC9C,OAAQ,KAAoB,CAAC,OAAO,KAAK,QAAQ,CACjD,CAAC;AACH,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type { ImplicitFieldSchema, TreeNode } from \"@fluidframework/tree\";\n// These are used for doc links\nimport type { FactoryContentObject, ReadableField } from \"@fluidframework/tree/alpha\";\n\n// This is used for doc links\n// eslint-disable-next-line unused-imports/no-unused-imports\nimport type { bindEditor, defaultEditor } from \"./agent.js\";\n\n/**\n * Logger interface for logging events from a {@link SharedTreeSemanticAgent}.\n * @alpha\n */\nexport interface Logger {\n\t/**\n\t * Log a message.\n\t */\n\tlog(message: string): void;\n}\n\n/**\n * A synchronous function that executes a string of JavaScript code to perform an edit within a {@link SharedTreeSemanticAgent}.\n * @param context - An object that must be provided to the generated code as a variable named \"context\" in its top-level scope.\n * @param code - The JavaScript code that should be executed.\n * @remarks To simulate the execution of an editor outside of an {@link SharedTreeSemanticAgent | agent}, you can use {@link bindEditor | bindEditor} to bind an editor to a specific subtree.\n * @alpha\n */\nexport type SynchronousEditor = (context: Record<string, unknown>, code: string) => void;\n/**\n * An asynchronous function that executes a string of JavaScript code to perform an edit within a {@link SharedTreeSemanticAgent}.\n * @param context - An object that must be provided to the generated code as a variable named \"context\" in its top-level scope.\n * @param code - The JavaScript code that should be executed.\n * @remarks To simulate the execution of an editor outside of an {@link SharedTreeSemanticAgent | agent}, you can use {@link bindEditor | bindEditor} to bind an editor to a specific subtree.\n * @alpha\n */\nexport type AsynchronousEditor = (\n\tcontext: Record<string, unknown>,\n\tcode: string,\n) => Promise<void>;\n\n/**\n * Options used to parameterize the creation of a {@link SharedTreeSemanticAgent}.\n * @alpha\n */\nexport interface SemanticAgentOptions {\n\t/**\n\t * Additional information about the application domain that will be included in the context provided to the {@link SharedTreeChatModel | model}.\n\t */\n\tdomainHints?: string;\n\t/**\n\t * Executes any generated JavaScript created by the {@link SharedTreeChatModel.editToolName | model's editing tool}.\n\t * @remarks If an error is thrown while executing the code, it will be caught and the message will be forwarded to the {@link SharedTreeChatModel | model} for debugging.\n\t * @remarks If this function is not provided, the generated code will be executed using a {@link defaultEditor | simple default} which may not provide sufficient security guarantees for some environments.\n\t * Use a library such as SES to provide a more secure implementation - see `@fluidframework/tree-agent-ses` for a drop-in implementation.\n\t *\n\t * To simulate the execution of an editor outside of an {@link SharedTreeSemanticAgent | agent}, you can use {@link bindEditor | bindEditor} to bind an editor to a specific subtree.\n\t */\n\teditor?: SynchronousEditor | AsynchronousEditor;\n\t/**\n\t * The maximum number of sequential edits the LLM can make before we assume it's stuck in a loop.\n\t */\n\tmaximumSequentialEdits?: number;\n\t/**\n\t * If supplied, generates human-readable markdown text describing the actions taken by the {@link SharedTreeSemanticAgent | agent} as it performs queries.\n\t */\n\tlogger?: Logger;\n}\n\n/**\n * A result from an edit attempt via the {@link SharedTreeChatQuery.edit} function.\n * @alpha\n */\nexport interface EditResult {\n\t/**\n\t * The type of the edit result.\n\t * @remarks\n\t * - `success`: The edit was successfully applied.\n\t * - `disabledError`: The model is not allowed to edit the tree (i.e. {@link SharedTreeChatModel.editToolName} was not provided).\n\t * - `editingError`: An error was thrown while parsing or executing the provided JavaScript.\n\t * - `tooManyEditsError`: The {@link SharedTreeChatQuery.edit} function has been called more than the number of times specified by {@link SemanticAgentOptions.maximumSequentialEdits} for the same message.\n\t * - `expiredError`: The {@link SharedTreeChatQuery.edit} function was called after the issuing query has already completed.\n\t */\n\ttype: \"success\" | \"disabledError\" | \"editingError\" | \"tooManyEditsError\" | \"expiredError\";\n\n\t/**\n\t * A human-readable message describing the result of the edit attempt.\n\t * @remarks In the case of an error, this message is appropriate to include in a model's chat history.\n\t */\n\tmessage: string;\n}\n\n/**\n * Type guard for {@link EditResult}.\n */\nexport function isEditResult(value: unknown): value is EditResult {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn false;\n\t}\n\treturn (\n\t\ttypeof (value as EditResult).type === \"string\" &&\n\t\ttypeof (value as EditResult).message === \"string\"\n\t);\n}\n\n/**\n * A query from a user to a {@link SharedTreeSemanticAgent}.\n * @remarks Processing a query may involve editing the SharedTree via the provided {@link SharedTreeChatQuery.edit} function.\n * @alpha\n */\nexport interface SharedTreeChatQuery {\n\t/**\n\t * The user's query.\n\t */\n\ttext: string;\n\t/**\n\t * Edit the tree with the provided JavaScript function code.\n\t * @remarks Attempting an edit may fail for a variety of reasons which are captured in the {@link EditResult | returned object}.\n\t * If an edit fails, the tree will not be modified and the model may attempt another edit if desired.\n\t * When the query ends, if the last edit attempt was successful, all edits made during the query will be merged into the agent's SharedTree.\n\t * Otherwise, all edits made during the query will be discarded.\n\t */\n\tedit(js: string): Promise<EditResult>;\n}\n\n/**\n * A plugin interface that handles queries from a {@link SharedTreeSemanticAgent}.\n * @remarks This wraps an underlying communication with an LLM and receives all necessary {@link SharedTreeChatModel.appendContext | context} from the {@link SharedTreeSemanticAgent | agent} for the LLM to properly analyze and edit the tree.\n * See `@fluidframework/tree-agent-langchain` for a drop-in implementation based on the LangChain library.\n * @alpha\n */\nexport interface SharedTreeChatModel {\n\t/**\n\t * A optional name of this chat model.\n\t * @remarks If supplied, this may be used in logging or debugging information.\n\t * @example \"gpt-5\"\n\t */\n\tname?: string;\n\t/**\n\t * The name of the tool that the model should use to edit the tree.\n\t * @remarks If supplied, this will be mentioned in the context provided to the model so that the underlying LLM will be encouraged to use it when a user query requires an edit.\n\t * The model should \"implement\" the tool by registering it with the underlying LLM API.\n\t * The tool should take an LLM-generated JavaScript function as input and supply it to the {@link SharedTreeChatQuery.edit | edit} function.\n\t * Instructions for generating the proper function signature and implementation will be provided by the {@link SharedTreeSemanticAgent | agent} via {@link SharedTreeChatModel.appendContext | context}.\n\t * If not supplied, the model will not be able to edit the tree (running the {@link SharedTreeChatQuery.edit | edit} function will fail).\n\t */\n\teditToolName?: string;\n\t/**\n\t * Add contextual information to the model that may be relevant to future queries.\n\t * @remarks In practice, this may be implemented by e.g. appending a \"system\" message to an LLM's chat/message history.\n\t * This context must be present in the context window of every {@link SharedTreeChatModel.query | query} for e.g. {@link SharedTreeChatModel.editToolName | editing} to work.\n\t * @param text - The message or context to append.\n\t */\n\tappendContext?(text: string): void;\n\t/**\n\t * Queries the chat model with a request from the user.\n\t * @remarks This model may simply return a text response to the query, or it may first call the {@link SharedTreeChatQuery.edit} function (potentially multiple times) to modify the tree in response to the query.\n\t */\n\tquery(message: SharedTreeChatQuery): Promise<string>;\n}\n\n/**\n * A function that edits a SharedTree.\n */\nexport type EditFunction<TSchema extends ImplicitFieldSchema> = ({\n\troot,\n\tcreate,\n}: {\n\troot: ReadableField<TSchema>;\n\tcreate: Record<string, (input: FactoryContentObject) => TreeNode>;\n}) => void | Promise<void>;\n"]}
package/lib/index.d.ts CHANGED
@@ -7,8 +7,8 @@
7
7
  *
8
8
  * @packageDocumentation
9
9
  */
10
- export { SharedTreeSemanticAgent } from "./agent.js";
11
- export type { EditResult, SharedTreeChatModel, SharedTreeChatQuery, Logger, SemanticAgentOptions, } from "./api.js";
10
+ export { SharedTreeSemanticAgent, bindEditor, bindEditorImpl, defaultEditor, } from "./agent.js";
11
+ export type { EditResult, SharedTreeChatModel, SharedTreeChatQuery, Logger, SemanticAgentOptions, SynchronousEditor, AsynchronousEditor, } from "./api.js";
12
12
  export { type TreeView, llmDefault } from "./utils.js";
13
13
  export { buildFunc, exposeMethodsSymbol, type ArgsTuple, type ExposedMethods, type Arg, type FunctionDef, type MethodKeys, type BindableSchema, type Ctor, type Infer, type IExposedMethods, } from "./methodBinding.js";
14
14
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;GAIG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AACrD,YAAY,EACX,UAAU,EACV,mBAAmB,EACnB,mBAAmB,EACnB,MAAM,EACN,oBAAoB,GACpB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,KAAK,QAAQ,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EACN,SAAS,EACT,mBAAmB,EACnB,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,KAAK,GAAG,EACR,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,cAAc,EACnB,KAAK,IAAI,EACT,KAAK,KAAK,EACV,KAAK,eAAe,GACpB,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;GAIG;AAEH,OAAO,EACN,uBAAuB,EACvB,UAAU,EACV,cAAc,EACd,aAAa,GACb,MAAM,YAAY,CAAC;AACpB,YAAY,EACX,UAAU,EACV,mBAAmB,EACnB,mBAAmB,EACnB,MAAM,EACN,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,GAClB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,KAAK,QAAQ,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EACN,SAAS,EACT,mBAAmB,EACnB,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,KAAK,GAAG,EACR,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,cAAc,EACnB,KAAK,IAAI,EACT,KAAK,KAAK,EACV,KAAK,eAAe,GACpB,MAAM,oBAAoB,CAAC"}
package/lib/index.js CHANGED
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * @packageDocumentation
9
9
  */
10
- export { SharedTreeSemanticAgent } from "./agent.js";
10
+ export { SharedTreeSemanticAgent, bindEditor, bindEditorImpl, defaultEditor, } from "./agent.js";
11
11
  export { llmDefault } from "./utils.js";
12
12
  export { buildFunc, exposeMethodsSymbol, } from "./methodBinding.js";
13
13
  //# sourceMappingURL=index.js.map
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;GAIG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAQrD,OAAO,EAAiB,UAAU,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EACN,SAAS,EACT,mBAAmB,GAUnB,MAAM,oBAAoB,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * A library for creating AI agents to interact with a {@link SharedTree | https://fluidframework.com/docs/data-structures/tree/}.\n *\n * @packageDocumentation\n */\n\nexport { SharedTreeSemanticAgent } from \"./agent.js\";\nexport type {\n\tEditResult,\n\tSharedTreeChatModel,\n\tSharedTreeChatQuery,\n\tLogger,\n\tSemanticAgentOptions,\n} from \"./api.js\";\nexport { type TreeView, llmDefault } from \"./utils.js\";\nexport {\n\tbuildFunc,\n\texposeMethodsSymbol,\n\ttype ArgsTuple,\n\ttype ExposedMethods,\n\ttype Arg,\n\ttype FunctionDef,\n\ttype MethodKeys,\n\ttype BindableSchema,\n\ttype Ctor,\n\ttype Infer,\n\ttype IExposedMethods,\n} from \"./methodBinding.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;GAIG;AAEH,OAAO,EACN,uBAAuB,EACvB,UAAU,EACV,cAAc,EACd,aAAa,GACb,MAAM,YAAY,CAAC;AAUpB,OAAO,EAAiB,UAAU,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EACN,SAAS,EACT,mBAAmB,GAUnB,MAAM,oBAAoB,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * A library for creating AI agents to interact with a {@link SharedTree | https://fluidframework.com/docs/data-structures/tree/}.\n *\n * @packageDocumentation\n */\n\nexport {\n\tSharedTreeSemanticAgent,\n\tbindEditor,\n\tbindEditorImpl,\n\tdefaultEditor,\n} from \"./agent.js\";\nexport type {\n\tEditResult,\n\tSharedTreeChatModel,\n\tSharedTreeChatQuery,\n\tLogger,\n\tSemanticAgentOptions,\n\tSynchronousEditor,\n\tAsynchronousEditor,\n} from \"./api.js\";\nexport { type TreeView, llmDefault } from \"./utils.js\";\nexport {\n\tbuildFunc,\n\texposeMethodsSymbol,\n\ttype ArgsTuple,\n\ttype ExposedMethods,\n\ttype Arg,\n\ttype FunctionDef,\n\ttype MethodKeys,\n\ttype BindableSchema,\n\ttype Ctor,\n\ttype Infer,\n\ttype IExposedMethods,\n} from \"./methodBinding.js\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,mBAAmB,EAAe,MAAM,sBAAsB,CAAC;AAC7E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAIhE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAW5C;;GAEG;AACH,wBAAgB,SAAS,CAAC,KAAK,SAAS,mBAAmB,EAAE,IAAI,EAAE;IAClE,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IACxB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB,GAAG,MAAM,CA4IT;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,aAAa,CAAC,mBAAmB,CAAC,GAAG,MAAM,CA8C9E"}
1
+ {"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,mBAAmB,EAAe,MAAM,sBAAsB,CAAC;AAC7E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAIhE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAW5C;;GAEG;AACH,wBAAgB,SAAS,CAAC,KAAK,SAAS,mBAAmB,EAAE,IAAI,EAAE;IAClE,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IACxB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB,GAAG,MAAM,CAsLT;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,aAAa,CAAC,mBAAmB,CAAC,GAAG,MAAM,CA8C9E"}
package/lib/prompt.js CHANGED
@@ -65,6 +65,42 @@ const ${communize(exampleObjectName)} = context.create.${exampleObjectName}({ /*
65
65
  // Don't do this:
66
66
  // const ${communize(exampleObjectName)} = { /* ...properties... */ };
67
67
  \`\`\`\n\n`;
68
+ 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
+ Instead, it must be deep cloned and recreated.
70
+ ${exampleObjectName === undefined
71
+ ? ""
72
+ : `For example:
73
+
74
+ \`\`\`javascript
75
+ // Data is removed from the tree:
76
+ const ${communize(exampleObjectName)} = parent.${communize(exampleObjectName)};
77
+ parent.${communize(exampleObjectName)} = undefined;
78
+ // \`${communize(exampleObjectName)}\` cannot be directly re-inserted into the tree - this will throw an error:
79
+ // parent.${communize(exampleObjectName)} = ${communize(exampleObjectName)}; // ❌ A node may not be inserted into the tree more than once
80
+ // Instead, it must be deep cloned and recreated before insertion:
81
+ parent.${communize(exampleObjectName)} = context.create.${exampleObjectName}({ /*... deep clone all properties from \`${communize(exampleObjectName)}\` */ });
82
+ \`\`\`${hasArrays
83
+ ? `\n\nThe same applies when using arrays:\n\`\`\`javascript
84
+ // Data is removed from the tree:
85
+ const item = arrayOf${exampleObjectName}[0];
86
+ arrayOf${exampleObjectName}.removeAt(0);
87
+ // \`item\` cannot be directly re-inserted into the tree - this will throw an error:
88
+ arrayOf${exampleObjectName}.insertAt(0, item); // ❌ A node may not be inserted into the tree more than once
89
+ // Instead, it must be deep cloned and recreated before insertion:
90
+ arrayOf${exampleObjectName}.insertAt(0, context.create.${exampleObjectName}({ /*... deep clone all properties from \`item\` */ }));
91
+ \`\`\``
92
+ : ""}${hasMaps
93
+ ? `\n\nThe same applies when using maps:
94
+ \`\`\`javascript
95
+ // Data is removed from the tree:
96
+ const value = mapOf${exampleObjectName}.get("someKey");
97
+ mapOf${exampleObjectName}.delete("someKey");
98
+ // \`value\` cannot be directly re-inserted into the tree - this will throw an error:
99
+ mapOf${exampleObjectName}.set("someKey", value); // ❌ A node may not be inserted into the tree more than once
100
+ // Instead, it must be deep cloned and recreated before insertion:
101
+ mapOf${exampleObjectName}.set("someKey", context.create.${exampleObjectName}({ /*... deep clone all properties from \`value\` */ }));
102
+ \`\`\``
103
+ : ""}`}`;
68
104
  const arrayEditing = `#### Editing Arrays
69
105
 
70
106
  The arrays in the tree are somewhat different than normal JavaScript \`Array\`s.
@@ -109,14 +145,13 @@ This \`context\` variable holds the current state of the tree in the \`root\` pr
109
145
  You may mutate any part of the root tree as necessary, taking into account the caveats around${hasArrays ? ` arrays${hasMaps ? " and" : ""}` : ""}${hasMaps ? " maps" : ""} detailed below.
110
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 (\`${Array.from(rootTypes.values(), (t) => getFriendlyName(t)).join(" | ")}\`).
111
147
  ${helperMethodExplanation}
112
-
113
148
  ${hasArrays ? arrayEditing : ""}${hasMaps ? mapEditing : ""}#### Additional Notes
114
149
 
115
150
  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.
116
151
 
117
- Once data has been removed from the tree (e.g. replaced via assignment, or removed from an array), that data cannot be re-inserted into the tree - instead, it must be deep cloned and recreated.
152
+ ${builderExplanation}${reinsertionExplanation}
118
153
 
119
- ${builderExplanation}Finally, double check that the edits would accomplish the user's request (if it is possible).
154
+ Finally, double check that the edits would accomplish the user's request (if it is possible).
120
155
 
121
156
  `;
122
157
  const 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.
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,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;;GAIG;AACH,SAAS,2BAA2B,CAAC,QAAgB;IACpD,OAAO;;;mBAGW,QAAQ;;;;;;;;kFAQuD,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyDxF,CAAC;AACH,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { NodeKind, Tree, TreeNode } from \"@fluidframework/tree\";\nimport type { ImplicitFieldSchema, TreeMapNode } from \"@fluidframework/tree\";\nimport type { ReadableField } from \"@fluidframework/tree/alpha\";\nimport { getSimpleSchema } from \"@fluidframework/tree/alpha\";\nimport { normalizeFieldSchema } from \"@fluidframework/tree/internal\";\n\nimport type { Subtree } from \"./subtree.js\";\nimport { generateEditTypesForPrompt } from \"./typeGeneration.js\";\nimport {\n\tgetFriendlyName,\n\tgetZodSchemaAsTypeScript,\n\tisNamedSchema,\n\tcommunize,\n\tunqualifySchema,\n\ttype SchemaDetails,\n} from \"./utils.js\";\n\n/**\n * Produces a \"system\" prompt for the tree agent, based on the provided subtree.\n */\nexport function getPrompt<TRoot extends ImplicitFieldSchema>(args: {\n\tsubtree: Subtree<TRoot>;\n\teditToolName: string | undefined;\n\tdomainHints?: string;\n}): string {\n\tconst { subtree, editToolName, domainHints } = args;\n\tconst { field, schema } = subtree;\n\tconst arrayInterfaceName = \"TreeArray\";\n\tconst mapInterfaceName = \"TreeMap\";\n\tconst simpleSchema = getSimpleSchema(schema);\n\t// Inspect the schema to determine what kinds of nodes are possible - this will affect how much information we need to include in the prompt.\n\tlet hasArrays = false;\n\tlet hasMaps = false;\n\tlet exampleObjectName: string | undefined;\n\tfor (const [definition, nodeSchema] of simpleSchema.definitions) {\n\t\tswitch (nodeSchema.kind) {\n\t\t\tcase NodeKind.Array: {\n\t\t\t\thasArrays = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Map: {\n\t\t\t\thasMaps = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Object: {\n\t\t\t\texampleObjectName ??= unqualifySchema(definition);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tconst { domainTypes } = generateEditTypesForPrompt(schema, simpleSchema);\n\tfor (const [key, value] of Object.entries(domainTypes)) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n\t\tdelete domainTypes[key];\n\t\tif (isNamedSchema(key)) {\n\t\t\tconst friendlyKey = unqualifySchema(key);\n\t\t\tdomainTypes[friendlyKey] = value;\n\t\t}\n\t}\n\n\tconst stringified = stringifyTree(field);\n\tconst details: SchemaDetails = { hasHelperMethods: false };\n\tconst typescriptSchemaTypes = getZodSchemaAsTypeScript(domainTypes, details);\n\tconst helperMethodExplanation = details.hasHelperMethods\n\t\t? `Manipulating the data using the APIs described below is allowed, but when possible ALWAYS prefer to use any application helper methods exposed on the schema TypeScript types if the goal can be accomplished that way.\nIt will often not be possible to fully accomplish the goal using those helpers. When this is the case, mutate the objects as normal, taking into account the following guidance.`\n\t\t: \"\";\n\n\tconst builderExplanation =\n\t\texampleObjectName === undefined\n\t\t\t? \"\"\n\t\t\t: `When constructing new objects, you should wrap them in the appropriate builder function rather than simply making a javascript object.\nThe builders are available on the \\`create\\` property on the context object and are named according to the type that they create.\nFor example:\n\n\\`\\`\\`javascript\n// This creates a new ${exampleObjectName} object:\nconst ${communize(exampleObjectName)} = context.create.${exampleObjectName}({ /* ...properties... */ });\n// Don't do this:\n// const ${communize(exampleObjectName)} = { /* ...properties... */ };\n\\`\\`\\`\\n\\n`;\n\n\tconst arrayEditing = `#### Editing Arrays\n\nThe arrays in the tree are somewhat different than normal JavaScript \\`Array\\`s.\nRead-only operations are generally the same - you can create them, read via index, and call non-mutating methods like \\`concat\\`, \\`map\\`, \\`filter\\`, \\`find\\`, \\`forEach\\`, \\`indexOf\\`, \\`slice\\`, \\`join\\`, etc.\nHowever, write operations (e.g. index assignment, \\`push\\`, \\`pop\\`, \\`splice\\`, etc.) are not supported.\nInstead, you must use the methods on the following interface to mutate the array:\n\n\\`\\`\\`typescript\n${getTreeArrayNodeDocumentation(arrayInterfaceName)}\n\\`\\`\\`\n\nWhen possible, ensure that the edits preserve the identity of objects already in the tree.\nFor example, prefer \\`array.moveToIndex\\` over \\`array.removeAt\\` + \\`array.insertAt\\` and prefer \\`array.moveRangeToIndex\\` over \\`array.removeRange\\` + \\`array.insertAt\\`.\n\n`;\n\n\tconst mapEditing = `#### Editing Maps\n\nThe maps in the tree are somewhat different than normal JavaScript \\`Map\\`s.\nMap keys are always strings.\nRead-only operations are generally the same - you can create them, read via \\`get\\`, and call non-mutating methods like \\`has\\`, \\`forEach\\`, \\`entries\\`, \\`keys\\`, \\`values\\`, etc. (note the subtle differences around return values and iteration order).\nHowever, write operations (e.g. \\`set\\`, \\`delete\\`, etc.) are not supported.\nInstead, you must use the methods on the following interface to mutate the map:\n\n\\`\\`\\`typescript\n${getTreeMapNodeDocumentation(mapInterfaceName)}\n\\`\\`\\`\n\n`;\n\n\tconst rootTypes = normalizeFieldSchema(schema).allowedTypeSet;\n\tconst editing = `If the user asks you to edit the tree, you should author a snippet of JavaScript code to accomplish the user-specified goal, following the instructions for editing detailed below.\nYou must use the \"${editToolName}\" tool to run the generated code.\nAfter editing the tree, review the latest state of the tree to see if it satisfies the user's request.\nIf it does not, or if you receive an error, you may try again with a different approach.\nOnce the tree is in the desired state, you should inform the user that the request has been completed.\n\n### Editing\n\nIf the user asks you to edit the document, you will write a snippet of JavaScript code that mutates the data in-place to achieve the user's goal.\nThe snippet may be synchronous or asynchronous (i.e. it may \\`await\\` functions if necessary).\nThe snippet has a \\`context\\` variable in its scope.\nThis \\`context\\` variable holds the current state of the tree in the \\`root\\` property.\nYou may mutate any part of the root tree as necessary, taking into account the caveats around${hasArrays ? ` arrays${hasMaps ? \" and\" : \"\"}` : \"\"}${hasMaps ? \" maps\" : \"\"} detailed below.\nYou may also set the \\`root\\` property of the context to be an entirely new value as long as it is one of the types allowed at the root of the tree (\\`${Array.from(rootTypes.values(), (t) => getFriendlyName(t)).join(\" | \")}\\`).\n${helperMethodExplanation}\n\n${hasArrays ? arrayEditing : \"\"}${hasMaps ? mapEditing : \"\"}#### Additional Notes\n\nBefore outputting the edit function, you should check that it is valid according to both the application tree's schema and any restrictions of the editing APIs described above.\n\nOnce data has been removed from the tree (e.g. replaced via assignment, or removed from an array), that data cannot be re-inserted into the tree - instead, it must be deep cloned and recreated.\n\n${builderExplanation}Finally, double check that the edits would accomplish the user's request (if it is possible).\n\n`;\n\n\tconst prompt = `You are a helpful assistant collaborating with the user on a document. The document state is a JSON tree, and you are able to analyze and edit it.\nThe JSON tree adheres to the following Typescript schema:\n\n\\`\\`\\`typescript\n${typescriptSchemaTypes}\n\\`\\`\\`\n\nIf the user asks you a question about the tree, you should inspect the state of the tree and answer the question.\nWhen answering such a question, DO NOT answer with information that is not part of the document unless requested to do so.\n\n${editToolName === undefined ? \"\" : editing}### Application data\n\n${\n\tdomainHints === undefined\n\t\t? \"\"\n\t\t: `\\nThe application supplied the following additional instructions: ${domainHints}`\n}\nThe current state of \\`context.root\\` (a \\`${field === undefined ? \"undefined\" : getFriendlyName(Tree.schema(field))}\\`) is:\n\n\\`\\`\\`JSON\n${stringified}\n\\`\\`\\``;\n\treturn prompt;\n}\n\n/**\n * Serializes tree data e.g. to include in a prompt or message.\n * @remarks This includes some extra metadata to make it easier to understand the structure of the tree.\n */\nexport function stringifyTree(tree: ReadableField<ImplicitFieldSchema>): string {\n\tconst typeReplacementKey = \"_e944da5a5fd04ea2b8b2eb6109e089ed\";\n\tconst indexReplacementKey = \"_27bb216b474d45e6aaee14d1ec267b96\";\n\tconst mapReplacementKey = \"_a0d98d22a1c644539f07828d3f064d71\";\n\tconst stringified = JSON.stringify(\n\t\ttree,\n\t\t(_, node: unknown) => {\n\t\t\tif (node instanceof TreeNode) {\n\t\t\t\tconst key = Tree.key(node);\n\t\t\t\tconst index = typeof key === \"number\" ? key : undefined;\n\t\t\t\tconst schema = Tree.schema(node);\n\t\t\t\tswitch (schema.kind) {\n\t\t\t\t\tcase NodeKind.Object: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[typeReplacementKey]: getFriendlyName(schema),\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t...node,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tcase NodeKind.Map: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t[mapReplacementKey]: \"\",\n\t\t\t\t\t\t\t...Object.fromEntries(node as TreeMapNode),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t...node,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn node;\n\t\t},\n\t\t2,\n\t);\n\n\treturn stringified\n\t\t.replace(new RegExp(`\"${typeReplacementKey}\":`, \"g\"), `// Type:`)\n\t\t.replace(new RegExp(`\"${indexReplacementKey}\":`, \"g\"), `// Index:`)\n\t\t.replace(\n\t\t\tnew RegExp(`\"${mapReplacementKey}\": \"\"`, \"g\"),\n\t\t\t`// Note: This is a map that has been serialized to JSON. It is not a key-value object/record but is being printed as such.`,\n\t\t);\n}\n\n/**\n * Retrieves the documentation for the `TreeArrayNode` interface to feed to the LLM.\n * @remarks The documentation has been simplified in various ways to make it easier for the LLM to understand.\n * @privateRemarks TODO: How do we keep this in sync with the actual `TreeArrayNode` docs if/when those docs change?\n */\nfunction getTreeArrayNodeDocumentation(typeName: string): string {\n\treturn `/** A special type of array which implements 'readonly T[]' (i.e. it supports all read-only JS array methods) and provides custom array mutation APIs. */\nexport interface ${typeName}<T> extends ReadonlyArray<T> {\n\t/**\n\t * Inserts new item(s) at a specified location.\n\t * @param index - The index at which to insert \\`value\\`.\n\t * @param value - The content to insert.\n\t * @throws Throws if \\`index\\` is not in the range [0, \\`array.length\\`).\n\t */\n\tinsertAt(index: number, ...value: readonly T[]): void;\n\n\t/**\n\t * Removes the item at the specified location.\n\t * @param index - The index at which to remove the item.\n\t * @throws Throws if \\`index\\` is not in the range [0, \\`array.length\\`).\n\t */\n\tremoveAt(index: number): void;\n\n\t/**\n\t * Removes all items between the specified indices.\n\t * @param start - The starting index of the range to remove (inclusive). Defaults to the start of the array.\n\t * @param end - The ending index of the range to remove (exclusive). Defaults to \\`array.length\\`.\n\t * @throws Throws if \\`start\\` is not in the range [0, \\`array.length\\`].\n\t * @throws Throws if \\`end\\` is less than \\`start\\`.\n\t * If \\`end\\` is not supplied or is greater than the length of the array, all items after \\`start\\` are removed.\n\t *\n\t * @remarks\n\t * The default values for start and end are computed when this is called,\n\t * and thus the behavior is the same as providing them explicitly, even with respect to merge resolution with concurrent edits.\n\t * For example, two concurrent transactions both emptying the array with \\`node.removeRange()\\` then inserting an item,\n\t * will merge to result in the array having both inserted items.\n\t */\n\tremoveRange(start?: number, end?: number): void;\n\n\t/**\n\t * Moves the specified item to the desired location in the array.\n\t *\n\t * WARNING - This API is easily misused.\n\t * Please read the documentation for the \\`destinationGap\\` parameter carefully.\n\t *\n\t * @param destinationGap - The location *between* existing items that the moved item should be moved to.\n\t *\n\t * WARNING - \\`destinationGap\\` describes a location between existing items *prior to applying the move operation*.\n\t *\n\t * For example, if the array contains items \\`[A, B, C]\\` before the move, the \\`destinationGap\\` must be one of the following:\n\t *\n\t * - \\`0\\` (between the start of the array and \\`A\\`'s original position)\n\t * - \\`1\\` (between \\`A\\`'s original position and \\`B\\`'s original position)\n\t * - \\`2\\` (between \\`B\\`'s original position and \\`C\\`'s original position)\n\t * - \\`3\\` (between \\`C\\`'s original position and the end of the array)\n\t *\n\t * So moving \\`A\\` between \\`B\\` and \\`C\\` would require \\`destinationGap\\` to be \\`2\\`.\n\t *\n\t * This interpretation of \\`destinationGap\\` makes it easy to specify the desired destination relative to a sibling item that is not being moved,\n\t * or relative to the start or end of the array:\n\t *\n\t * - Move to the start of the array: \\`array.moveToIndex(0, ...)\\` (see also \\`moveToStart\\`)\n\t * - Move to before some item X: \\`array.moveToIndex(indexOfX, ...)\\`\n\t * - Move to after some item X: \\`array.moveToIndex(indexOfX + 1\\`, ...)\n\t * - Move to the end of the array: \\`array.moveToIndex(array.length, ...)\\` (see also \\`moveToEnd\\`)\n\t *\n\t * This interpretation of \\`destinationGap\\` does however make it less obvious how to move an item relative to its current position:\n\t *\n\t * - Move item B before its predecessor: \\`array.moveToIndex(indexOfB - 1, ...)\\`\n\t * - Move item B after its successor: \\`array.moveToIndex(indexOfB + 2, ...)\\`\n\t *\n\t * Notice the asymmetry between \\`-1\\` and \\`+2\\` in the above examples.\n\t * In such scenarios, it can often be easier to approach such edits by swapping adjacent items:\n\t * If items A and B are adjacent, such that A precedes B,\n\t * then they can be swapped with \\`array.moveToIndex(indexOfA, indexOfB)\\`.\n\t *\n\t * @param sourceIndex - The index of the item to move.\n\t * @param source - The optional source array to move the item out of (defaults to this array).\n\t * @throws Throws if any of the source index is not in the range [0, \\`array.length\\`),\n\t * or if the index is not in the range [0, \\`array.length\\`].\n\t */\n\tmoveToIndex(destinationGap: number, sourceIndex: number, source?: ${typeName}<T>): void;\n\n\t/**\n\t * Moves the specified items to the desired location within the array.\n\t *\n\t * WARNING - This API is easily misused.\n\t * Please read the documentation for the \\`destinationGap\\` parameter carefully.\n\t *\n\t * @param destinationGap - The location *between* existing items that the moved item should be moved to.\n\t *\n\t * WARNING - \\`destinationGap\\` describes a location between existing items *prior to applying the move operation*.\n\t *\n\t * For example, if the array contains items \\`[A, B, C]\\` before the move, the \\`destinationGap\\` must be one of the following:\n\t *\n\t * - \\`0\\` (between the start of the array and \\`A\\`'s original position)\n\t * - \\`1\\` (between \\`A\\`'s original position and \\`B\\`'s original position)\n\t * - \\`2\\` (between \\`B\\`'s original position and \\`C\\`'s original position)\n\t * - \\`3\\` (between \\`C\\`'s original position and the end of the array)\n\t *\n\t * So moving \\`A\\` between \\`B\\` and \\`C\\` would require \\`destinationGap\\` to be \\`2\\`.\n\t *\n\t * This interpretation of \\`destinationGap\\` makes it easy to specify the desired destination relative to a sibling item that is not being moved,\n\t * or relative to the start or end of the array:\n\t *\n\t * - Move to the start of the array: \\`array.moveToIndex(0, ...)\\` (see also \\`moveToStart\\`)\n\t * - Move to before some item X: \\`array.moveToIndex(indexOfX, ...)\\`\n\t * - Move to after some item X: \\`array.moveToIndex(indexOfX + 1\\`, ...)\n\t * - Move to the end of the array: \\`array.moveToIndex(array.length, ...)\\` (see also \\`moveToEnd\\`)\n\t *\n\t * This interpretation of \\`destinationGap\\` does however make it less obvious how to move an item relative to its current position:\n\t *\n\t * - Move item B before its predecessor: \\`array.moveToIndex(indexOfB - 1, ...)\\`\n\t * - Move item B after its successor: \\`array.moveToIndex(indexOfB + 2, ...)\\`\n\t *\n\t * Notice the asymmetry between \\`-1\\` and \\`+2\\` in the above examples.\n\t * In such scenarios, it can often be easier to approach such edits by swapping adjacent items:\n\t * If items A and B are adjacent, such that A precedes B,\n\t * then they can be swapped with \\`array.moveToIndex(indexOfA, indexOfB)\\`.\n\t *\n\t * @param sourceStart - The starting index of the range to move (inclusive).\n\t * @param sourceEnd - The ending index of the range to move (exclusive)\n\t * @param source - The optional source array to move items out of (defaults to this array).\n\t * @throws Throws if the types of any of the items being moved are not allowed in the destination array,\n\t * if any of the input indices are not in the range [0, \\`array.length\\`], or if \\`sourceStart\\` is greater than \\`sourceEnd\\`.\n\t */\n\tmoveRangeToIndex(\n\t\tdestinationGap: number,\n\t\tsourceStart: number,\n\t\tsourceEnd: number,\n\t\tsource?: ${typeName}<T>,\n\t): void;\n}`;\n}\n\n/**\n * Retrieves the documentation for the `TreeMapNode` interface to feed to the LLM.\n * @remarks The documentation has been simplified in various ways to make it easier for the LLM to understand.\n * @privateRemarks TODO: How do we keep this in sync with the actual `TreeMapNode` docs if/when those docs change?\n */\nfunction getTreeMapNodeDocumentation(typeName: string): string {\n\treturn `/**\n * A map of string keys to tree objects.\n */\nexport interface ${typeName}<T> extends ReadonlyMap<string, T> {\n\t/**\n\t * Adds or updates an entry in the map with a specified \\`key\\` and a \\`value\\`.\n\t *\n\t * @param key - The key of the element to add to the map.\n\t * @param value - The value of the element to add to the map.\n\t *\n\t * @remarks\n\t * Setting the value at a key to \\`undefined\\` is equivalent to calling {@link ${typeName}.delete} with that key.\n\t */\n\tset(key: string, value: T | undefined): void;\n\n\t/**\n\t * Removes the specified element from this map by its \\`key\\`.\n\t *\n\t * @remarks\n\t * Note: unlike JavaScript's Map API, this method does not return a flag indicating whether or not the value was\n\t * deleted.\n\t *\n\t * @param key - The key of the element to remove from the map.\n\t */\n\tdelete(key: string): void;\n\n\t/**\n\t * Returns an iterable of keys in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the keys returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tkeys(): IterableIterator<string>;\n\n\t/**\n\t * Returns an iterable of values in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the values returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tvalues(): IterableIterator<T>;\n\n\t/**\n\t * Returns an iterable of key/value pairs for every entry in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the entries returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tentries(): IterableIterator<[string, T]>;\n\n\t/**\n\t * Executes the provided function once per each key/value pair in this map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order in which the function is called with respect to the map's entries.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tforEach(\n\t\tcallbackfn: (\n\t\t\tvalue: T,\n\t\t\tkey: string,\n\t\t\tmap: ReadonlyMap<string, T>,\n\t\t) => void,\n\t\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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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fluidframework/tree-agent",
3
- "version": "2.63.0",
3
+ "version": "2.70.0-360753",
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.63.0",
74
- "@fluidframework/runtime-utils": "~2.63.0",
75
- "@fluidframework/telemetry-utils": "~2.63.0",
76
- "@fluidframework/tree": "~2.63.0",
73
+ "@fluidframework/core-utils": "2.70.0-360753",
74
+ "@fluidframework/runtime-utils": "2.70.0-360753",
75
+ "@fluidframework/telemetry-utils": "2.70.0-360753",
76
+ "@fluidframework/tree": "2.70.0-360753",
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.63.0",
83
+ "@fluid-internal/mocha-test-setup": "2.70.0-360753",
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
87
  "@fluidframework/eslint-config-fluid": "^6.0.0",
88
- "@fluidframework/id-compressor": "~2.63.0",
89
- "@fluidframework/runtime-utils": "~2.63.0",
90
- "@fluidframework/test-runtime-utils": "~2.63.0",
88
+ "@fluidframework/id-compressor": "2.70.0-360753",
89
+ "@fluidframework/runtime-utils": "2.70.0-360753",
90
+ "@fluidframework/test-runtime-utils": "2.70.0-360753",
91
91
  "@langchain/anthropic": "^0.3.24",
92
92
  "@langchain/core": "^0.3.78",
93
93
  "@langchain/google-genai": "^0.2.16",
@@ -122,9 +122,7 @@
122
122
  }
123
123
  },
124
124
  "typeValidation": {
125
- "disabled": true,
126
- "broken": {},
127
- "entrypoint": "internal"
125
+ "disabled": true
128
126
  },
129
127
  "scripts": {
130
128
  "api": "fluid-build . --task api",
package/src/agent.ts CHANGED
@@ -17,7 +17,14 @@ import type {
17
17
  } from "@fluidframework/tree/alpha";
18
18
  import { ObjectNodeSchema, Tree } from "@fluidframework/tree/alpha";
19
19
 
20
- import type { SharedTreeChatModel, EditResult, SemanticAgentOptions, Logger } from "./api.js";
20
+ import type {
21
+ SharedTreeChatModel,
22
+ EditResult,
23
+ SemanticAgentOptions,
24
+ Logger,
25
+ SynchronousEditor,
26
+ AsynchronousEditor,
27
+ } from "./api.js";
21
28
  import { getPrompt, stringifyTree } from "./prompt.js";
22
29
  import { Subtree } from "./subtree.js";
23
30
  import {
@@ -110,7 +117,7 @@ export class SharedTreeSemanticAgent<TSchema extends ImplicitFieldSchema> {
110
117
  const maxEditCount = this.options?.maximumSequentialEdits ?? defaultMaxSequentialEdits;
111
118
  let active = true;
112
119
  let editCount = 0;
113
- let editFailed = false;
120
+ let rollbackEdits = false;
114
121
  const { editToolName } = this.client;
115
122
  const edit = async (editCode: string): Promise<EditResult> => {
116
123
  if (editToolName === undefined) {
@@ -127,7 +134,7 @@ export class SharedTreeSemanticAgent<TSchema extends ImplicitFieldSchema> {
127
134
  }
128
135
 
129
136
  if (++editCount > maxEditCount) {
130
- editFailed = true;
137
+ rollbackEdits = true;
131
138
  return {
132
139
  type: "tooManyEditsError",
133
140
  message: `The maximum number of edits (${maxEditCount}) for this query has been exceeded.`,
@@ -137,12 +144,11 @@ export class SharedTreeSemanticAgent<TSchema extends ImplicitFieldSchema> {
137
144
  const editResult = await applyTreeFunction(
138
145
  queryTree,
139
146
  editCode,
140
- this.options?.validateEdit ?? defaultValidateEdit,
141
- this.options?.executeEdit ?? defaultExecuteEdit,
147
+ this.options?.editor ?? defaultEditor,
142
148
  this.options?.logger,
143
149
  );
144
150
 
145
- editFailed ||= editResult.type !== "success";
151
+ rollbackEdits = editResult.type !== "success";
146
152
  return editResult;
147
153
  };
148
154
 
@@ -152,7 +158,7 @@ export class SharedTreeSemanticAgent<TSchema extends ImplicitFieldSchema> {
152
158
  });
153
159
  active = false;
154
160
 
155
- if (!editFailed) {
161
+ if (!rollbackEdits) {
156
162
  this.outerTree.branch.merge(queryTree.branch);
157
163
  this.outerTreeIsDirty = false;
158
164
  }
@@ -199,51 +205,23 @@ function constructTreeNode(schema: TreeNodeSchema, value: FactoryContentObject):
199
205
  async function applyTreeFunction<TSchema extends ImplicitFieldSchema>(
200
206
  tree: Subtree<TSchema>,
201
207
  editCode: string,
202
- validateEdit: Required<SemanticAgentOptions>["validateEdit"],
203
- executeEdit: Required<SemanticAgentOptions>["executeEdit"],
208
+ editor: Required<SemanticAgentOptions>["editor"],
204
209
  logger: Logger | undefined,
205
210
  ): Promise<EditResult> {
206
211
  logger?.log(`### Editing Tool Invoked\n\n`);
207
212
  logger?.log(`#### Generated Code\n\n\`\`\`javascript\n${editCode}\n\`\`\`\n\n`);
208
213
 
209
- try {
210
- await validateEdit(editCode);
211
- } catch (error: unknown) {
212
- logger?.log(`#### Code Validation Failed\n\n`);
213
- logger?.log(`\`\`\`JSON\n${toErrorString(error)}\n\`\`\`\n\n`);
214
- return {
215
- type: "validationError",
216
- message: `The generated code did not pass validation: ${toErrorString(error)}`,
217
- };
218
- }
219
-
220
- // Stick the tree schema constructors on an object passed to the function so that the LLM can create new nodes.
221
- const create: Record<string, (input: FactoryContentObject) => TreeNode> = {};
222
- for (const schema of findNamedSchemas(tree.schema)) {
223
- const name = getFriendlyName(schema);
224
- create[name] = (input: FactoryContentObject) => constructTreeNode(schema, input);
225
- }
226
-
227
214
  // Fork a branch to edit. If the edit fails or produces an error, we discard this branch, otherwise we merge it.
228
215
  const editTree = tree.fork();
229
- const context = {
230
- get root(): ReadableField<TSchema> {
231
- return editTree.field;
232
- },
233
- set root(value: TreeFieldFromImplicitField<ReadSchema<TSchema>>) {
234
- editTree.field = value;
235
- },
236
- create,
237
- };
238
-
216
+ const boundEditor = bindEditorToSubtree(editTree, editor);
239
217
  try {
240
- await executeEdit(context, editCode);
218
+ await boundEditor(editCode);
241
219
  } catch (error: unknown) {
242
220
  logger?.log(`#### Error\n\n`);
243
221
  logger?.log(`\`\`\`JSON\n${toErrorString(error)}\n\`\`\`\n\n`);
244
222
  editTree.branch.dispose();
245
223
  return {
246
- type: "executionError",
224
+ type: "editingError",
247
225
  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)}`,
248
226
  };
249
227
  }
@@ -257,13 +235,82 @@ async function applyTreeFunction<TSchema extends ImplicitFieldSchema>(
257
235
  };
258
236
  }
259
237
 
260
- const defaultValidateEdit: Required<SemanticAgentOptions>["validateEdit"] = () => {};
261
-
262
- const defaultExecuteEdit: Required<SemanticAgentOptions>["executeEdit"] = async (
263
- context,
264
- code,
265
- ) => {
238
+ /**
239
+ * The default {@link AsynchronousEditor | editor} implementation that simply uses `new Function` to run the provided code.
240
+ * @remarks This editor allows both synchronous and asynchronous code (i.e. the provided code may return a Promise).
241
+ * @example `await new Function("context", code)(context);`
242
+ * @alpha
243
+ */
244
+ export const defaultEditor: AsynchronousEditor = async (context, code) => {
266
245
  // eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval
267
246
  const fn = new Function("context", code);
268
247
  await fn(context);
269
248
  };
249
+
250
+ /**
251
+ * Binds the given {@link SynchronousEditor | editor} to the given view or tree.
252
+ * @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
+ * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
254
+ * @alpha
255
+ */
256
+ export function bindEditorImpl<TSchema extends ImplicitFieldSchema>(
257
+ tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),
258
+ editor: SynchronousEditor,
259
+ ): (code: string) => void;
260
+ /**
261
+ * Binds the given {@link AsynchronousEditor | editor} to the given view or tree.
262
+ * @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
+ * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
264
+ * @alpha
265
+ */
266
+ export function bindEditorImpl<TSchema extends ImplicitFieldSchema>(
267
+ tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),
268
+ editor: AsynchronousEditor,
269
+ ): (code: string) => Promise<void>;
270
+ /**
271
+ * Binds the given {@link SynchronousEditor | editor} or {@link AsynchronousEditor | editor} to the given view or tree.
272
+ * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.
273
+ * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
274
+ * @alpha
275
+ */
276
+ export function bindEditorImpl<TSchema extends ImplicitFieldSchema>(
277
+ tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),
278
+ editor: SynchronousEditor | AsynchronousEditor,
279
+ ): ((code: string) => void) | ((code: string) => Promise<void>) {
280
+ const subtree = new Subtree(tree);
281
+ return bindEditorToSubtree(subtree, editor);
282
+ }
283
+
284
+ /**
285
+ * Binds the given {@link SynchronousEditor | synchronous} or {@link AsynchronousEditor | asynchronous} editor to the given view or tree.
286
+ * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor.
287
+ * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
288
+ * @alpha
289
+ * @privateRemarks This exists (as opposed to just exporting bindEditorImpl directly) so that API documentation links work correctly.
290
+ */
291
+ export const bindEditor = bindEditorImpl;
292
+
293
+ function bindEditorToSubtree<TSchema extends ImplicitFieldSchema>(
294
+ tree: Subtree<TSchema>,
295
+ executeEdit: SynchronousEditor | AsynchronousEditor,
296
+ ): (code: string) => void | Promise<void> {
297
+ // Stick the tree schema constructors on an object passed to the function so that the LLM can create new nodes.
298
+ const create: Record<string, (input: FactoryContentObject) => TreeNode> = {};
299
+ for (const schema of findNamedSchemas(tree.schema)) {
300
+ const name = getFriendlyName(schema);
301
+ create[name] = (input: FactoryContentObject) => constructTreeNode(schema, input);
302
+ }
303
+
304
+ const context = {
305
+ get root(): ReadableField<TSchema> {
306
+ return tree.field;
307
+ },
308
+ set root(value: TreeFieldFromImplicitField<ReadSchema<TSchema>>) {
309
+ tree.field = value;
310
+ },
311
+ create,
312
+ };
313
+
314
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
315
+ return (code: string) => executeEdit(context, code);
316
+ }