@fluidframework/ai-collab 2.33.2 → 2.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +156 -0
  3. package/api-report/ai-collab.alpha.api.md +88 -0
  4. package/dist/aiCollabApi.d.ts +9 -0
  5. package/dist/aiCollabApi.d.ts.map +1 -1
  6. package/dist/aiCollabApi.js.map +1 -1
  7. package/dist/alpha.d.ts +12 -0
  8. package/dist/diffTypes.d.ts +200 -0
  9. package/dist/diffTypes.d.ts.map +1 -0
  10. package/dist/diffTypes.js +7 -0
  11. package/dist/diffTypes.js.map +1 -0
  12. package/dist/explicit-strategy/agentEditReducer.d.ts +25 -3
  13. package/dist/explicit-strategy/agentEditReducer.d.ts.map +1 -1
  14. package/dist/explicit-strategy/agentEditReducer.js +239 -15
  15. package/dist/explicit-strategy/agentEditReducer.js.map +1 -1
  16. package/dist/explicit-strategy/index.d.ts +3 -0
  17. package/dist/explicit-strategy/index.d.ts.map +1 -1
  18. package/dist/explicit-strategy/index.js +6 -2
  19. package/dist/explicit-strategy/index.js.map +1 -1
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/lib/aiCollabApi.d.ts +9 -0
  24. package/lib/aiCollabApi.d.ts.map +1 -1
  25. package/lib/aiCollabApi.js.map +1 -1
  26. package/lib/alpha.d.ts +12 -0
  27. package/lib/diffTypes.d.ts +200 -0
  28. package/lib/diffTypes.d.ts.map +1 -0
  29. package/lib/diffTypes.js +6 -0
  30. package/lib/diffTypes.js.map +1 -0
  31. package/lib/explicit-strategy/agentEditReducer.d.ts +25 -3
  32. package/lib/explicit-strategy/agentEditReducer.d.ts.map +1 -1
  33. package/lib/explicit-strategy/agentEditReducer.js +239 -18
  34. package/lib/explicit-strategy/agentEditReducer.js.map +1 -1
  35. package/lib/explicit-strategy/index.d.ts +3 -0
  36. package/lib/explicit-strategy/index.d.ts.map +1 -1
  37. package/lib/explicit-strategy/index.js +6 -2
  38. package/lib/explicit-strategy/index.js.map +1 -1
  39. package/lib/index.d.ts +1 -0
  40. package/lib/index.d.ts.map +1 -1
  41. package/lib/index.js.map +1 -1
  42. package/package.json +9 -9
  43. package/src/aiCollabApi.ts +10 -0
  44. package/src/diffTypes.ts +211 -0
  45. package/src/explicit-strategy/agentEditReducer.ts +296 -19
  46. package/src/explicit-strategy/index.ts +10 -2
  47. package/src/index.ts +15 -0
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { type TreeNode } from "@fluidframework/tree/internal";
6
6
  import type { DebugEventLogHandler, OpenAiClientOptions, TokenLimits, TokenUsage } from "../aiCollabApi.js";
7
+ import type { Diff } from "../diffTypes.js";
7
8
  export type { ApplyEditFailure, ApplyEditSuccess, CoreEventLoopCompleted, CoreEventLoopStarted, FinalReviewCompleted, FinalReviewStarted, GenerateTreeEditCompleted, GenerateTreeEditStarted, LlmApiCallDebugEvent, PlanningPromptCompleted, PlanningPromptStarted, LlmTreeEdit, EventFlowDebugName, EventFlowDebugNames, } from "./debugEvents.js";
