@n8n/ai-utilities 0.14.1 → 0.15.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.
@@ -5,11 +5,13 @@ import type { BaseMessage } from '@langchain/core/messages';
5
5
  import type { LLMResult } from '@langchain/core/outputs';
6
6
  import type { IDataObject, ISupplyDataFunctions } from 'n8n-workflow';
7
7
  import { NodeError } from 'n8n-workflow';
8
- type TokensUsageParser = (result: LLMResult) => {
8
+ type TokenUsageResult = {
9
9
  completionTokens: number;
10
10
  promptTokens: number;
11
11
  totalTokens: number;
12
+ cost?: number;
12
13
  };
14
+ type TokensUsageParser = (result: LLMResult) => TokenUsageResult;
13
15
  type RunDetail = {
14
16
  index: number;
15
17
  messages: BaseMessage[] | string[] | string;
@@ -25,11 +27,7 @@ export declare class N8nLlmTracing extends BaseCallbackHandler {
25
27
  completionTokensEstimate: number;
26
28
  runsMap: Record<string, RunDetail>;
27
29
  options: {
28
- tokensUsageParser: (result: LLMResult) => {
29
- completionTokens: number;
30
- promptTokens: number;
31
- totalTokens: number;
32
- };
30
+ tokensUsageParser: TokensUsageParser;
33
31
  errorDescriptionMapper: (error: NodeError) => string | null | undefined;
34
32
  };
35
33
  constructor(executionFunctions: ISupplyDataFunctions, options?: {
@@ -42,5 +40,6 @@ export declare class N8nLlmTracing extends BaseCallbackHandler {
42
40
  handleLLMStart(llm: Serialized, prompts: string[], runId: string): Promise<void>;
43
41
  handleLLMError(error: IDataObject | Error, runId: string, parentRunId?: string): Promise<void>;
44
42
  setParentRunIndex(runIndex: number): void;
43
+ private applyTracingTokenMetadata;
45
44
  }
46
45
  export {};
@@ -32,6 +32,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
32
32
  const log_ai_event_1 = require("./log-ai-event");
33
33
  const token_estimator_1 = require("./tokenizer/token-estimator");
34
34
  const TIKTOKEN_ESTIMATE_MODEL = 'gpt-4o';
35
+ function canWriteTracingMetadata(context) {
36
+ return (typeof context === 'object' &&
37
+ context !== null &&
38
+ 'setMetadata' in context &&
39
+ typeof context.setMetadata === 'function');
40
+ }
35
41
  class N8nLlmTracing extends base_1.BaseCallbackHandler {
36
42
  constructor(executionFunctions, options) {
37
43
  super();
@@ -45,12 +51,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
45
51
  this.runsMap = {};
46
52
  this.options = {
47
53
  tokensUsageParser: (result) => {
48
- const completionTokens = result?.llmOutput?.tokenUsage?.completionTokens ?? 0;
49
- const promptTokens = result?.llmOutput?.tokenUsage?.promptTokens ?? 0;
54
+ const tokenUsage = result?.llmOutput?.tokenUsage;
55
+ const completionTokens = tokenUsage?.completionTokens ?? 0;
56
+ const promptTokens = tokenUsage?.promptTokens ?? 0;
57
+ const cost = tokenUsage?.cost ?? tokenUsage?.totalCost;
50
58
  return {
51
59
  completionTokens,
52
60
  promptTokens,
53
61
  totalTokens: completionTokens + promptTokens,
62
+ cost,
54
63
  };
55
64
  },
56
65
  errorDescriptionMapper: (error) => error.description,
@@ -85,9 +94,22 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
85
94
  };
86
95
  if (tokenUsage.completionTokens > 0) {
87
96
  response.tokenUsage = tokenUsage;
97
+ this.applyTracingTokenMetadata({
98
+ promptTokens: tokenUsage.promptTokens,
99
+ completionTokens: tokenUsage.completionTokens,
100
+ totalTokens: tokenUsage.totalTokens,
101
+ isEstimated: false,
102
+ cost: tokenUsage.cost,
103
+ });
88
104
  }
89
105
  else {
90
106
  response.tokenUsageEstimate = tokenUsageEstimate;
107
+ this.applyTracingTokenMetadata({
108
+ promptTokens: tokenUsageEstimate.promptTokens,
109
+ completionTokens: tokenUsageEstimate.completionTokens,
110
+ totalTokens: tokenUsageEstimate.totalTokens,
111
+ isEstimated: true,
112
+ });
91
113
  }
92
114
  const parsedMessages = typeof runDetails.messages === 'string'
93
115
  ? runDetails.messages
@@ -160,6 +182,20 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
160
182
  setParentRunIndex(runIndex) {
161
183
  __classPrivateFieldSet(this, _N8nLlmTracing_parentRunIndex, runIndex, "f");
162
184
  }
185
+ applyTracingTokenMetadata(params) {
186
+ if (!canWriteTracingMetadata(this.executionFunctions))
187
+ return;
188
+ const tracing = {
189
+ 'llm.tokens.in': params.promptTokens,
190
+ 'llm.tokens.out': params.completionTokens,
191
+ 'llm.tokens.total': params.totalTokens,
192
+ 'llm.tokens.estimated': params.isEstimated,
193
+ };
194
+ if (typeof params.cost === 'number' && Number.isFinite(params.cost)) {
195
+ tracing['llm.cost.total'] = params.cost;
196
+ }
197
+ this.executionFunctions.setMetadata({ tracing });
198
+ }
163
199
  }
164
200
  exports.N8nLlmTracing = N8nLlmTracing;
165
201
  _N8nLlmTracing_parentRunIndex = new WeakMap();
@@ -1 +1 @@
1
- {"version":3,"file":"n8n-llm-tracing.js","sourceRoot":"","sources":["../../../src/utils/n8n-llm-tracing.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;IAAA,yDAAqE;IAErE,+DAA+E;IAQ/E,uDAA+B;IAE/B,+CAAkF;IAElF,iDAA4C;IAC5C,iEAA2E;IAc3E,MAAM,uBAAuB,GAAG,QAAQ,CAAC;IACzC,MAAa,aAAc,SAAQ,0BAAmB;QAsCrD,YACS,kBAAwC,EAChD,OAGC;YAED,KAAK,EAAE,CAAC;YANA,uBAAkB,GAAlB,kBAAkB,CAAsB;YAtCjD,SAAI,GAAG,eAAe,CAAC;YAIvB,kBAAa,GAAG,IAAI,CAAC;YAErB,mBAAc,GAAG,kCAAmB,CAAC,eAAe,CAAC;YAErD,yBAAoB,GAAG,CAAC,CAAC;YAEzB,6BAAwB,GAAG,CAAC,CAAC;YAE7B,gDAAyB;YAQzB,YAAO,GAA8B,EAAE,CAAC;YAExC,YAAO,GAAG;gBAET,iBAAiB,EAAE,CAAC,MAAiB,EAAE,EAAE;oBACxC,MAAM,gBAAgB,GAAI,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,gBAA2B,IAAI,CAAC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AC;QACjC,CAAC;QAEO,yBAAyB,CAAC,MAMjC;YACA,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,kBAAkB,CAAC;gBAAE,OAAO;YAE9D,MAAM,OAAO,GAA4B;gBACxC,eAAe,EAAE,MAAM,CAAC,YAAY;gBACpC,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;gBACzC,kBAAkB,EAAE,MAAM,CAAC,WAAW;gBACtC,sBAAsB,EAAE,MAAM,CAAC,WAAW;aAC1C,CAAC;YACF,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC;gBACrE,OAAO,CAAC,gBAAgB,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC;YACzC,CAAC;YAED,IAAI,CAAC,kBAAkB,CAAC,WAAW,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC;QAClD,CAAC;KACD;IAvPD,sCAuPC"}
@@ -0,0 +1,105 @@
1
+ export interface ViewCommand {
2
+ command: 'view';
3
+ path: string;
4
+ view_range?: [number, number];
5
+ }
6
+ export interface CreateCommand {
7
+ command: 'create';
8
+ path: string;
9
+ file_text: string;
10
+ }
11
+ export interface StrReplaceCommand {
12
+ command: 'str_replace';
13
+ path: string;
14
+ old_str: string;
15
+ new_str: string;
16
+ }
17
+ export interface InsertCommand {
18
+ command: 'insert';
19
+ path: string;
20
+ insert_line: number;
21
+ insert_text: string;
22
+ }
23
+ export interface BatchStrReplaceCommand {
24
+ command: 'batch_str_replace';
25
+ path: string;
26
+ replacements: StrReplacement[];
27
+ }
28
+ export type TextEditorCommand = ViewCommand | CreateCommand | StrReplaceCommand | InsertCommand;
29
+ export type TextEditorCommandWithBatch = TextEditorCommand | BatchStrReplaceCommand;
30
+ export interface TextEditorToolCall {
31
+ name: 'str_replace_based_edit_tool';
32
+ args: TextEditorCommand;
33
+ id: string;
34
+ }
35
+ export interface TextEditorResult {
36
+ content: string;
37
+ }
38
+ export declare class NoMatchFoundError extends Error {
39
+ constructor(_searchStr: string, nearMatchContext?: string);
40
+ }
41
+ export declare class MultipleMatchesError extends Error {
42
+ constructor(count: number);
43
+ }
44
+ export declare class InvalidLineNumberError extends Error {
45
+ constructor(line: number, maxLine: number);
46
+ }
47
+ export declare class InvalidViewRangeError extends Error {
48
+ constructor(start: number, end: number, maxLine: number);
49
+ }
50
+ export declare class InvalidPathError extends Error {
51
+ constructor(path: string, supportedPath?: string, message?: string);
52
+ }
53
+ export declare class FileExistsError extends Error {
54
+ constructor();
55
+ }
56
+ export declare class FileNotFoundError extends Error {
57
+ constructor(message?: string);
58
+ }
59
+ export interface StrReplacement {
60
+ old_str: string;
61
+ new_str: string;
62
+ }
63
+ export interface BatchReplaceResult {
64
+ index: number;
65
+ old_str: string;
66
+ status: 'success' | 'failed' | 'not_attempted';
67
+ error?: string;
68
+ }
69
+ export declare class BatchReplacementError extends Error {
70
+ readonly failedIndex: number;
71
+ readonly totalCount: number;
72
+ readonly cause: NoMatchFoundError | MultipleMatchesError;
73
+ constructor(failedIndex: number, totalCount: number, cause: NoMatchFoundError | MultipleMatchesError);
74
+ }
75
+ export interface TextEditorDocumentOptions {
76
+ initialText?: string | null;
77
+ supportedPath?: string;
78
+ createInvalidPathMessage?: (path: string, supportedPath: string) => string;
79
+ invalidPathMessage?: (path: string, supportedPath: string) => string;
80
+ fileNotFoundMessage?: string;
81
+ }
82
+ export declare function formatTextWithLineNumbers(text: string): string;
83
+ export declare function findDivergenceContext(code: string, searchStr: string): string | undefined;
84
+ export declare function parseStrReplacements(raw: unknown): StrReplacement[];
85
+ export declare class TextEditorDocument {
86
+ private text;
87
+ private readonly options;
88
+ constructor(options?: TextEditorDocumentOptions);
89
+ execute(command: TextEditorCommand): string;
90
+ executeBatch(replacements: StrReplacement[]): string | BatchReplaceResult[];
91
+ getText(): string | null;
92
+ setText(text: string): void;
93
+ hasText(): boolean;
94
+ clearText(): void;
95
+ private validateCreatePath;
96
+ private validatePath;
97
+ private handleView;
98
+ private handleCreate;
99
+ private handleStrReplace;
100
+ private handleInsert;
101
+ private countOccurrences;
102
+ private appendNotAttemptedResults;
103
+ private createFileNotFoundError;
104
+ private escapeReplacement;
105
+ }
@@ -0,0 +1,333 @@
1
+ (function (factory) {
2
+ if (typeof module === "object" && typeof module.exports === "object") {
3
+ var v = factory(require, exports);
4
+ if (v !== undefined) module.exports = v;
5
+ }
6
+ else if (typeof define === "function" && define.amd) {
7
+ define(["require", "exports"], factory);
8
+ }
9
+ })(function (require, exports) {
10
+ "use strict";
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.TextEditorDocument = exports.BatchReplacementError = exports.FileNotFoundError = exports.FileExistsError = exports.InvalidPathError = exports.InvalidViewRangeError = exports.InvalidLineNumberError = exports.MultipleMatchesError = exports.NoMatchFoundError = void 0;
13
+ exports.formatTextWithLineNumbers = formatTextWithLineNumbers;
14
+ exports.findDivergenceContext = findDivergenceContext;
15
+ exports.parseStrReplacements = parseStrReplacements;
16
+ class NoMatchFoundError extends Error {
17
+ constructor(_searchStr, nearMatchContext) {
18
+ const base = 'No exact match found for str_replace. The old_str content was not found in the file.';
19
+ const message = nearMatchContext ? `${base}\n${nearMatchContext}` : base;
20
+ super(message);
21
+ this.name = 'NoMatchFoundError';
22
+ }
23
+ }
24
+ exports.NoMatchFoundError = NoMatchFoundError;
25
+ class MultipleMatchesError extends Error {
26
+ constructor(count) {
27
+ super(`Found ${count} matches. Please provide more context to make the replacement unique.`);
28
+ this.name = 'MultipleMatchesError';
29
+ }
30
+ }
31
+ exports.MultipleMatchesError = MultipleMatchesError;
32
+ class InvalidLineNumberError extends Error {
33
+ constructor(line, maxLine) {
34
+ super(`Invalid line number ${line}. File has ${maxLine} lines (valid range: 0-${maxLine}).`);
35
+ this.name = 'InvalidLineNumberError';
36
+ }
37
+ }
38
+ exports.InvalidLineNumberError = InvalidLineNumberError;
39
+ class InvalidViewRangeError extends Error {
40
+ constructor(start, end, maxLine) {
41
+ super(`Invalid view range: end (${end}) must be >= start (${start}). File has ${maxLine} lines (valid range: 1-${maxLine}).`);
42
+ this.name = 'InvalidViewRangeError';
43
+ }
44
+ }
45
+ exports.InvalidViewRangeError = InvalidViewRangeError;
46
+ class InvalidPathError extends Error {
47
+ constructor(path, supportedPath = '/workflow.js', message) {
48
+ super(message ?? `Invalid path "${path}". Only ${supportedPath} is supported.`);
49
+ this.name = 'InvalidPathError';
50
+ }
51
+ }
52
+ exports.InvalidPathError = InvalidPathError;
53
+ class FileExistsError extends Error {
54
+ constructor() {
55
+ super('File already exists. Use text editor tools to modify existing content.');
56
+ this.name = 'FileExistsError';
57
+ }
58
+ }
59
+ exports.FileExistsError = FileExistsError;
60
+ class FileNotFoundError extends Error {
61
+ constructor(message = 'No workflow code exists yet. Use create first.') {
62
+ super(message);
63
+ this.name = 'FileNotFoundError';
64
+ }
65
+ }
66
+ exports.FileNotFoundError = FileNotFoundError;
67
+ class BatchReplacementError extends Error {
68
+ constructor(failedIndex, totalCount, cause) {
69
+ super(`Batch replacement failed at index ${failedIndex} of ${totalCount}: ${cause.message}. All changes have been rolled back.`);
70
+ this.name = 'BatchReplacementError';
71
+ this.failedIndex = failedIndex;
72
+ this.totalCount = totalCount;
73
+ this.cause = cause;
74
+ }
75
+ }
76
+ exports.BatchReplacementError = BatchReplacementError;
77
+ const PREVIEW_MAX_LENGTH = 80;
78
+ const MIN_PREFIX_LENGTH = 10;
79
+ const CONTEXT_LINES = 3;
80
+ const OLD_STR_CONTEXT_LENGTH = 40;
81
+ function truncatePreview(str) {
82
+ if (str.length <= PREVIEW_MAX_LENGTH)
83
+ return str;
84
+ return str.slice(0, PREVIEW_MAX_LENGTH) + '...';
85
+ }
86
+ function escapeWhitespace(str) {
87
+ return str.replace(/\n/g, '\\n').replace(/\t/g, '\\t').replace(/\r/g, '\\r');
88
+ }
89
+ function isObjectRecord(value) {
90
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
91
+ }
92
+ function formatTextWithLineNumbers(text) {
93
+ const lines = text.split('\n');
94
+ return lines.map((line, i) => `${i + 1}: ${line}`).join('\n');
95
+ }
96
+ function findDivergenceContext(code, searchStr) {
97
+ let lo = 0;
98
+ let hi = searchStr.length;
99
+ while (lo < hi) {
100
+ const mid = Math.ceil((lo + hi) / 2);
101
+ if (code.includes(searchStr.substring(0, mid))) {
102
+ lo = mid;
103
+ }
104
+ else {
105
+ hi = mid - 1;
106
+ }
107
+ }
108
+ const matchLength = lo;
109
+ if (matchLength < MIN_PREFIX_LENGTH)
110
+ return undefined;
111
+ const matchPos = code.indexOf(searchStr.substring(0, matchLength));
112
+ const divergePos = matchPos + matchLength;
113
+ const percentage = Math.round((matchLength / searchStr.length) * 100);
114
+ const codeUpToDiverge = code.substring(0, divergePos);
115
+ const divergeLine = codeUpToDiverge.split('\n').length;
116
+ const oldStrRemainder = searchStr.substring(matchLength, matchLength + OLD_STR_CONTEXT_LENGTH);
117
+ const oldStrPrefix = searchStr.substring(Math.max(0, matchLength - 20), matchLength);
118
+ const codeLines = code.split('\n');
119
+ const startLine = Math.max(0, divergeLine - CONTEXT_LINES);
120
+ const endLine = Math.min(codeLines.length, divergeLine + 1);
121
+ const fileContext = codeLines
122
+ .slice(startLine, endLine)
123
+ .map((line, i) => ` ${startLine + i + 1}: ${line}`)
124
+ .join('\n');
125
+ return (`Closest match (${percentage}% of old_str matched, diverges at line ${divergeLine}):\n` +
126
+ ` old_str: ...${escapeWhitespace(oldStrPrefix)}>>> ${escapeWhitespace(oldStrRemainder)}\n` +
127
+ ` file:\n${fileContext}`);
128
+ }
129
+ function parseStrReplacements(raw) {
130
+ let parsed = raw;
131
+ if (typeof parsed === 'string') {
132
+ try {
133
+ parsed = JSON.parse(parsed);
134
+ }
135
+ catch {
136
+ throw new Error('replacements must be a JSON array of {old_str, new_str} objects, but received an invalid JSON string.');
137
+ }
138
+ }
139
+ if (!Array.isArray(parsed)) {
140
+ throw new Error('replacements must be an array of {old_str, new_str} objects. Example: {"replacements": [{"old_str": "foo", "new_str": "bar"}]}');
141
+ }
142
+ const replacements = [];
143
+ for (let i = 0; i < parsed.length; i++) {
144
+ const item = parsed[i];
145
+ if (!isObjectRecord(item) || typeof item.old_str !== 'string') {
146
+ throw new Error(`replacements[${i}] is missing a valid "old_str" string. Each replacement must have {old_str: string, new_str: string}.`);
147
+ }
148
+ if (typeof item.new_str !== 'string') {
149
+ throw new Error(`replacements[${i}] is missing a valid "new_str" string. Each replacement must have {old_str: string, new_str: string}.`);
150
+ }
151
+ replacements.push({ old_str: item.old_str, new_str: item.new_str });
152
+ }
153
+ return replacements;
154
+ }
155
+ class TextEditorDocument {
156
+ constructor(options = {}) {
157
+ this.text = options.initialText ?? null;
158
+ this.options = options;
159
+ }
160
+ execute(command) {
161
+ if (command.command === 'create') {
162
+ this.validateCreatePath(command.path);
163
+ }
164
+ this.validatePath(command.path);
165
+ switch (command.command) {
166
+ case 'view':
167
+ return this.handleView(command);
168
+ case 'create':
169
+ return this.handleCreate(command);
170
+ case 'str_replace':
171
+ return this.handleStrReplace(command);
172
+ case 'insert':
173
+ return this.handleInsert(command);
174
+ }
175
+ }
176
+ executeBatch(replacements) {
177
+ if (this.text === null) {
178
+ throw this.createFileNotFoundError();
179
+ }
180
+ if (replacements.length === 0) {
181
+ return 'No replacements to apply.';
182
+ }
183
+ const snapshot = this.text;
184
+ const results = [];
185
+ for (let i = 0; i < replacements.length; i++) {
186
+ const { old_str, new_str } = replacements[i];
187
+ const preview = truncatePreview(old_str);
188
+ const count = this.countOccurrences(this.text, old_str);
189
+ if (count === 0) {
190
+ this.text = snapshot;
191
+ results.push({
192
+ index: i,
193
+ old_str: preview,
194
+ status: 'failed',
195
+ error: new NoMatchFoundError(old_str).message,
196
+ });
197
+ this.appendNotAttemptedResults(results, replacements, i + 1);
198
+ return results;
199
+ }
200
+ if (count > 1) {
201
+ this.text = snapshot;
202
+ results.push({
203
+ index: i,
204
+ old_str: preview,
205
+ status: 'failed',
206
+ error: new MultipleMatchesError(count).message,
207
+ });
208
+ this.appendNotAttemptedResults(results, replacements, i + 1);
209
+ return results;
210
+ }
211
+ this.text = this.text.replace(old_str, this.escapeReplacement(new_str));
212
+ results.push({ index: i, old_str: preview, status: 'success' });
213
+ }
214
+ return `All ${replacements.length} replacements applied successfully.`;
215
+ }
216
+ getText() {
217
+ return this.text;
218
+ }
219
+ setText(text) {
220
+ this.text = text;
221
+ }
222
+ hasText() {
223
+ return this.text !== null;
224
+ }
225
+ clearText() {
226
+ this.text = null;
227
+ }
228
+ validateCreatePath(path) {
229
+ const supportedPath = this.options.supportedPath;
230
+ if (supportedPath === undefined || path === supportedPath) {
231
+ return;
232
+ }
233
+ throw new Error(this.options.createInvalidPathMessage?.(path, supportedPath) ??
234
+ `Cannot create "${path}". Only ${supportedPath} is supported.`);
235
+ }
236
+ validatePath(path) {
237
+ const supportedPath = this.options.supportedPath;
238
+ if (supportedPath === undefined || path === supportedPath) {
239
+ return;
240
+ }
241
+ throw new InvalidPathError(path, supportedPath, this.options.invalidPathMessage?.(path, supportedPath));
242
+ }
243
+ handleView(command) {
244
+ if (this.text === null) {
245
+ throw this.createFileNotFoundError();
246
+ }
247
+ const lines = this.text.split('\n');
248
+ if (command.view_range) {
249
+ const [start, rawEnd] = command.view_range;
250
+ const end = rawEnd === -1 ? lines.length : rawEnd;
251
+ if (start < 1 || start > lines.length) {
252
+ throw new InvalidLineNumberError(start, lines.length);
253
+ }
254
+ if (end < start) {
255
+ throw new InvalidViewRangeError(start, end, lines.length);
256
+ }
257
+ const startIndex = start - 1;
258
+ const endIndex = Math.min(end, lines.length);
259
+ const selectedLines = lines.slice(startIndex, endIndex);
260
+ return selectedLines.map((line, i) => `${startIndex + i + 1}: ${line}`).join('\n');
261
+ }
262
+ return formatTextWithLineNumbers(this.text);
263
+ }
264
+ handleCreate(command) {
265
+ this.text = command.file_text;
266
+ return 'File created successfully.';
267
+ }
268
+ handleStrReplace(command) {
269
+ if (this.text === null) {
270
+ throw this.createFileNotFoundError();
271
+ }
272
+ const { old_str, new_str } = command;
273
+ const count = this.countOccurrences(this.text, old_str);
274
+ if (count === 0) {
275
+ const normalized = old_str.endsWith('\n') ? old_str.slice(0, -1) : old_str + '\n';
276
+ const normalizedCount = this.countOccurrences(this.text, normalized);
277
+ if (normalizedCount === 1) {
278
+ this.text = this.text.replace(normalized, this.escapeReplacement(new_str));
279
+ return 'Edit applied successfully.';
280
+ }
281
+ const context = findDivergenceContext(this.text, old_str);
282
+ throw new NoMatchFoundError(old_str, context);
283
+ }
284
+ if (count > 1) {
285
+ throw new MultipleMatchesError(count);
286
+ }
287
+ this.text = this.text.replace(old_str, this.escapeReplacement(new_str));
288
+ return 'Edit applied successfully.';
289
+ }
290
+ handleInsert(command) {
291
+ if (this.text === null) {
292
+ throw this.createFileNotFoundError();
293
+ }
294
+ const { insert_line, insert_text } = command;
295
+ const lines = this.text.split('\n');
296
+ if (insert_line < 0 || insert_line > lines.length) {
297
+ throw new InvalidLineNumberError(insert_line, lines.length);
298
+ }
299
+ lines.splice(insert_line, 0, insert_text);
300
+ this.text = lines.join('\n');
301
+ return 'Text inserted successfully.';
302
+ }
303
+ countOccurrences(text, search) {
304
+ if (search.length === 0) {
305
+ return 0;
306
+ }
307
+ let count = 0;
308
+ let pos = 0;
309
+ while ((pos = text.indexOf(search, pos)) !== -1) {
310
+ count++;
311
+ pos += search.length;
312
+ }
313
+ return count;
314
+ }
315
+ appendNotAttemptedResults(results, replacements, startIndex) {
316
+ for (let i = startIndex; i < replacements.length; i++) {
317
+ results.push({
318
+ index: i,
319
+ old_str: truncatePreview(replacements[i].old_str),
320
+ status: 'not_attempted',
321
+ });
322
+ }
323
+ }
324
+ createFileNotFoundError() {
325
+ return new FileNotFoundError(this.options.fileNotFoundMessage);
326
+ }
327
+ escapeReplacement(replacement) {
328
+ return replacement.replace(/\$/g, '$$$$');
329
+ }
330
+ }
331
+ exports.TextEditorDocument = TextEditorDocument;
332
+ });
333
+ //# sourceMappingURL=text-editor.js.map
@@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AiB,CAAC,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC;QAChE,CAAC;QAEO,iBAAiB,CAAC,WAAmB;YAC5C,OAAO,WAAW,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC3C,CAAC;KACD;IAzOD,gDAyOC"}
@@ -1 +1 @@
1
- {"version":3,"file":"ai-node-sdk-version.js","sourceRoot":"","sources":["../../src/ai-node-sdk-version.ts"],"names":[],"mappings":";;;AAEa,QAAA,mBAAmB,GAAW,CAAC,CAAC"}
1
+ {"version":3,"file":"ai-node-sdk-version.js","sourceRoot":"","sources":["../../src/ai-node-sdk-version.ts"],"names":[],"mappings":";;;AAIa,QAAA,mBAAmB,GAAW,CAAC,CAAC"}
@@ -7,6 +7,8 @@ export { getMetadataFiltersValues, hasLongSequentialRepeat } from './utils/helpe
7
7
  export { N8nBinaryLoader } from './utils/n8n-binary-loader';
8
8
  export { N8nJsonLoader } from './utils/n8n-json-loader';
9
9
  export { N8nLlmTracing } from './utils/n8n-llm-tracing';
10
+ export { TextEditorDocument, NoMatchFoundError, MultipleMatchesError, InvalidLineNumberError, InvalidViewRangeError, InvalidPathError, FileExistsError, FileNotFoundError, BatchReplacementError, formatTextWithLineNumbers, findDivergenceContext, parseStrReplacements, } from './utils/text-editor';
11
+ export type { ViewCommand, CreateCommand, StrReplaceCommand, InsertCommand, BatchStrReplaceCommand, TextEditorCommand, TextEditorCommandWithBatch, TextEditorToolCall, TextEditorResult, StrReplacement, BatchReplaceResult, TextEditorDocumentOptions, } from './utils/text-editor';
10
12
  export { estimateTokensFromStringList, estimateTokensByCharCount, estimateTextSplitsByTokens, } from './utils/tokenizer/token-estimator';
11
13
  export { encodingForModel, getEncoding } from './utils/tokenizer/tiktoken';
12
14
  export { makeN8nLlmFailedAttemptHandler } from './utils/failed-attempt-handler/n8nLlmFailedAttemptHandler';
package/dist/esm/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.supplyModel = exports.supplyMemory = exports.WindowedChatMemory = exports.BaseChatMemory = exports.BaseChatHistory = exports.BaseChatModel = exports.LangchainChatModelAdapter = exports.isToolsInstance = exports.isChatInstance = exports.isBaseChatMessageHistory = exports.isBaseChatMemory = exports.fromLcContent = exports.toLcContent = exports.toLcMessage = exports.fromLcMessage = exports.getParametersJsonSchema = exports.processDocument = exports.processDocuments = exports.MemoryVectorStoreManager = exports.createVectorStoreNode = exports.extractFromAIParameters = exports.createZodSchemaFromArgs = exports.createToolFromNode = exports.getTemplateNoticeField = exports.getBatchingOptionFields = exports.metadataFilterField = exports.getConnectionHintNoticeField = exports.proxyFetch = exports.getNodeProxyAgent = exports.getProxyAgent = exports.makeN8nLlmFailedAttemptHandler = exports.getEncoding = exports.encodingForModel = exports.estimateTextSplitsByTokens = exports.estimateTokensByCharCount = exports.estimateTokensFromStringList = exports.N8nLlmTracing = exports.N8nJsonLoader = exports.N8nBinaryLoader = exports.hasLongSequentialRepeat = exports.getMetadataFiltersValues = exports.validateEmbedDocumentsInput = exports.validateEmbedQueryInput = exports.parseSSEStream = exports.logAiEvent = exports.logWrapper = exports.AI_NODE_SDK_VERSION = void 0;
3
+ exports.isBaseChatMessageHistory = exports.isBaseChatMemory = exports.fromLcContent = exports.toLcContent = exports.toLcMessage = exports.fromLcMessage = exports.getParametersJsonSchema = exports.processDocument = exports.processDocuments = exports.MemoryVectorStoreManager = exports.createVectorStoreNode = exports.extractFromAIParameters = exports.createZodSchemaFromArgs = exports.createToolFromNode = exports.getTemplateNoticeField = exports.getBatchingOptionFields = exports.metadataFilterField = exports.getConnectionHintNoticeField = exports.proxyFetch = exports.getNodeProxyAgent = exports.getProxyAgent = exports.makeN8nLlmFailedAttemptHandler = exports.getEncoding = exports.encodingForModel = exports.estimateTextSplitsByTokens = exports.estimateTokensByCharCount = exports.estimateTokensFromStringList = exports.parseStrReplacements = exports.findDivergenceContext = exports.formatTextWithLineNumbers = exports.BatchReplacementError = exports.FileNotFoundError = exports.FileExistsError = exports.InvalidPathError = exports.InvalidViewRangeError = exports.InvalidLineNumberError = exports.MultipleMatchesError = exports.NoMatchFoundError = exports.TextEditorDocument = exports.N8nLlmTracing = exports.N8nJsonLoader = exports.N8nBinaryLoader = exports.hasLongSequentialRepeat = exports.getMetadataFiltersValues = exports.validateEmbedDocumentsInput = exports.validateEmbedQueryInput = exports.parseSSEStream = exports.logAiEvent = exports.logWrapper = exports.AI_NODE_SDK_VERSION = void 0;
4
+ exports.supplyModel = exports.supplyMemory = exports.WindowedChatMemory = exports.BaseChatMemory = exports.BaseChatHistory = exports.BaseChatModel = exports.LangchainChatModelAdapter = exports.isToolsInstance = exports.isChatInstance = void 0;
4
5
  var ai_node_sdk_version_1 = require("./ai-node-sdk-version");
5
6
  Object.defineProperty(exports, "AI_NODE_SDK_VERSION", { enumerable: true, get: function () { return ai_node_sdk_version_1.AI_NODE_SDK_VERSION; } });
6
7
  var log_wrapper_1 = require("./utils/log-wrapper");
@@ -21,6 +22,19 @@ var n8n_json_loader_1 = require("./utils/n8n-json-loader");
21
22
  Object.defineProperty(exports, "N8nJsonLoader", { enumerable: true, get: function () { return n8n_json_loader_1.N8nJsonLoader; } });
22
23
  var n8n_llm_tracing_1 = require("./utils/n8n-llm-tracing");
23
24
  Object.defineProperty(exports, "N8nLlmTracing", { enumerable: true, get: function () { return n8n_llm_tracing_1.N8nLlmTracing; } });
25
+ var text_editor_1 = require("./utils/text-editor");
26
+ Object.defineProperty(exports, "TextEditorDocument", { enumerable: true, get: function () { return text_editor_1.TextEditorDocument; } });
27
+ Object.defineProperty(exports, "NoMatchFoundError", { enumerable: true, get: function () { return text_editor_1.NoMatchFoundError; } });
28
+ Object.defineProperty(exports, "MultipleMatchesError", { enumerable: true, get: function () { return text_editor_1.MultipleMatchesError; } });
29
+ Object.defineProperty(exports, "InvalidLineNumberError", { enumerable: true, get: function () { return text_editor_1.InvalidLineNumberError; } });
30
+ Object.defineProperty(exports, "InvalidViewRangeError", { enumerable: true, get: function () { return text_editor_1.InvalidViewRangeError; } });
31
+ Object.defineProperty(exports, "InvalidPathError", { enumerable: true, get: function () { return text_editor_1.InvalidPathError; } });
32
+ Object.defineProperty(exports, "FileExistsError", { enumerable: true, get: function () { return text_editor_1.FileExistsError; } });
33
+ Object.defineProperty(exports, "FileNotFoundError", { enumerable: true, get: function () { return text_editor_1.FileNotFoundError; } });
34
+ Object.defineProperty(exports, "BatchReplacementError", { enumerable: true, get: function () { return text_editor_1.BatchReplacementError; } });
35
+ Object.defineProperty(exports, "formatTextWithLineNumbers", { enumerable: true, get: function () { return text_editor_1.formatTextWithLineNumbers; } });
36
+ Object.defineProperty(exports, "findDivergenceContext", { enumerable: true, get: function () { return text_editor_1.findDivergenceContext; } });
37
+ Object.defineProperty(exports, "parseStrReplacements", { enumerable: true, get: function () { return text_editor_1.parseStrReplacements; } });
24
38
  var token_estimator_1 = require("./utils/tokenizer/token-estimator");
25
39
  Object.defineProperty(exports, "estimateTokensFromStringList", { enumerable: true, get: function () { return token_estimator_1.estimateTokensFromStringList; } });
26
40
  Object.defineProperty(exports, "estimateTokensByCharCount", { enumerable: true, get: function () { return token_estimator_1.estimateTokensByCharCount; } });