@polka-codes/core 0.9.46 → 0.9.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,29 +1,206 @@
1
- // src/tools/askFollowupQuestion.ts
1
+ // src/Agent/parseJsonFromMarkdown.ts
2
+ var parseJsonFromMarkdown = (markdown) => {
3
+ const jsonRegex = /```(?:json)?\n([\s\S]*?)\n```/;
4
+ const match = markdown.match(jsonRegex);
5
+ const tryParse = (str) => {
6
+ try {
7
+ let parsed = JSON.parse(str);
8
+ if (typeof parsed === "string") {
9
+ try {
10
+ parsed = JSON.parse(parsed);
11
+ } catch {
12
+ }
13
+ }
14
+ return { success: true, data: parsed };
15
+ } catch (e) {
16
+ const error = e instanceof Error ? e.message : String(e);
17
+ return { success: false, error: `Failed to parse JSON: ${error}` };
18
+ }
19
+ };
20
+ if (match?.[1]) {
21
+ const content = match[1].trim();
22
+ return tryParse(content);
23
+ }
24
+ const parseResult = tryParse(markdown);
25
+ if (parseResult.success) {
26
+ return parseResult;
27
+ }
28
+ return { success: false, error: "No JSON object found in the string." };
29
+ };
30
+
31
+ // src/Agent/prompts.ts
32
+ var responsePrompts = {
33
+ errorInvokeTool: (tool, error) => `An error occurred while invoking the tool "${tool}": ${error}`,
34
+ requireUseTool: `Error: No tool use detected. You MUST use a tool before proceeding.
35
+ e.g. <tool_tool_name>tool_name</tool_tool_name>
36
+
37
+ Ensure the opening and closing tags are correctly nested and closed, and that you are using the correct tool name.
38
+ Avoid unnecessary text or symbols before or after the tool use.
39
+ Avoid unnecessary escape characters or special characters.
40
+ `,
41
+ requireUseToolNative: `Error: No tool use detected. You MUST use a tool before proceeding.
42
+ `,
43
+ toolResults: (tool, result) => {
44
+ switch (result.type) {
45
+ case "text":
46
+ return [
47
+ {
48
+ type: "text",
49
+ text: `<tool_response name=${tool}>${result.value}</tool_response>`
50
+ }
51
+ ];
52
+ case "error-text":
53
+ return [
54
+ {
55
+ type: "text",
56
+ text: `<tool_response_error name=${tool}>${result.value}</tool_response_error>`
57
+ }
58
+ ];
59
+ case "json":
60
+ return [
61
+ {
62
+ type: "text",
63
+ text: `<tool_response_json name=${tool}>${JSON.stringify(result.value)}</tool_response_json>`
64
+ }
65
+ ];
66
+ case "error-json":
67
+ return [
68
+ {
69
+ type: "text",
70
+ text: `<tool_response_error_json name=${tool}>${JSON.stringify(result.value)}</tool_response_error_json>`
71
+ }
72
+ ];
73
+ case "content":
74
+ return [
75
+ {
76
+ type: "text",
77
+ text: `<tool_response name=${tool}>`
78
+ },
79
+ ...result.value.map((part) => {
80
+ if (part.type === "text") {
81
+ return part;
82
+ }
83
+ if (part.mediaType.startsWith("image/")) {
84
+ return {
85
+ type: "image",
86
+ mediaType: part.mediaType,
87
+ image: part.data
88
+ };
89
+ }
90
+ return {
91
+ type: "file",
92
+ mediaType: part.mediaType,
93
+ data: part.data
94
+ };
95
+ }),
96
+ {
97
+ type: "text",
98
+ text: "</tool_response>"
99
+ }
100
+ ];
101
+ }
102
+ },
103
+ commandResult: (command, exitCode, stdout, stderr) => `<command>${command}</command>
104
+ <command_exit_code>${exitCode}</command_exit_code>
105
+ <command_stdout>
106
+ ${stdout}
107
+ </command_stdout>
108
+ <command_stderr>
109
+ ${stderr}
110
+ </command_stderr>`
111
+ };
112
+
113
+ // src/Agent/backoff.ts
114
+ function computeRateLimitBackoffSeconds(count, baseSeconds = 2, capSeconds = 60) {
115
+ if (!Number.isFinite(count) || count <= 0) {
116
+ count = 1;
117
+ }
118
+ if (!Number.isFinite(baseSeconds) || baseSeconds <= 0) {
119
+ baseSeconds = 2;
120
+ }
121
+ if (!Number.isFinite(capSeconds) || capSeconds <= 0) {
122
+ capSeconds = 60;
123
+ }
124
+ const delay = baseSeconds * 2 ** (count - 1);
125
+ return Math.min(delay, capSeconds);
126
+ }
127
+
128
+ // src/config.ts
2
129
  import { z } from "zod";
130
+ var providerModelSchema = z.object({
131
+ provider: z.string().optional(),
132
+ model: z.string().optional(),
133
+ parameters: z.record(z.string(), z.any()).optional()
134
+ });
135
+ var configSchema = z.object({
136
+ prices: z.record(
137
+ z.string(),
138
+ // provider
139
+ z.record(
140
+ z.string(),
141
+ // model
142
+ z.object({
143
+ inputPrice: z.number().optional(),
144
+ outputPrice: z.number().optional(),
145
+ cacheWritesPrice: z.number().optional(),
146
+ cacheReadsPrice: z.number().optional()
147
+ })
148
+ )
149
+ ).optional(),
150
+ providers: z.record(
151
+ z.string(),
152
+ z.object({
153
+ apiKey: z.string().optional(),
154
+ defaultModel: z.string().optional(),
155
+ defaultParameters: z.record(z.string(), z.any()).optional(),
156
+ location: z.string().optional(),
157
+ project: z.string().optional(),
158
+ keyFile: z.string().optional()
159
+ })
160
+ ).optional(),
161
+ defaultProvider: z.string().optional(),
162
+ defaultModel: z.string().optional(),
163
+ defaultParameters: z.record(z.string(), z.any()).optional(),
164
+ maxMessageCount: z.number().int().positive().optional(),
165
+ budget: z.number().positive().optional(),
166
+ retryCount: z.number().int().min(0).optional(),
167
+ requestTimeoutSeconds: z.number().int().positive().optional(),
168
+ summaryThreshold: z.number().int().positive().optional(),
169
+ scripts: z.record(
170
+ z.string(),
171
+ z.string().or(
172
+ z.object({
173
+ command: z.string(),
174
+ description: z.string()
175
+ })
176
+ )
177
+ ).optional(),
178
+ commands: z.object({
179
+ default: providerModelSchema.optional()
180
+ }).catchall(providerModelSchema).optional(),
181
+ rules: z.array(z.string()).optional().or(z.string()).optional(),
182
+ excludeFiles: z.array(z.string()).optional()
183
+ }).strict();
3
184
 
4
185
  // src/tool.ts
5
186
  var ToolResponseType = /* @__PURE__ */ ((ToolResponseType2) => {
6
187
  ToolResponseType2["Reply"] = "Reply";
7
188
  ToolResponseType2["Exit"] = "Exit";
8
- ToolResponseType2["Invalid"] = "Invalid";
9
189
  ToolResponseType2["Error"] = "Error";
10
- ToolResponseType2["Interrupted"] = "Interrupted";
11
- ToolResponseType2["HandOver"] = "HandOver";
12
- ToolResponseType2["Delegate"] = "Delegate";
13
- ToolResponseType2["Pause"] = "Pause";
14
190
  return ToolResponseType2;
15
191
  })(ToolResponseType || {});
16
192
 
17
193
  // src/tools/askFollowupQuestion.ts