8
9
  /**
9
10
  * {@link generateTreeEdits} options.
@@ -31,11 +32,13 @@ export interface GenerateTreeEditsOptions {
31
32
  interface GenerateTreeEditsSuccessResponse {
32
33
  status: "success";
33
34
  tokensUsed: TokenUsage;
35
+ readonly diffs: readonly Diff[];
34
36
  }
35
37
  interface GenerateTreeEditsErrorResponse {
36
38
  status: "failure" | "partial-failure";
37
39
  errorMessage: "tokenLimitExceeded" | "tooManyErrors" | "tooManyModelCalls" | "aborted" | "unexpectedError";
38
40
  tokensUsed: TokenUsage;
41
+ readonly diffs: readonly Diff[];
39
42
  }
40
43
  /**
41
44
  * Prompts the provided LLM client to generate valid tree edits.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/explicit-strategy/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO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AAU,gCAAgC;IACzC,MAAM,EAAE,SAAS,CAAC;IAClB,UAAU,EAAE,UAAU,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,CAAC;CAChC;AAED,UAAU,8BAA8B;IACvC,MAAM,EAAE,SAAS,GAAG,iBAAiB,CAAC;IACtC,YAAY,EACT,oBAAoB,GACpB,eAAe,GACf,mBAAmB,GACnB,SAAS,GACT,iBAAiB,CAAC;IACrB,UAAU,EAAE,UAAU,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,CAAC;CAChC;AAED;;;;;;;;;GASG;AACH,wBAAsB,iBAAiB,CACtC,OAAO,EAAE,wBAAwB,GAC/B,OAAO,CAAC,gCAAgC,GAAG,8BAA8B,CAAC,CAmJ5E"}
@@ -30,6 +30,7 @@ const utils_js_1 = require("./utils.js");
30
30
  async function generateTreeEdits(options) {
31
31
  const idGenerator = new idGenerator_js_1.IdGenerator();
32
32
  const editLog = [];
33
+ const diffs = [];
33
34
  let editCount = 0;
34
35
  let sequentialErrorCount = 0;
35
36
  const simpleSchema = (0, internal_2.getSimpleSchema)(internal_2.Tree.schema(options.treeNode));
@@ -49,8 +50,8 @@ async function generateTreeEdits(options) {
49
50
  })) {
50
51
  try {
51
52
  const result = (0, agentEditReducer_js_1.applyAgentEdit)(generateEditResult.edit, idGenerator, simpleSchema.definitions, options.validator);
52
- const explanation = result.explanation;
53
- editLog.push({ edit: { ...result, explanation } });
53
+ editLog.push({ edit: { ...result.edit } });
54
+ diffs.push(result.diff);
54
55
  sequentialErrorCount = 0;
55
56
  options.debugEventLogHandler?.({
56
57
  ...(0, debugEvents_js_1.generateDebugEvent)("APPLIED_EDIT_SUCCESS", debugLogTraceId),
@@ -83,6 +84,7 @@ async function generateTreeEdits(options) {
83
84
  status: editCount > 0 && sequentialErrorCount < editCount ? "partial-failure" : "failure",
84
85
  errorMessage: "unexpectedError",
85
86
  tokensUsed,
87
+ diffs,
86
88
  };
87
89
  if (options.limiters?.abortController?.signal.aborted === true) {
88
90
  completionResponse.errorMessage = "aborted";
@@ -125,6 +127,7 @@ async function generateTreeEdits(options) {
125
127
  status: editCount > 0 && sequentialErrorCount < editCount ? "partial-failure" : "failure",
126
128
  errorMessage: "tokenLimitExceeded",
127
129
  tokensUsed,
130
+ diffs,
128
131
  };
129
132
  }
130
133
  throw error;
@@ -139,6 +142,7 @@ async function generateTreeEdits(options) {
139
142
  return {
140
143
  status: "success",
141
144
  tokensUsed,
145
+ diffs,
142
146
  };
143
147
  }
144
148
  exports.generateTreeEdits = generateTreeEdits;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/explicit-strategy/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,uEAAsE;AACtE,4DAKuC;AACvC,sDAAsD;AACtD,4CAAuD;AAKvD,+BAAoC;AACpC,6BAAwB;AASxB,+DAAuD;AAEvD,qDAe0B;AAC1B,qDAA+C;AAC/C,+DAM+B;AAC/B,2DAA+D;AAC/D,yCAAkC;AA4DlC;;;;;;;;;GASG;AACI,KAAK,UAAU,iBAAiB,CACtC,OAAiC;IAEjC,MAAM,WAAW,GAAG,IAAI,4BAAW,EAAE,CAAC;IACtC,MAAM,OAAO,GAAY,EAAE,CAAC;IAC5B,IAAI,SAAS,GAAG,CAAC,CAAC;IAClB,IAAI,oBAAoB,GAAG,CAAC,CAAC;IAE7B,MAAM,YAAY,GAAG,IAAA,0BAAe,EAAC,eAAI,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IAEpE,MAAM,UAAU,GAAG,EAAE,WAAW,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,CAAC;IAEvD,MAAM,eAAe,GAAG,IAAA,SAAM,GAAE,CAAC;IAEjC,MAAM,oBAAoB,GAAG,IAAA,SAAM,GAAE,CAAC;IACtC,OAAO,CAAC,oBAAoB,EAAE,CAAC;QAC9B,GAAG,IAAA,mCA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E,YAAY,CAAC,gBAAgB;QAC/C,SAAS,EAAE,MAAM,CAAC,SAAS,IAAI,QAAQ;QACvC,aAAa,EAAE,IAAI;QACnB,QAAQ,EAAE,EAAE,GAAG,MAAM,EAAE;QACvB,GAAG,CAAC,MAAM,CAAC,KAAK,IAAI;YACnB,UAAU,EAAE;gBACX,YAAY,EAAE,MAAM,CAAC,KAAK,CAAC,aAAa;gBACxC,gBAAgB,EAAE,MAAM,CAAC,KAAK,CAAC,iBAAiB;aAChD;SACD,CAAC;KAC6B,CAAC,CAAC;IAElC,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS,IAAI,UAAU,KAAK,SAAS,EAAE,CAAC;QAC5D,UAAU,CAAC,WAAW,IAAI,MAAM,CAAC,KAAK,EAAE,aAAa,CAAC;QACtD,UAAU,CAAC,YAAY,IAAI,MAAM,CAAC,KAAK,EAAE,iBAAiB,CAAC;IAC5D,CAAC;IAED,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,IAAI,SAAS,CAAC;AACxD,CAAC;AAED,MAAM,uBAAwB,SAAQ,KAAK;CAAG","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { UsageError } from \"@fluidframework/telemetry-utils/internal\";\nimport {\n\tgetSimpleSchema,\n\tTree,\n\ttype SimpleTreeSchema,\n\ttype TreeNode,\n} from \"@fluidframework/tree/internal\";\n// eslint-disable-next-line import/no-internal-modules\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport type {\n\tChatCompletionCreateParams,\n\t// eslint-disable-next-line import/no-internal-modules\n} from \"openai/resources/index.mjs\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { z } from \"zod\";\n\nimport type {\n\tDebugEventLogHandler,\n\tOpenAiClientOptions,\n\tTokenLimits,\n\tTokenUsage,\n} from \"../aiCollabApi.js\";\n\nimport { applyAgentEdit } from \"./agentEditReducer.js\";\nimport type { EditWrapper, TreeEdit } from \"./agentEditTypes.js\";\nimport {\n\ttype ApplyEditFailure,\n\ttype ApplyEditSuccess,\n\ttype GenerateTreeEditCompleted,\n\ttype GenerateTreeEditStarted,\n\ttype FinalReviewCompleted,\n\ttype FinalReviewStarted,\n\ttype LlmApiCallDebugEvent,\n\ttype PlanningPromptCompleted,\n\ttype CoreEventLoopStarted,\n\ttype CoreEventLoopCompleted,\n\tgenerateDebugEvent,\n\ttype PlanningPromptStarted,\n\ttype EventFlowDebugName,\n\tEventFlowDebugNames,\n} from \"./debugEvents.js\";\nimport { IdGenerator } from \"./idGenerator.js\";\nimport {\n\tgetEditingSystemPrompt,\n\tgetPlanningSystemPrompt,\n\tgetReviewSystemPrompt,\n\ttoDecoratedJson,\n\ttype EditLog,\n} from \"./promptGeneration.js\";\nimport { generateGenericEditTypes } from \"./typeGeneration.js\";\nimport { fail } from \"./utils.js\";\n\n// TODO: Create a proper index file and move the logic of this file to a new location\nexport type {\n\tApplyEditFailure,\n\tApplyEditSuccess,\n\tCoreEventLoopCompleted,\n\tCoreEventLoopStarted,\n\tFinalReviewCompleted,\n\tFinalReviewStarted,\n\tGenerateTreeEditCompleted,\n\tGenerateTreeEditStarted,\n\tLlmApiCallDebugEvent,\n\tPlanningPromptCompleted,\n\tPlanningPromptStarted,\n\tLlmTreeEdit,\n\tEventFlowDebugName,\n\tEventFlowDebugNames,\n} from \"./debugEvents.js\";\n\n/**\n * {@link generateTreeEdits} options.\n *\n * @internal\n */\nexport interface GenerateTreeEditsOptions {\n\topenAI: OpenAiClientOptions;\n\ttreeNode: TreeNode;\n\tprompt: {\n\t\tsystemRoleContext: string;\n\t\tuserAsk: string;\n\t};\n\tlimiters?: {\n\t\tabortController?: AbortController;\n\t\tmaxSequentialErrors?: number;\n\t\tmaxModelCalls?: number;\n\t\ttokenLimits?: TokenLimits;\n\t};\n\tfinalReviewStep?: boolean;\n\tvalidator?: (newContent: TreeNode) => void;\n\tdebugEventLogHandler?: DebugEventLogHandler;\n\tplanningStep?: boolean;\n}\n\ninterface GenerateTreeEditsSuccessResponse {\n\tstatus: \"success\";\n\ttokensUsed: TokenUsage;\n}\n\ninterface GenerateTreeEditsErrorResponse {\n\tstatus: \"failure\" | \"partial-failure\";\n\terrorMessage:\n\t\t| \"tokenLimitExceeded\"\n\t\t| \"tooManyErrors\"\n\t\t| \"tooManyModelCalls\"\n\t\t| \"aborted\"\n\t\t| \"unexpectedError\";\n\ttokensUsed: TokenUsage;\n}\n\n/**\n * Prompts the provided LLM client to generate valid tree edits.\n * Applies those edits to the provided tree branch before returning.\n *\n * @remarks\n * - Optional root nodes are not supported\n * - Primitive root nodes are not supported\n *\n * @internal\n */\nexport async function generateTreeEdits(\n\toptions: GenerateTreeEditsOptions,\n): Promise<GenerateTreeEditsSuccessResponse | GenerateTreeEditsErrorResponse> {\n\tconst idGenerator = new IdGenerator();\n\tconst editLog: EditLog = [];\n\tlet editCount = 0;\n\tlet sequentialErrorCount = 0;\n\n\tconst simpleSchema = getSimpleSchema(Tree.schema(options.treeNode));\n\n\tconst tokensUsed = { inputTokens: 0, outputTokens: 0 };\n\n\tconst debugLogTraceId = uuidv4();\n\n\tconst coreEventFlowTraceId = uuidv4();\n\toptions.debugEventLogHandler?.({\n\t\t...generateDebugEvent(\"CORE_EVENT_LOOP_STARTED\", debugLogTraceId),\n\t\teventFlowName: EventFlowDebugNames.CORE_EVENT_LOOP,\n\t\teventFlowStatus: \"STARTED\",\n\t\teventFlowTraceId: coreEventFlowTraceId,\n\t} satisfies CoreEventLoopStarted);\n\n\ttry {\n\t\tfor await (const generateEditResult of generateEdits(\n\t\t\toptions,\n\t\t\tsimpleSchema,\n\t\t\tidGenerator,\n\t\t\teditLog,\n\t\t\toptions.limiters?.tokenLimits,\n\t\t\ttokensUsed,\n\t\t\toptions.debugEventLogHandler && {\n\t\t\t\teventLogHandler: options.debugEventLogHandler,\n\t\t\t\ttraceId: debugLogTraceId,\n\t\t\t},\n\t\t)) {\n\t\t\ttry {\n\t\t\t\tconst result = applyAgentEdit(\n\t\t\t\t\tgenerateEditResult.edit,\n\t\t\t\t\tidGenerator,\n\t\t\t\t\tsimpleSchema.definitions,\n\t\t\t\t\toptions.validator,\n\t\t\t\t);\n\t\t\t\tconst explanation = result.explanation;\n\t\t\t\teditLog.push({ edit: { ...result, explanation } });\n\t\t\t\tsequentialErrorCount = 0;\n\n\t\t\t\toptions.debugEventLogHandler?.({\n\t\t\t\t\t...generateDebugEvent(\"APPLIED_EDIT_SUCCESS\", debugLogTraceId),\n\t\t\t\t\teventFlowName: EventFlowDebugNames.GENERATE_AND_APPLY_TREE_EDIT,\n\t\t\t\t\teventFlowStatus: \"IN_PROGRESS\",\n\t\t\t\t\teventFlowTraceId: generateEditResult.eventFlowTraceId,\n\t\t\t\t\tedit: generateEditResult.edit as unknown as Record<string, unknown>,\n\t\t\t\t} satisfies ApplyEditSuccess);\n\t\t\t} catch (error: unknown) {\n\t\t\t\toptions.debugEventLogHandler?.({\n\t\t\t\t\t...generateDebugEvent(\"APPLIED_EDIT_FAILURE\", debugLogTraceId),\n\t\t\t\t\teventFlowName: EventFlowDebugNames.GENERATE_AND_APPLY_TREE_EDIT,\n\t\t\t\t\teventFlowStatus: \"IN_PROGRESS\",\n\t\t\t\t\teventFlowTraceId: generateEditResult.eventFlowTraceId,\n\t\t\t\t\tedit: generateEditResult.edit as unknown as Record<string, unknown>,\n\t\t\t\t\terrorMessage: (error as Error)?.message,\n\t\t\t\t\tsequentialErrorCount,\n\t\t\t\t} satisfies ApplyEditFailure);\n\n\t\t\t\tif (error instanceof UsageError) {\n\t\t\t\t\tsequentialErrorCount += 1;\n\t\t\t\t\teditLog.push({ edit: generateEditResult.edit, error: error.message });\n\t\t\t\t} else {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet shouldExitEarly = false;\n\t\t\tconst completionResponse: GenerateTreeEditsErrorResponse = {\n\t\t\t\tstatus:\n\t\t\t\t\teditCount > 0 && sequentialErrorCount < editCount ? \"partial-failure\" : \"failure\",\n\t\t\t\terrorMessage: \"unexpectedError\",\n\t\t\t\ttokensUsed,\n\t\t\t};\n\n\t\t\tif (options.limiters?.abortController?.signal.aborted === true) {\n\t\t\t\tcompletionResponse.errorMessage = \"aborted\";\n\t\t\t\tshouldExitEarly = true;\n\t\t\t} else if (\n\t\t\t\tsequentialErrorCount >\n\t\t\t\t(options.limiters?.maxSequentialErrors ?? Number.POSITIVE_INFINITY)\n\t\t\t) {\n\t\t\t\tcompletionResponse.errorMessage = \"tooManyErrors\";\n\t\t\t\tshouldExitEarly = true;\n\t\t\t} else if (\n\t\t\t\t++editCount >= (options.limiters?.maxModelCalls ?? Number.POSITIVE_INFINITY)\n\t\t\t) {\n\t\t\t\tcompletionResponse.errorMessage = \"tooManyModelCalls\";\n\t\t\t\tshouldExitEarly = true;\n\t\t\t}\n\n\t\t\tif (shouldExitEarly) {\n\t\t\t\toptions.debugEventLogHandler?.({\n\t\t\t\t\t...generateDebugEvent(\"CORE_EVENT_LOOP_COMPLETED\", debugLogTraceId),\n\t\t\t\t\teventFlowName: EventFlowDebugNames.CORE_EVENT_LOOP,\n\t\t\t\t\teventFlowStatus: \"COMPLETED\",\n\t\t\t\t\tstatus: \"failure\",\n\t\t\t\t\tfailureReason: completionResponse.errorMessage,\n\t\t\t\t\teventFlowTraceId: coreEventFlowTraceId,\n\t\t\t\t} satisfies CoreEventLoopCompleted);\n\n\t\t\t\treturn completionResponse;\n\t\t\t}\n\t\t}\n\t} catch (error: unknown) {\n\t\toptions.debugEventLogHandler?.({\n\t\t\t...generateDebugEvent(\"CORE_EVENT_LOOP_COMPLETED\", debugLogTraceId),\n\t\t\teventFlowName: EventFlowDebugNames.CORE_EVENT_LOOP,\n\t\t\teventFlowStatus: \"COMPLETED\",\n\t\t\tstatus: \"failure\",\n\t\t\teventFlowTraceId: coreEventFlowTraceId,\n\t\t\tfailureReason:\n\t\t\t\terror instanceof TokenLimitExceededError ? \"tokenLimitExceeded\" : \"unexpectedError\",\n\t\t\terrorMessage: (error as Error)?.message,\n\t\t} satisfies CoreEventLoopCompleted);\n\n\t\tif (error instanceof TokenLimitExceededError) {\n\t\t\treturn {\n\t\t\t\tstatus:\n\t\t\t\t\teditCount > 0 && sequentialErrorCount < editCount ? \"partial-failure\" : \"failure\",\n\t\t\t\terrorMessage: \"tokenLimitExceeded\",\n\t\t\t\ttokensUsed,\n\t\t\t};\n\t\t}\n\t\tthrow error;\n\t}\n\n\toptions.debugEventLogHandler?.({\n\t\t...generateDebugEvent(\"CORE_EVENT_LOOP_COMPLETED\", debugLogTraceId),\n\t\teventFlowName: EventFlowDebugNames.CORE_EVENT_LOOP,\n\t\teventFlowStatus: \"COMPLETED\",\n\t\teventFlowTraceId: coreEventFlowTraceId,\n\t\tstatus: \"success\",\n\t} satisfies CoreEventLoopCompleted);\n\n\treturn {\n\t\tstatus: \"success\",\n\t\ttokensUsed,\n\t};\n}\n\ninterface ReviewResult {\n\tgoalAccomplished: \"yes\" | \"no\";\n}\n\n/**\n * Generates a single {@link TreeEdit} from an LLM.\n *\n * @remarks\n * The design of this async generator function is such that which each iteration of this functions values,\n * an LLM will be prompted to generate the next value (a {@link TreeEdit}) based on the users ask.\n * Once the LLM believes it has completed the user's ask, it will no longer return an edit and as a result\n * this generator will no longer yield a next value.\n */\nasync function* generateEdits(\n\toptions: GenerateTreeEditsOptions,\n\tsimpleSchema: SimpleTreeSchema,\n\tidGenerator: IdGenerator,\n\teditLog: EditLog,\n\ttokenLimits: TokenLimits | undefined,\n\ttokensUsed: TokenUsage,\n\tdebugOptions?: {\n\t\teventLogHandler: DebugEventLogHandler;\n\t\ttraceId: string;\n\t},\n): AsyncGenerator<{ edit: TreeEdit; eventFlowTraceId: string }> {\n\tconst [types, rootTypeName] = generateGenericEditTypes(simpleSchema, true);\n\n\tlet plan: string | undefined;\n\tif (options.planningStep !== undefined) {\n\t\tconst planningPrompt = getPlanningSystemPrompt(\n\t\t\toptions.treeNode,\n\t\t\toptions.prompt.userAsk,\n\t\t\toptions.prompt.systemRoleContext,\n\t\t);\n\n\t\tconst generatePlanningPromptEventFlowId = uuidv4();\n\t\tdebugOptions?.eventLogHandler?.({\n\t\t\t...generateDebugEvent(\"GENERATE_PLANNING_PROMPT_STARTED\", debugOptions.traceId),\n\t\t\teventFlowName: EventFlowDebugNames.GENERATE_PLANNING_PROMPT,\n\t\t\teventFlowTraceId: generatePlanningPromptEventFlowId,\n\t\t\teventFlowStatus: \"STARTED\",\n\t\t} satisfies PlanningPromptStarted);\n\n\t\tplan = await getStringFromLlm(\n\t\t\tplanningPrompt,\n\t\t\toptions.openAI,\n\t\t\ttokensUsed,\n\t\t\tdebugOptions && {\n\t\t\t\t...debugOptions,\n\t\t\t\ttriggeringEventFlowName: EventFlowDebugNames.GENERATE_PLANNING_PROMPT,\n\t\t\t\teventFlowTraceId: generatePlanningPromptEventFlowId,\n\t\t\t},\n\t\t);\n\n\t\tdebugOptions?.eventLogHandler?.({\n\t\t\t...generateDebugEvent(\"GENERATE_PLANNING_PROMPT_COMPLETED\", debugOptions.traceId),\n\t\t\teventFlowName: EventFlowDebugNames.GENERATE_PLANNING_PROMPT,\n\t\t\teventFlowStatus: \"COMPLETED\",\n\t\t\teventFlowTraceId: generatePlanningPromptEventFlowId,\n\t\t\tisLlmResponseValid: plan !== undefined,\n\t\t\tllmGeneratedPlan: plan,\n\t\t} satisfies PlanningPromptCompleted);\n\t}\n\n\tconst originalDecoratedJson =\n\t\t(options.finalReviewStep ?? false)\n\t\t\t? toDecoratedJson(idGenerator, options.treeNode)\n\t\t\t: undefined;\n\t// reviewed is implicitly true if finalReviewStep is false\n\tlet hasReviewed = (options.finalReviewStep ?? false) ? false : true;\n\tasync function getNextEdit(): Promise<\n\t\t{ edit: TreeEdit; eventFlowTraceId: string } | undefined\n\t> {\n\t\tconst systemPrompt = getEditingSystemPrompt(\n\t\t\toptions.prompt.userAsk,\n\t\t\tidGenerator,\n\t\t\toptions.treeNode,\n\t\t\teditLog,\n\t\t\toptions.prompt.systemRoleContext,\n\t\t\tplan,\n\t\t);\n\n\t\tconst schema = types[rootTypeName] ?? fail(\"Root type not found.\");\n\n\t\tconst generateTreeEditEventFlowId = uuidv4();\n\t\tdebugOptions?.eventLogHandler?.({\n\t\t\t...generateDebugEvent(\"GENERATE_TREE_EDIT_STARTED\", debugOptions.traceId),\n\t\t\teventFlowName: EventFlowDebugNames.GENERATE_AND_APPLY_TREE_EDIT,\n\t\t\teventFlowStatus: \"STARTED\",\n\t\t\teventFlowTraceId: generateTreeEditEventFlowId,\n\t\t\tllmPrompt: systemPrompt,\n\t\t} satisfies GenerateTreeEditStarted);\n\n\t\tconst wrapper = await getStructuredOutputFromLlm<EditWrapper>(\n\t\t\tsystemPrompt,\n\t\t\toptions.openAI,\n\t\t\tschema,\n\t\t\t\"A JSON object that represents an edit to a JSON tree.\",\n\t\t\ttokensUsed,\n\t\t\tdebugOptions && {\n\t\t\t\t...debugOptions,\n\t\t\t\ttriggeringEventFlowName: EventFlowDebugNames.GENERATE_AND_APPLY_TREE_EDIT,\n\t\t\t\teventFlowTraceId: generateTreeEditEventFlowId,\n\t\t\t},\n\t\t);\n\n\t\tdebugOptions?.eventLogHandler?.({\n\t\t\t...generateDebugEvent(\"GENERATE_TREE_EDIT_COMPLETED\", debugOptions.traceId),\n\t\t\teventFlowName: EventFlowDebugNames.GENERATE_AND_APPLY_TREE_EDIT,\n\t\t\teventFlowStatus: \"COMPLETED\",\n\t\t\teventFlowTraceId: generateTreeEditEventFlowId,\n\t\t\tisLlmResponseValid: wrapper?.edit !== undefined,\n\t\t\tllmGeneratedEdit: wrapper?.edit as Record<string, unknown> | null,\n\t\t} satisfies GenerateTreeEditCompleted);\n\n\t\tif (wrapper === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (wrapper.edit === null) {\n\t\t\tif ((options.finalReviewStep ?? false) && !hasReviewed) {\n\t\t\t\tconst reviewResult = await reviewGoal();\n\t\t\t\tif (reviewResult === undefined) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\t// eslint-disable-next-line require-atomic-updates\n\t\t\t\thasReviewed = true;\n\t\t\t\tif (reviewResult.goalAccomplished === \"yes\") {\n\t\t\t\t\treturn undefined;\n\t\t\t\t} else {\n\t\t\t\t\t// eslint-disable-next-line require-atomic-updates\n\t\t\t\t\teditLog.length = 0;\n\t\t\t\t\treturn getNextEdit();\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn { edit: wrapper.edit, eventFlowTraceId: generateTreeEditEventFlowId };\n\t\t}\n\t}\n\n\tasync function reviewGoal(): Promise<ReviewResult | undefined> {\n\t\tconst systemPrompt = getReviewSystemPrompt(\n\t\t\toptions.prompt.userAsk,\n\t\t\tidGenerator,\n\t\t\toptions.treeNode,\n\t\t\toriginalDecoratedJson ?? fail(\"Original decorated tree not provided.\"),\n\t\t\toptions.prompt.systemRoleContext,\n\t\t);\n\n\t\tconst schema = z.object({\n\t\t\tgoalAccomplished: z\n\t\t\t\t.enum([\"yes\", \"no\"])\n\t\t\t\t.describe('Whether the user\\'s goal was met in the \"after\" tree.'),\n\t\t});\n\n\t\tconst finalReviewEventFlowTraceId = uuidv4();\n\t\tdebugOptions?.eventLogHandler?.({\n\t\t\t...generateDebugEvent(\"FINAL_REVIEW_STARTED\", debugOptions.traceId),\n\t\t\teventFlowName: EventFlowDebugNames.FINAL_REVIEW,\n\t\t\teventFlowStatus: \"STARTED\",\n\t\t\teventFlowTraceId: finalReviewEventFlowTraceId,\n\t\t\tllmPrompt: systemPrompt,\n\t\t} satisfies FinalReviewStarted);\n\n\t\t// TODO: In the future, when using structured output isn't guarenteed, we will\n\t\t// need to add a custom type guard to ensure that output is in the right shape.\n\t\tconst output = await getStructuredOutputFromLlm<ReviewResult>(\n\t\t\tsystemPrompt,\n\t\t\toptions.openAI,\n\t\t\tschema,\n\t\t\tundefined,\n\t\t\ttokensUsed,\n\t\t\tdebugOptions && {\n\t\t\t\t...debugOptions,\n\t\t\t\ttriggeringEventFlowName: EventFlowDebugNames.FINAL_REVIEW,\n\t\t\t\teventFlowTraceId: finalReviewEventFlowTraceId,\n\t\t\t},\n\t\t);\n\n\t\tdebugOptions?.eventLogHandler?.({\n\t\t\t...generateDebugEvent(\"FINAL_REVIEW_COMPLETED\", debugOptions.traceId),\n\t\t\teventFlowName: EventFlowDebugNames.FINAL_REVIEW,\n\t\t\teventFlowStatus: \"COMPLETED\",\n\t\t\teventFlowTraceId: finalReviewEventFlowTraceId,\n\t\t\tisLlmResponseValid: output !== undefined,\n\t\t\tdidLlmAccomplishGoal: output?.goalAccomplished,\n\t\t} satisfies FinalReviewCompleted);\n\n\t\treturn output;\n\t}\n\n\tlet edit = await getNextEdit();\n\twhile (edit !== undefined) {\n\t\tyield edit;\n\t\tif (tokensUsed.inputTokens > (tokenLimits?.inputTokens ?? Number.POSITIVE_INFINITY)) {\n\t\t\tthrow new TokenLimitExceededError(\"Input token limit exceeded.\");\n\t\t}\n\t\tif (tokensUsed.outputTokens > (tokenLimits?.outputTokens ?? Number.POSITIVE_INFINITY)) {\n\t\t\tthrow new TokenLimitExceededError(\"Output token limit exceeded.\");\n\t\t}\n\t\tedit = await getNextEdit();\n\t}\n}\n\n/**\n * Calls the LLM to generate a structured output response based on the provided prompt.\n */\nasync function getStructuredOutputFromLlm<T>(\n\tprompt: string,\n\topenAi: OpenAiClientOptions,\n\tstructuredOutputSchema: Zod.ZodTypeAny,\n\tdescription?: string,\n\ttokensUsed?: TokenUsage,\n\tdebugOptions?: {\n\t\teventLogHandler: DebugEventLogHandler;\n\t\ttraceId: string;\n\t\ttriggeringEventFlowName: EventFlowDebugName;\n\t\teventFlowTraceId: string;\n\t},\n): Promise<T | undefined> {\n\tconst response_format = zodResponseFormat(structuredOutputSchema, \"SharedTreeAI\", {\n\t\tdescription,\n\t});\n\n\tconst body: ChatCompletionCreateParams = {\n\t\tmessages: [{ role: \"system\", content: prompt }],\n\t\tmodel: openAi.modelName ?? \"gpt-4o\",\n\t\tresponse_format,\n\t};\n\n\tconst result = await openAi.client.beta.chat.completions.parse(body);\n\n\tdebugOptions?.eventLogHandler?.({\n\t\t...generateDebugEvent(\"LLM_API_CALL\", debugOptions.traceId),\n\t\ttriggeringEventFlowName: debugOptions.triggeringEventFlowName,\n\t\teventFlowTraceId: debugOptions.eventFlowTraceId,\n\t\tmodelName: openAi.modelName ?? \"gpt-4o\",\n\t\trequestParams: body,\n\t\tresponse: { ...result },\n\t\t...(result.usage && {\n\t\t\ttokenUsage: {\n\t\t\t\tpromptTokens: result.usage.prompt_tokens,\n\t\t\t\tcompletionTokens: result.usage.completion_tokens,\n\t\t\t},\n\t\t}),\n\t} satisfies LlmApiCallDebugEvent);\n\n\tif (result.usage !== undefined && tokensUsed !== undefined) {\n\t\ttokensUsed.inputTokens += result.usage?.prompt_tokens;\n\t\ttokensUsed.outputTokens += result.usage?.completion_tokens;\n\t}\n\n\t// TODO: fix types so this isn't null and doesn't need a cast\n\t// The type should be derived from the zod schema\n\t// TODO: Determine why this value would be undefined.\n\treturn result.choices[0]?.message.parsed as T | undefined;\n}\n\n/**\n * Calls the LLM to generate a response based on the provided prompt.\n */\nasync function getStringFromLlm(\n\tprompt: string,\n\topenAi: OpenAiClientOptions,\n\ttokensUsed?: TokenUsage,\n\tdebugOptions?: {\n\t\teventLogHandler: DebugEventLogHandler;\n\t\ttraceId: string;\n\t\ttriggeringEventFlowName: EventFlowDebugName;\n\t\teventFlowTraceId: string;\n\t},\n): Promise<string | undefined> {\n\tconst body: ChatCompletionCreateParams = {\n\t\tmessages: [{ role: \"system\", content: prompt }],\n\t\tmodel: openAi.modelName ?? \"gpt-4o\",\n\t};\n\n\tconst result = await openAi.client.chat.completions.create(body);\n\n\tdebugOptions?.eventLogHandler?.({\n\t\t...generateDebugEvent(\"LLM_API_CALL\", debugOptions.traceId),\n\t\ttriggeringEventFlowName: debugOptions.triggeringEventFlowName,\n\t\teventFlowTraceId: debugOptions.eventFlowTraceId,\n\t\tmodelName: openAi.modelName ?? \"gpt-4o\",\n\t\trequestParams: body,\n\t\tresponse: { ...result },\n\t\t...(result.usage && {\n\t\t\ttokenUsage: {\n\t\t\t\tpromptTokens: result.usage.prompt_tokens,\n\t\t\t\tcompletionTokens: result.usage.completion_tokens,\n\t\t\t},\n\t\t}),\n\t} satisfies LlmApiCallDebugEvent);\n\n\tif (result.usage !== undefined && tokensUsed !== undefined) {\n\t\ttokensUsed.inputTokens += result.usage?.prompt_tokens;\n\t\ttokensUsed.outputTokens += result.usage?.completion_tokens;\n\t}\n\n\treturn result.choices[0]?.message.content ?? undefined;\n}\n\nclass TokenLimitExceededError extends Error {}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/explicit-strategy/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,uEAAsE;AACtE,4DAKuC;AACvC,sDAAsD;AACtD,4CAAuD;AAKvD,+BAAoC;AACpC,6BAAwB;AAUxB,+DAAuD;AAEvD,qDAe0B;AAC1B,qDAA+C;AAC/C,+DAM+B;AAC/B,2DAA+D;AAC/D,yCAAkC;AA8DlC;;;;;;;;;GASG;AACI,KAAK,UAAU,iBAAiB,CACtC,OAAiC;IAEjC,MAAM,WAAW,GAAG,IAAI,4BAAW,EAAE,CAAC;IACtC,MAAM,OAAO,GAAY,EAAE,CAAC;IAC5B,MAAM,KAAK,GAAW,EAAE,CAAC;IAEzB,IAAI,SAAS,GAAG,CAAC,CAAC;IAClB,IAAI,oBAAoB,GAAG,CAAC,CAAC;IAE7B,MAAM,YAAY,GAAG,IAAA,0BAAe,EAAC,eAAI,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IAEpE,MAAM,UAAU,GAAG,EAAE,WAAW,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,CAAC;IAEvD,MAAM,eAAe,GAAG,IAAA,SAAM,GAAE,CAAC;IAEjC,MAAM,oBAAoB,GAAG,IAAA,SAAM,GAAE,CAAC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AAkB,EAAC,cAAc,EAAE,YAAY,CAAC,OAAO,CAAC;QAC3D,uBAAuB,EAAE,YAAY,CAAC,uBAAuB;QAC7D,gBAAgB,EAAE,YAAY,CAAC,gBAAgB;QAC/C,SAAS,EAAE,MAAM,CAAC,SAAS,IAAI,QAAQ;QACvC,aAAa,EAAE,IAAI;QACnB,QAAQ,EAAE,EAAE,GAAG,MAAM,EAAE;QACvB,GAAG,CAAC,MAAM,CAAC,KAAK,IAAI;YACnB,UAAU,EAAE;gBACX,YAAY,EAAE,MAAM,CAAC,KAAK,CAAC,aAAa;gBACxC,gBAAgB,EAAE,MAAM,CAAC,KAAK,CAAC,iBAAiB;aAChD;SACD,CAAC;KAC6B,CAAC,CAAC;IAElC,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS,IAAI,UAAU,KAAK,SAAS,EAAE,CAAC;QAC5D,UAAU,CAAC,WAAW,IAAI,MAAM,CAAC,KAAK,EAAE,aAAa,CAAC;QACtD,UAAU,CAAC,YAAY,IAAI,MAAM,CAAC,KAAK,EAAE,iBAAiB,CAAC;IAC5D,CAAC;IAED,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,IAAI,SAAS,CAAC;AACxD,CAAC;AAED,MAAM,uBAAwB,SAAQ,KAAK;CAAG","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { UsageError } from \"@fluidframework/telemetry-utils/internal\";\nimport {\n\tgetSimpleSchema,\n\tTree,\n\ttype SimpleTreeSchema,\n\ttype TreeNode,\n} from \"@fluidframework/tree/internal\";\n// eslint-disable-next-line import/no-internal-modules\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport type {\n\tChatCompletionCreateParams,\n\t// eslint-disable-next-line import/no-internal-modules\n} from \"openai/resources/index.mjs\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { z } from \"zod\";\n\nimport type {\n\tDebugEventLogHandler,\n\tOpenAiClientOptions,\n\tTokenLimits,\n\tTokenUsage,\n} from \"../aiCollabApi.js\";\nimport type { Diff } from \"../diffTypes.js\";\n\nimport { applyAgentEdit } from \"./agentEditReducer.js\";\nimport type { EditWrapper, TreeEdit } from \"./agentEditTypes.js\";\nimport {\n\ttype ApplyEditFailure,\n\ttype ApplyEditSuccess,\n\ttype GenerateTreeEditCompleted,\n\ttype GenerateTreeEditStarted,\n\ttype FinalReviewCompleted,\n\ttype FinalReviewStarted,\n\ttype LlmApiCallDebugEvent,\n\ttype PlanningPromptCompleted,\n\ttype CoreEventLoopStarted,\n\ttype CoreEventLoopCompleted,\n\tgenerateDebugEvent,\n\ttype PlanningPromptStarted,\n\ttype EventFlowDebugName,\n\tEventFlowDebugNames,\n} from \"./debugEvents.js\";\nimport { IdGenerator } from \"./idGenerator.js\";\nimport {\n\tgetEditingSystemPrompt,\n\tgetPlanningSystemPrompt,\n\tgetReviewSystemPrompt,\n\ttoDecoratedJson,\n\ttype EditLog,\n} from \"./promptGeneration.js\";\nimport { generateGenericEditTypes } from \"./typeGeneration.js\";\nimport { fail } from \"./utils.js\";\n\n// TODO: Create a proper index file and move the logic of this file to a new location\nexport type {\n\tApplyEditFailure,\n\tApplyEditSuccess,\n\tCoreEventLoopCompleted,\n\tCoreEventLoopStarted,\n\tFinalReviewCompleted,\n\tFinalReviewStarted,\n\tGenerateTreeEditCompleted,\n\tGenerateTreeEditStarted,\n\tLlmApiCallDebugEvent,\n\tPlanningPromptCompleted,\n\tPlanningPromptStarted,\n\tLlmTreeEdit,\n\tEventFlowDebugName,\n\tEventFlowDebugNames,\n} from \"./debugEvents.js\";\n\n/**\n * {@link generateTreeEdits} options.\n *\n * @internal\n */\nexport interface GenerateTreeEditsOptions {\n\topenAI: OpenAiClientOptions;\n\ttreeNode: TreeNode;\n\tprompt: {\n\t\tsystemRoleContext: string;\n\t\tuserAsk: string;\n\t};\n\tlimiters?: {\n\t\tabortController?: AbortController;\n\t\tmaxSequentialErrors?: number;\n\t\tmaxModelCalls?: number;\n\t\ttokenLimits?: TokenLimits;\n\t};\n\tfinalReviewStep?: boolean;\n\tvalidator?: (newContent: TreeNode) => void;\n\tdebugEventLogHandler?: DebugEventLogHandler;\n\tplanningStep?: boolean;\n}\n\ninterface GenerateTreeEditsSuccessResponse {\n\tstatus: \"success\";\n\ttokensUsed: TokenUsage;\n\treadonly diffs: readonly Diff[];\n}\n\ninterface GenerateTreeEditsErrorResponse {\n\tstatus: \"failure\" | \"partial-failure\";\n\terrorMessage:\n\t\t| \"tokenLimitExceeded\"\n\t\t| \"tooManyErrors\"\n\t\t| \"tooManyModelCalls\"\n\t\t| \"aborted\"\n\t\t| \"unexpectedError\";\n\ttokensUsed: TokenUsage;\n\treadonly diffs: readonly Diff[];\n}\n\n/**\n * Prompts the provided LLM client to generate valid tree edits.\n * Applies those edits to the provided tree branch before returning.\n *\n * @remarks\n * - Optional root nodes are not supported\n * - Primitive root nodes are not supported\n *\n * @internal\n */\nexport async function generateTreeEdits(\n\toptions: GenerateTreeEditsOptions,\n): Promise<GenerateTreeEditsSuccessResponse | GenerateTreeEditsErrorResponse> {\n\tconst idGenerator = new IdGenerator();\n\tconst editLog: EditLog = [];\n\tconst diffs: Diff[] = [];\n\n\tlet editCount = 0;\n\tlet sequentialErrorCount = 0;\n\n\tconst simpleSchema = getSimpleSchema(Tree.schema(options.treeNode));\n\n\tconst tokensUsed = { inputTokens: 0, outputTokens: 0 };\n\n\tconst debugLogTraceId = uuidv4();\n\n\tconst coreEventFlowTraceId = uuidv4();\n\toptions.debugEventLogHandler?.({\n\t\t...generateDebugEvent(\"CORE_EVENT_LOOP_STARTED\", debugLogTraceId),\n\t\teventFlowName: EventFlowDebugNames.CORE_EVENT_LOOP,\n\t\teventFlowStatus: \"STARTED\",\n\t\teventFlowTraceId: coreEventFlowTraceId,\n\t} satisfies CoreEventLoopStarted);\n\n\ttry {\n\t\tfor await (const generateEditResult of generateEdits(\n\t\t\toptions,\n\t\t\tsimpleSchema,\n\t\t\tidGenerator,\n\t\t\teditLog,\n\t\t\toptions.limiters?.tokenLimits,\n\t\t\ttokensUsed,\n\t\t\toptions.debugEventLogHandler && {\n\t\t\t\teventLogHandler: options.debugEventLogHandler,\n\t\t\t\ttraceId: debugLogTraceId,\n\t\t\t},\n\t\t)) {\n\t\t\ttry {\n\t\t\t\tconst result = applyAgentEdit(\n\t\t\t\t\tgenerateEditResult.edit,\n\t\t\t\t\tidGenerator,\n\t\t\t\t\tsimpleSchema.definitions,\n\t\t\t\t\toptions.validator,\n\t\t\t\t);\n\t\t\t\teditLog.push({ edit: { ...result.edit } });\n\t\t\t\tdiffs.push(result.diff);\n\t\t\t\tsequentialErrorCount = 0;\n\n\t\t\t\toptions.debugEventLogHandler?.({\n\t\t\t\t\t...generateDebugEvent(\"APPLIED_EDIT_SUCCESS\", debugLogTraceId),\n\t\t\t\t\teventFlowName: EventFlowDebugNames.GENERATE_AND_APPLY_TREE_EDIT,\n\t\t\t\t\teventFlowStatus: \"IN_PROGRESS\",\n\t\t\t\t\teventFlowTraceId: generateEditResult.eventFlowTraceId,\n\t\t\t\t\tedit: generateEditResult.edit as unknown as Record<string, unknown>,\n\t\t\t\t} satisfies ApplyEditSuccess);\n\t\t\t} catch (error: unknown) {\n\t\t\t\toptions.debugEventLogHandler?.({\n\t\t\t\t\t...generateDebugEvent(\"APPLIED_EDIT_FAILURE\", debugLogTraceId),\n\t\t\t\t\teventFlowName: EventFlowDebugNames.GENERATE_AND_APPLY_TREE_EDIT,\n\t\t\t\t\teventFlowStatus: \"IN_PROGRESS\",\n\t\t\t\t\teventFlowTraceId: generateEditResult.eventFlowTraceId,\n\t\t\t\t\tedit: generateEditResult.edit as unknown as Record<string, unknown>,\n\t\t\t\t\terrorMessage: (error as Error)?.message,\n\t\t\t\t\tsequentialErrorCount,\n\t\t\t\t} satisfies ApplyEditFailure);\n\n\t\t\t\tif (error instanceof UsageError) {\n\t\t\t\t\tsequentialErrorCount += 1;\n\t\t\t\t\teditLog.push({ edit: generateEditResult.edit, error: error.message });\n\t\t\t\t} else {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet shouldExitEarly = false;\n\t\t\tconst completionResponse: GenerateTreeEditsErrorResponse = {\n\t\t\t\tstatus:\n\t\t\t\t\teditCount > 0 && sequentialErrorCount < editCount ? \"partial-failure\" : \"failure\",\n\t\t\t\terrorMessage: \"unexpectedError\",\n\t\t\t\ttokensUsed,\n\t\t\t\tdiffs,\n\t\t\t};\n\n\t\t\tif (options.limiters?.abortController?.signal.aborted === true) {\n\t\t\t\tcompletionResponse.errorMessage = \"aborted\";\n\t\t\t\tshouldExitEarly = true;\n\t\t\t} else if (\n\t\t\t\tsequentialErrorCount >\n\t\t\t\t(options.limiters?.maxSequentialErrors ?? Number.POSITIVE_INFINITY)\n\t\t\t) {\n\t\t\t\tcompletionResponse.errorMessage = \"tooManyErrors\";\n\t\t\t\tshouldExitEarly = true;\n\t\t\t} else if (\n\t\t\t\t++editCount >= (options.limiters?.maxModelCalls ?? Number.POSITIVE_INFINITY)\n\t\t\t) {\n\t\t\t\tcompletionResponse.errorMessage = \"tooManyModelCalls\";\n\t\t\t\tshouldExitEarly = true;\n\t\t\t}\n\n\t\t\tif (shouldExitEarly) {\n\t\t\t\toptions.debugEventLogHandler?.({\n\t\t\t\t\t...generateDebugEvent(\"CORE_EVENT_LOOP_COMPLETED\", debugLogTraceId),\n\t\t\t\t\teventFlowName: EventFlowDebugNames.CORE_EVENT_LOOP,\n\t\t\t\t\teventFlowStatus: \"COMPLETED\",\n\t\t\t\t\tstatus: \"failure\",\n\t\t\t\t\tfailureReason: completionResponse.errorMessage,\n\t\t\t\t\teventFlowTraceId: coreEventFlowTraceId,\n\t\t\t\t} satisfies CoreEventLoopCompleted);\n\n\t\t\t\treturn completionResponse;\n\t\t\t}\n\t\t}\n\t} catch (error: unknown) {\n\t\toptions.debugEventLogHandler?.({\n\t\t\t...generateDebugEvent(\"CORE_EVENT_LOOP_COMPLETED\", debugLogTraceId),\n\t\t\teventFlowName: EventFlowDebugNames.CORE_EVENT_LOOP,\n\t\t\teventFlowStatus: \"COMPLETED\",\n\t\t\tstatus: \"failure\",\n\t\t\teventFlowTraceId: coreEventFlowTraceId,\n\t\t\tfailureReason:\n\t\t\t\terror instanceof TokenLimitExceededError ? \"tokenLimitExceeded\" : \"unexpectedError\",\n\t\t\terrorMessage: (error as Error)?.message,\n\t\t} satisfies CoreEventLoopCompleted);\n\n\t\tif (error instanceof TokenLimitExceededError) {\n\t\t\treturn {\n\t\t\t\tstatus:\n\t\t\t\t\teditCount > 0 && sequentialErrorCount < editCount ? \"partial-failure\" : \"failure\",\n\t\t\t\terrorMessage: \"tokenLimitExceeded\",\n\t\t\t\ttokensUsed,\n\t\t\t\tdiffs,\n\t\t\t};\n\t\t}\n\t\tthrow error;\n\t}\n\n\toptions.debugEventLogHandler?.({\n\t\t...generateDebugEvent(\"CORE_EVENT_LOOP_COMPLETED\", debugLogTraceId),\n\t\teventFlowName: EventFlowDebugNames.CORE_EVENT_LOOP,\n\t\teventFlowStatus: \"COMPLETED\",\n\t\teventFlowTraceId: coreEventFlowTraceId,\n\t\tstatus: \"success\",\n\t} satisfies CoreEventLoopCompleted);\n\n\treturn {\n\t\tstatus: \"success\",\n\t\ttokensUsed,\n\t\tdiffs,\n\t};\n}\n\ninterface ReviewResult {\n\tgoalAccomplished: \"yes\" | \"no\";\n}\n\n/**\n * Generates a single {@link TreeEdit} from an LLM.\n *\n * @remarks\n * The design of this async generator function is such that which each iteration of this functions values,\n * an LLM will be prompted to generate the next value (a {@link TreeEdit}) based on the users ask.\n * Once the LLM believes it has completed the user's ask, it will no longer return an edit and as a result\n * this generator will no longer yield a next value.\n */\nasync function* generateEdits(\n\toptions: GenerateTreeEditsOptions,\n\tsimpleSchema: SimpleTreeSchema,\n\tidGenerator: IdGenerator,\n\teditLog: EditLog,\n\ttokenLimits: TokenLimits | undefined,\n\ttokensUsed: TokenUsage,\n\tdebugOptions?: {\n\t\teventLogHandler: DebugEventLogHandler;\n\t\ttraceId: string;\n\t},\n): AsyncGenerator<{ edit: TreeEdit; eventFlowTraceId: string }> {\n\tconst [types, rootTypeName] = generateGenericEditTypes(simpleSchema, true);\n\n\tlet plan: string | undefined;\n\tif (options.planningStep !== undefined) {\n\t\tconst planningPrompt = getPlanningSystemPrompt(\n\t\t\toptions.treeNode,\n\t\t\toptions.prompt.userAsk,\n\t\t\toptions.prompt.systemRoleContext,\n\t\t);\n\n\t\tconst generatePlanningPromptEventFlowId = uuidv4();\n\t\tdebugOptions?.eventLogHandler?.({\n\t\t\t...generateDebugEvent(\"GENERATE_PLANNING_PROMPT_STARTED\", debugOptions.traceId),\n\t\t\teventFlowName: EventFlowDebugNames.GENERATE_PLANNING_PROMPT,\n\t\t\teventFlowTraceId: generatePlanningPromptEventFlowId,\n\t\t\teventFlowStatus: \"STARTED\",\n\t\t} satisfies PlanningPromptStarted);\n\n\t\tplan = await getStringFromLlm(\n\t\t\tplanningPrompt,\n\t\t\toptions.openAI,\n\t\t\ttokensUsed,\n\t\t\tdebugOptions && {\n\t\t\t\t...debugOptions,\n\t\t\t\ttriggeringEventFlowName: EventFlowDebugNames.GENERATE_PLANNING_PROMPT,\n\t\t\t\teventFlowTraceId: generatePlanningPromptEventFlowId,\n\t\t\t},\n\t\t);\n\n\t\tdebugOptions?.eventLogHandler?.({\n\t\t\t...generateDebugEvent(\"GENERATE_PLANNING_PROMPT_COMPLETED\", debugOptions.traceId),\n\t\t\teventFlowName: EventFlowDebugNames.GENERATE_PLANNING_PROMPT,\n\t\t\teventFlowStatus: \"COMPLETED\",\n\t\t\teventFlowTraceId: generatePlanningPromptEventFlowId,\n\t\t\tisLlmResponseValid: plan !== undefined,\n\t\t\tllmGeneratedPlan: plan,\n\t\t} satisfies PlanningPromptCompleted);\n\t}\n\n\tconst originalDecoratedJson =\n\t\t(options.finalReviewStep ?? false)\n\t\t\t? toDecoratedJson(idGenerator, options.treeNode)\n\t\t\t: undefined;\n\t// reviewed is implicitly true if finalReviewStep is false\n\tlet hasReviewed = (options.finalReviewStep ?? false) ? false : true;\n\tasync function getNextEdit(): Promise<\n\t\t{ edit: TreeEdit; eventFlowTraceId: string } | undefined\n\t> {\n\t\tconst systemPrompt = getEditingSystemPrompt(\n\t\t\toptions.prompt.userAsk,\n\t\t\tidGenerator,\n\t\t\toptions.treeNode,\n\t\t\teditLog,\n\t\t\toptions.prompt.systemRoleContext,\n\t\t\tplan,\n\t\t);\n\n\t\tconst schema = types[rootTypeName] ?? fail(\"Root type not found.\");\n\n\t\tconst generateTreeEditEventFlowId = uuidv4();\n\t\tdebugOptions?.eventLogHandler?.({\n\t\t\t...generateDebugEvent(\"GENERATE_TREE_EDIT_STARTED\", debugOptions.traceId),\n\t\t\teventFlowName: EventFlowDebugNames.GENERATE_AND_APPLY_TREE_EDIT,\n\t\t\teventFlowStatus: \"STARTED\",\n\t\t\teventFlowTraceId: generateTreeEditEventFlowId,\n\t\t\tllmPrompt: systemPrompt,\n\t\t} satisfies GenerateTreeEditStarted);\n\n\t\tconst wrapper = await getStructuredOutputFromLlm<EditWrapper>(\n\t\t\tsystemPrompt,\n\t\t\toptions.openAI,\n\t\t\tschema,\n\t\t\t\"A JSON object that represents an edit to a JSON tree.\",\n\t\t\ttokensUsed,\n\t\t\tdebugOptions && {\n\t\t\t\t...debugOptions,\n\t\t\t\ttriggeringEventFlowName: EventFlowDebugNames.GENERATE_AND_APPLY_TREE_EDIT,\n\t\t\t\teventFlowTraceId: generateTreeEditEventFlowId,\n\t\t\t},\n\t\t);\n\n\t\tdebugOptions?.eventLogHandler?.({\n\t\t\t...generateDebugEvent(\"GENERATE_TREE_EDIT_COMPLETED\", debugOptions.traceId),\n\t\t\teventFlowName: EventFlowDebugNames.GENERATE_AND_APPLY_TREE_EDIT,\n\t\t\teventFlowStatus: \"COMPLETED\",\n\t\t\teventFlowTraceId: generateTreeEditEventFlowId,\n\t\t\tisLlmResponseValid: wrapper?.edit !== undefined,\n\t\t\tllmGeneratedEdit: wrapper?.edit as Record<string, unknown> | null,\n\t\t} satisfies GenerateTreeEditCompleted);\n\n\t\tif (wrapper === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (wrapper.edit === null) {\n\t\t\tif ((options.finalReviewStep ?? false) && !hasReviewed) {\n\t\t\t\tconst reviewResult = await reviewGoal();\n\t\t\t\tif (reviewResult === undefined) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\t// eslint-disable-next-line require-atomic-updates\n\t\t\t\thasReviewed = true;\n\t\t\t\tif (reviewResult.goalAccomplished === \"yes\") {\n\t\t\t\t\treturn undefined;\n\t\t\t\t} else {\n\t\t\t\t\t// eslint-disable-next-line require-atomic-updates\n\t\t\t\t\teditLog.length = 0;\n\t\t\t\t\treturn getNextEdit();\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn { edit: wrapper.edit, eventFlowTraceId: generateTreeEditEventFlowId };\n\t\t}\n\t}\n\n\tasync function reviewGoal(): Promise<ReviewResult | undefined> {\n\t\tconst systemPrompt = getReviewSystemPrompt(\n\t\t\toptions.prompt.userAsk,\n\t\t\tidGenerator,\n\t\t\toptions.treeNode,\n\t\t\toriginalDecoratedJson ?? fail(\"Original decorated tree not provided.\"),\n\t\t\toptions.prompt.systemRoleContext,\n\t\t);\n\n\t\tconst schema = z.object({\n\t\t\tgoalAccomplished: z\n\t\t\t\t.enum([\"yes\", \"no\"])\n\t\t\t\t.describe('Whether the user\\'s goal was met in the \"after\" tree.'),\n\t\t});\n\n\t\tconst finalReviewEventFlowTraceId = uuidv4();\n\t\tdebugOptions?.eventLogHandler?.({\n\t\t\t...generateDebugEvent(\"FINAL_REVIEW_STARTED\", debugOptions.traceId),\n\t\t\teventFlowName: EventFlowDebugNames.FINAL_REVIEW,\n\t\t\teventFlowStatus: \"STARTED\",\n\t\t\teventFlowTraceId: finalReviewEventFlowTraceId,\n\t\t\tllmPrompt: systemPrompt,\n\t\t} satisfies FinalReviewStarted);\n\n\t\t// TODO: In the future, when using structured output isn't guarenteed, we will\n\t\t// need to add a custom type guard to ensure that output is in the right shape.\n\t\tconst output = await getStructuredOutputFromLlm<ReviewResult>(\n\t\t\tsystemPrompt,\n\t\t\toptions.openAI,\n\t\t\tschema,\n\t\t\tundefined,\n\t\t\ttokensUsed,\n\t\t\tdebugOptions && {\n\t\t\t\t...debugOptions,\n\t\t\t\ttriggeringEventFlowName: EventFlowDebugNames.FINAL_REVIEW,\n\t\t\t\teventFlowTraceId: finalReviewEventFlowTraceId,\n\t\t\t},\n\t\t);\n\n\t\tdebugOptions?.eventLogHandler?.({\n\t\t\t...generateDebugEvent(\"FINAL_REVIEW_COMPLETED\", debugOptions.traceId),\n\t\t\teventFlowName: EventFlowDebugNames.FINAL_REVIEW,\n\t\t\teventFlowStatus: \"COMPLETED\",\n\t\t\teventFlowTraceId: finalReviewEventFlowTraceId,\n\t\t\tisLlmResponseValid: output !== undefined,\n\t\t\tdidLlmAccomplishGoal: output?.goalAccomplished,\n\t\t} satisfies FinalReviewCompleted);\n\n\t\treturn output;\n\t}\n\n\tlet edit = await getNextEdit();\n\twhile (edit !== undefined) {\n\t\tyield edit;\n\t\tif (tokensUsed.inputTokens > (tokenLimits?.inputTokens ?? Number.POSITIVE_INFINITY)) {\n\t\t\tthrow new TokenLimitExceededError(\"Input token limit exceeded.\");\n\t\t}\n\t\tif (tokensUsed.outputTokens > (tokenLimits?.outputTokens ?? Number.POSITIVE_INFINITY)) {\n\t\t\tthrow new TokenLimitExceededError(\"Output token limit exceeded.\");\n\t\t}\n\t\tedit = await getNextEdit();\n\t}\n}\n\n/**\n * Calls the LLM to generate a structured output response based on the provided prompt.\n */\nasync function getStructuredOutputFromLlm<T>(\n\tprompt: string,\n\topenAi: OpenAiClientOptions,\n\tstructuredOutputSchema: Zod.ZodTypeAny,\n\tdescription?: string,\n\ttokensUsed?: TokenUsage,\n\tdebugOptions?: {\n\t\teventLogHandler: DebugEventLogHandler;\n\t\ttraceId: string;\n\t\ttriggeringEventFlowName: EventFlowDebugName;\n\t\teventFlowTraceId: string;\n\t},\n): Promise<T | undefined> {\n\tconst response_format = zodResponseFormat(structuredOutputSchema, \"SharedTreeAI\", {\n\t\tdescription,\n\t});\n\n\tconst body: ChatCompletionCreateParams = {\n\t\tmessages: [{ role: \"system\", content: prompt }],\n\t\tmodel: openAi.modelName ?? \"gpt-4o\",\n\t\tresponse_format,\n\t};\n\n\tconst result = await openAi.client.beta.chat.completions.parse(body);\n\n\tdebugOptions?.eventLogHandler?.({\n\t\t...generateDebugEvent(\"LLM_API_CALL\", debugOptions.traceId),\n\t\ttriggeringEventFlowName: debugOptions.triggeringEventFlowName,\n\t\teventFlowTraceId: debugOptions.eventFlowTraceId,\n\t\tmodelName: openAi.modelName ?? \"gpt-4o\",\n\t\trequestParams: body,\n\t\tresponse: { ...result },\n\t\t...(result.usage && {\n\t\t\ttokenUsage: {\n\t\t\t\tpromptTokens: result.usage.prompt_tokens,\n\t\t\t\tcompletionTokens: result.usage.completion_tokens,\n\t\t\t},\n\t\t}),\n\t} satisfies LlmApiCallDebugEvent);\n\n\tif (result.usage !== undefined && tokensUsed !== undefined) {\n\t\ttokensUsed.inputTokens += result.usage?.prompt_tokens;\n\t\ttokensUsed.outputTokens += result.usage?.completion_tokens;\n\t}\n\n\t// TODO: fix types so this isn't null and doesn't need a cast\n\t// The type should be derived from the zod schema\n\t// TODO: Determine why this value would be undefined.\n\treturn result.choices[0]?.message.parsed as T | undefined;\n}\n\n/**\n * Calls the LLM to generate a response based on the provided prompt.\n */\nasync function getStringFromLlm(\n\tprompt: string,\n\topenAi: OpenAiClientOptions,\n\ttokensUsed?: TokenUsage,\n\tdebugOptions?: {\n\t\teventLogHandler: DebugEventLogHandler;\n\t\ttraceId: string;\n\t\ttriggeringEventFlowName: EventFlowDebugName;\n\t\teventFlowTraceId: string;\n\t},\n): Promise<string | undefined> {\n\tconst body: ChatCompletionCreateParams = {\n\t\tmessages: [{ role: \"system\", content: prompt }],\n\t\tmodel: openAi.modelName ?? \"gpt-4o\",\n\t};\n\n\tconst result = await openAi.client.chat.completions.create(body);\n\n\tdebugOptions?.eventLogHandler?.({\n\t\t...generateDebugEvent(\"LLM_API_CALL\", debugOptions.traceId),\n\t\ttriggeringEventFlowName: debugOptions.triggeringEventFlowName,\n\t\teventFlowTraceId: debugOptions.eventFlowTraceId,\n\t\tmodelName: openAi.modelName ?? \"gpt-4o\",\n\t\trequestParams: body,\n\t\tresponse: { ...result },\n\t\t...(result.usage && {\n\t\t\ttokenUsage: {\n\t\t\t\tpromptTokens: result.usage.prompt_tokens,\n\t\t\t\tcompletionTokens: result.usage.completion_tokens,\n\t\t\t},\n\t\t}),\n\t} satisfies LlmApiCallDebugEvent);\n\n\tif (result.usage !== undefined && tokensUsed !== undefined) {\n\t\ttokensUsed.inputTokens += result.usage?.prompt_tokens;\n\t\ttokensUsed.outputTokens += result.usage?.completion_tokens;\n\t}\n\n\treturn result.choices[0]?.message.content ?? undefined;\n}\n\nclass TokenLimitExceededError extends Error {}\n"]}
package/dist/index.d.ts CHANGED
@@ -13,5 +13,6 @@
13
13
  export { type DifferenceCreate, type DifferenceChange, type DifferenceMove, type DifferenceRemove, type Difference, type ObjectPath, type Options, sharedTreeDiff, createMergableIdDiffSeries, createMergableDiffSeries, SharedTreeBranchManager, sharedTreeTraverse, } from "./implicit-strategy/index.js";
14
14
  export type { ApplyEditFailure, ApplyEditSuccess, CoreEventLoopCompleted, CoreEventLoopStarted, FinalReviewCompleted, FinalReviewStarted, GenerateTreeEditCompleted, GenerateTreeEditStarted, LlmApiCallDebugEvent, PlanningPromptCompleted, PlanningPromptStarted, LlmTreeEdit, EventFlowDebugName, EventFlowDebugNames, } from "./explicit-strategy/index.js";
15
15
  export { type AiCollabOptions, type AiCollabSuccessResponse, type AiCollabErrorResponse, type TokenUsage, type TokenLimits, type OpenAiClientOptions, type DebugEvent, type DebugEventLogHandler, type EventFlowDebugEvent, } from "./aiCollabApi.js";
16
+ export { type DiffBase, type Diff, type NodePath, type InsertDiff, type ModifyDiff, type RemoveDiff, type RemoveNodeDiff, type ArraySingleRemoveDiff, type ArrayRangeRemoveDiff, type MoveDiff, type MoveSingleDiff, type MoveRangeDiff, } from "./diffTypes.js";
16
17
  export { aiCollab } from "./aiCollab.js";