18
- var questionObject = z.object({
19
- prompt: z.string().describe("The text of the question.").meta({ usageValue: "question text here" }),
20
- options: z.array(z.string()).default([]).describe("Ordered list of suggested answers (omit if none).").meta({ usageValue: "suggested answer here" })
194
+ import { z as z2 } from "zod";
195
+ var questionObject = z2.object({
196
+ prompt: z2.string().describe("The text of the question.").meta({ usageValue: "question text here" }),
197
+ options: z2.array(z2.string()).default([]).describe("Ordered list of suggested answers (omit if none).").meta({ usageValue: "suggested answer here" })
21
198
  });
22
199
  var toolInfo = {
23
- name: "ask_followup_question",
200
+ name: "askFollowupQuestion",
24
201
  description: "Call this when vital details are missing. Pose each follow-up as one direct, unambiguous question. If it speeds the reply, add up to five short, mutually-exclusive answer options. Group any related questions in the same call to avoid a back-and-forth chain.",
25
- parameters: z.object({
26
- questions: z.array(questionObject).describe("One or more follow-up questions you need answered before you can continue.").meta({ usageValue: "questions here" })
202
+ parameters: z2.object({
203
+ questions: z2.array(questionObject).describe("One or more follow-up questions you need answered before you can continue.").meta({ usageValue: "questions here" })
27
204
  }).meta({
28
205
  examples: [
29
206
  {
@@ -82,7 +259,7 @@ var handler = async (provider, args) => {
82
259
  const { questions } = toolInfo.parameters.parse(args);
83
260
  if (questions.length === 0) {
84
261
  return {
85
- type: "Invalid" /* Invalid */,
262
+ type: "Error" /* Error */,
86
263
  message: {
87
264
  type: "error-text",
88
265
  value: "No questions provided"
@@ -105,143 +282,26 @@ ${answer}
105
282
  }
106
283
  };
107
284
  };
108
- var isAvailable = (provider) => {
109
- return !!provider.askFollowupQuestion;
110
- };
111
285
  var askFollowupQuestion_default = {
112
286
  ...toolInfo,
113
- handler,
114
- isAvailable
115
- };
116
-
117
- // src/tools/attemptCompletion.ts
118
- import { z as z2 } from "zod";
119
- var toolInfo2 = {
120
- name: "attempt_completion",
121
- description: "Use this tool when you believe the user\u2019s requested task is complete. Indicate that your work is finished, but acknowledge the user may still provide additional instructions or questions if they want to continue. This tool MUST NOT to be used with any other tool.",
122
- parameters: z2.object({
123
- result: z2.string().describe(
124
- "The result of the task. Formulate this result in a way that is final and does not require further input from the user. Don't end your result with questions or offers for further assistance."
125
- ).meta({ usageValue: "Your final result description here" })
126
- }).meta({
127
- examples: [
128
- {
129
- description: "Request to present the result of the task",
130
- input: {
131
- result: "Your final result description here"
132
- }
133
- }
134
- ]
135
- })
136
- };
137
- var handler2 = async (provider, args) => {
138
- const parsed = toolInfo2.parameters.safeParse(args);
139
- if (!parsed.success) {
140
- return {
141
- type: "Invalid" /* Invalid */,
142
- message: {
143
- type: "error-text",
144
- value: `Invalid arguments for attempt_completion: ${parsed.error.message}`
145
- }
146
- };
147
- }
148
- const { result } = parsed.data;
149
- const moreMessage = await provider.attemptCompletion?.(result);
150
- if (!moreMessage) {
151
- return {
152
- type: "Exit" /* Exit */,
153
- message: result
154
- };
155
- }
156
- return {
157
- type: "Reply" /* Reply */,
158
- message: {
159
- type: "text",
160
- value: `<user_message>${moreMessage}</user_message>`
161
- }
162
- };
163
- };
164
- var isAvailable2 = (_provider) => {
165
- return true;
166
- };
167
- var attemptCompletion_default = {
168
- ...toolInfo2,
169
- handler: handler2,
170
- isAvailable: isAvailable2
171
- };
172
-
173
- // src/tools/delegate.ts
174
- import { z as z3 } from "zod";
175
- var toolInfo3 = {
176
- name: "delegate",
177
- description: "Temporarily delegate a task to another agent and receive the result back. This tool MUST NOT to be used with any other tool.",
178
- parameters: z3.object({
179
- agentName: z3.string().describe("The name of the agent to delegate the task to").meta({ usageValue: "Name of the target agent" }),
180
- task: z3.string().describe("The task to be completed by the target agent").meta({ usageValue: "Task description" }),
181
- context: z3.string().describe("The context information for the task").meta({ usageValue: "Context information" }),
182
- files: z3.preprocess((val) => {
183
- if (!val) return [];
184
- const values = Array.isArray(val) ? val : [val];
185
- return values.flatMap((i) => typeof i === "string" ? i.split(",") : []).filter((s) => s.length > 0);
186
- }, z3.array(z3.string())).optional().describe("The files relevant to the task. Comma separated paths").meta({ usageValue: "Relevant files" })
187
- }).meta({
188
- examples: [
189
- {
190
- description: "Delegate a code analysis task to the analyzer agent",
191
- input: {
192
- agentName: "analyzer",
193
- task: "Analyze the authentication implementation",
194
- context: "Need to understand the security implications of the current auth system",
195
- files: "src/auth/login.ts,src/auth/types.ts"
196
- }
197
- }
198
- ]
199
- })
200
- };
201
- var handler3 = async (_provider, args) => {
202
- const parsed = toolInfo3.parameters.safeParse(args);
203
- if (!parsed.success) {
204
- return {
205
- type: "Invalid" /* Invalid */,
206
- message: {
207
- type: "error-text",
208
- value: `Invalid arguments for delegate: ${parsed.error.message}`
209
- }
210
- };
211
- }
212
- const { agentName, task, context, files } = parsed.data;
213
- return {
214
- type: "Delegate" /* Delegate */,
215
- agentName,
216
- task,
217
- context,
218
- files: files ?? []
219
- };
220
- };
221
- var isAvailable3 = (_provider) => {
222
- return true;
223
- };
224
- var delegate_default = {
225
- ...toolInfo3,
226
- handler: handler3,
227
- isAvailable: isAvailable3
287
+ handler
228
288
  };
229
289
 
230
290
  // src/tools/executeCommand.ts
231
- import { z as z4 } from "zod";
232
- var toolInfo4 = {
233
- name: "execute_command",
291
+ import { z as z3 } from "zod";
292
+ var toolInfo2 = {
293
+ name: "executeCommand",
234
294
  description: "Run a single CLI command. The command is always executed in the project-root working directory (regardless of earlier commands). Prefer one-off shell commands over wrapper scripts for flexibility. **IMPORTANT**: After an `execute_command` call, you MUST stop and NOT allowed to make further tool calls in the same message.",
235
- parameters: z4.object({
236
- command: z4.string().describe("The exact command to run (valid for the current OS). It must be correctly formatted and free of harmful instructions.").meta({ usageValue: "your-command-here" }),
237
- requiresApproval: z4.preprocess((val) => {
295
+ parameters: z3.object({
296
+ command: z3.string().describe("The exact command to run (valid for the current OS). It must be correctly formatted and free of harmful instructions.").meta({ usageValue: "your-command-here" }),
297
+ requiresApproval: z3.preprocess((val) => {
238
298
  if (typeof val === "string") {
239
299
  const lower = val.toLowerCase();
240
300
  if (lower === "false") return false;
241
301
  if (lower === "true") return true;
242
302
  }
243
303
  return val;
244
- }, z4.boolean().optional().default(false)).describe(
304
+ }, z3.boolean().optional().default(false)).describe(
245
305
  "Set to `true` for commands that install/uninstall software, modify or delete files, change system settings, perform network operations, or have other side effects. Use `false` for safe, read-only, or purely local development actions (e.g., listing files, make a build, running tests)."
246
306
  ).meta({ usageValue: "true | false" })
247
307
  }).meta({
@@ -256,7 +316,7 @@ var toolInfo4 = {
256
316
  ]
257
317
  })
258
318
  };
259
- var handler4 = async (provider, args) => {
319
+ var handler2 = async (provider, args) => {
260
320
  if (!provider.executeCommand) {
261
321
  return {
262
322
  type: "Error" /* Error */,
@@ -266,7 +326,7 @@ var handler4 = async (provider, args) => {
266
326
  }
267
327
  };
268
328
  }
269
- const { command, requiresApproval } = toolInfo4.parameters.parse(args);
329
+ const { command, requiresApproval } = toolInfo2.parameters.parse(args);
270
330
  try {
271
331
  const result = await provider.executeCommand(command, requiresApproval);
272
332
  let message = `<command>${command}</command>
@@ -312,26 +372,22 @@ ${result.stderr}
312
372
  };
313
373
  }
314
374
  };
315
- var isAvailable4 = (provider) => {
316
- return !!provider.executeCommand;
317
- };
318
375
  var executeCommand_default = {
319
- ...toolInfo4,
320
- handler: handler4,
321
- isAvailable: isAvailable4
376
+ ...toolInfo2,
377
+ handler: handler2
322
378
  };
323
379
 
324
380
  // src/tools/fetchUrl.ts
325
- import { z as z5 } from "zod";
326
- var toolInfo5 = {
327
- name: "fetch_url",
381
+ import { z as z4 } from "zod";
382
+ var toolInfo3 = {
383
+ name: "fetchUrl",
328
384
  description: "Fetch the content located at one or more HTTP(S) URLs and return it in Markdown format. This works for standard web pages as well as raw files (e.g. README.md, source code) hosted on platforms like GitHub.",
329
- parameters: z5.object({
330
- url: z5.preprocess((val) => {
385
+ parameters: z4.object({
386
+ url: z4.preprocess((val) => {
331
387
  if (!val) return [];
332
388
  const values = Array.isArray(val) ? val : [val];
333
389
  return values.flatMap((i) => typeof i === "string" ? i.split(",") : []).filter((s) => s.length > 0);
334
- }, z5.array(z5.string())).describe("One or more URLs to fetch, separated by commas if multiple.").meta({ usageValue: "url" })
390
+ }, z4.array(z4.string())).describe("One or more URLs to fetch, separated by commas if multiple.").meta({ usageValue: "url" })
335
391
  }).meta({
336
392
  examples: [
337
393
  {
@@ -355,7 +411,7 @@ var toolInfo5 = {
355
411
  ]
356
412
  })
357
413
  };
358
- var handler5 = async (provider, args) => {
414
+ var handler3 = async (provider, args) => {
359
415
  if (!provider.fetchUrl) {
360
416
  return {
361
417
  type: "Error" /* Error */,
@@ -365,7 +421,7 @@ var handler5 = async (provider, args) => {
365
421
  }
366
422
  };
367
423
  }
368
- const { url: urls } = toolInfo5.parameters.parse(args);
424
+ const { url: urls } = toolInfo3.parameters.parse(args);
369
425
  if (urls.length === 0) {
370
426
  return {
371
427
  type: "Error" /* Error */,
@@ -394,109 +450,48 @@ var handler5 = async (provider, args) => {
394
450
  }
395
451
  };
396
452
  };
397
- var isAvailable5 = (provider) => {
398
- return typeof provider.fetchUrl === "function";
399
- };
400
453
  var fetchUrl_default = {
401
- ...toolInfo5,
402
- handler: handler5,
403
- isAvailable: isAvailable5
454
+ ...toolInfo3,
455
+ handler: handler3
404
456
  };
405
457
 
406
- // src/tools/handOver.ts
407
- import { z as z6 } from "zod";
408
- var toolInfo6 = {
409
- name: "hand_over",
410
- description: "Hand over the current task to another agent to complete. This tool MUST NOT to be used with any other tool.",
411
- parameters: z6.object({
412
- agentName: z6.string().describe("The name of the agent to hand over the task to").meta({ usageValue: "Name of the target agent" }),
413
- task: z6.string().describe("The task to be completed by the target agent").meta({ usageValue: "Task description" }),
414
- context: z6.string().describe("The context information for the task").meta({ usageValue: "Context information" }),
415
- files: z6.preprocess((val) => {
416
- if (!val) return [];
417
- const values = Array.isArray(val) ? val : [val];
418
- return values.flatMap((i) => typeof i === "string" ? i.split(",") : []).filter((s) => s.length > 0);
419
- }, z6.array(z6.string())).optional().describe("The files relevant to the task. Comma separated paths").meta({ usageValue: "Relevant files" })
458
+ // src/tools/listFiles.ts
459
+ import { z as z5 } from "zod";
460
+ var toolInfo4 = {
461
+ name: "listFiles",
462
+ description: "Request to list files and directories within the specified directory. If recursive is true, it will list all files and directories recursively. If recursive is false or not provided, it will only list the top-level contents. Do not use this tool to confirm the existence of files you may have created, as the user will let you know if the files were created successfully or not.",
463
+ parameters: z5.object({
464
+ path: z5.string().describe("The path of the directory to list contents for (relative to the current working directory)").meta({ usageValue: "Directory path here" }),
465
+ maxCount: z5.coerce.number().optional().default(2e3).describe("The maximum number of files to list. Default to 2000").meta({ usageValue: "Maximum number of files to list (optional)" }),
466
+ recursive: z5.preprocess((val) => {
467
+ if (typeof val === "string") {
468
+ const lower = val.toLowerCase();
469
+ if (lower === "false") return false;
470
+ if (lower === "true") return true;
471
+ }
472
+ return val;
473
+ }, z5.boolean().optional().default(true)).describe("Whether to list files recursively. Use true for recursive listing, false or omit for top-level only.").meta({ usageValue: "true or false (optional)" }),
474
+ includeIgnored: z5.preprocess((val) => {
475
+ if (typeof val === "string") {
476
+ const lower = val.toLowerCase();
477
+ if (lower === "false") return false;
478
+ if (lower === "true") return true;
479
+ }
480
+ return val;
481
+ }, z5.boolean().optional().default(false)).describe("Whether to include ignored files. Use true to include files ignored by .gitignore.").meta({ usageValue: "true or false (optional)" })
420
482
  }).meta({
421
483
  examples: [
422
484
  {
423
- description: "Hand over a coding task to the coder agent",
485
+ description: "Request to list files",
424
486
  input: {
425
- agentName: "coder",
426
- task: "Implement the login feature",
427
- context: "We need a secure login system with email and password",
428
- files: "src/auth/login.ts,src/auth/types.ts"
487
+ path: "src",
488
+ maxCount: "100"
429
489
  }
430
490
  }
431
491
  ]
432
492
  })
433
493
  };
434
- var handler6 = async (_provider, args) => {
435
- const parsed = toolInfo6.parameters.safeParse(args);
436
- if (!parsed.success) {
437
- return {
438
- type: "Invalid" /* Invalid */,
439
- message: {
440
- type: "error-text",
441
- value: `Invalid arguments for hand_over: ${parsed.error.message}`
442
- }
443
- };
444
- }
445
- const { agentName, task, context, files } = parsed.data;
446
- return {
447
- type: "HandOver" /* HandOver */,
448
- agentName,
449
- task,
450
- context,
451
- files: files ?? []
452
- };
453
- };
454
- var isAvailable6 = (_provider) => {
455
- return true;
456
- };
457
- var handOver_default = {
458
- ...toolInfo6,
459
- handler: handler6,
460
- isAvailable: isAvailable6
461
- };
462
-
463
- // src/tools/listFiles.ts
464
- import { z as z7 } from "zod";
465
- var toolInfo7 = {
466
- name: "list_files",
467
- description: "Request to list files and directories within the specified directory. If recursive is true, it will list all files and directories recursively. If recursive is false or not provided, it will only list the top-level contents. Do not use this tool to confirm the existence of files you may have created, as the user will let you know if the files were created successfully or not.",
468
- parameters: z7.object({
469
- path: z7.string().describe("The path of the directory to list contents for (relative to the current working directory)").meta({ usageValue: "Directory path here" }),
470
- maxCount: z7.coerce.number().optional().default(2e3).describe("The maximum number of files to list. Default to 2000").meta({ usageValue: "Maximum number of files to list (optional)" }),
471
- recursive: z7.preprocess((val) => {
472
- if (typeof val === "string") {
473
- const lower = val.toLowerCase();
474
- if (lower === "false") return false;
475
- if (lower === "true") return true;
476
- }
477
- return val;
478
- }, z7.boolean().optional().default(true)).describe("Whether to list files recursively. Use true for recursive listing, false or omit for top-level only.").meta({ usageValue: "true or false (optional)" }),
479
- includeIgnored: z7.preprocess((val) => {
480
- if (typeof val === "string") {
481
- const lower = val.toLowerCase();
482
- if (lower === "false") return false;
483
- if (lower === "true") return true;
484
- }
485
- return val;
486
- }, z7.boolean().optional().default(false)).describe("Whether to include ignored files. Use true to include files ignored by .gitignore.").meta({ usageValue: "true or false (optional)" })
487
- }).meta({
488
- examples: [
489
- {
490
- description: "Request to list files",
491
- input: {
492
- path: "src",
493
- maxCount: "100"
494
- }
495
- }
496
- ]
497
- })
498
- };
499
- var handler7 = async (provider, args) => {
494
+ var handler4 = async (provider, args) => {
500
495
  if (!provider.listFiles) {
501
496
  return {
502
497
  type: "Error" /* Error */,
@@ -506,7 +501,7 @@ var handler7 = async (provider, args) => {
506
501
  }
507
502
  };
508
503
  }
509
- const { path, maxCount, recursive, includeIgnored } = toolInfo7.parameters.parse(args);
504
+ const { path, maxCount, recursive, includeIgnored } = toolInfo4.parameters.parse(args);
510
505
  const [files, limitReached] = await provider.listFiles(path, recursive, maxCount, includeIgnored);
511
506
  return {
512
507
  type: "Reply" /* Reply */,
@@ -520,13 +515,35 @@ ${files.join("\n")}
520
515
  }
521
516
  };
522
517
  };
523
- var isAvailable7 = (provider) => {
524
- return !!provider.listFiles;
525
- };
526
518
  var listFiles_default = {
527
- ...toolInfo7,
528
- handler: handler7,
529
- isAvailable: isAvailable7
519
+ ...toolInfo4,
520
+ handler: handler4
521
+ };
522
+
523
+ // src/tools/listMemoryTopics.ts
524
+ import { z as z6 } from "zod";
525
+ var toolInfo5 = {
526
+ name: "listMemoryTopics",
527
+ description: "Lists all topics in memory.",
528
+ parameters: z6.object({})
529
+ };
530
+ var handler5 = async (provider, _args) => {
531
+ const topics = await provider.listMemoryTopics();
532
+ if (!topics.length) {
533
+ return { type: "Reply" /* Reply */, message: { type: "text", value: "No topics found." } };
534
+ }
535
+ return {
536
+ type: "Reply" /* Reply */,
537
+ message: {
538
+ type: "text",
539
+ value: `Memory topics:
540
+ ${topics.join("\n")}`
541
+ }
542
+ };
543
+ };
544
+ var listMemoryTopics_default = {
545
+ ...toolInfo5,
546
+ handler: handler5
530
547
  };
531
548
 
532
549
  // src/tools/provider.ts
@@ -555,21 +572,27 @@ var MockProvider = class {
555
572
  async askFollowupQuestion(_question, _options) {
556
573
  return "mock answer";
557
574
  }
558
- async attemptCompletion(_result) {
559
- return "mock completion";
575
+ async listMemoryTopics() {
576
+ return ["default"];
577
+ }
578
+ async readMemory(_topic) {
579
+ return "mock memory content";
580
+ }
581
+ async updateMemory(_operation, _topic, _content) {
582
+ return;
560
583
  }
561
584
  };
562
585
 
563
586
  // src/tools/readBinaryFile.ts
564
- import { z as z8 } from "zod";
565
- var toolInfo8 = {
566
- name: "read_binary_file",
587
+ import { z as z7 } from "zod";
588
+ var toolInfo6 = {
589
+ name: "readBinaryFile",
567
590
  description: "Read a binary file from a URL or local path. Use file:// prefix to access local files. This can be used to access non-text files such as PDFs or images.",
568
- parameters: z8.object({
569
- url: z8.string().describe("The URL or local path of the file to read.")
591
+ parameters: z7.object({
592
+ url: z7.string().describe("The URL or local path of the file to read.")
570
593
  })
571
594
  };
572
- var handler8 = async (provider, args) => {
595
+ var handler6 = async (provider, args) => {
573
596
  if (!provider.readBinaryFile) {
574
597
  return {
575
598
  type: "Error" /* Error */,
@@ -579,7 +602,7 @@ var handler8 = async (provider, args) => {
579
602
  }
580
603
  };
581
604
  }
582
- const { url } = toolInfo8.parameters.parse(args);
605
+ const { url } = toolInfo6.parameters.parse(args);
583
606
  try {
584
607
  const filePart = await provider.readBinaryFile(url);
585
608
  return {
@@ -607,34 +630,30 @@ var handler8 = async (provider, args) => {
607
630
  };
608
631
  }
609
632
  };
610
- var isAvailable8 = (provider) => {
611
- return typeof provider.readBinaryFile === "function";
612
- };
613
633
  var readBinaryFile_default = {
614
- ...toolInfo8,
615
- handler: handler8,
616
- isAvailable: isAvailable8
634
+ ...toolInfo6,
635
+ handler: handler6
617
636
  };
618
637
 
619
638
  // src/tools/readFile.ts
620
- import { z as z9 } from "zod";
621
- var toolInfo9 = {
622
- name: "read_file",
639
+ import { z as z8 } from "zod";
640
+ var toolInfo7 = {
641
+ name: "readFile",
623
642
  description: "Request to read the contents of one or multiple files at the specified paths. Use comma separated paths to read multiple files. Use this when you need to examine the contents of an existing file you do not know the contents of, for example to analyze code, review text files, or extract information from configuration files. May not be suitable for other types of binary files, as it returns the raw content as a string. Try to list all the potential files are relevent to the task, and then use this tool to read all the relevant files.",
624
- parameters: z9.object({
625
- path: z9.preprocess((val) => {
643
+ parameters: z8.object({
644
+ path: z8.preprocess((val) => {
626
645
  if (!val) return [];
627
646
  const values = Array.isArray(val) ? val : [val];
628
647
  return values.flatMap((i) => typeof i === "string" ? i.split(",") : []).filter((s) => s.length > 0);
629
- }, z9.array(z9.string())).describe("The path of the file to read").meta({ usageValue: "Comma separated paths here" }),
630
- includeIgnored: z9.preprocess((val) => {
648
+ }, z8.array(z8.string())).describe("The path of the file to read").meta({ usageValue: "Comma separated paths here" }),
649
+ includeIgnored: z8.preprocess((val) => {
631
650
  if (typeof val === "string") {
632
651
  const lower = val.toLowerCase();
633
652
  if (lower === "false") return false;
634
653
  if (lower === "true") return true;
635
654
  }
636
655
  return val;
637
- }, z9.boolean().optional().default(false)).describe("Whether to include ignored files. Use true to include files ignored by .gitignore.").meta({ usageValue: "true or false (optional)" })
656
+ }, z8.boolean().optional().default(false)).describe("Whether to include ignored files. Use true to include files ignored by .gitignore.").meta({ usageValue: "true or false (optional)" })
638
657
  }).meta({
639
658
  examples: [
640
659
  {
@@ -652,7 +671,7 @@ var toolInfo9 = {
652
671
  ]
653
672
  })
654
673
  };
655
- var handler9 = async (provider, args) => {
674
+ var handler7 = async (provider, args) => {
656
675
  if (!provider.readFile) {
657
676
  return {
658
677
  type: "Error" /* Error */,
@@ -662,7 +681,7 @@ var handler9 = async (provider, args) => {
662
681
  }
663
682
  };
664
683
  }
665
- const { path: paths, includeIgnored } = toolInfo9.parameters.parse(args);
684
+ const { path: paths, includeIgnored } = toolInfo7.parameters.parse(args);
666
685
  const resp = [];
667
686
  for (const path of paths) {
668
687
  const fileContent = await provider.readFile(path, includeIgnored);
@@ -685,19 +704,51 @@ var handler9 = async (provider, args) => {
685
704
  }
686
705
  };
687
706
  };
688
- var isAvailable9 = (provider) => {
689
- return !!provider.readFile;
690
- };
691
707
  var readFile_default = {
692
- ...toolInfo9,
693
- handler: handler9,
694
- isAvailable: isAvailable9
708
+ ...toolInfo7,
709
+ handler: handler7
710
+ };
711
+
712
+ // src/tools/readMemory.ts
713
+ import { z as z9 } from "zod";
714
+ var toolInfo8 = {
715
+ name: "readMemory",
716
+ description: "Reads content from a memory topic.",
717
+ parameters: z9.object({
718
+ topic: z9.string().optional().describe('The topic to read from memory. Defaults to ":default:".')
719
+ })
720
+ };
721
+ var handler8 = async (provider, args) => {
722
+ const { topic } = toolInfo8.parameters.parse(args);
723
+ const content = await provider.readMemory(topic);
724
+ if (content) {
725
+ return {
726
+ type: "Reply" /* Reply */,
727
+ message: {
728
+ type: "text",
729
+ value: `<memory${topic ? ` topic="${topic}"` : ""}>
730
+ ${content}
731
+ </memory>`
732
+ }
733
+ };
734
+ }
735
+ return {
736
+ type: "Reply" /* Reply */,
737
+ message: {
738
+ type: "text",
739
+ value: `<memory ${topic ? `topic="${topic}"` : ""} isEmpty="true" />`
740
+ }
741
+ };
742
+ };
743
+ var readMemory_default = {
744
+ ...toolInfo8,
745
+ handler: handler8
695
746
  };
696
747
 
697
748
  // src/tools/removeFile.ts
698
749
  import { z as z10 } from "zod";
699
- var toolInfo10 = {
700
- name: "remove_file",
750
+ var toolInfo9 = {
751
+ name: "removeFile",
701
752
  description: "Request to remove a file at the specified path.",
702
753
  parameters: z10.object({
703
754
  path: z10.string().describe("The path of the file to remove").meta({ usageValue: "File path here" })
@@ -712,7 +763,7 @@ var toolInfo10 = {
712
763
  ]
713
764
  })
714
765
  };
715
- var handler10 = async (provider, args) => {
766
+ var handler9 = async (provider, args) => {
716
767
  if (!provider.removeFile) {
717
768
  return {
718
769
  type: "Error" /* Error */,
@@ -722,13 +773,13 @@ var handler10 = async (provider, args) => {
722
773
  }
723
774
  };
724
775
  }
725
- const parsed = toolInfo10.parameters.safeParse(args);
776
+ const parsed = toolInfo9.parameters.safeParse(args);
726
777
  if (!parsed.success) {
727
778
  return {
728
- type: "Invalid" /* Invalid */,
779
+ type: "Error" /* Error */,
729
780
  message: {
730
781
  type: "error-text",
731
- value: `Invalid arguments for remove_file: ${parsed.error.message}`
782
+ value: `Invalid arguments for removeFile: ${parsed.error.message}`
732
783
  }
733
784
  };
734
785
  }
@@ -742,19 +793,15 @@ var handler10 = async (provider, args) => {
742
793
  }
743
794
  };
744
795
  };
745
- var isAvailable10 = (provider) => {
746
- return !!provider.removeFile;
747
- };
748
796
  var removeFile_default = {
749
- ...toolInfo10,
750
- handler: handler10,
751
- isAvailable: isAvailable10
797
+ ...toolInfo9,
798
+ handler: handler9
752
799
  };
753
800
 
754
801
  // src/tools/renameFile.ts
755
802
  import { z as z11 } from "zod";
756
- var toolInfo11 = {
757
- name: "rename_file",
803
+ var toolInfo10 = {
804
+ name: "renameFile",
758
805
  description: "Request to rename a file from source path to target path.",
759
806
  parameters: z11.object({
760
807
  source_path: z11.string().describe("The current path of the file").meta({ usageValue: "Source file path here" }),
@@ -771,7 +818,7 @@ var toolInfo11 = {
771
818
  ]
772
819
  })
773
820
  };
774
- var handler11 = async (provider, args) => {
821
+ var handler10 = async (provider, args) => {
775
822
  if (!provider.renameFile) {
776
823
  return {
777
824
  type: "Error" /* Error */,
@@ -781,7 +828,7 @@ var handler11 = async (provider, args) => {
781
828
  }
782
829
  };
783
830
  }
784
- const { source_path, target_path } = toolInfo11.parameters.parse(args);
831
+ const { source_path, target_path } = toolInfo10.parameters.parse(args);
785
832
  await provider.renameFile(source_path, target_path);
786
833
  return {
787
834
  type: "Reply" /* Reply */,
@@ -791,13 +838,9 @@ var handler11 = async (provider, args) => {
791
838
  }
792
839
  };
793
840
  };
794
- var isAvailable11 = (provider) => {
795
- return !!provider.renameFile;
796
- };
797
841
  var renameFile_default = {
798
- ...toolInfo11,
799
- handler: handler11,
800
- isAvailable: isAvailable11
842
+ ...toolInfo10,
843
+ handler: handler10
801
844
  };
802
845
 
803
846
  // src/tools/replaceInFile.ts
@@ -878,8 +921,8 @@ var replaceInFile = (fileContent, diff) => {
878
921
  };
879
922
 
880
923
  // src/tools/replaceInFile.ts
881
- var toolInfo12 = {
882
- name: "replace_in_file",
924
+ var toolInfo11 = {
925
+ name: "replaceInFile",
883
926
  description: "Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.",
884
927
  parameters: z12.object({
885
928
  path: z12.string().describe("The path of the file to modify").meta({ usageValue: "File path here" }),
@@ -990,7 +1033,7 @@ function oldFeature() {
990
1033
  ]
991
1034
  })
992
1035
  };
993
- var handler12 = async (provider, args) => {
1036
+ var handler11 = async (provider, args) => {
994
1037
  if (!provider.readFile || !provider.writeFile) {
995
1038
  return {
996
1039
  type: "Error" /* Error */,
@@ -1000,13 +1043,13 @@ var handler12 = async (provider, args) => {
1000
1043
  }
1001
1044
  };
1002
1045
  }
1003
- const parsed = toolInfo12.parameters.safeParse(args);
1046
+ const parsed = toolInfo11.parameters.safeParse(args);
1004
1047
  if (!parsed.success) {
1005
1048
  return {
1006
- type: "Invalid" /* Invalid */,
1049
+ type: "Error" /* Error */,
1007
1050
  message: {
1008
1051
  type: "error-text",
1009
- value: `Invalid arguments for replace_in_file: ${parsed.error.message}`
1052
+ value: `Invalid arguments for replaceInFile: ${parsed.error.message}`
1010
1053
  }
1011
1054
  };
1012
1055
  }
@@ -1055,27 +1098,23 @@ var handler12 = async (provider, args) => {
1055
1098
  };
1056
1099
  } catch (error) {
1057
1100
  return {
1058
- type: "Invalid" /* Invalid */,
1101
+ type: "Error" /* Error */,
1059
1102
  message: {
1060
1103
  type: "error-text",
1061
- value: `Invalid arguments for replace_in_file: ${error}`
1104
+ value: `Invalid arguments for replaceInFile: ${error}`
1062
1105
  }
1063
1106
  };
1064
1107
  }
1065
1108
  };
1066
- var isAvailable12 = (provider) => {
1067
- return !!provider.readFile && !!provider.writeFile;
1068
- };
1069
1109
  var replaceInFile_default = {
1070
- ...toolInfo12,
1071
- handler: handler12,
1072
- isAvailable: isAvailable12
1110
+ ...toolInfo11,
1111
+ handler: handler11
1073
1112
  };
1074
1113
 
1075
1114
  // src/tools/searchFiles.ts
1076
1115
  import { z as z13 } from "zod";
1077
- var toolInfo13 = {
1078
- name: "search_files",
1116
+ var toolInfo12 = {
1117
+ name: "searchFiles",
1079
1118
  description: "Request to perform a regex search across files in a specified directory, outputting context-rich results that include surrounding lines. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.",
1080
1119
  parameters: z13.object({
1081
1120
  path: z13.string().describe(
@@ -1102,7 +1141,7 @@ var toolInfo13 = {
1102
1141
  ]
1103
1142
  })
1104
1143
  };
1105
- var handler13 = async (provider, args) => {
1144
+ var handler12 = async (provider, args) => {
1106
1145
  if (!provider.searchFiles) {
1107
1146
  return {
1108
1147
  type: "Error" /* Error */,
@@ -1112,13 +1151,13 @@ var handler13 = async (provider, args) => {
1112
1151
  }
1113
1152
  };
1114
1153
  }
1115
- const parsed = toolInfo13.parameters.safeParse(args);
1154
+ const parsed = toolInfo12.parameters.safeParse(args);
1116
1155
  if (!parsed.success) {
1117
1156
  return {
1118
- type: "Invalid" /* Invalid */,
1157
+ type: "Error" /* Error */,
1119
1158
  message: {
1120
1159
  type: "error-text",
1121
- value: `Invalid arguments for search_files: ${parsed.error.message}`
1160
+ value: `Invalid arguments for searchFiles: ${parsed.error.message}`
1122
1161
  }
1123
1162
  };
1124
1163
  }
@@ -1148,23 +1187,92 @@ ${files.join("\n")}
1148
1187
  };
1149
1188
  }
1150
1189
  };
1151
- var isAvailable13 = (provider) => {
1152
- return !!provider.searchFiles;
1153
- };
1154
1190
  var searchFiles_default = {
1191
+ ...toolInfo12,
1192
+ handler: handler12
1193
+ };
1194
+
1195
+ // src/tools/updateMemory.ts
1196
+ import { z as z14 } from "zod";
1197
+ var toolInfo13 = {
1198
+ name: "updateMemory",
1199
+ description: "Appends, replaces, or removes content from a memory topic.",
1200
+ parameters: z14.object({
1201
+ operation: z14.enum(["append", "replace", "remove"]).describe("The operation to perform."),
1202
+ topic: z14.string().nullish().describe('The topic to update in memory. Defaults to ":default:".'),
1203
+ content: z14.string().optional().describe("The content for append or replace operations. Must be omitted for remove operation.")
1204
+ }).superRefine((data, ctx) => {
1205
+ if (data.operation === "append" || data.operation === "replace") {
1206
+ if (data.content === void 0) {
1207
+ ctx.addIssue({
1208
+ code: "custom",
1209
+ message: 'Content is required for "append" and "replace" operations.',
1210
+ path: ["content"]
1211
+ });
1212
+ }
1213
+ } else if (data.operation === "remove") {
1214
+ if (data.content !== void 0) {
1215
+ ctx.addIssue({
1216
+ code: "custom",
1217
+ message: 'Content must not be provided for "remove" operation.',
1218
+ path: ["content"]
1219
+ });
1220
+ }
1221
+ }
1222
+ })
1223
+ };
1224
+ var handler13 = async (provider, args) => {
1225
+ if (!provider.updateMemory) {
1226
+ return {
1227
+ type: "Error" /* Error */,
1228
+ message: {
1229
+ type: "error-text",
1230
+ value: "Memory operations are not supported by the current provider."
1231
+ }
1232
+ };
1233
+ }
1234
+ const params = toolInfo13.parameters.parse(args);
1235
+ await provider.updateMemory(params.operation, params.topic ?? void 0, "content" in params ? params.content : void 0);
1236
+ switch (params.operation) {
1237
+ case "append":
1238
+ return {
1239
+ type: "Reply" /* Reply */,
1240
+ message: {
1241
+ type: "text",
1242
+ value: `Content appended to memory topic '${params.topic || ":default:"}'.`
1243
+ }
1244
+ };
1245
+ case "replace":
1246
+ return {
1247
+ type: "Reply" /* Reply */,
1248
+ message: {
1249
+ type: "text",
1250
+ value: `Memory topic '${params.topic || ":default:"}' replaced.`
1251
+ }
1252
+ };
1253
+ case "remove":
1254
+ return {
1255
+ type: "Reply" /* Reply */,
1256
+ message: {
1257
+ type: "text",
1258
+ value: `Memory topic '${params.topic || ":default:"}' removed.`
1259
+ }
1260
+ };
1261
+ }
1262
+ };
1263
+ var updateMemory_default = {
1155
1264
  ...toolInfo13,
1156
- handler: handler13,
1157
- isAvailable: isAvailable13
1265
+ handler: handler13
1158
1266
  };
1159
1267
 
1160
1268
  // src/tools/writeToFile.ts
1161
- import { z as z14 } from "zod";
1269
+ import { z as z15 } from "zod";
1162
1270
  var toolInfo14 = {
1163
- name: "write_to_file",
1271
+ name: "writeToFile",
1164
1272
  description: "Request to write content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file. Ensure that the output content does not include incorrect escaped character patterns such as `&lt;`, `&gt;`, or `&amp;`. Also ensure there is no unwanted CDATA tags in the content.",
1165
- parameters: z14.object({
1166
- path: z14.string().describe("The path of the file to write to").meta({ usageValue: "File path here" }),
1167
- content: z14.string().describe(
1273
+ parameters: z15.object({
1274
+ path: z15.string().describe("The path of the file to write to").meta({ usageValue: "File path here" }),
1275
+ content: z15.string().describe(
1168
1276
  "The content to write to the file. ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. You MUST include ALL parts of the file, even if they haven't been modified."
1169
1277
  ).meta({ usageValue: "Your file content here" })
1170
1278
  }).meta({
@@ -1203,10 +1311,10 @@ var handler14 = async (provider, args) => {
1203
1311
  const parsed = toolInfo14.parameters.safeParse(args);
1204
1312
  if (!parsed.success) {
1205
1313
  return {
1206
- type: "Invalid" /* Invalid */,
1314
+ type: "Error" /* Error */,
1207
1315
  message: {
1208
1316
  type: "error-text",
1209
- value: `Invalid arguments for write_to_file: ${parsed.error.message}`
1317
+ value: `Invalid arguments for writeToFile: ${parsed.error.message}`
1210
1318
  }
1211
1319
  };
1212
1320
  }
@@ -1222,35 +1330,9 @@ var handler14 = async (provider, args) => {
1222
1330
  }
1223
1331
  };
1224
1332
  };
1225
- var isAvailable14 = (provider) => {
1226
- return !!provider.writeFile;
1227
- };
1228
1333
  var writeToFile_default = {
1229
1334
  ...toolInfo14,
1230
- handler: handler14,
1231
- isAvailable: isAvailable14
1232
- };
1233
-
1234
- // src/getAvailableTools.ts
1235
- var getAvailableTools = ({
1236
- provider,
1237
- allTools,
1238
- hasAgent
1239
- }) => {
1240
- const tools = [];
1241
- for (const tool of allTools) {
1242
- if (!hasAgent) {
1243
- switch (tool.name) {
1244
- case handOver_default.name:
1245
- case delegate_default.name:
1246
- continue;
1247
- }
1248
- }
1249
- if (tool.isAvailable(provider)) {
1250
- tools.push(tool);
1251
- }
1252
- }
1253
- return tools;
1335
+ handler: handler14
1254
1336
  };
1255
1337
 
1256
1338
  // src/UsageMeter.ts
@@ -1400,2036 +1482,27 @@ var UsageMeter = class {
1400
1482
  };
1401
1483
  }
1402
1484
  };
1403
-
1404
- // src/Agent/AgentBase.ts
1405
- import { jsonSchema, streamText } from "ai";
1406
- import { camelCase } from "lodash-es";
1407
- import { toJSONSchema } from "zod";
1408
-
1409
- // src/tool-v1-compat.ts
1410
- import { z as z15 } from "zod";
1411
- function zodSchemaToParameters(schema) {
1412
- const parameters = [];
1413
- const { shape } = schema;
1414
- for (const name in shape) {
1415
- const def = shape[name];
1416
- const isOptional = def.safeParse(void 0).success;
1417
- const description = def.description || "";
1418
- const param = {
1419
- name,
1420
- description,
1421
- required: !isOptional
1422
- };
1423
- const usageValue = def.meta()?.usageValue;
1424
- if (usageValue) {
1425
- param.usageValue = usageValue;
1426
- }
1427
- if (def instanceof z15.ZodObject) {
1428
- param.children = zodSchemaToParameters(def);
1429
- } else if (def instanceof z15.ZodArray) {
1430
- param.allowMultiple = true;
1431
- const element = def.element;
1432
- if (element instanceof z15.ZodObject) {
1433
- param.children = zodSchemaToParameters(element);
1434
- }
1435
- }
1436
- parameters.push(param);
1437
- }
1438
- return parameters;
1439
- }
1440
- function toToolInfoV1(tool) {
1441
- const { parameters: zodSchema, ...rest } = tool;
1442
- const v1Parameters = zodSchemaToParameters(zodSchema);
1443
- const examples = zodSchema.meta()?.examples;
1444
- const v1Tool = {
1445
- ...rest,
1446
- parameters: v1Parameters
1447
- };
1448
- if (examples) {
1449
- v1Tool.examples = examples;
1450
- }
1451
- return v1Tool;
1452
- }
1453
-
1454
- // src/Agent/backoff.ts
1455
- function computeRateLimitBackoffSeconds(count, baseSeconds = 2, capSeconds = 60) {
1456
- if (!Number.isFinite(count) || count <= 0) {
1457
- count = 1;
1458
- }
1459
- if (!Number.isFinite(baseSeconds) || baseSeconds <= 0) {
1460
- baseSeconds = 2;
1461
- }
1462
- if (!Number.isFinite(capSeconds) || capSeconds <= 0) {
1463
- capSeconds = 60;
1464
- }
1465
- const delay = baseSeconds * 2 ** (count - 1);
1466
- return Math.min(delay, capSeconds);
1467
- }
1468
-
1469
- // src/Agent/parseAssistantMessage.ts
1470
- function parseNestedParameters(content, parameterPrefix, childrenParams) {
1471
- const result = {};
1472
- const nestedParamRegex = new RegExp(`<${parameterPrefix}([^>]+)>([\\s\\S]*?)<\\/${parameterPrefix}\\1>`, "gs");
1473
- const arrayParams = /* @__PURE__ */ new Set();
1474
- if (childrenParams) {
1475
- for (const param of childrenParams) {
1476
- if (param.allowMultiple) {
1477
- arrayParams.add(param.name);
1478
- }
1479
- }
1480
- }
1481
- while (true) {
1482
- const match = nestedParamRegex.exec(content);
1483
- if (match === null) break;
1484
- const paramName = match[1];
1485
- const paramContent = match[2].trim();
1486
- const childParam = childrenParams?.find((p) => p.name === paramName);
1487
- if (paramContent.includes(`<${parameterPrefix}`) && childParam?.children) {
1488
- const nestedResult = parseNestedParameters(paramContent, parameterPrefix, childParam.children);
1489
- if (arrayParams.has(paramName)) {
1490
- if (!result[paramName]) {
1491
- result[paramName] = [];
1492
- }
1493
- if (Array.isArray(result[paramName])) {
1494
- result[paramName].push(nestedResult);
1495
- } else {
1496
- result[paramName] = [nestedResult];
1497
- }
1498
- } else {
1499
- result[paramName] = nestedResult;
1500
- }
1501
- } else if (arrayParams.has(paramName)) {
1502
- if (!result[paramName]) {
1503
- result[paramName] = [];
1504
- }
1505
- if (Array.isArray(result[paramName])) {
1506
- result[paramName].push(paramContent);
1507
- } else {
1508
- result[paramName] = [paramContent];
1509
- }
1510
- } else {
1511
- result[paramName] = paramContent;
1512
- }
1513
- }
1514
- return result;
1515
- }
1516
- function parseAssistantMessage(assistantMessage, tools, toolNamePrefix) {
1517
- const parameterPrefix = `${toolNamePrefix}parameter_`;
1518
- const results = [];
1519
- const toolTags = tools.map((tool) => `${toolNamePrefix}${tool.name}`);
1520
- const toolPattern = toolTags.join("|");
1521
- let remainingMessage = assistantMessage;
1522
- let match;
1523
- const tagRegex = new RegExp(`<(${toolPattern})>([\\s\\S]*?)<\\/\\1>`, "s");
1524
- while (true) {
1525
- match = tagRegex.exec(remainingMessage);
1526
- if (match === null) break;
1527
- const beforeTag = remainingMessage.slice(0, match.index).trim();
1528
- if (beforeTag) {
1529
- results.push({
1530
- type: "text",
1531
- content: beforeTag
1532
- });
1533
- }
1534
- const tagName = match[1];
1535
- const toolName = tagName.replace(toolNamePrefix, "");
1536
- const tool = tools.find((t) => t.name === toolName);
1537
- const fullTagContent = match[0];
1538
- if (tool) {
1539
- const params = {};
1540
- for (const param of tool.parameters) {
1541
- const paramName = `${parameterPrefix}${param.name}`;
1542
- const escapedParamName = paramName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1543
- const paramRegex = new RegExp(`<${escapedParamName}>([\\s\\S]*?)<\\/${escapedParamName}>`, "gs");
1544
- const paramMatches = [];
1545
- while (true) {
1546
- const paramMatch = paramRegex.exec(fullTagContent);
1547
- if (paramMatch === null) break;
1548
- paramMatches.push(paramMatch[1].trim());
1549
- }
1550
- if (paramMatches.length > 0) {
1551
- if (paramMatches.length === 1 && !param.allowMultiple) {
1552
- const paramContent = paramMatches[0];
1553
- if (paramContent.includes(`<${parameterPrefix}`) && param.children) {
1554
- params[param.name] = parseNestedParameters(paramContent, parameterPrefix, param.children);
1555
- } else {
1556
- params[param.name] = paramContent;
1557
- }
1558
- } else {
1559
- if (param.allowMultiple) {
1560
- params[param.name] = paramMatches.map((paramContent) => {
1561
- if (paramContent.includes(`<${parameterPrefix}`) && param.children) {
1562
- return parseNestedParameters(paramContent, parameterPrefix, param.children);
1563
- }
1564
- return paramContent;
1565
- });
1566
- } else {
1567
- const paramContent = paramMatches[0];
1568
- if (paramContent.includes(`<${parameterPrefix}`) && param.children) {
1569
- params[param.name] = parseNestedParameters(paramContent, parameterPrefix, param.children);
1570
- } else {
1571
- params[param.name] = paramContent;
1572
- }
1573
- }
1574
- }
1575
- }
1576
- }
1577
- results.push({
1578
- type: "tool_use",
1579
- name: toolName,
1580
- params
1581
- });
1582
- } else {
1583
- results.push({
1584
- type: "text",
1585
- content: fullTagContent
1586
- });
1587
- }
1588
- remainingMessage = remainingMessage.slice(match.index + fullTagContent.length);
1589
- }
1590
- if (remainingMessage.trim()) {
1591
- results.push({
1592
- type: "text",
1593
- content: remainingMessage.trim()
1594
- });
1595
- }
1596
- if (results.length === 0) {
1597
- results.push({
1598
- type: "text",
1599
- content: assistantMessage
1600
- });
1601
- }
1602
- return results;
1603
- }
1604
-
1605
- // src/Agent/prompts.ts
1606
- var renderParameterValue = (key, value, parameterPrefix) => {
1607
- if (typeof value === "string") {
1608
- return `<${parameterPrefix}${key}>${value}</${parameterPrefix}${key}>`;
1609
- }
1610
- if (Array.isArray(value)) {
1611
- return value.map((v) => renderParameterValue(key, v, parameterPrefix)).join("\n");
1612
- }
1613
- const inner = Object.entries(value).map(([key2, v]) => renderParameterValue(key2, v, parameterPrefix)).join("\n");
1614
- return `<${parameterPrefix}${key}>
1615
- ${inner}
1616
- </${parameterPrefix}${key}>`;
1617
- };
1618
- var toolInfoPrompt = (tool, toolNamePrefix, parameterPrefix) => `
1619
- ## ${toolNamePrefix}${tool.name}
1620
-
1621
- Description: ${tool.description}
1622
-
1623
- Parameters:
1624
- ${tool.parameters.map(
1625
- (param) => `- ${parameterPrefix}${param.name}: (${param.required ? "required" : "optional"})${param.allowMultiple ? " (multiple allowed)" : ""} ${param.description}`
1626
- ).join("\n")}
1627
-
1628
- Usage:
1629
- <${toolNamePrefix}${tool.name}>
1630
- ${tool.parameters.map(
1631
- (param) => param.allowMultiple ? `<${parameterPrefix}${param.name}>${param.usageValue}</${parameterPrefix}${param.name}>
1632
- <${parameterPrefix}${param.name}>${param.usageValue}</${parameterPrefix}${param.name}>` : `<${parameterPrefix}${param.name}>${param.usageValue}</${parameterPrefix}${param.name}>`
1633
- ).join("\n")}
1634
- </${toolNamePrefix}${tool.name}>`;
1635
- var toolInfoExamplesPrompt = (tool, example, toolNamePrefix, parameterPrefix) => `
1636
- ## Example: ${example.description}
1637
-
1638
- <${toolNamePrefix}${tool.name}>
1639
- ${Object.entries(example.input).map(([name, value]) => renderParameterValue(name, value, parameterPrefix)).join("\n")}
1640
- </${toolNamePrefix}${tool.name}>
1641
- `;
1642
- var toolUsePrompt = (useNativeTool, tools, toolNamePrefix) => {
1643
- if (useNativeTool) {
1644
- return `
1645
- ====
1646
-
1647
- TOOL USE
1648
-
1649
- - You MUST use a tool.
1650
- - Batch tool use when feasible; avoid redundant calls.
1651
- `;
1652
- }
1653
- if (tools.length === 0) {
1654
- return "";
1655
- }
1656
- const parameterPrefix = `${toolNamePrefix}parameter_`;
1657
- const v1Tools = tools.map(toToolInfoV1);
1658
- return `
1659
- ====
1660
-
1661
- TOOL USE
1662
-
1663
- You have access to a set of tools that are executed upon the user's approval. You can use up to 5 tool calls per message, and will receive the results of those tool uses in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
1664
-
1665
- # Tool Use Formatting
1666
-
1667
- Tool use is formatted using XML-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags. Here's the structure:
1668
-
1669
- <${toolNamePrefix}tool_name>
1670
- <${parameterPrefix}name1>value1</${parameterPrefix}name1>
1671
- <${parameterPrefix}name2>value2</${parameterPrefix}name2>
1672
- ...
1673
- </${toolNamePrefix}tool_name>
1674
-
1675
- **It is crucial that all tags are correctly nested and closed.**
1676
-
1677
- ## Array Parameters
1678
-
1679
- To create an array of values for a parameter, repeat the parameter tag multiple times:
1680
-
1681
- <${toolNamePrefix}process_file>
1682
- <${parameterPrefix}path>test.ts</${parameterPrefix}path>
1683
- <${parameterPrefix}path>main.ts</${parameterPrefix}path>
1684
- </${toolNamePrefix}process_file>
1685
-
1686
- ## Nested Object Parameters
1687
-
1688
- To create nested objects, nest parameter tags within other parameter tags:
1689
-
1690
- <${toolNamePrefix}example_tool>
1691
- <${parameterPrefix}key>
1692
- <${parameterPrefix}key2>value</${parameterPrefix}key2>
1693
- <${parameterPrefix}key3>value2</${parameterPrefix}key3>
1694
- </${parameterPrefix}key>
1695
- </${toolNamePrefix}example_tool>
1696
-
1697
- You can also combine array parameters with nested objects:
1698
-
1699
- <${toolNamePrefix}example_tool>
1700
- <${parameterPrefix}key>
1701
- <${parameterPrefix}key2>value</${parameterPrefix}key2>
1702
- <${parameterPrefix}key3>value2</${parameterPrefix}key3>
1703
- </${parameterPrefix}key>
1704
- <${parameterPrefix}key>
1705
- <${parameterPrefix}key2>value3</${parameterPrefix}key2>
1706
- <${parameterPrefix}key3>value4</${parameterPrefix}key3>
1707
- <${parameterPrefix}key3>value5</${parameterPrefix}key3>
1708
- </${parameterPrefix}key>
1709
- </${toolNamePrefix}example_tool>
1710
-
1711
- Always adhere to this format, ensuring every opening tag has a matching closing tag, to ensure proper parsing and execution.
1712
-
1713
- NEVER surround tool use with triple backticks (\`\`\`).
1714
-
1715
- # Tools
1716
- ${v1Tools.map((tool) => toolInfoPrompt(tool, toolNamePrefix, parameterPrefix)).join("\n")}
1717
-
1718
- # Tool Use Examples
1719
- ${v1Tools.map((tool) => {
1720
- let promp = "";
1721
- for (const example of tool.examples ?? []) {
1722
- promp += toolInfoExamplesPrompt(tool, example, toolNamePrefix, parameterPrefix);
1723
- }
1724
- return promp;
1725
- }).join("")}
1726
- # Tool Use Guidelines
1727
-
1728
- 1. **Wait for Feedback**
1729
- - After using a tool, wait for the user's response indicating success/failure or any output logs. Do not assume the result of a tool without explicit confirmation.
1730
- 2. **Error Handling**
1731
- - If a tool fails or produces an unexpected result, analyze the error, decide on an alternative approach or tool, and proceed carefully.
1732
- 3. **Avoid Repetition**
1733
- - Do not quote or repeat previous commands or prompts verbatim. Move the conversation forward by focusing on the latest required action.
1734
- 4. **Tool Call Limit**
1735
- - It is **STRIGHTLY FORBIDDEN** to make more than 5 tool calls in a single message.`;
1736
- };
1737
- var agentsPrompt = (agents, name) => `
1738
- ====
1739
-
1740
- AVAILABLE AGENTS
1741
-
1742
- The following agents are available for task handover/delegate:
1743
- ${agents.map(
1744
- (agent) => `
1745
- - **${agent.name}**
1746
- - Responsibilities:
1747
- ${agent.responsibilities.map((resp) => ` - ${resp}`).join("\n")}`
1748
- ).join("\n")}
1749
-
1750
- - **Current Agent Role**
1751
- You are currently acting as **${name}**. If you identify the task is beyond your current scope, use the handover or delegate tool to transition to the other agent. Include sufficient context so the new agent can seamlessly continue the work.
1752
- `;
1753
- var capabilities = (_toolNamePrefix) => `
1754
- ====
1755
-
1756
- CAPABILITIES
1757
-
1758
- - You have access to a range of tools to aid you in your work. These tools help you effectively accomplish a wide range of tasks.
1759
- - When the user initially gives you a task, a recursive list of all filepaths in the current working directory will be included in context. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further.`;
1760
- var systemInformation = (info) => `
1761
- ====
1762
-
1763
- SYSTEM INFORMATION
1764
-
1765
- Operating System: ${info.os}`;
1766
- var customInstructions = (customInstructions2) => {
1767
- const joined = customInstructions2.join("\n");
1768
- if (joined.trim() === "") {
1769
- return "";
1770
- }
1771
- return `
1772
- ====
1773
-
1774
- USER'S CUSTOM INSTRUCTIONS
1775
-
1776
- The following additional instructions are provided by the user, and should be followed to the best of your ability without interfering with the TOOL USE guidelines.
1777
-
1778
- ${joined}`;
1779
- };
1780
- var customScripts = (commands) => {
1781
- const joined = Object.entries(commands).map(([name, command]) => {
1782
- if (typeof command === "string") {
1783
- return `- ${name}
1784
- - Command: \`${command}\``;
1785
- }
1786
- return `- ${name}
1787
- - Command: \`${command.command}\`
1788
- - Description: ${command.description}`;
1789
- }).join("\n");
1790
- if (joined.trim() === "") {
1791
- return "";
1792
- }
1793
- return `
1794
- ====
1795
-
1796
- USER'S CUSTOM COMMANDS
1797
-
1798
- The following additional commands are provided by the user, and should be followed to the best of your ability without interfering with the TOOL USE guidelines.
1799
-
1800
- ${joined}`;
1801
- };
1802
- var responsePrompts = {
1803
- errorInvokeTool: (tool, error) => `An error occurred while invoking the tool "${tool}": ${error}`,
1804
- requireUseTool: `Error: No tool use detected. You MUST use a tool before proceeding.
1805
- e.g. <tool_tool_name>tool_name</tool_tool_name>
1806
-
1807
- Ensure the opening and closing tags are correctly nested and closed, and that you are using the correct tool name.
1808
- Avoid unnecessary text or symbols before or after the tool use.
1809
- Avoid unnecessary escape characters or special characters.
1810
- `,
1811
- requireUseToolNative: `Error: No tool use detected. You MUST use a tool before proceeding.
1812
- `,
1813
- toolResults: (tool, result) => {
1814
- switch (result.type) {
1815
- case "text":
1816
- return [
1817
- {
1818
- type: "text",
1819
- text: `<tool_response name=${tool}>${result.value}</tool_response>`
1820
- }
1821
- ];
1822
- case "error-text":
1823
- return [
1824
- {
1825
- type: "text",
1826
- text: `<tool_response_error name=${tool}>${result.value}</tool_response_error>`
1827
- }
1828
- ];
1829
- case "json":
1830
- return [
1831
- {
1832
- type: "text",
1833
- text: `<tool_response_json name=${tool}>${JSON.stringify(result.value)}</tool_response_json>`
1834
- }
1835
- ];
1836
- case "error-json":
1837
- return [
1838
- {
1839
- type: "text",
1840
- text: `<tool_response_error_json name=${tool}>${JSON.stringify(result.value)}</tool_response_error_json>`
1841
- }
1842
- ];
1843
- case "content":
1844
- return [
1845
- {
1846
- type: "text",
1847
- text: `<tool_response name=${tool}>`
1848
- },
1849
- ...result.value.map((part) => {
1850
- if (part.type === "text") {
1851
- return part;
1852
- }
1853
- if (part.mediaType.startsWith("image/")) {
1854
- return {
1855
- type: "image",
1856
- mediaType: part.mediaType,
1857
- image: part.data
1858
- };
1859
- }
1860
- return {
1861
- type: "file",
1862
- mediaType: part.mediaType,
1863
- data: part.data
1864
- };
1865
- }),
1866
- {
1867
- type: "text",
1868
- text: "</tool_response>"
1869
- }
1870
- ];
1871
- }
1872
- },
1873
- commandResult: (command, exitCode, stdout, stderr) => `<command>${command}</command>
1874
- <command_exit_code>${exitCode}</command_exit_code>
1875
- <command_stdout>
1876
- ${stdout}
1877
- </command_stdout>
1878
- <command_stderr>
1879
- ${stderr}
1880
- </command_stderr>`
1881
- };
1882
-
1883
- // src/Agent/AgentBase.ts
1884
- var TaskEventKind = /* @__PURE__ */ ((TaskEventKind2) => {
1885
- TaskEventKind2["StartTask"] = "StartTask";
1886
- TaskEventKind2["StartRequest"] = "StartRequest";
1887
- TaskEventKind2["EndRequest"] = "EndRequest";
1888
- TaskEventKind2["Usage"] = "Usage";
1889
- TaskEventKind2["Text"] = "Text";
1890
- TaskEventKind2["Reasoning"] = "Reasoning";
1891
- TaskEventKind2["ToolUse"] = "ToolUse";
1892
- TaskEventKind2["ToolReply"] = "ToolReply";
1893
- TaskEventKind2["ToolInvalid"] = "ToolInvalid";
1894
- TaskEventKind2["ToolError"] = "ToolError";
1895
- TaskEventKind2["ToolInterrupted"] = "ToolInterrupted";
1896
- TaskEventKind2["ToolHandOver"] = "ToolHandOver";
1897
- TaskEventKind2["ToolDelegate"] = "ToolDelegate";
1898
- TaskEventKind2["ToolPause"] = "ToolPause";
1899
- TaskEventKind2["UsageExceeded"] = "UsageExceeded";
1900
- TaskEventKind2["EndTask"] = "EndTask";
1901
- return TaskEventKind2;
1902
- })(TaskEventKind || {});
1903
- var AgentBase = class {
1904
- ai;
1905
- config;
1906
- handlers;
1907
- #policies;
1908
- #toolSet;
1909
- #messages = [];
1910
- #aborted = false;
1911
- #abortController;
1912
- constructor(name, ai, config) {
1913
- this.ai = ai;
1914
- if (config.agents && config.agents.length > 0) {
1915
- const agents = agentsPrompt(config.agents, name);
1916
- config.systemPrompt += `
1917
- ${agents}`;
1918
- }
1919
- const handlers = {};
1920
- for (const tool of config.tools) {
1921
- handlers[tool.name] = tool;
1922
- }
1923
- const policies = [];
1924
- for (const policy of config.policies) {
1925
- const instance = policy(handlers, config.parameters);
1926
- if (instance) {
1927
- policies.push(instance);
1928
- if (instance.prompt) {
1929
- config.systemPrompt += `
1930
- ${instance.prompt}`;
1931
- }
1932
- if (instance.tools) {
1933
- for (const tool of instance.tools) {
1934
- handlers[tool.name] = tool;
1935
- }
1936
- }
1937
- }
1938
- }
1939
- this.handlers = handlers;
1940
- this.config = config;
1941
- this.#policies = policies;
1942
- this.#messages.push({
1943
- role: "system",
1944
- content: this.config.systemPrompt
1945
- });
1946
- if (this.config.toolFormat === "native") {
1947
- const tools = {};
1948
- for (const tool of Object.values(this.handlers)) {
1949
- const toolName = camelCase(tool.name);
1950
- tools[toolName] = {
1951
- description: tool.description,
1952
- inputSchema: jsonSchema(toJSONSchema(tool.parameters))
1953
- };
1954
- this.handlers[toolName] = tool;
1955
- }
1956
- this.#toolSet = tools;
1957
- } else {
1958
- this.#toolSet = {};
1959
- }
1960
- }
1961
- abort() {
1962
- this.#aborted = true;
1963
- if (this.#abortController) {
1964
- this.#abortController.abort();
1965
- }
1966
- }
1967
- get parameters() {
1968
- return this.config.parameters;
1969
- }
1970
- get messages() {
1971
- return this.#messages;
1972
- }
1973
- setMessages(messages) {
1974
- this.#messages = [...messages];
1975
- }
1976
- async #callback(event) {
1977
- await this.config.callback?.(event);
1978
- }
1979
- async start(prompt) {
1980
- this.#callback({ kind: "StartTask" /* StartTask */, systemPrompt: this.config.systemPrompt });
1981
- return await this.#processLoop(prompt);
1982
- }
1983
- async step(message) {
1984
- if (this.#messages.length === 0) {
1985
- this.#callback({ kind: "StartTask" /* StartTask */, systemPrompt: this.config.systemPrompt });
1986
- }
1987
- return await this.#request(message);
1988
- }
1989
- async handleStepResponse(response) {
1990
- return this.#handleResponse(response);
1991
- }
1992
- async #processLoop(userMessage) {
1993
- let nextRequest = [
1994
- {
1995
- role: "user",
1996
- content: userMessage
1997
- }
1998
- ];
1999
- while (true) {
2000
- if (this.#aborted) {
2001
- return { type: "Aborted" };
2002
- }
2003
- if (this.config.usageMeter.isLimitExceeded().result) {
2004
- this.#callback({ kind: "UsageExceeded" /* UsageExceeded */ });
2005
- return { type: "UsageExceeded" };
2006
- }
2007
- const response = await this.#request(nextRequest);
2008
- if (this.#aborted) {
2009
- return { type: "Aborted" };
2010
- }
2011
- const resp = await this.#handleResponse(response);
2012
- if (resp.type === "exit") {
2013
- this.#callback({ kind: "EndTask" /* EndTask */, exitReason: resp.reason });
2014
- return resp.reason;
2015
- }
2016
- nextRequest = resp.message;
2017
- }
2018
- }
2019
- async continueTask(userMessage) {
2020
- return await this.#processLoop(userMessage);
2021
- }
2022
- async #request(userMessage) {
2023
- if (!userMessage) {
2024
- throw new Error("userMessage is missing");
2025
- }
2026
- await this.#callback({ kind: "StartRequest" /* StartRequest */, userMessage });
2027
- this.#messages.push(...userMessage);
2028
- for (const instance of this.#policies) {
2029
- if (instance.onBeforeRequest) {
2030
- await instance.onBeforeRequest(this);
2031
- }
2032
- }
2033
- let messages = this.#messages;
2034
- for (const instance of this.#policies) {
2035
- if (instance.prepareMessages) {
2036
- messages = await instance.prepareMessages(this, messages);
2037
- }
2038
- }
2039
- const retryCount = this.config.retryCount ?? 5;
2040
- const requestTimeoutSeconds = this.config.requestTimeoutSeconds ?? 90;
2041
- let respMessages = [];
2042
- let rateLimitErrorCount = 0;
2043
- for (let i = 0; i < retryCount; i++) {
2044
- if (this.#aborted) {
2045
- break;
2046
- }
2047
- respMessages = [];
2048
- let timeout;
2049
- let requestAbortController;
2050
- requestAbortController = new AbortController();
2051
- this.#abortController = requestAbortController;
2052
- const resetTimeout = () => {
2053
- if (timeout) {
2054
- clearTimeout(timeout);
2055
- }
2056
- if (requestTimeoutSeconds > 0 && requestAbortController) {
2057
- timeout = setTimeout(() => {
2058
- console.error(
2059
- `
2060
- Request timeout after ${requestTimeoutSeconds} seconds. Canceling current request attempt ${i + 1}/${retryCount}.`
2061
- );
2062
- requestAbortController?.abort();
2063
- }, requestTimeoutSeconds * 1e3);
2064
- }
2065
- };
2066
- try {
2067
- resetTimeout();
2068
- const usageMeterOnFinishHandler = this.config.usageMeter.onFinishHandler(this.ai);
2069
- const streamTextOptions = {
2070
- model: this.ai,
2071
- temperature: 0,
2072
- messages,
2073
- providerOptions: this.config.parameters?.providerOptions,
2074
- onChunk: async ({ chunk }) => {
2075
- resetTimeout();
2076
- switch (chunk.type) {
2077
- case "text-delta":
2078
- await this.#callback({ kind: "Text" /* Text */, newText: chunk.text });
2079
- break;
2080
- case "reasoning-delta":
2081
- await this.#callback({ kind: "Reasoning" /* Reasoning */, newText: chunk.text });
2082
- break;
2083
- case "tool-call":
2084
- break;
2085
- }
2086
- },
2087
- onFinish: (evt) => {
2088
- usageMeterOnFinishHandler(evt);
2089
- this.#callback({ kind: "Usage" /* Usage */, usage: evt.totalUsage });
2090
- },
2091
- onError: async (error) => {
2092
- console.error("Error in stream:", error);
2093
- },
2094
- abortSignal: requestAbortController.signal
2095
- };
2096
- if (this.config.toolFormat === "native") {
2097
- streamTextOptions.tools = this.#toolSet;
2098
- }
2099
- const stream = streamText(streamTextOptions);
2100
- await stream.consumeStream({
2101
- onError: (error) => {
2102
- console.error("Error in stream:", error);
2103
- }
2104
- });
2105
- const resp = await stream.response;
2106
- respMessages = resp.messages;
2107
- rateLimitErrorCount = 0;
2108
- if (timeout) {
2109
- clearTimeout(timeout);
2110
- timeout = void 0;
2111
- }
2112
- } catch (error) {
2113
- if (error instanceof Error && error.name === "AbortError") {
2114
- if (this.#aborted) {
2115
- break;
2116
- }
2117
- console.error(`Request attempt ${i + 1} timed out, will retry`);
2118
- } else if (error?.error?.error?.code === "rate_limit_exceeded" || error?.error?.code === "rate_limit_exceeded" || error?.code === "rate_limit_exceeded" || error?.status === 429 || error?.error?.status === 429) {
2119
- rateLimitErrorCount++;
2120
- const waitSeconds = computeRateLimitBackoffSeconds(rateLimitErrorCount);
2121
- console.error(`Rate limit exceeded. Waiting ${waitSeconds}s before retrying...`);
2122
- if (timeout) {
2123
- clearTimeout(timeout);
2124
- timeout = void 0;
2125
- }
2126
- await new Promise((resolve) => setTimeout(resolve, waitSeconds * 1e3));
2127
- console.error("Retrying request...");
2128
- } else {
2129
- rateLimitErrorCount = 0;
2130
- console.error("Error in stream:", error);
2131
- }
2132
- } finally {
2133
- if (timeout) {
2134
- clearTimeout(timeout);
2135
- }
2136
- }
2137
- if (this.config.toolFormat === "native") {
2138
- if (respMessages.some((m) => {
2139
- if (m.role === "tool") {
2140
- return true;
2141
- }
2142
- if (typeof m.content === "string") {
2143
- return true;
2144
- }
2145
- return m.content.some((part) => part.type === "tool-call" || part.type === "tool-result" || part.type === "text");
2146
- })) {
2147
- break;
2148
- }
2149
- } else {
2150
- if (respMessages.length > 0) {
2151
- break;
2152
- }
2153
- }
2154
- if (this.#aborted) {
2155
- break;
2156
- }
2157
- if (i < retryCount - 1) {
2158
- console.error(`
2159
- Retrying request ${i + 2} of ${retryCount}`);
2160
- }
2161
- }
2162
- if (respMessages.length === 0) {
2163
- if (this.#aborted) {
2164
- return [];
2165
- }
2166
- throw new Error("No assistant message received after all retry attempts");
2167
- }
2168
- this.#messages.push(...respMessages);
2169
- if (this.config.toolFormat === "native") {
2170
- const assistantText = respMessages.map((msg) => {
2171
- if (typeof msg.content === "string") {
2172
- return msg.content;
2173
- }
2174
- return msg.content.map((part) => part.type === "text" || part.type === "reasoning" ? part.text : "").join("");
2175
- }).join("\n");
2176
- await this.#callback({ kind: "EndRequest" /* EndRequest */, message: assistantText });
2177
- return respMessages.flatMap((msg) => {
2178
- if (msg.role === "assistant") {
2179
- const content = msg.content;
2180
- if (typeof content === "string") {
2181
- return [{ type: "text", content }];
2182
- }
2183
- return content.flatMap((part) => {
2184
- if (part.type === "text" || part.type === "reasoning") {
2185
- return [{ type: "text", content: part.text }];
2186
- }
2187
- if (part.type === "tool-call") {
2188
- return [{ type: "tool_use", id: part.toolCallId, name: part.toolName, params: part.input }];
2189
- }
2190
- return [];
2191
- });
2192
- }
2193
- return [];
2194
- });
2195
- }
2196
- const currentAssistantMessage = respMessages.map((msg) => {
2197
- if (typeof msg.content === "string") {
2198
- return msg.content;
2199
- }
2200
- return msg.content.map((part) => {
2201
- if (part.type === "text") {
2202
- return part.text;
2203
- }
2204
- return "";
2205
- });
2206
- }).join("\n");
2207
- const ret = parseAssistantMessage(currentAssistantMessage, this.config.tools.map(toToolInfoV1), this.config.toolNamePrefix);
2208
- await this.#callback({ kind: "EndRequest" /* EndRequest */, message: currentAssistantMessage });
2209
- return ret;
2210
- }
2211
- async #handleResponse(response) {
2212
- const toolResponses = [];
2213
- const medias = [];
2214
- const processResponse = (resp) => {
2215
- if (resp.type === "content") {
2216
- return {
2217
- type: "content",
2218
- value: resp.value.map((part) => {
2219
- if (part.type === "media") {
2220
- medias.push(part);
2221
- return {
2222
- type: "text",
2223
- text: `<media url="${part.url}" media-type="${part.mediaType}" />`
2224
- };
2225
- }
2226
- return part;
2227
- })
2228
- };
2229
- }
2230
- return resp;
2231
- };
2232
- let hasPause = false;
2233
- const toolUseContents = response.filter((c) => c.type === "tool_use");
2234
- outer: for (const content of response) {
2235
- switch (content.type) {
2236
- case "text":
2237
- break;
2238
- case "tool_use": {
2239
- await this.#callback({ kind: "ToolUse" /* ToolUse */, tool: content.name, params: content.params });
2240
- const toolResp = await this.#invokeTool(content.name, content.params);
2241
- switch (toolResp.type) {
2242
- case "Reply" /* Reply */: {
2243
- await this.#callback({ kind: "ToolReply" /* ToolReply */, tool: content.name, content: toolResp.message });
2244
- toolResponses.push({ type: "response", tool: content.name, response: processResponse(toolResp.message), id: content.id });
2245
- break;
2246
- }
2247
- case "Exit" /* Exit */:
2248
- case "HandOver" /* HandOver */:
2249
- case "Delegate" /* Delegate */: {
2250
- if (this.config.toolFormat === "native" && toolUseContents.length > 1) {
2251
- const message = {
2252
- type: "Error" /* Error */,
2253
- message: {
2254
- type: "error-text",
2255
- value: `Error: The tool '${content.name}' must be called alone, but it was called with other tools.`
2256
- },
2257
- canRetry: false
2258
- };
2259
- await this.#callback({ kind: "ToolError" /* ToolError */, tool: content.name, error: message });
2260
- toolResponses.push({
2261
- type: "response",
2262
- tool: content.name,
2263
- response: processResponse(message.message),
2264
- id: content.id
2265
- });
2266
- break;
2267
- }
2268
- if (toolResponses.length > 0) {
2269
- break outer;
2270
- }
2271
- if (toolResp.type === "Exit" /* Exit */) {
2272
- return { type: "exit", reason: toolResp };
2273
- }
2274
- if (toolResp.type === "HandOver" /* HandOver */) {
2275
- await this.#callback({
2276
- kind: "ToolHandOver" /* ToolHandOver */,
2277
- tool: content.name,
2278
- agentName: toolResp.agentName,
2279
- task: toolResp.task,
2280
- context: toolResp.context,
2281
- files: toolResp.files
2282
- });
2283
- return { type: "exit", reason: toolResp };
2284
- }
2285
- if (toolResp.type === "Delegate" /* Delegate */) {
2286
- await this.#callback({
2287
- kind: "ToolDelegate" /* ToolDelegate */,
2288
- tool: content.name,
2289
- agentName: toolResp.agentName,
2290
- task: toolResp.task,
2291
- context: toolResp.context,
2292
- files: toolResp.files
2293
- });
2294
- return { type: "exit", reason: toolResp };
2295
- }
2296
- break;
2297
- }
2298
- case "Invalid" /* Invalid */: {
2299
- await this.#callback({ kind: "ToolInvalid" /* ToolInvalid */, tool: content.name, content: toolResp.message });
2300
- toolResponses.push({ type: "response", tool: content.name, response: processResponse(toolResp.message), id: content.id });
2301
- if (this.config.toolFormat !== "native") {
2302
- break outer;
2303
- }
2304
- break;
2305
- }
2306
- case "Error" /* Error */: {
2307
- await this.#callback({ kind: "ToolError" /* ToolError */, tool: content.name, error: toolResp.message });
2308
- toolResponses.push({ type: "response", tool: content.name, response: processResponse(toolResp.message), id: content.id });
2309
- if (this.config.toolFormat !== "native") {
2310
- break outer;
2311
- }
2312
- break;
2313
- }
2314
- case "Pause" /* Pause */: {
2315
- await this.#callback({ kind: "ToolPause" /* ToolPause */, tool: content.name, object: toolResp.object });
2316
- toolResponses.push({ type: "pause", tool: content.name, object: toolResp.object, id: content.id });
2317
- hasPause = true;
2318
- }
2319
- }
2320
- break;
2321
- }
2322
- }
2323
- }
2324
- if (hasPause) {
2325
- return { type: "exit", reason: { type: "Pause", responses: toolResponses } };
2326
- }
2327
- if (toolResponses.length === 0) {
2328
- if (this.config.requireToolUse) {
2329
- return {
2330
- type: "reply",
2331
- message: [
2332
- {
2333
- role: "user",
2334
- content: responsePrompts.requireUseToolNative
2335
- }
2336
- ]
2337
- };
2338
- }
2339
- return {
2340
- type: "exit",
2341
- reason: {
2342
- type: "Exit" /* Exit */,
2343
- message: response.filter((c) => c.type === "text").map((c) => c.content).join("")
2344
- }
2345
- };
2346
- }
2347
- const mediaUserMessage = medias.length > 0 ? [
2348
- {
2349
- role: "user",
2350
- content: medias.map((m) => {
2351
- if (m.mediaType.startsWith("image/")) {
2352
- return {
2353
- type: "image",
2354
- image: m.base64Data,
2355
- mediaType: m.mediaType
2356
- };
2357
- }
2358
- return {
2359
- type: "file",
2360
- data: m.base64Data,
2361
- mediaType: m.mediaType,
2362
- filename: m.url.split("/").pop()
2363
- };
2364
- })
2365
- }
2366
- ] : [];
2367
- if (this.config.toolFormat === "native") {
2368
- const toolResults = toolResponses.filter((resp) => resp.type === "response").map(
2369
- (resp) => ({
2370
- type: "tool-result",
2371
- toolCallId: resp.id,
2372
- toolName: resp.tool,
2373
- output: resp.response
2374
- })
2375
- );
2376
- return {
2377
- type: "reply",
2378
- message: [
2379
- {
2380
- role: "tool",
2381
- content: toolResults
2382
- },
2383
- ...mediaUserMessage
2384
- ]
2385
- };
2386
- }
2387
- if (toolResponses.length === 0) {
2388
- if (this.config.requireToolUse) {
2389
- return {
2390
- type: "reply",
2391
- message: [
2392
- {
2393
- role: "user",
2394
- content: responsePrompts.requireUseTool
2395
- }
2396
- ]
2397
- };
2398
- }
2399
- return {
2400
- type: "exit",
2401
- reason: {
2402
- type: "Exit" /* Exit */,
2403
- message: response.filter((c) => c.type === "text").map((c) => c.content).join("")
2404
- }
2405
- };
2406
- }
2407
- const finalResp = toolResponses.filter((resp) => resp.type === "response").flatMap(({ tool, response: response2 }) => responsePrompts.toolResults(tool, response2));
2408
- return {
2409
- type: "reply",
2410
- message: [
2411
- {
2412
- role: "user",
2413
- content: finalResp
2414
- },
2415
- ...mediaUserMessage
2416
- ]
2417
- };
2418
- }
2419
- async #invokeTool(name, args) {
2420
- try {
2421
- const handler15 = this.handlers[name]?.handler;
2422
- if (!handler15) {
2423
- return {
2424
- type: "Error" /* Error */,
2425
- message: {
2426
- type: "error-text",
2427
- value: responsePrompts.errorInvokeTool(name, "Tool not found")
2428
- },
2429
- canRetry: false
2430
- };
2431
- }
2432
- for (const instance of this.#policies) {
2433
- if (instance.onBeforeInvokeTool) {
2434
- const resp2 = await instance.onBeforeInvokeTool(name, args);
2435
- if (resp2) {
2436
- return resp2;
2437
- }
2438
- }
2439
- }
2440
- const resp = await this.onBeforeInvokeTool(this.handlers[name].name, args);
2441
- if (resp) {
2442
- return resp;
2443
- }
2444
- return await handler15(this.config.provider, args);
2445
- } catch (error) {
2446
- return {
2447
- type: "Error" /* Error */,
2448
- message: {
2449
- type: "error-text",
2450
- value: responsePrompts.errorInvokeTool(name, error)
2451
- },
2452
- canRetry: false
2453
- };
2454
- }
2455
- }
2456
- get model() {
2457
- return `${this.ai.provider}:${this.ai.modelId}`;
2458
- }
2459
- get usage() {
2460
- return this.config.usageMeter.usage;
2461
- }
2462
- };
2463
-
2464
- // src/Agent/AnalyzerAgent/prompts.ts
2465
- var fullSystemPrompt = (info, tools, toolNamePrefix, instructions, scripts, useNativeTool) => `
2466
- # Analyzer Agent
2467
-
2468
- ## Role
2469
- You are the **Analyzer** agent, responsible for:
2470
- 1. **Project Structure Analysis** \u2013 Understand codebase organization and architecture.
2471
- 2. **Code Pattern Analysis** \u2013 Identify common patterns, conventions, and best practices.
2472
- 3. **Dependency Analysis** \u2013 Examine project dependencies and their usage.
2473
- 4. **Workflow Analysis** \u2013 Understand development tools, scripts, and processes.
2474
- 5. **Documentation Review** \u2013 Analyze documentation and code comments.
2475
-
2476
- > **Note**: The **Analyzer** agent focuses on understanding and analyzing the codebase without making modifications. Your role is to provide insights and understanding that can inform development decisions.
2477
-
2478
- ## Rules
2479
- 1. **Thoroughness**: Conduct comprehensive analysis of relevant project aspects.
2480
- 2. **Pattern Recognition**: Identify recurring patterns, conventions, and architectural decisions.
2481
- 3. **Dependency Mapping**: Track and understand relationships between components.
2482
- 4. **Workflow Understanding**: Analyze build processes, testing approaches, and development tools.
2483
- 5. **Documentation Assessment**: Review documentation quality and completeness.
2484
- 6. **Non-Modification**: Never modify code or files - focus solely on analysis.
2485
-
2486
- ${toolUsePrompt(useNativeTool, tools, toolNamePrefix)}
2487
- ${capabilities(toolNamePrefix)}
2488
- ${systemInformation(info)}
2489
- ${customInstructions(instructions)}
2490
- ${customScripts(scripts)}
2491
- `;
2492
-
2493
- // src/Agent/AnalyzerAgent/index.ts
2494
- var agentTools = [attemptCompletion_default, delegate_default, fetchUrl_default, handOver_default, listFiles_default, readBinaryFile_default, readFile_default, searchFiles_default];
2495
- var AnalyzerAgent = class extends AgentBase {
2496
- constructor(options) {
2497
- const combinedTools = [...options.additionalTools ?? [], ...agentTools];
2498
- const tools = getAvailableTools({
2499
- provider: options.provider,
2500
- allTools: combinedTools,
2501
- hasAgent: (options.agents?.length ?? 0) > 0
2502
- });
2503
- const toolNamePrefix = options.toolFormat === "native" ? "" : "tool_";
2504
- const systemPrompt = fullSystemPrompt(
2505
- {
2506
- os: options.os
2507
- },
2508
- tools,
2509
- toolNamePrefix,
2510
- options.customInstructions ?? [],
2511
- options.scripts ?? {},
2512
- options.toolFormat === "native"
2513
- );
2514
- super(analyzerAgentInfo.name, options.ai, {
2515
- systemPrompt,
2516
- tools,
2517
- toolNamePrefix,
2518
- provider: options.provider,
2519
- agents: options.agents,
2520
- scripts: options.scripts,
2521
- callback: options.callback,
2522
- policies: options.policies,
2523
- toolFormat: options.toolFormat,
2524
- parameters: options.parameters ?? {},
2525
- usageMeter: options.usageMeter ?? new UsageMeter(),
2526
- requestTimeoutSeconds: options.requestTimeoutSeconds,
2527
- requireToolUse: options.requireToolUse ?? true
2528
- });
2529
- }
2530
- onBeforeInvokeTool() {
2531
- return Promise.resolve(void 0);
2532
- }
2533
- };
2534
- var analyzerAgentInfo = {
2535
- name: "analyzer",
2536
- responsibilities: [
2537
- "Analyzing project structure and organization",
2538
- "Identifying key source code files and their relationships",
2539
- "Understanding common coding patterns and conventions",
2540
- "Examining development workflow and tooling",
2541
- "Analyzing dependencies and their usage patterns"
2542
- ]
2543
- };
2544
-
2545
- // src/Agent/ArchitectAgent/prompts.ts
2546
- var fullSystemPrompt2 = (info, tools, toolNamePrefix, instructions, scripts, useNativeTool) => `
2547
- # Architect Agent
2548
-
2549
- ## Role
2550
- You are the **Architect** agent, responsible for:
2551
- 1. **Task Analysis** - Understand requirements.
2552
- 2. **File Identification** - Select relevant files.
2553
- 3. **File Reading** - Use provided tools to gather information.
2554
- 4. **Implementation Plan** - Draft a *code-free* plan (pseudocode/interface stubs permitted).
2555
- 5. **Review & Improve** - Refine the plan.
2556
- 6. **Handover/Delegate** - Provide the final plan, context, and files to the **Coder** agent.
2557
-
2558
- > **Never** modify project files directly. Only produce the implementation plan; the **Coder** agent performs all code changes.
2559
-
2560
- ## Rules
2561
- 1. **Consistency** - Align with user objectives.
2562
- 2. **Relevance** - Consult only essential files.
2563
- 3. **Conciseness** - Be succinct; avoid repetition.
2564
- 4. **Accuracy** - Ensure conclusions are verifiable.
2565
- 5. **Clarity** - Present information in a structured format.
2566
- 6. **Minimal Queries** - Ask questions only when truly needed.
2567
- 7. **Completion** - Only use the \`attemptCompletion\` tool if the user's request has been fully satisfied and no coding tasks need to be delegated to the Coder agent.
2568
-
2569
- ## Steps
2570
- 1. **Analyze Task** - Capture goals, constraints, and success criteria.
2571
- 2. **Identify Relevant Files** - List files and justify each choice.
2572
- 3. **Read Files via Tools** - Summarize key insights.
2573
- 4. **Create Implementation Plan** - Provide a detailed, step-by-step breakdown:
2574
- * Tasks, resources, and dependencies.
2575
- * Pseudocode or interface declarations only\u2014no concrete code.
2576
- * Sufficient detail for the **Coder** to implement without follow-ups.
2577
- 5. **Review & Improve** - Confirm the plan is unambiguous and complete.
2578
- 6. **Handover/Delegate**
2579
- - If the plan consists of a single self-contained step, hand it over as one task.
2580
- - If multiple steps are required, break them into numbered tasks to delegate to the **Coder** agent.
2581
- - When handing over or delegating, you MUST provide the full implementation plan. Include all necessary context, file references, and clarifications for successful execution.
2582
-
2583
- ${toolUsePrompt(useNativeTool, tools, toolNamePrefix)}
2584
- ${capabilities(toolNamePrefix)}
2585
- ${systemInformation(info)}
2586
- ${customInstructions(instructions)}
2587
- ${customScripts(scripts)}
2588
- `;
2589
-
2590
- // src/Agent/ArchitectAgent/index.ts
2591
- var agentTools2 = [attemptCompletion_default, delegate_default, fetchUrl_default, handOver_default, listFiles_default, readBinaryFile_default, readFile_default, searchFiles_default];
2592
- var ArchitectAgent = class extends AgentBase {
2593
- constructor(options) {
2594
- const combinedTools = [...options.additionalTools ?? [], ...agentTools2];
2595
- const tools = getAvailableTools({
2596
- provider: options.provider,
2597
- allTools: combinedTools,
2598
- hasAgent: (options.agents?.length ?? 0) > 0
2599
- });
2600
- const toolNamePrefix = options.toolFormat === "native" ? "" : "tool_";
2601
- const systemPrompt = fullSystemPrompt2(
2602
- {
2603
- os: options.os
2604
- },
2605
- tools,
2606
- toolNamePrefix,
2607
- options.customInstructions ?? [],
2608
- options.scripts ?? {},
2609
- options.toolFormat === "native"
2610
- );
2611
- super(architectAgentInfo.name, options.ai, {
2612
- systemPrompt,
2613
- tools,
2614
- toolNamePrefix,
2615
- provider: options.provider,
2616
- agents: options.agents,
2617
- scripts: options.scripts,
2618
- callback: options.callback,
2619
- policies: options.policies,
2620
- toolFormat: options.toolFormat,
2621
- parameters: options.parameters ?? {},
2622
- usageMeter: options.usageMeter ?? new UsageMeter(),
2623
- requestTimeoutSeconds: options.requestTimeoutSeconds,
2624
- requireToolUse: options.requireToolUse ?? true
2625
- });
2626
- }
2627
- onBeforeInvokeTool() {
2628
- return Promise.resolve(void 0);
2629
- }
2630
- };
2631
- var architectAgentInfo = {
2632
- name: "architect",
2633
- responsibilities: [
2634
- "Analyzing the user\u2019s overall task and requirements.",
2635
- "Creating plans and making higher-level decisions about system structure and design.",
2636
- "Reviewing and analyzing existing code or components for maintainability and scalability.",
2637
- "Laying out the roadmap for implementation."
2638
- ]
2639
- };
2640
-
2641
- // src/Agent/CodeFixerAgent/prompts.ts
2642
- var basePrompt = `You are a highly skilled software engineer specializing in debugging and fixing code issues. You have extensive experience with:
2643
- - Type systems and type checking
2644
- - Test frameworks and debugging test failures
2645
- - Code quality tools and best practices
2646
- - Systematic debugging approaches`;
2647
- var codeFixingStrategies = `
2648
- ====
2649
-
2650
- CODE FIXING STRATEGIES
2651
-
2652
- 1. Type Errors
2653
- - Analyze type error messages carefully
2654
- - Check type definitions and imports
2655
- - Consider type assertions only as a last resort
2656
- - Verify type compatibility across function boundaries
2657
- - Look for null/undefined handling issues
2658
-
2659
- 2. Test Failures
2660
- - Examine test output and error messages
2661
- - Check test setup and fixtures
2662
- - Verify assertions and expectations
2663
- - Look for async/timing issues
2664
- - Consider edge cases and input validation
2665
-
2666
- 3. Code Quality Issues
2667
- - Follow project's coding standards
2668
- - Address linter warnings systematically
2669
- - Improve code readability
2670
- - Fix potential runtime issues
2671
- - Consider performance implications
2672
-
2673
- 4. General Approach
2674
- - Start with the most critical issues
2675
- - Make minimal necessary changes
2676
- - Verify fixes don't introduce new issues
2677
- - Document complex fixes with comments
2678
- - Track attempted solutions for each issue`;
2679
- var retryGuidelines = `
2680
- ====
2681
-
2682
- RETRY GUIDELINES
2683
-
2684
- 1. Before Retrying
2685
- - Analyze previous attempt's failure
2686
- - Consider alternative approaches
2687
- - Check if similar issues were fixed
2688
- - Verify no new issues were introduced
2689
-
2690
- 2. When to Retry
2691
- - Error message changed but issue persists
2692
- - New information available about the root cause
2693
- - Different fixing strategy available
2694
- - Previous attempt partially successful
2695
-
2696
- 3. When to Stop
2697
- - Maximum retry limit reached
2698
- - Same error occurs repeatedly
2699
- - Fix would require major refactoring
2700
- - Issue requires human intervention
2701
-
2702
- 4. After Maximum Retries
2703
- - Document attempted solutions
2704
- - Explain why the issue remains
2705
- - Suggest manual intervention steps
2706
- - Report any partial improvements`;
2707
- var fullSystemPrompt3 = (info, tools, toolNamePrefix, instructions, scripts, useNativeTool) => `
2708
- ${basePrompt}
2709
- ${toolUsePrompt(useNativeTool, tools, toolNamePrefix)}
2710
- ${codeFixingStrategies}
2711
- ${retryGuidelines}
2712
- ${capabilities(toolNamePrefix)}
2713
- ${systemInformation(info)}
2714
- ${customInstructions(instructions)}
2715
- ${customScripts(scripts)}`;
2716
-
2717
- // src/Agent/CodeFixerAgent/index.ts
2718
- var agentTools3 = [
2719
- attemptCompletion_default,
2720
- delegate_default,
2721
- executeCommand_default,
2722
- fetchUrl_default,
2723
- handOver_default,
2724
- listFiles_default,
2725
- readBinaryFile_default,
2726
- readFile_default,
2727
- removeFile_default,
2728
- renameFile_default,
2729
- replaceInFile_default,
2730
- searchFiles_default,
2731
- writeToFile_default
2732
- ];
2733
- var CodeFixerAgent = class extends AgentBase {
2734
- #maxRetries;
2735
- #retryCount = 0;
2736
- constructor(options) {
2737
- const combinedTools = [...options.additionalTools ?? [], ...agentTools3];
2738
- const tools = getAvailableTools({
2739
- provider: options.provider,
2740
- allTools: combinedTools,
2741
- hasAgent: (options.agents?.length ?? 0) > 0
2742
- });
2743
- const toolNamePrefix = options.toolFormat === "native" ? "" : "tool_";
2744
- const systemPrompt = fullSystemPrompt3(
2745
- {
2746
- os: options.os
2747
- },
2748
- tools,
2749
- toolNamePrefix,
2750
- options.customInstructions ?? [],
2751
- options.scripts ?? {},
2752
- options.toolFormat === "native"
2753
- );
2754
- super(codeFixerAgentInfo.name, options.ai, {
2755
- systemPrompt,
2756
- tools,
2757
- toolNamePrefix,
2758
- provider: options.provider,
2759
- agents: options.agents,
2760
- scripts: options.scripts,
2761
- callback: options.callback,
2762
- policies: options.policies,
2763
- toolFormat: options.toolFormat,
2764
- parameters: options.parameters ?? {},
2765
- usageMeter: options.usageMeter ?? new UsageMeter(),
2766
- requestTimeoutSeconds: options.requestTimeoutSeconds,
2767
- requireToolUse: options.requireToolUse ?? true
2768
- });
2769
- this.#maxRetries = options.maxRetries ?? 5;
2770
- }
2771
- async onBeforeInvokeTool(name, _args) {
2772
- if (name === attemptCompletion_default.name) {
2773
- if (this.#retryCount > this.#maxRetries) {
2774
- return;
2775
- }
2776
- this.#retryCount++;
2777
- const executeCommand = this.config.provider.executeCommand;
2778
- if (!executeCommand) {
2779
- return;
2780
- }
2781
- const check = this.config.scripts?.check;
2782
- const checkCommand = typeof check === "string" ? check : check?.command;
2783
- if (checkCommand) {
2784
- try {
2785
- const { exitCode, stdout, stderr } = await executeCommand(checkCommand, false);
2786
- if (exitCode !== 0) {
2787
- return {
2788
- type: "Reply" /* Reply */,
2789
- message: {
2790
- type: "error-text",
2791
- value: responsePrompts.commandResult(checkCommand, exitCode, stdout, stderr)
2792
- }
2793
- };
2794
- }
2795
- } catch (error) {
2796
- console.warn(`Failed to check code using command: ${checkCommand}`, error);
2797
- }
2798
- }
2799
- const test = this.config.scripts?.test;
2800
- const testCommand = typeof test === "string" ? test : test?.command;
2801
- if (testCommand) {
2802
- try {
2803
- const { exitCode, stdout, stderr } = await executeCommand(testCommand, false);
2804
- if (exitCode !== 0) {
2805
- return {
2806
- type: "Reply" /* Reply */,
2807
- message: {
2808
- type: "error-text",
2809
- value: responsePrompts.commandResult(testCommand, exitCode, stdout, stderr)
2810
- }
2811
- };
2812
- }
2813
- } catch (error) {
2814
- console.warn(`Failed to test code using command: ${testCommand}`, error);
2815
- }
2816
- }
2817
- }
2818
- }
2819
- };
2820
- var codeFixerAgentInfo = {
2821
- name: "codefixer",
2822
- responsibilities: [
2823
- "Fixing type errors and type-related issues",
2824
- "Resolving failing tests",
2825
- "Addressing code quality issues",
2826
- "Tracking and reporting unfixed issues"
2827
- ]
2828
- };
2829
-
2830
- // src/Agent/CoderAgent/prompts.ts
2831
- var basePrompt2 = "You are a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.";
2832
- var editingFilesPrompt = (toolNamePrefix) => `
2833
- ====
2834
-
2835
- EDITING FILES
2836
-
2837
- You have two file-manipulation tools: **${toolNamePrefix}write_to_file** (full overwrite) and **${toolNamePrefix}replace_in_file** (targeted anchor-based edits). Choose the smallest safe operation for every change.
2838
-
2839
- # ${toolNamePrefix}write_to_file
2840
-
2841
- ## Purpose
2842
-
2843
- - Create a new file, or overwrite the entire contents of an existing file.
2844
-
2845
- ## When to Use
2846
-
2847
- - Initial file creation, such as when scaffolding a new project.
2848
- - Overwriting large boilerplate files where you want to replace the entire content at once.
2849
- - When the complexity or number of changes would make ${toolNamePrefix}replace_in_file unwieldy or error-prone.
2850
- - When you need to completely restructure a file's content or change its fundamental organization.
2851
-
2852
- ## Important Considerations
2853
-
2854
- - Using ${toolNamePrefix}write_to_file requires providing the file's complete final content.
2855
- - If you only need to make small changes to an existing file, consider using ${toolNamePrefix}replace_in_file instead to avoid unnecessarily rewriting the entire file.
2856
- - While ${toolNamePrefix}write_to_file should not be your default choice, don't hesitate to use it when the situation truly calls for it.
2857
-
2858
- # ${toolNamePrefix}replace_in_file
2859
-
2860
- ## Purpose
2861
-
2862
- - Make targeted edits to specific parts of an existing file without overwriting the entire file.
2863
-
2864
- ## When to Use
2865
-
2866
- - Small, localized changes like updating a few lines, function implementations, changing variable names, modifying a section of text, etc.
2867
- - Targeted improvements where only specific portions of the file's content needs to be altered.
2868
- - Especially useful for long files where much of the file will remain unchanged.
2869
-
2870
- ## Advantages
2871
-
2872
- - More efficient for minor edits, since you don't need to supply the entire file content.
2873
- - Reduces the chance of errors that can occur when overwriting large files.
2874
-
2875
- # Choosing the Appropriate Tool
2876
-
2877
- - **Default to ${toolNamePrefix}replace_in_file** for most changes. It keeps diffs small and reduces risk.
2878
- - **Use ${toolNamePrefix}write_to_file** when:
2879
- - Creating new files
2880
- - The changes are so extensive that using ${toolNamePrefix}replace_in_file would be more complex or risky
2881
- - You need to completely reorganize or restructure a file
2882
- - The file is relatively small and the changes affect most of its content
2883
- - You're generating boilerplate or template files
2884
-
2885
- # Workflow Tips
2886
-
2887
- 1. Before editing, assess the scope of your changes and decide which tool to use.
2888
- 2. For targeted edits, apply ${toolNamePrefix}replace_in_file with carefully crafted before/after text anchors. If you need multiple changes, you can stack multiple operations within a single ${toolNamePrefix}replace_in_file call.
2889
- 3. For major overhauls or initial file creation, rely on ${toolNamePrefix}write_to_file.
2890
- 4. Once the file has been edited with either ${toolNamePrefix}write_to_file or ${toolNamePrefix}replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent operations, since it reflects any auto-formatting or user-applied changes.
2891
-
2892
- Picking the right tool keeps edits minimal, safe, and easy to review.
2893
- `;
2894
- var rules = (toolNamePrefix) => `
2895
- ====
2896
-
2897
- RULES
2898
-
2899
- - Work only with relative paths; you may \`cd\` into child directories but never use \`cd ..\`, root, or absolute paths.
2900
- - When generating code, tests, or other comment-capable files, prepend a comment describing the file's purpose plus \u201Cgenerated by polka.codes\u201D.
2901
- For text files (e.g. README.md), append a footer with the same notice.
2902
- - Never describe what changed inside code comments; comments must focus on purpose or usage only.
2903
- - Before using ${toolNamePrefix}execute_command, consider SYSTEM INFORMATION to ensure commands suit the user's OS. If a command must run in a subdirectory, prepend a single \`cd childDir &&\` segment.
2904
- - Use ${toolNamePrefix}search_files for broad analysis, then ${toolNamePrefix}read_file to inspect context, and finally ${toolNamePrefix}replace_in_file or ${toolNamePrefix}write_to_file to modify.
2905
- - Prefer ${toolNamePrefix}replace_in_file for focused edits; choose ${toolNamePrefix}write_to_file for new files or complete rewrites.
2906
- - When creating a new file, look for existing files with similar content or patterns; if found, read them and use their structure or conventions as a reference.
2907
- - Use before/after text anchors in ${toolNamePrefix}replace_in_file to target changes. If multiple operations are needed, list them in file order.
2908
- - Do not guess unseen content. Read existing files first unless creating new ones.
2909
- - Follow existing style, lint, and naming conventions. Ensure all changes compile and pass tests where applicable.
2910
- - ALWAYS wait for the user's confirmation after each tool call before starting the next step.
2911
- - The agent must never invoke more than 5 tools in a single response.
2912
- - Do not end ${toolNamePrefix}attempt_completion output with questions or conversational prompts.
2913
- - Avoid filler words like \u201CGreat\u201D, \u201CCertainly\u201D, \u201COkay\u201D, \u201CSure\u201D at the start of responses; be direct and technical.
2914
- - Keep inline documentation current as you edit.
2915
- `;
2916
- var objectives = (toolNamePrefix) => `
2917
- ====
2918
-
2919
- OBJECTIVE
2920
-
2921
- You solve the user's task by working in small, verifiable steps.
2922
-
2923
- 1. **Plan** - Parse the task, list clear goals, and order them logically.
2924
- 2. **Think** - Wrap private reasoning in <thinking></thinking>.
2925
- \u2022 Review project context.
2926
- \u2022 Select the single best tool for the next goal.
2927
- \u2022 Ensure every required parameter is available or can be inferred.
2928
- 3. **Act** - Invoke one tool per step. Wait for the system's response (and user confirmation where required) before continuing.
2929
- 4. **Iterate** - Repeat Plan \u2192 Think \u2192 Act until all goals are complete.
2930
- 5. **Complete** - Use ${toolNamePrefix}attempt_completion to deliver the final result. Do not invite further discussion unless the user explicitly requests changes.
2931
- `;
2932
- var fullSystemPrompt4 = (info, tools, toolNamePrefix, instructions, scripts, useNativeTool) => `
2933
- ${basePrompt2}
2934
- ${toolUsePrompt(useNativeTool, tools, toolNamePrefix)}
2935
- ${editingFilesPrompt(toolNamePrefix)}
2936
- ${capabilities(toolNamePrefix)}
2937
- ${rules(toolNamePrefix)}
2938
- ${objectives(toolNamePrefix)}
2939
- ${systemInformation(info)}
2940
- ${customInstructions(instructions)}
2941
- ${customScripts(scripts)}
2942
- `;
2943
-
2944
- // src/Agent/CoderAgent/index.ts
2945
- var agentTools4 = [
2946
- attemptCompletion_default,
2947
- delegate_default,
2948
- executeCommand_default,
2949
- fetchUrl_default,
2950
- handOver_default,
2951
- listFiles_default,
2952
- readBinaryFile_default,
2953
- readFile_default,
2954
- removeFile_default,
2955
- renameFile_default,
2956
- replaceInFile_default,
2957
- searchFiles_default,
2958
- writeToFile_default
2959
- ];
2960
- var CoderAgent = class extends AgentBase {
2961
- constructor(options) {
2962
- const combinedTools = [...options.additionalTools ?? [], ...agentTools4];
2963
- const tools = getAvailableTools({
2964
- provider: options.provider,
2965
- allTools: combinedTools,
2966
- hasAgent: (options.agents?.length ?? 0) > 0
2967
- });
2968
- const toolNamePrefix = options.toolFormat === "native" ? "" : "tool_";
2969
- const systemPrompt = fullSystemPrompt4(
2970
- {
2971
- os: options.os
2972
- },
2973
- tools,
2974
- toolNamePrefix,
2975
- options.customInstructions ?? [],
2976
- options.scripts ?? {},
2977
- options.toolFormat === "native"
2978
- );
2979
- super(coderAgentInfo.name, options.ai, {
2980
- systemPrompt,
2981
- tools,
2982
- toolNamePrefix,
2983
- provider: options.provider,
2984
- agents: options.agents,
2985
- scripts: options.scripts,
2986
- callback: options.callback,
2987
- policies: options.policies,
2988
- toolFormat: options.toolFormat,
2989
- parameters: options.parameters ?? {},
2990
- usageMeter: options.usageMeter ?? new UsageMeter(),
2991
- requestTimeoutSeconds: options.requestTimeoutSeconds,
2992
- requireToolUse: options.requireToolUse ?? true
2993
- });
2994
- }
2995
- async #runScript(scriptName, shouldReplyWithError) {
2996
- const executeCommand = this.config.provider.executeCommand;
2997
- if (!executeCommand) {
2998
- return;
2999
- }
3000
- const script = this.config.scripts?.[scriptName];
3001
- const command = typeof script === "string" ? script : script?.command;
3002
- if (command) {
3003
- try {
3004
- const { exitCode, stdout, stderr } = await executeCommand(command, false);
3005
- if (exitCode !== 0 && shouldReplyWithError) {
3006
- return {
3007
- type: "Reply" /* Reply */,
3008
- message: {
3009
- type: "error-text",
3010
- value: responsePrompts.commandResult(command, exitCode, stdout, stderr)
3011
- }
3012
- };
3013
- }
3014
- } catch (error) {
3015
- console.warn(`Failed to run ${scriptName} using command: ${command}`, error);
3016
- }
3017
- }
3018
- }
3019
- async onBeforeInvokeTool(name, _args) {
3020
- if (name !== attemptCompletion_default.name) {
3021
- return;
3022
- }
3023
- await this.#runScript("format", false);
3024
- const checkResult = await this.#runScript("check", true);
3025
- if (checkResult) {
3026
- return checkResult;
3027
- }
3028
- const testResult = await this.#runScript("test", true);
3029
- if (testResult) {
3030
- return testResult;
3031
- }
3032
- }
3033
- };
3034
- var coderAgentInfo = {
3035
- name: "coder",
3036
- responsibilities: [
3037
- "Editing and refactoring existing code.",
3038
- "Creating new features or modules.",
3039
- "Running tests and analyzing test results.",
3040
- "Maintaining coding standards, lint rules, and general code quality."
3041
- ]
3042
- };
3043
-
3044
- // src/Agent/MultiAgent.ts
3045
- var MultiAgent = class {
3046
- #config;
3047
- #agents = [];
3048
- #originalTask;
3049
- constructor(config) {
3050
- this.#config = config;
3051
- }
3052
- async #handleTaskResult(exitReason) {
3053
- switch (exitReason.type) {
3054
- case "HandOver" /* HandOver */: {
3055
- this.#agents.pop();
3056
- const prompt = await this.#config.getPrompt?.(
3057
- exitReason.agentName,
3058
- exitReason.task,
3059
- exitReason.context,
3060
- exitReason.files,
3061
- this.#originalTask
3062
- ) ?? exitReason.task;
3063
- return await this.#startTask(exitReason.agentName, prompt);
3064
- }
3065
- case "Delegate" /* Delegate */: {
3066
- const prompt = await this.#config.getPrompt?.(
3067
- exitReason.agentName,
3068
- exitReason.task,
3069
- exitReason.context,
3070
- exitReason.files,
3071
- this.#originalTask
3072
- ) ?? exitReason.task;
3073
- const delegateResult = await this.#startTask(exitReason.agentName, prompt);
3074
- switch (delegateResult.type) {
3075
- case "HandOver" /* HandOver */:
3076
- case "Delegate" /* Delegate */:
3077
- console.warn("Unexpected exit reason", delegateResult);
3078
- break;
3079
- case "Aborted":
3080
- case "Interrupted" /* Interrupted */:
3081
- return delegateResult;
3082
- case "Exit" /* Exit */:
3083
- return this.continueTask(delegateResult.message);
3084
- }
3085
- return delegateResult;
3086
- }
3087
- case "Aborted":
3088
- case "Interrupted" /* Interrupted */:
3089
- case "Exit" /* Exit */:
3090
- this.#agents.pop();
3091
- return exitReason;
3092
- default:
3093
- return exitReason;
3094
- }
3095
- }
3096
- async #startTask(agentName, task) {
3097
- const newAgent = await this.#config.createAgent(agentName);
3098
- this.#agents.push(newAgent);
3099
- const exitReason = await newAgent.start(task);
3100
- return await this.#handleTaskResult(exitReason);
3101
- }
3102
- async startTask(options) {
3103
- if (this.#agents.length > 0) {
3104
- throw new Error("An active agent already exists");
3105
- }
3106
- this.#originalTask = options.task;
3107
- const userContent = options.files ?? [];
3108
- userContent.push({
3109
- type: "text",
3110
- text: `<task>${options.task}</task>
3111
- <context>${options.context}</context>`
3112
- });
3113
- return this.#startTask(options.agentName, userContent);
3114
- }
3115
- async continueTask(userMessage) {
3116
- if (!this.#agents.length) {
3117
- throw new Error("No active agent");
3118
- }
3119
- const exitReason = await this.#agents[this.#agents.length - 1].continueTask(userMessage);
3120
- return await this.#handleTaskResult(exitReason);
3121
- }
3122
- get hasActiveAgent() {
3123
- return this.#agents.length > 0;
3124
- }
3125
- abort() {
3126
- if (this.hasActiveAgent) {
3127
- this.#agents[this.#agents.length - 1].abort();
3128
- }
3129
- }
3130
- };
3131
-
3132
- // src/Agent/parseJsonFromMarkdown.ts
3133
- var parseJsonFromMarkdown = (markdown) => {
3134
- const jsonRegex = /```(?:json)?\n([\s\S]*?)\n```/;
3135
- const match = markdown.match(jsonRegex);
3136
- const tryParse = (str) => {
3137
- try {
3138
- let parsed = JSON.parse(str);
3139
- if (typeof parsed === "string") {
3140
- try {
3141
- parsed = JSON.parse(parsed);
3142
- } catch {
3143
- }
3144
- }
3145
- return { success: true, data: parsed };
3146
- } catch (e) {
3147
- const error = e instanceof Error ? e.message : String(e);
3148
- return { success: false, error: `Failed to parse JSON: ${error}` };
3149
- }
3150
- };
3151
- if (match?.[1]) {
3152
- const content = match[1].trim();
3153
- return tryParse(content);
3154
- }
3155
- const parseResult = tryParse(markdown);
3156
- if (parseResult.success) {
3157
- return parseResult;
3158
- }
3159
- return { success: false, error: "No JSON object found in the string." };
3160
- };
3161
-
3162
- // src/config.ts
3163
- import { z as z16 } from "zod";
3164
- var toolFormatSchema = z16.enum(["native", "polka-codes"]).optional();
3165
- var providerModelSchema = z16.object({
3166
- provider: z16.string().optional(),
3167
- model: z16.string().optional(),
3168
- parameters: z16.record(z16.string(), z16.any()).optional(),
3169
- toolFormat: toolFormatSchema
3170
- });
3171
- var agentSchema = providerModelSchema.extend({
3172
- initialContext: z16.object({
3173
- maxFileCount: z16.number().int().positive().optional(),
3174
- excludes: z16.array(z16.string()).optional()
3175
- }).optional(),
3176
- retryCount: z16.number().int().min(0).optional(),
3177
- requestTimeoutSeconds: z16.number().int().positive().optional()
3178
- });
3179
- var configSchema = z16.object({
3180
- agent: z16.string().optional(),
3181
- prices: z16.record(
3182
- z16.string(),
3183
- // provider
3184
- z16.record(
3185
- z16.string(),
3186
- // model
3187
- z16.object({
3188
- inputPrice: z16.number().optional(),
3189
- outputPrice: z16.number().optional(),
3190
- cacheWritesPrice: z16.number().optional(),
3191
- cacheReadsPrice: z16.number().optional()
3192
- })
3193
- )
3194
- ).optional(),
3195
- providers: z16.record(
3196
- z16.string(),
3197
- z16.object({
3198
- apiKey: z16.string().optional(),
3199
- defaultModel: z16.string().optional(),
3200
- defaultParameters: z16.record(z16.string(), z16.any()).optional(),
3201
- location: z16.string().optional(),
3202
- project: z16.string().optional(),
3203
- keyFile: z16.string().optional()
3204
- })
3205
- ).optional(),
3206
- defaultProvider: z16.string().optional(),
3207
- defaultModel: z16.string().optional(),
3208
- defaultParameters: z16.record(z16.string(), z16.any()).optional(),
3209
- toolFormat: toolFormatSchema,
3210
- maxMessageCount: z16.number().int().positive().optional(),
3211
- budget: z16.number().positive().optional(),
3212
- retryCount: z16.number().int().min(0).optional(),
3213
- requestTimeoutSeconds: z16.number().int().positive().optional(),
3214
- summaryThreshold: z16.number().int().positive().optional(),
3215
- scripts: z16.record(
3216
- z16.string(),
3217
- z16.string().or(
3218
- z16.object({
3219
- command: z16.string(),
3220
- description: z16.string()
3221
- })
3222
- )
3223
- ).optional(),
3224
- agents: z16.record(z16.string(), agentSchema).optional(),
3225
- commands: z16.object({
3226
- default: providerModelSchema.optional()
3227
- }).catchall(providerModelSchema).optional(),
3228
- rules: z16.array(z16.string()).optional().or(z16.string()).optional(),
3229
- excludeFiles: z16.array(z16.string()).optional(),
3230
- policies: z16.array(z16.string()).optional()
3231
- }).strict();
3232
- var Policies = /* @__PURE__ */ ((Policies2) => {
3233
- Policies2["TruncateContext"] = "truncatecontext";
3234
- Policies2["EnableCache"] = "enablecache";
3235
- return Policies2;
3236
- })(Policies || {});
3237
-
3238
- // src/Agent/policies/EnableCachePolicy.ts
3239
- var CACHEABLE_MODELS = ["sonnet", "opus", "haiku", "gemini"];
3240
- function isCacheableModel(modelId) {
3241
- return CACHEABLE_MODELS.some((model) => modelId.includes(model));
3242
- }
3243
- function getProviderKey(provider) {
3244
- if (provider === "openrouter") {
3245
- return "openrouter";
3246
- }
3247
- if (provider.includes("anthropic")) {
3248
- return "anthropic";
3249
- }
3250
- return void 0;
3251
- }
3252
- var EnableCachePolicy = () => {
3253
- return {
3254
- name: "enablecache" /* EnableCache */,
3255
- async prepareMessages(agent, messages) {
3256
- const providerKey = getProviderKey(agent.ai.provider);
3257
- if (!providerKey || !isCacheableModel(agent.ai.modelId)) {
3258
- return messages;
3259
- }
3260
- const providerOptions = { [providerKey]: { cacheControl: { type: "ephemeral" } } };
3261
- const newMessages = messages.slice();
3262
- let userMessagesToUpdate = 2;
3263
- for (let i = newMessages.length - 1; i >= 0; i--) {
3264
- const message = newMessages[i];
3265
- if (message.role === "user" && userMessagesToUpdate > 0) {
3266
- newMessages[i] = {
3267
- ...message,
3268
- providerOptions: {
3269
- ...providerOptions,
3270
- ...message.providerOptions ?? {}
3271
- }
3272
- };
3273
- userMessagesToUpdate--;
3274
- } else if (message.role === "system") {
3275
- newMessages[i] = {
3276
- ...message,
3277
- providerOptions: {
3278
- ...providerOptions,
3279
- ...message.providerOptions ?? {}
3280
- }
3281
- };
3282
- break;
3283
- }
3284
- }
3285
- return newMessages;
3286
- }
3287
- };
3288
- };
3289
-
3290
- // src/Agent/policies/TruncateContextPolicy.ts
3291
- var DEFAULT_MAX_TOKENS_ESTIMATE = 32e3;
3292
- function getMaxTokens(agent) {
3293
- const params = agent.parameters || {};
3294
- if (params.maxTokens && typeof params.maxTokens === "number" && params.maxTokens > 0) {
3295
- return params.maxTokens;
3296
- }
3297
- return DEFAULT_MAX_TOKENS_ESTIMATE;
3298
- }
3299
- function estimateTokens(text) {
3300
- return Math.ceil(text.length / 4);
3301
- }
3302
- function estimateMessageTokens(msg) {
3303
- if (typeof msg.content === "string") {
3304
- return estimateTokens(msg.content);
3305
- }
3306
- if (Array.isArray(msg.content)) {
3307
- let messageTokens = 0;
3308
- for (const block of msg.content) {
3309
- if (typeof block === "object" && "text" in block && typeof block.text === "string") {
3310
- messageTokens += estimateTokens(block.text);
3311
- }
3312
- }
3313
- return messageTokens;
3314
- }
3315
- return 0;
3316
- }
3317
- var TruncateContextPolicy = (() => {
3318
- return {
3319
- name: "truncatecontext" /* TruncateContext */,
3320
- async onBeforeRequest(agent) {
3321
- const messages = agent.messages;
3322
- if (messages.length < 3) {
3323
- return;
3324
- }
3325
- let totalTokens = messages.reduce((acc, msg) => acc + estimateMessageTokens(msg), 0);
3326
- const maxTokens = getMaxTokens(agent);
3327
- if (totalTokens <= maxTokens) {
3328
- return;
3329
- }
3330
- const protectedIndices = /* @__PURE__ */ new Set();
3331
- let userMessagesFound = 0;
3332
- messages.forEach((msg, index) => {
3333
- if (msg.role === "system") {
3334
- protectedIndices.add(index);
3335
- }
3336
- if (msg.role === "user") {
3337
- if (userMessagesFound < 2) {
3338
- protectedIndices.add(index);
3339
- }
3340
- userMessagesFound++;
3341
- }
3342
- });
3343
- if (messages.length > 0) {
3344
- protectedIndices.add(messages.length - 1);
3345
- }
3346
- const truncatableIndices = [];
3347
- for (let i = 0; i < messages.length; i++) {
3348
- if (!protectedIndices.has(i)) {
3349
- truncatableIndices.push(i);
3350
- }
3351
- }
3352
- const removedIndices = /* @__PURE__ */ new Set();
3353
- const initialTotalTokens = totalTokens;
3354
- while (totalTokens > maxTokens && truncatableIndices.length > 0) {
3355
- const middleIndex = Math.floor(truncatableIndices.length / 2);
3356
- const indexToRemove = truncatableIndices.splice(middleIndex, 1)[0];
3357
- removedIndices.add(indexToRemove);
3358
- totalTokens -= estimateMessageTokens(messages[indexToRemove]);
3359
- }
3360
- if (removedIndices.size === 0) {
3361
- if (initialTotalTokens > maxTokens) {
3362
- console.warn("Warning: Protected messages exceed token limit. Cannot truncate further.");
3363
- }
3364
- return;
3365
- }
3366
- const truncatedMessages = [];
3367
- let truncationNoticeAdded = false;
3368
- for (let i = 0; i < messages.length; i++) {
3369
- if (removedIndices.has(i)) {
3370
- if (!truncationNoticeAdded) {
3371
- truncatedMessages.push({
3372
- role: "user",
3373
- content: `Note: ${removedIndices.size} messages were truncated from the conversation to prevent context overflow.`
3374
- });
3375
- truncationNoticeAdded = true;
3376
- }
3377
- } else {
3378
- truncatedMessages.push(messages[i]);
3379
- }
3380
- }
3381
- console.log(`Truncated context: removed ${removedIndices.size} messages.`);
3382
- agent.setMessages(truncatedMessages);
3383
- }
3384
- };
3385
- });
3386
-
3387
- // src/Agent/index.ts
3388
- var allAgents = [architectAgentInfo, coderAgentInfo, analyzerAgentInfo, codeFixerAgentInfo];
3389
1485
  export {
3390
- AgentBase,
3391
- AnalyzerAgent,
3392
- ArchitectAgent,
3393
- CodeFixerAgent,
3394
- CoderAgent,
3395
- EnableCachePolicy,
3396
1486
  MockProvider,
3397
- MultiAgent,
3398
- Policies,
3399
- TaskEventKind,
3400
1487
  ToolResponseType,
3401
- TruncateContextPolicy,
3402
1488
  UsageMeter,
3403
- agentsPrompt,
3404
- allAgents,
3405
- analyzerAgentInfo,
3406
- architectAgentInfo,
3407
1489
  askFollowupQuestion_default as askFollowupQuestion,
3408
- attemptCompletion_default as attemptCompletion,
3409
- capabilities,
3410
- codeFixerAgentInfo,
3411
- coderAgentInfo,
3412
1490
  computeRateLimitBackoffSeconds,
3413
1491
  configSchema,
3414
- customInstructions,
3415
- customScripts,
3416
- delegate_default as delegate,
3417
1492
  executeCommand_default as executeCommand,
3418
1493
  fetchUrl_default as fetchUrl,
3419
- getAvailableTools,
3420
- handOver_default as handOver,
3421
1494
  listFiles_default as listFiles,
3422
- parseAssistantMessage,
1495
+ listMemoryTopics_default as listMemoryTopics,
3423
1496
  parseJsonFromMarkdown,
3424
1497
  readBinaryFile_default as readBinaryFile,
3425
1498
  readFile_default as readFile,
1499
+ readMemory_default as readMemory,
3426
1500
  removeFile_default as removeFile,
3427
1501
  renameFile_default as renameFile,
3428
1502
  replaceInFile_default as replaceInFile,
3429
1503
  replaceInFile as replaceInFileHelper,
3430
1504
  responsePrompts,
3431
1505
  searchFiles_default as searchFiles,
3432
- systemInformation,
3433
- toolUsePrompt,
1506
+ updateMemory_default as updateMemory,
3434
1507
  writeToFile_default as writeToFile
3435
1508
  };