17
18
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;;;;GAOG;AAEH,OAAO,EACN,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,OAAO,EACZ,cAAc,EACd,0BAA0B,EAC1B,wBAAwB,EACxB,uBAAuB,EACvB,kBAAkB,GAClB,MAAM,8BAA8B,CAAC;AAEtC,YAAY,EACX,gBAAgB,EAChB,gBAAgB,EAChB,sBAAsB,EACtB,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,EACzB,uBAAuB,EACvB,oBAAoB,EACpB,uBAAuB,EACvB,qBAAqB,EACrB,WAAW,EACX,kBAAkB,EAClB,mBAAmB,GACnB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACN,KAAK,eAAe,EACpB,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,mBAAmB,EACxB,KAAK,UAAU,EACf,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,GACxB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;;;;GAOG;AAEH,OAAO,EACN,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,OAAO,EACZ,cAAc,EACd,0BAA0B,EAC1B,wBAAwB,EACxB,uBAAuB,EACvB,kBAAkB,GAClB,MAAM,8BAA8B,CAAC;AAEtC,YAAY,EACX,gBAAgB,EAChB,gBAAgB,EAChB,sBAAsB,EACtB,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,EACzB,uBAAuB,EACvB,oBAAoB,EACpB,uBAAuB,EACvB,qBAAqB,EACrB,WAAW,EACX,kBAAkB,EAClB,mBAAmB,GACnB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACN,KAAK,eAAe,EACpB,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,mBAAmB,EACxB,KAAK,UAAU,EACf,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,GACxB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACN,KAAK,QAAQ,EACb,KAAK,IAAI,EACT,KAAK,QAAQ,EACb,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,cAAc,EACnB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,QAAQ,EACb,KAAK,cAAc,EACnB,KAAK,aAAa,GAClB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH;;;;;;;GAOG;AAEH,yDAasC;AALrC,0GAAA,cAAc,OAAA;AACd,sHAAA,0BAA0B,OAAA;AAC1B,oHAAA,wBAAwB,OAAA;AACxB,mHAAA,uBAAuB,OAAA;AACvB,8GAAA,kBAAkB,OAAA;AAgCnB,6CAAyC;AAAhC,uGAAA,QAAQ,OAAA","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Experimental package for utilities that enable/simplify interaction with LLMs for apps based on SharedTree.\n *\n * See {@link https://github.com/microsoft/FluidFramework/tree/main/packages/framework/ai-collab#readme | README.md }\n * for an overview of the package.\n *\n * @packageDocumentation\n */\n\nexport {\n\ttype DifferenceCreate,\n\ttype DifferenceChange,\n\ttype DifferenceMove,\n\ttype DifferenceRemove,\n\ttype Difference,\n\ttype ObjectPath,\n\ttype Options,\n\tsharedTreeDiff,\n\tcreateMergableIdDiffSeries,\n\tcreateMergableDiffSeries,\n\tSharedTreeBranchManager,\n\tsharedTreeTraverse,\n} from \"./implicit-strategy/index.js\";\n\nexport type {\n\tApplyEditFailure,\n\tApplyEditSuccess,\n\tCoreEventLoopCompleted,\n\tCoreEventLoopStarted,\n\tFinalReviewCompleted,\n\tFinalReviewStarted,\n\tGenerateTreeEditCompleted,\n\tGenerateTreeEditStarted,\n\tLlmApiCallDebugEvent,\n\tPlanningPromptCompleted,\n\tPlanningPromptStarted,\n\tLlmTreeEdit,\n\tEventFlowDebugName,\n\tEventFlowDebugNames,\n} from \"./explicit-strategy/index.js\";\n\nexport {\n\ttype AiCollabOptions,\n\ttype AiCollabSuccessResponse,\n\ttype AiCollabErrorResponse,\n\ttype TokenUsage,\n\ttype TokenLimits,\n\ttype OpenAiClientOptions,\n\ttype DebugEvent,\n\ttype DebugEventLogHandler,\n\ttype EventFlowDebugEvent,\n} from \"./aiCollabApi.js\";\n\nexport { aiCollab } from \"./aiCollab.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH;;;;;;;GAOG;AAEH,yDAasC;AALrC,0GAAA,cAAc,OAAA;AACd,sHAAA,0BAA0B,OAAA;AAC1B,oHAAA,wBAAwB,OAAA;AACxB,mHAAA,uBAAuB,OAAA;AACvB,8GAAA,kBAAkB,OAAA;AA+CnB,6CAAyC;AAAhC,uGAAA,QAAQ,OAAA","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Experimental package for utilities that enable/simplify interaction with LLMs for apps based on SharedTree.\n *\n * See {@link https://github.com/microsoft/FluidFramework/tree/main/packages/framework/ai-collab#readme | README.md }\n * for an overview of the package.\n *\n * @packageDocumentation\n */\n\nexport {\n\ttype DifferenceCreate,\n\ttype DifferenceChange,\n\ttype DifferenceMove,\n\ttype DifferenceRemove,\n\ttype Difference,\n\ttype ObjectPath,\n\ttype Options,\n\tsharedTreeDiff,\n\tcreateMergableIdDiffSeries,\n\tcreateMergableDiffSeries,\n\tSharedTreeBranchManager,\n\tsharedTreeTraverse,\n} from \"./implicit-strategy/index.js\";\n\nexport type {\n\tApplyEditFailure,\n\tApplyEditSuccess,\n\tCoreEventLoopCompleted,\n\tCoreEventLoopStarted,\n\tFinalReviewCompleted,\n\tFinalReviewStarted,\n\tGenerateTreeEditCompleted,\n\tGenerateTreeEditStarted,\n\tLlmApiCallDebugEvent,\n\tPlanningPromptCompleted,\n\tPlanningPromptStarted,\n\tLlmTreeEdit,\n\tEventFlowDebugName,\n\tEventFlowDebugNames,\n} from \"./explicit-strategy/index.js\";\n\nexport {\n\ttype AiCollabOptions,\n\ttype AiCollabSuccessResponse,\n\ttype AiCollabErrorResponse,\n\ttype TokenUsage,\n\ttype TokenLimits,\n\ttype OpenAiClientOptions,\n\ttype DebugEvent,\n\ttype DebugEventLogHandler,\n\ttype EventFlowDebugEvent,\n} from \"./aiCollabApi.js\";\n\nexport {\n\ttype DiffBase,\n\ttype Diff,\n\ttype NodePath,\n\ttype InsertDiff,\n\ttype ModifyDiff,\n\ttype RemoveDiff,\n\ttype RemoveNodeDiff,\n\ttype ArraySingleRemoveDiff,\n\ttype ArrayRangeRemoveDiff,\n\ttype MoveDiff,\n\ttype MoveSingleDiff,\n\ttype MoveRangeDiff,\n} from \"./diffTypes.js\";\n\nexport { aiCollab } from \"./aiCollab.js\";\n"]}
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import type { TreeNode } from "@fluidframework/tree";
6
6
  import type OpenAI from "openai";
7
+ import type { Diff } from "./diffTypes.js";
7
8
  /**
8
9
  * Core Debug event type for the ai-collab
9
10
  * @alpha
@@ -160,6 +161,10 @@ export interface AiCollabSuccessResponse {
160
161
  * {@inheritDoc TokenUsage}
161
162
  */
162
163
  readonly tokensUsed: TokenUsage;
164
+ /**
165
+ * A list of diffs that represent the changes made by the AI collaboration.
166
+ */
167
+ readonly diffs: readonly Diff[];
163
168
  }
164
169
  /**
165
170
  * An error response from the AI collaboration.
@@ -186,6 +191,10 @@ export interface AiCollabErrorResponse {
186
191
  * {@inheritDoc TokenUsage}
187
192
  */
188
193
  readonly tokensUsed: TokenUsage;
194
+ /**
195
+ * A list of diffs that represent the changes made by the AI collaboration.
196
+ */
197
+ readonly diffs: readonly Diff[];
189
198
  }
190
199
  /**
191
200
  * Total usage of tokens by an LLM.
@@ -1 +1 @@
1
- {"version":3,"file":"aiCollabApi.d.ts","sourceRoot":"","sources":["../src/aiCollabApi.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAEjC;;;GAGG;AACH,MAAM,WAAW,UAAU;IAC1B;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IACX;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAoB,SAAQ,UAAU;IACtD;;OAEG;IACH,aAAa,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,eAAe,EAAE,SAAS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,EAAE,OAAO,CAAC;IACnC;;OAEG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,UAAU,EAAE,QAAQ,KAAK,IAAI,CAAC;IACpD;;OAEG;IACH,QAAQ,CAAC,oBAAoB,CAAC,EAAE,oBAAoB,CAAC;CACrD;AAED;;;;GAIG;AACH,MAAM,WAAW,uBAAuB;IACvC;;;OAGG;IACH,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;IAC3B;;OAEG;IACH,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC;IAChC;;OAEG;IACH,QAAQ,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,CAAC;CAChC;AAED;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IACrC;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,SAAS,GAAG,iBAAiB,CAAC;IAC/C;;;;;;;OAOG;IACH,QAAQ,CAAC,YAAY,EAClB,oBAAoB,GACpB,eAAe,GACf,mBAAmB,GACnB,SAAS,GACT,iBAAiB,CAAC;IACrB;;OAEG;IACH,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC;IAChC;;OAEG;IACH,QAAQ,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,CAAC;CAChC;AAED;;;;GAIG;AACH,MAAM,WAAW,UAAU;IAC1B;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;CACrB;AAED;;;;GAIG;AACH,MAAM,WAAW,WAAW;IAC3B;;OAEG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B;;OAEG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;CAC/B"}
@@ -1 +1 @@
1
- {"version":3,"file":"aiCollabApi.js","sourceRoot":"","sources":["../src/aiCollabApi.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type { TreeNode } from \"@fluidframework/tree\";\n// eslint-disable-next-line import/no-named-as-default\nimport type OpenAI from \"openai\";\n\n/**\n * Core Debug event type for the ai-collab\n * @alpha\n */\nexport interface DebugEvent {\n\t/**\n\t * The unique id of the debug event.\n\t */\n\tid: string;\n\t/**\n\t * An id that will be shared across all debug events that originate from the same single execution of ai-collab.\n\t * @remarks This is intended to be used to correlate all debug events that originate from the same execution\n\t */\n\ttraceId: string;\n\t/**\n\t * The name of the debug event.\n\t */\n\teventName: string;\n\t/**\n\t * The date and time at which the debug event was created.\n\t */\n\ttimestamp: string;\n}\n\n/**\n * A Debug event that marks the start or end of a single core logic flow, such as generated tree edits, planning prompt, etc.\n * @alpha\n */\nexport interface EventFlowDebugEvent extends DebugEvent {\n\t/**\n\t * The name of the particular event flow.\n\t */\n\teventFlowName: string;\n\t/**\n\t * The status of the particular event flow.\n\t */\n\teventFlowStatus: \"STARTED\" | \"COMPLETED\" | \"IN_PROGRESS\";\n\t/**\n\t * A unique id that will be shared across all debug events that are part of the same event flow.\n\t */\n\teventFlowTraceId: string;\n}\n\n/**\n * A callback function that can be used to handle debug events that occur during the AI collaboration process.\n * @alpha\n */\nexport type DebugEventLogHandler = <T extends DebugEvent>(event: T) => unknown;\n\n/**\n * OpenAI client options for the {@link AiCollabOptions} interface.\n *\n * @alpha\n */\nexport interface OpenAiClientOptions {\n\t/**\n\t * The OpenAI client to use for the AI collaboration.\n\t */\n\tclient: OpenAI;\n\t/**\n\t * The name of the target OpenAI model to use for the AI collaboration.\n\t */\n\tmodelName?: string;\n}\n\n/**\n * Options for the AI collaboration.\n *\n * @alpha\n */\nexport interface AiCollabOptions {\n\t/**\n\t * The OpenAI client options to use for the LLM based AI collaboration.\n\t */\n\treadonly openAI: OpenAiClientOptions;\n\t/**\n\t * The specific tree node you want the AI to collaborate on. Pass the root node of your tree if you intend\n\t * for the AI to work on the entire tree.\n\t * @remarks\n\t * - Optional root nodes are not supported\n\t * - Primitive root nodes are not supported\n\t */\n\treadonly treeNode: TreeNode;\n\t/**\n\t * The prompt context to give the LLM in order to collaborate with your applications data.\n\t */\n\treadonly prompt: {\n\t\t/**\n\t\t * The context to give the LLM about its role in the collaboration.\n\t\t * @remarks It's highly recommended to give context about your applications data model and the LLM's role in the collaboration.\n\t\t */\n\t\treadonly systemRoleContext: string;\n\t\t/**\n\t\t * The request from the users to the LLM.\n\t\t */\n\t\treadonly userAsk: string;\n\t};\n\t/**\n\t * Limiters are various optional ways to limit this library's usage of the LLM.\n\t */\n\treadonly limiters?: {\n\t\t/**\n\t\t * An optional AbortController that can be used to abort the AI collaboration while it is still in progress.\n\t\t */\n\t\treadonly abortController?: AbortController;\n\t\t/**\n\t\t * The maximum number of sequential errors the LLM can make before aborting the collaboration.\n\t\t * If the maximum number of sequential errors is reached, the AI collaboration will be aborted and return with the errorMessage 'tooManyErrors'.\n\t\t * Leaving this undefined will disable this limiter.\n\t\t */\n\t\treadonly maxSequentialErrors?: number;\n\t\t/**\n\t\t * The maximum number of model calls the LLM can make before aborting the collaboration.\n\t\t * If the maximum number of model calls is reached, the AI collaboration will be aborted and return with the errorMessage 'tooManyModelCalls'.\n\t\t * Leaving this undefined will disable this limiter.\n\t\t */\n\t\treadonly maxModelCalls?: number;\n\t\t/**\n\t\t * The maximum token usage limits for the LLM.\n\t\t * If the LLM exceeds the token limits, the AI collaboration will be aborted and return with the errorMessage 'tokenLimitExceeded'.\n\t\t * This happens after the first model call's token usage is calculated, meaning that the limits set may be exceeded by a certain amount.\n\t\t * Leaving this undefined will disable this limiter.\n\t\t */\n\t\treadonly tokenLimits?: TokenLimits;\n\t};\n\t/**\n\t * When set to true, the LLM will be asked to first produce a plan, based on the user's ask, before generating any changes to your applications data.\n\t * This can help the LLM produce better results.\n\t * When set to false, the LLM will not be asked to produce a plan.\n\t */\n\treadonly planningStep?: boolean;\n\t/**\n\t * When set to true, the LLM will be asked to complete a final review of the changes and determine if any additional changes need to be made.\n\t * When set to false, the LLM will not be asked to complete a final review.\n\t */\n\treadonly finalReviewStep?: boolean;\n\t/**\n\t * An optional validator function that can be used to validate the new content produced by the LLM.\n\t */\n\treadonly validator?: (newContent: TreeNode) => void;\n\t/**\n\t * An optional handler for debug events that occur during the AI collaboration.\n\t */\n\treadonly debugEventLogHandler?: DebugEventLogHandler;\n}\n\n/**\n * A successful response from the AI collaboration.\n *\n * @alpha\n */\nexport interface AiCollabSuccessResponse {\n\t/**\n\t * The status of the Ai Collaboration.\n\t * A 'success' status indicates that the AI collaboration was successful at creating changes.\n\t */\n\treadonly status: \"success\";\n\t/**\n\t * {@inheritDoc TokenUsage}\n\t */\n\treadonly tokensUsed: TokenUsage;\n}\n\n/**\n * An error response from the AI collaboration.\n *\n * @alpha\n */\nexport interface AiCollabErrorResponse {\n\t/**\n\t * The status of the Ai Collaboration.\n\t * - A 'partial-failure' status indicates that the AI collaboration was partially successful, but was aborted due to a limiter or other error\n\t * - A \"failure\" status indicates that the AI collaboration was not successful at creating any changes.\n\t */\n\treadonly status: \"failure\" | \"partial-failure\";\n\t/**\n\t * The type of known error that occured\n\t * - 'tokenLimitExceeded' indicates that the LLM exceeded the token limits set by the user\n\t * - 'tooManyErrors' indicates that the LLM made too many errors in a row\n\t * - 'tooManyModelCalls' indicates that the LLM made too many model calls\n\t * - 'aborted' indicates that the AI collaboration was aborted by the user or a limiter\n\t * - 'unexpectedError' indicates that an unexpected error occured\n\t */\n\treadonly errorMessage:\n\t\t| \"tokenLimitExceeded\"\n\t\t| \"tooManyErrors\"\n\t\t| \"tooManyModelCalls\"\n\t\t| \"aborted\"\n\t\t| \"unexpectedError\";\n\t/**\n\t * {@inheritDoc TokenUsage}\n\t */\n\treadonly tokensUsed: TokenUsage;\n}\n\n/**\n * Total usage of tokens by an LLM.\n *\n * @alpha\n */\nexport interface TokenUsage {\n\t/**\n\t * The total number of tokens used by the LLM for input.\n\t */\n\tinputTokens: number;\n\t/**\n\t * The total number of tokens used by the LLM for output.\n\t */\n\toutputTokens: number;\n}\n\n/**\n * Maximum limits for the total tokens that can be used by an llm\n *\n * @alpha\n */\nexport interface TokenLimits {\n\t/**\n\t * The maximum number of tokens that can be used by the LLM for input.\n\t */\n\treadonly inputTokens?: number;\n\t/**\n\t * The maximum number of tokens that can be used by the LLM for output.\n\t */\n\treadonly outputTokens?: number;\n}\n"]}
1
+ {"version":3,"file":"aiCollabApi.js","sourceRoot":"","sources":["../src/aiCollabApi.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type { TreeNode } from \"@fluidframework/tree\";\n// eslint-disable-next-line import/no-named-as-default\nimport type OpenAI from \"openai\";\n\nimport type { Diff } from \"./diffTypes.js\";\n\n/**\n * Core Debug event type for the ai-collab\n * @alpha\n */\nexport interface DebugEvent {\n\t/**\n\t * The unique id of the debug event.\n\t */\n\tid: string;\n\t/**\n\t * An id that will be shared across all debug events that originate from the same single execution of ai-collab.\n\t * @remarks This is intended to be used to correlate all debug events that originate from the same execution\n\t */\n\ttraceId: string;\n\t/**\n\t * The name of the debug event.\n\t */\n\teventName: string;\n\t/**\n\t * The date and time at which the debug event was created.\n\t */\n\ttimestamp: string;\n}\n\n/**\n * A Debug event that marks the start or end of a single core logic flow, such as generated tree edits, planning prompt, etc.\n * @alpha\n */\nexport interface EventFlowDebugEvent extends DebugEvent {\n\t/**\n\t * The name of the particular event flow.\n\t */\n\teventFlowName: string;\n\t/**\n\t * The status of the particular event flow.\n\t */\n\teventFlowStatus: \"STARTED\" | \"COMPLETED\" | \"IN_PROGRESS\";\n\t/**\n\t * A unique id that will be shared across all debug events that are part of the same event flow.\n\t */\n\teventFlowTraceId: string;\n}\n\n/**\n * A callback function that can be used to handle debug events that occur during the AI collaboration process.\n * @alpha\n */\nexport type DebugEventLogHandler = <T extends DebugEvent>(event: T) => unknown;\n\n/**\n * OpenAI client options for the {@link AiCollabOptions} interface.\n *\n * @alpha\n */\nexport interface OpenAiClientOptions {\n\t/**\n\t * The OpenAI client to use for the AI collaboration.\n\t */\n\tclient: OpenAI;\n\t/**\n\t * The name of the target OpenAI model to use for the AI collaboration.\n\t */\n\tmodelName?: string;\n}\n\n/**\n * Options for the AI collaboration.\n *\n * @alpha\n */\nexport interface AiCollabOptions {\n\t/**\n\t * The OpenAI client options to use for the LLM based AI collaboration.\n\t */\n\treadonly openAI: OpenAiClientOptions;\n\t/**\n\t * The specific tree node you want the AI to collaborate on. Pass the root node of your tree if you intend\n\t * for the AI to work on the entire tree.\n\t * @remarks\n\t * - Optional root nodes are not supported\n\t * - Primitive root nodes are not supported\n\t */\n\treadonly treeNode: TreeNode;\n\t/**\n\t * The prompt context to give the LLM in order to collaborate with your applications data.\n\t */\n\treadonly prompt: {\n\t\t/**\n\t\t * The context to give the LLM about its role in the collaboration.\n\t\t * @remarks It's highly recommended to give context about your applications data model and the LLM's role in the collaboration.\n\t\t */\n\t\treadonly systemRoleContext: string;\n\t\t/**\n\t\t * The request from the users to the LLM.\n\t\t */\n\t\treadonly userAsk: string;\n\t};\n\t/**\n\t * Limiters are various optional ways to limit this library's usage of the LLM.\n\t */\n\treadonly limiters?: {\n\t\t/**\n\t\t * An optional AbortController that can be used to abort the AI collaboration while it is still in progress.\n\t\t */\n\t\treadonly abortController?: AbortController;\n\t\t/**\n\t\t * The maximum number of sequential errors the LLM can make before aborting the collaboration.\n\t\t * If the maximum number of sequential errors is reached, the AI collaboration will be aborted and return with the errorMessage 'tooManyErrors'.\n\t\t * Leaving this undefined will disable this limiter.\n\t\t */\n\t\treadonly maxSequentialErrors?: number;\n\t\t/**\n\t\t * The maximum number of model calls the LLM can make before aborting the collaboration.\n\t\t * If the maximum number of model calls is reached, the AI collaboration will be aborted and return with the errorMessage 'tooManyModelCalls'.\n\t\t * Leaving this undefined will disable this limiter.\n\t\t */\n\t\treadonly maxModelCalls?: number;\n\t\t/**\n\t\t * The maximum token usage limits for the LLM.\n\t\t * If the LLM exceeds the token limits, the AI collaboration will be aborted and return with the errorMessage 'tokenLimitExceeded'.\n\t\t * This happens after the first model call's token usage is calculated, meaning that the limits set may be exceeded by a certain amount.\n\t\t * Leaving this undefined will disable this limiter.\n\t\t */\n\t\treadonly tokenLimits?: TokenLimits;\n\t};\n\t/**\n\t * When set to true, the LLM will be asked to first produce a plan, based on the user's ask, before generating any changes to your applications data.\n\t * This can help the LLM produce better results.\n\t * When set to false, the LLM will not be asked to produce a plan.\n\t */\n\treadonly planningStep?: boolean;\n\t/**\n\t * When set to true, the LLM will be asked to complete a final review of the changes and determine if any additional changes need to be made.\n\t * When set to false, the LLM will not be asked to complete a final review.\n\t */\n\treadonly finalReviewStep?: boolean;\n\t/**\n\t * An optional validator function that can be used to validate the new content produced by the LLM.\n\t */\n\treadonly validator?: (newContent: TreeNode) => void;\n\t/**\n\t * An optional handler for debug events that occur during the AI collaboration.\n\t */\n\treadonly debugEventLogHandler?: DebugEventLogHandler;\n}\n\n/**\n * A successful response from the AI collaboration.\n *\n * @alpha\n */\nexport interface AiCollabSuccessResponse {\n\t/**\n\t * The status of the Ai Collaboration.\n\t * A 'success' status indicates that the AI collaboration was successful at creating changes.\n\t */\n\treadonly status: \"success\";\n\t/**\n\t * {@inheritDoc TokenUsage}\n\t */\n\treadonly tokensUsed: TokenUsage;\n\t/**\n\t * A list of diffs that represent the changes made by the AI collaboration.\n\t */\n\treadonly diffs: readonly Diff[];\n}\n\n/**\n * An error response from the AI collaboration.\n *\n * @alpha\n */\nexport interface AiCollabErrorResponse {\n\t/**\n\t * The status of the Ai Collaboration.\n\t * - A 'partial-failure' status indicates that the AI collaboration was partially successful, but was aborted due to a limiter or other error\n\t * - A \"failure\" status indicates that the AI collaboration was not successful at creating any changes.\n\t */\n\treadonly status: \"failure\" | \"partial-failure\";\n\t/**\n\t * The type of known error that occured\n\t * - 'tokenLimitExceeded' indicates that the LLM exceeded the token limits set by the user\n\t * - 'tooManyErrors' indicates that the LLM made too many errors in a row\n\t * - 'tooManyModelCalls' indicates that the LLM made too many model calls\n\t * - 'aborted' indicates that the AI collaboration was aborted by the user or a limiter\n\t * - 'unexpectedError' indicates that an unexpected error occured\n\t */\n\treadonly errorMessage:\n\t\t| \"tokenLimitExceeded\"\n\t\t| \"tooManyErrors\"\n\t\t| \"tooManyModelCalls\"\n\t\t| \"aborted\"\n\t\t| \"unexpectedError\";\n\t/**\n\t * {@inheritDoc TokenUsage}\n\t */\n\treadonly tokensUsed: TokenUsage;\n\t/**\n\t * A list of diffs that represent the changes made by the AI collaboration.\n\t */\n\treadonly diffs: readonly Diff[];\n}\n\n/**\n * Total usage of tokens by an LLM.\n *\n * @alpha\n */\nexport interface TokenUsage {\n\t/**\n\t * The total number of tokens used by the LLM for input.\n\t */\n\tinputTokens: number;\n\t/**\n\t * The total number of tokens used by the LLM for output.\n\t */\n\toutputTokens: number;\n}\n\n/**\n * Maximum limits for the total tokens that can be used by an llm\n *\n * @alpha\n */\nexport interface TokenLimits {\n\t/**\n\t * The maximum number of tokens that can be used by the LLM for input.\n\t */\n\treadonly inputTokens?: number;\n\t/**\n\t * The maximum number of tokens that can be used by the LLM for output.\n\t */\n\treadonly outputTokens?: number;\n}\n"]}
package/lib/alpha.d.ts CHANGED
@@ -24,10 +24,14 @@ export {
24
24
  AiCollabSuccessResponse,
25
25
  ApplyEditFailure,
26
26
  ApplyEditSuccess,
27
+ ArrayRangeRemoveDiff,
28
+ ArraySingleRemoveDiff,
27
29
  CoreEventLoopCompleted,
28
30
  CoreEventLoopStarted,
29
31
  DebugEvent,
30
32
  DebugEventLogHandler,
33
+ Diff,
34
+ DiffBase,
31
35
  Difference,
32
36
  DifferenceChange,
33
37
  DifferenceCreate,
@@ -40,13 +44,21 @@ export {
40
44
  FinalReviewStarted,
41
45
  GenerateTreeEditCompleted,
42
46
  GenerateTreeEditStarted,
47
+ InsertDiff,
43
48
  LlmApiCallDebugEvent,
44
49
  LlmTreeEdit,
50
+ ModifyDiff,
51
+ MoveDiff,
52
+ MoveRangeDiff,
53
+ MoveSingleDiff,
54
+ NodePath,
45
55
  ObjectPath,
46
56
  OpenAiClientOptions,
47
57
  Options,
48
58
  PlanningPromptCompleted,
49
59
  PlanningPromptStarted,
60
+ RemoveDiff,
61
+ RemoveNodeDiff,
50
62
  SharedTreeBranchManager,
51
63
  TokenLimits,
52
64
  TokenUsage,
@@ -0,0 +1,200 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ /**
6
+ * A base interface to enforce consistency between all Diff objects.
7
+ * @remarks This object is not intended to be used directly.
8
+ * The union type Diff provides a better typescript experience
9
+ *
10
+ * @alpha
11
+ */
12
+ export interface DiffBase {
13
+ /**
14
+ * The operation type performed by an ai agent on a SharedTree
15
+ * @remarks This is intended to be used to correlate the diff with the operation that generated it.
16
+ */
17
+ readonly type: string;
18
+ /**
19
+ * An explanation from the ai as to why the edit is being made.
20
+ */
21
+ readonly aiExplanation: string;
22
+ }
23
+ /**
24
+ * An object that provides relevant information to visualize a single edit performed by an ai agent on a SharedTree
25
+ * @alpha
26
+ */
27
+ export type Diff = InsertDiff | ModifyDiff | RemoveDiff | MoveDiff;
28
+ /**
29
+ * A path from the root of the tree node passed to ai-collab to a specific node within the tree.
30
+ * @alpha
31
+ */
32
+ export type NodePath = {
33
+ /**
34
+ * The short id of the node.
35
+ * @remarks the root tree node and nodes without a defined SchemaFactory.identifier field will not have a short id.
36
+ */
37
+ readonly shortId: string | number | undefined;
38
+ /**
39
+ * The schema of the node.
40
+ */
41
+ readonly schemaIdentifier: string;
42
+ /**
43
+ * The field within the parent node that the node is located at.
44
+ * @remarks
45
+ * The root node will have a parentField name of 'rootFieldKey'.
46
+ * Nodes in an array use numbers to represent their index within the array.
47
+ */
48
+ readonly parentField: string | number;
49
+ }[];
50
+ /**
51
+ * An object that describes the insertion of a new node into a tree.
52
+ * @alpha
53
+ */
54
+ export interface InsertDiff extends DiffBase {
55
+ readonly type: "insert";
56
+ /**
57
+ * The path from the root node to the newly inserted node.
58
+ * The last value in the path will be the newly inserted node.
59
+ * If the newly inserted node is a primitive value, the last value in the path will be the parent array node.
60
+ */
61
+ readonly nodePath: NodePath;
62
+ /**
63
+ * The content of the newly inserted node.
64
+ */
65
+ readonly nodeContent: unknown;
66
+ }
67
+ /**
68
+ * An object that describes the modification of an existing node on a tree.
69
+ * @alpha
70
+ */
71
+ export interface ModifyDiff extends DiffBase {
72
+ readonly type: "modify";
73
+ /**
74
+ * The path from the root node to the ndoe being modified.
75
+ */
76
+ readonly nodePath: NodePath;
77
+ /**
78
+ * The new value of the node.
79
+ */
80
+ readonly newValue: unknown;
81
+ /**
82
+ * The old value of the node.
83
+ */
84
+ readonly oldValue: unknown;
85
+ }
86
+ /**
87
+ * An object that describes the removal of one or more nodes from a tree.
88
+ * @alpha
89
+ */
90
+ export type RemoveDiff = RemoveNodeDiff | ArraySingleRemoveDiff | ArrayRangeRemoveDiff;
91
+ /**
92
+ * Details about a node being removed from a field in an object node.
93
+ * @alpha
94
+ */
95
+ export interface RemoveNodeDiff extends DiffBase {
96
+ readonly type: "remove";
97
+ /**
98
+ * The type of removal being performed.
99
+ */
100
+ readonly removalType: "remove-node";
101
+ /**
102
+ * The path from the root of the tree to the node being removed.
103
+ */
104
+ readonly nodePath: NodePath;
105
+ /**
106
+ * The content of the node being removed.
107
+ */
108
+ readonly nodeContent: unknown;
109
+ }
110
+ /**
111
+ * An object that describes the removal of a single node from an array node.
112
+ * @alpha
113
+ */
114
+ export interface ArraySingleRemoveDiff extends DiffBase {
115
+ readonly type: "remove";
116
+ /**
117
+ * The type of removal being performed.
118
+ */
119
+ readonly removalType: "remove-array-single";
120
+ /**
121
+ * The path from the root of the tree to the node being removed from the array node.
122
+ */
123
+ readonly nodePath: NodePath;
124
+ /**
125
+ * The content of the node being removed from the array node.
126
+ */
127
+ readonly nodeContent: unknown;
128
+ }
129
+ /**
130
+ * An object that describes the removal of a range of nodes from an array node.
131
+ * @alpha
132
+ */
133
+ export interface ArrayRangeRemoveDiff extends DiffBase {
134
+ readonly type: "remove";
135
+ /**
136
+ * The type of removal being performed.
137
+ */
138
+ readonly removalType: "remove-array-range";
139
+ /**
140
+ * The paths to each node being removed from the array node.
141
+ */
142
+ readonly nodePaths: NodePath[];
143
+ /**
144
+ * The content of each of the nodes being removed from the array node.
145
+ */
146
+ readonly nodeContents: unknown[];
147
+ }
148
+ /**
149
+ * An object that describes the movement of nodes from one array node to another array node.
150
+ * @alpha
151
+ */
152
+ export type MoveDiff = MoveSingleDiff | MoveRangeDiff;
153
+ /**
154
+ * An object that describes the movement of a single node from one array node to another array node.
155
+ * @alpha
156
+ */
157
+ export interface MoveSingleDiff extends DiffBase {
158
+ readonly type: "move";
159
+ /**
160
+ * The type of movement being performed.
161
+ */
162
+ readonly moveType: "move-single";
163
+ /**
164
+ * The path from the root of the tree to the source node.
165
+ * The last value in the path will be the node being moved
166
+ */
167
+ readonly sourceNodePath: NodePath;
168
+ /**
169
+ * The path from the root of the tree to the destination array node.
170
+ */
171
+ readonly destinationNodePath: NodePath;
172
+ /**
173
+ * The content of the node being moved from the source array node to the destination array node.
174
+ */
175
+ readonly nodeContent: unknown;
176
+ }
177
+ /**
178
+ * An object that describes the movement of a range of nodes from one array node to another array node.
179
+ * @alpha
180
+ */
181
+ export interface MoveRangeDiff extends DiffBase {
182
+ readonly type: "move";
183
+ /**
184
+ * The type of movement being performed.
185
+ */
186
+ readonly moveType: "move-range";
187
+ /**
188
+ * The paths to each node being moved from the source array node.
189
+ */
190
+ readonly sourceNodePaths: NodePath[];
191
+ /**
192
+ * The path from the root of the tree to the destination array node.
193
+ */
194
+ readonly destinationNodePath: NodePath;
195
+ /**
196
+ * The content of each of the nodes being moved from the source array node to the destination array node.
197
+ */
198
+ readonly nodeContents: unknown[];
199
+ }
200
+ //# sourceMappingURL=diffTypes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diffTypes.d.ts","sourceRoot":"","sources":["../src/diffTypes.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,MAAM,CAAC;IACtB;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;IAChC;;OAEG;IACH,QAAQ,CAAC,eAAe,EAAE,QAAQ,EAAE,CAAC;IACrC;;OAEG;IACH,QAAQ,CAAC,mBAAmB,EAAE,QAAQ,CAAC;IACvC;;OAEG;IACH,QAAQ,CAAC,YAAY,EAAE,OAAO,EAAE,CAAC;CACjC"}
@@ -0,0 +1,6 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=diffTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diffTypes.js","sourceRoot":"","sources":["../src/diffTypes.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * A base interface to enforce consistency between all Diff objects.\n * @remarks This object is not intended to be used directly.\n * The union type Diff provides a better typescript experience\n *\n * @alpha\n */\nexport interface DiffBase {\n\t/**\n\t * The operation type performed by an ai agent on a SharedTree\n\t * @remarks This is intended to be used to correlate the diff with the operation that generated it.\n\t */\n\treadonly type: string;\n\t/**\n\t * An explanation from the ai as to why the edit is being made.\n\t */\n\treadonly aiExplanation: string;\n}\n\n/**\n * An object that provides relevant information to visualize a single edit performed by an ai agent on a SharedTree\n * @alpha\n */\nexport type Diff = InsertDiff | ModifyDiff | RemoveDiff | MoveDiff;\n\n/**\n * A path from the root of the tree node passed to ai-collab to a specific node within the tree.\n * @alpha\n */\nexport type NodePath = {\n\t/**\n\t * The short id of the node.\n\t * @remarks the root tree node and nodes without a defined SchemaFactory.identifier field will not have a short id.\n\t */\n\treadonly shortId: string | number | undefined;\n\t/**\n\t * The schema of the node.\n\t */\n\treadonly schemaIdentifier: string;\n\t/**\n\t * The field within the parent node that the node is located at.\n\t * @remarks\n\t * The root node will have a parentField name of 'rootFieldKey'.\n\t * Nodes in an array use numbers to represent their index within the array.\n\t */\n\treadonly parentField: string | number;\n}[];\n\n/**\n * An object that describes the insertion of a new node into a tree.\n * @alpha\n */\nexport interface InsertDiff extends DiffBase {\n\treadonly type: \"insert\";\n\t/**\n\t * The path from the root node to the newly inserted node.\n\t * The last value in the path will be the newly inserted node.\n\t * If the newly inserted node is a primitive value, the last value in the path will be the parent array node.\n\t */\n\treadonly nodePath: NodePath;\n\t/**\n\t * The content of the newly inserted node.\n\t */\n\treadonly nodeContent: unknown;\n}\n\n/**\n * An object that describes the modification of an existing node on a tree.\n * @alpha\n */\nexport interface ModifyDiff extends DiffBase {\n\treadonly type: \"modify\";\n\t/**\n\t * The path from the root node to the ndoe being modified.\n\t */\n\treadonly nodePath: NodePath;\n\t/**\n\t * The new value of the node.\n\t */\n\treadonly newValue: unknown;\n\t/**\n\t * The old value of the node.\n\t */\n\treadonly oldValue: unknown;\n}\n\n/**\n * An object that describes the removal of one or more nodes from a tree.\n * @alpha\n */\nexport type RemoveDiff = RemoveNodeDiff | ArraySingleRemoveDiff | ArrayRangeRemoveDiff;\n\n/**\n * Details about a node being removed from a field in an object node.\n * @alpha\n */\nexport interface RemoveNodeDiff extends DiffBase {\n\treadonly type: \"remove\";\n\t/**\n\t * The type of removal being performed.\n\t */\n\treadonly removalType: \"remove-node\";\n\t/**\n\t * The path from the root of the tree to the node being removed.\n\t */\n\treadonly nodePath: NodePath;\n\t/**\n\t * The content of the node being removed.\n\t */\n\treadonly nodeContent: unknown;\n}\n\n/**\n * An object that describes the removal of a single node from an array node.\n * @alpha\n */\nexport interface ArraySingleRemoveDiff extends DiffBase {\n\treadonly type: \"remove\";\n\t/**\n\t * The type of removal being performed.\n\t */\n\treadonly removalType: \"remove-array-single\";\n\t/**\n\t * The path from the root of the tree to the node being removed from the array node.\n\t */\n\treadonly nodePath: NodePath;\n\t/**\n\t * The content of the node being removed from the array node.\n\t */\n\treadonly nodeContent: unknown;\n}\n\n/**\n * An object that describes the removal of a range of nodes from an array node.\n * @alpha\n */\nexport interface ArrayRangeRemoveDiff extends DiffBase {\n\treadonly type: \"remove\";\n\t/**\n\t * The type of removal being performed.\n\t */\n\treadonly removalType: \"remove-array-range\";\n\t/**\n\t * The paths to each node being removed from the array node.\n\t */\n\treadonly nodePaths: NodePath[];\n\t/**\n\t * The content of each of the nodes being removed from the array node.\n\t */\n\treadonly nodeContents: unknown[];\n}\n\n/**\n * An object that describes the movement of nodes from one array node to another array node.\n * @alpha\n */\nexport type MoveDiff = MoveSingleDiff | MoveRangeDiff;\n\n/**\n * An object that describes the movement of a single node from one array node to another array node.\n * @alpha\n */\nexport interface MoveSingleDiff extends DiffBase {\n\treadonly type: \"move\";\n\t/**\n\t * The type of movement being performed.\n\t */\n\treadonly moveType: \"move-single\";\n\t/**\n\t * The path from the root of the tree to the source node.\n\t * The last value in the path will be the node being moved\n\t */\n\treadonly sourceNodePath: NodePath;\n\t/**\n\t * The path from the root of the tree to the destination array node.\n\t */\n\treadonly destinationNodePath: NodePath;\n\t/**\n\t * The content of the node being moved from the source array node to the destination array node.\n\t */\n\treadonly nodeContent: unknown;\n}\n\n/**\n * An object that describes the movement of a range of nodes from one array node to another array node.\n * @alpha\n */\nexport interface MoveRangeDiff extends DiffBase {\n\treadonly type: \"move\";\n\t/**\n\t * The type of movement being performed.\n\t */\n\treadonly moveType: \"move-range\";\n\t/**\n\t * The paths to each node being moved from the source array node.\n\t */\n\treadonly sourceNodePaths: NodePath[];\n\t/**\n\t * The path from the root of the tree to the destination array node.\n\t */\n\treadonly destinationNodePath: NodePath;\n\t/**\n\t * The content of each of the nodes being moved from the source array node to the destination array node.\n\t */\n\treadonly nodeContents: unknown[];\n}\n"]}