@polka-codes/core 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +542 -262
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2865,62 +2865,11 @@ Anthropic.Models = Models2;
2865
2865
  Anthropic.ModelInfosPage = ModelInfosPage;
2866
2866
  Anthropic.Beta = Beta;
2867
2867
 
2868
- // src/AiService/UsageMeter.ts
2869
- class UsageMeter {
2870
- #usage = {
2871
- inputTokens: 0,
2872
- outputTokens: 0,
2873
- cacheWriteTokens: 0,
2874
- cacheReadTokens: 0,
2875
- totalCost: 0
2876
- };
2877
- #messageCount = 0;
2878
- maxCost;
2879
- maxMessageCount;
2880
- constructor(options = {}) {
2881
- this.maxCost = options.maxCost || 1000;
2882
- this.maxMessageCount = options.maxMessageCount || 1000;
2883
- }
2884
- addUsage(usage, model) {
2885
- this.#usage.inputTokens += usage.inputTokens ?? 0;
2886
- this.#usage.outputTokens += usage.outputTokens ?? 0;
2887
- this.#usage.cacheWriteTokens += usage.cacheWriteTokens ?? 0;
2888
- this.#usage.cacheReadTokens += usage.cacheReadTokens ?? 0;
2889
- if (!usage.totalCost && model) {
2890
- usage.totalCost = ((model.inputPrice ?? 0) * (usage.inputTokens ?? 0) + (model.outputPrice ?? 0) * (usage.outputTokens ?? 0) + (model.cacheWritesPrice ?? 0) * (usage.cacheWriteTokens ?? 0) + (model.cacheReadsPrice ?? 0) * (usage.cacheReadTokens ?? 0)) / 1e6;
2891
- }
2892
- this.#usage.totalCost += usage.totalCost ?? 0;
2893
- }
2894
- incrementMessageCount(count = 1) {
2895
- this.#messageCount += count;
2896
- }
2897
- isLimitExceeded() {
2898
- const messageCount = this.#messageCount >= this.maxMessageCount;
2899
- const cost = this.#usage.totalCost >= this.maxCost;
2900
- return {
2901
- messageCount,
2902
- cost,
2903
- result: messageCount || cost
2904
- };
2905
- }
2906
- get usage() {
2907
- return { ...this.#usage };
2908
- }
2909
- printUsage() {
2910
- console.log("Usages:");
2911
- console.log(`Input tokens: ${this.#usage.inputTokens}`);
2912
- console.log(`Output tokens: ${this.#usage.outputTokens}`);
2913
- console.log(`Cache read tokens: ${this.#usage.cacheReadTokens}`);
2914
- console.log(`Cache write tokens: ${this.#usage.cacheWriteTokens}`);
2915
- console.log(`Total cost: ${this.#usage.totalCost}`);
2916
- }
2917
- }
2918
-
2919
2868
  // src/AiService/AiServiceBase.ts
2920
2869
  class AiServiceBase {
2921
2870
  usageMeter;
2922
2871
  constructor(usageMeter) {
2923
- this.usageMeter = usageMeter ?? new UsageMeter;
2872
+ this.usageMeter = usageMeter;
2924
2873
  }
2925
2874
  async* send(systemPrompt, messages) {
2926
2875
  this.usageMeter.incrementMessageCount();
@@ -8156,6 +8105,61 @@ class OpenRouterService extends AiServiceBase {
8156
8105
  }
8157
8106
  }
8158
8107
 
8108
+ // src/AiService/UsageMeter.ts
8109
+ class UsageMeter {
8110
+ #usage = {
8111
+ inputTokens: 0,
8112
+ outputTokens: 0,
8113
+ cacheWriteTokens: 0,
8114
+ cacheReadTokens: 0,
8115
+ totalCost: 0
8116
+ };
8117
+ #messageCount = 0;
8118
+ maxCost;
8119
+ maxMessageCount;
8120
+ constructor(options = {}) {
8121
+ this.maxCost = options.maxCost || 1000;
8122
+ this.maxMessageCount = options.maxMessageCount || 1000;
8123
+ }
8124
+ addUsage(usage, model) {
8125
+ this.#usage.inputTokens += usage.inputTokens ?? 0;
8126
+ this.#usage.outputTokens += usage.outputTokens ?? 0;
8127
+ this.#usage.cacheWriteTokens += usage.cacheWriteTokens ?? 0;
8128
+ this.#usage.cacheReadTokens += usage.cacheReadTokens ?? 0;
8129
+ if (!usage.totalCost && model) {
8130
+ usage.totalCost = ((model.inputPrice ?? 0) * (usage.inputTokens ?? 0) + (model.outputPrice ?? 0) * (usage.outputTokens ?? 0) + (model.cacheWritesPrice ?? 0) * (usage.cacheWriteTokens ?? 0) + (model.cacheReadsPrice ?? 0) * (usage.cacheReadTokens ?? 0)) / 1e6;
8131
+ }
8132
+ this.#usage.totalCost += usage.totalCost ?? 0;
8133
+ }
8134
+ incrementMessageCount(count = 1) {
8135
+ this.#messageCount += count;
8136
+ }
8137
+ isLimitExceeded() {
8138
+ const messageCount = this.#messageCount >= this.maxMessageCount;
8139
+ const cost = this.#usage.totalCost >= this.maxCost;
8140
+ return {
8141
+ messageCount,
8142
+ cost,
8143
+ result: messageCount || cost
8144
+ };
8145
+ }
8146
+ get usage() {
8147
+ return { ...this.#usage };
8148
+ }
8149
+ printUsage() {
8150
+ const { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens } = this.#usage;
8151
+ const allTokensZero = inputTokens === 0 && outputTokens === 0 && cacheReadTokens === 0 && cacheWriteTokens === 0;
8152
+ console.log("Usages:");
8153
+ if (!allTokensZero) {
8154
+ console.log(`Input tokens: ${this.#usage.inputTokens}`);
8155
+ console.log(`Output tokens: ${this.#usage.outputTokens}`);
8156
+ console.log(`Cache read tokens: ${this.#usage.cacheReadTokens}`);
8157
+ console.log(`Cache write tokens: ${this.#usage.cacheWriteTokens}`);
8158
+ }
8159
+ console.log(`Total cost: ${this.#usage.totalCost}`);
8160
+ }
8161
+ }
8162
+
8159
8163
  // src/AiService/index.ts
8160
8164
  var AiServiceProvider;
8161
8165
  ((AiServiceProvider2) => {
@@ -8182,20 +8186,6 @@ var createService = (provider, options) => {
8182
8186
  return new OpenRouterService(options);
8183
8187
  }
8184
8188
  };
8185
- // src/tool.ts
8186
- var ToolResponseType;
8187
- ((ToolResponseType2) => {
8188
- ToolResponseType2["Reply"] = "Reply";
8189
- ToolResponseType2["Exit"] = "Exit";
8190
- ToolResponseType2["Invalid"] = "Invalid";
8191
- ToolResponseType2["Error"] = "Error";
8192
- ToolResponseType2["Interrupted"] = "Interrupted";
8193
- ToolResponseType2["HandOver"] = "HandOver";
8194
- })(ToolResponseType ||= {});
8195
- var getAvailableTools = (provider, allTools) => {
8196
- return allTools.filter((tool) => tool.isAvailable(provider));
8197
- };
8198
-
8199
8189
  // src/tools/provider.ts
8200
8190
  class MockProvider {
8201
8191
  async readFile(path) {
@@ -8217,7 +8207,7 @@ class MockProvider {
8217
8207
  return ["mock-file.txt"];
8218
8208
  }
8219
8209
  async listCodeDefinitionNames(path) {
8220
- return ["mockDefinition"];
8210
+ return "mockDefinition";
8221
8211
  }
8222
8212
  async executeCommand(command, needApprove) {
8223
8213
  return { stdout: "mock output", stderr: "", exitCode: 0 };
@@ -8242,6 +8232,7 @@ __export(exports_allTools, {
8242
8232
  listCodeDefinitionNames: () => listCodeDefinitionNames_default,
8243
8233
  handOver: () => handOver_default,
8244
8234
  executeCommand: () => executeCommand_default,
8235
+ delegate: () => delegate_default,
8245
8236
  attemptCompletion: () => attemptCompletion_default,
8246
8237
  askFollowupQuestion: () => askFollowupQuestion_default
8247
8238
  });
@@ -8466,8 +8457,83 @@ var attemptCompletion_default = {
8466
8457
  handler: handler2,
8467
8458
  isAvailable: isAvailable2
8468
8459
  };
8469
- // src/tools/executeCommand.ts
8460
+ // src/tools/delegate.ts
8470
8461
  var toolInfo3 = {
8462
+ name: "delegate",
8463
+ description: "Temporarily delegate a task to another agent and receive the result back",
8464
+ parameters: [
8465
+ {
8466
+ name: "agent_name",
8467
+ description: "The name of the agent to delegate the task to",
8468
+ required: true,
8469
+ usageValue: "Name of the target agent"
8470
+ },
8471
+ {
8472
+ name: "task",
8473
+ description: "The task to be completed by the target agent",
8474
+ required: true,
8475
+ usageValue: "Task description"
8476
+ },
8477
+ {
8478
+ name: "context",
8479
+ description: "The context information for the task",
8480
+ required: true,
8481
+ usageValue: "Context information"
8482
+ },
8483
+ {
8484
+ name: "files",
8485
+ description: "The files relevant to the task. Comma separated paths",
8486
+ required: false,
8487
+ usageValue: "Relevant files"
8488
+ }
8489
+ ],
8490
+ examples: [
8491
+ {
8492
+ description: "Delegate a code analysis task to the analyzer agent",
8493
+ parameters: [
8494
+ {
8495
+ name: "agent_name",
8496
+ value: "analyzer"
8497
+ },
8498
+ {
8499
+ name: "task",
8500
+ value: "Analyze the authentication implementation"
8501
+ },
8502
+ {
8503
+ name: "context",
8504
+ value: "Need to understand the security implications of the current auth system"
8505
+ },
8506
+ {
8507
+ name: "files",
8508
+ value: "src/auth/login.ts,src/auth/types.ts"
8509
+ }
8510
+ ]
8511
+ }
8512
+ ]
8513
+ };
8514
+ var handler3 = async (_provider, args) => {
8515
+ const agentName = getString(args, "agent_name");
8516
+ const task = getString(args, "task");
8517
+ const context = getString(args, "context", undefined);
8518
+ const files = getStringArray(args, "files", []);
8519
+ return {
8520
+ type: "Delegate" /* Delegate */,
8521
+ agentName,
8522
+ task,
8523
+ context,
8524
+ files
8525
+ };
8526
+ };
8527
+ var isAvailable3 = (_provider) => {
8528
+ return true;
8529
+ };
8530
+ var delegate_default = {
8531
+ ...toolInfo3,
8532
+ handler: handler3,
8533
+ isAvailable: isAvailable3
8534
+ };
8535
+ // src/tools/executeCommand.ts
8536
+ var toolInfo4 = {
8471
8537
  name: "execute_command",
8472
8538
  description: `Request to execute a CLI command on the system. Use this when you need to perform system operations or run specific commands to accomplish any step in the user's task. You must tailor your command to the user's system and provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run. Commands will also be executed in the project root directory regardless of executed commands in previous tool uses.`,
8473
8539
  parameters: [
@@ -8500,7 +8566,7 @@ var toolInfo3 = {
8500
8566
  }
8501
8567
  ]
8502
8568
  };
8503
- var handler3 = async (provider, args) => {
8569
+ var handler4 = async (provider, args) => {
8504
8570
  if (!provider.executeCommand) {
8505
8571
  return {
8506
8572
  type: "Error" /* Error */,
@@ -8529,16 +8595,16 @@ ${result.stderr}
8529
8595
  message
8530
8596
  };
8531
8597
  };
8532
- var isAvailable3 = (provider) => {
8598
+ var isAvailable4 = (provider) => {
8533
8599
  return !!provider.executeCommand;
8534
8600
  };
8535
8601
  var executeCommand_default = {
8536
- ...toolInfo3,
8537
- handler: handler3,
8538
- isAvailable: isAvailable3
8602
+ ...toolInfo4,
8603
+ handler: handler4,
8604
+ isAvailable: isAvailable4
8539
8605
  };
8540
8606
  // src/tools/listCodeDefinitionNames.ts
8541
- var toolInfo4 = {
8607
+ var toolInfo5 = {
8542
8608
  name: "list_code_definition_names",
8543
8609
  description: "Request to list definition names (classes, functions, methods, etc.) used in a file. This tool provides insights into the codebase structure and important constructs, encapsulating high-level concepts and relationships that are crucial for understanding the overall architecture.",
8544
8610
  parameters: [
@@ -8550,7 +8616,7 @@ var toolInfo4 = {
8550
8616
  }
8551
8617
  ]
8552
8618
  };
8553
- var handler4 = async (provider, args) => {
8619
+ var handler5 = async (provider, args) => {
8554
8620
  if (!provider.listCodeDefinitionNames) {
8555
8621
  return {
8556
8622
  type: "Error" /* Error */,
@@ -8558,26 +8624,25 @@ var handler4 = async (provider, args) => {
8558
8624
  };
8559
8625
  }
8560
8626
  const path = getString(args, "path");
8561
- const files = await provider.listCodeDefinitionNames(path);
8627
+ const result = await provider.listCodeDefinitionNames(path);
8562
8628
  return {
8563
8629
  type: "Reply" /* Reply */,
8564
8630
  message: `<list_code_definition_names_path>${path}</list_code_definition_names_path>
8565
- <list_code_definition_names_files>
8566
- ${files.join(`
8567
- `)}
8568
- </list_code_definition_names_files>`
8631
+ <list_code_definition_names_result>
8632
+ ${result}
8633
+ </list_code_definition_names_result>`
8569
8634
  };
8570
8635
  };
8571
- var isAvailable4 = (provider) => {
8636
+ var isAvailable5 = (provider) => {
8572
8637
  return !!provider.listCodeDefinitionNames;
8573
8638
  };
8574
8639
  var listCodeDefinitionNames_default = {
8575
- ...toolInfo4,
8576
- handler: handler4,
8577
- isAvailable: isAvailable4
8640
+ ...toolInfo5,
8641
+ handler: handler5,
8642
+ isAvailable: isAvailable5
8578
8643
  };
8579
8644
  // src/tools/listFiles.ts
8580
- var toolInfo5 = {
8645
+ var toolInfo6 = {
8581
8646
  name: "list_files",
8582
8647
  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.",
8583
8648
  parameters: [
@@ -8616,7 +8681,7 @@ var toolInfo5 = {
8616
8681
  }
8617
8682
  ]
8618
8683
  };
8619
- var handler5 = async (provider, args) => {
8684
+ var handler6 = async (provider, args) => {
8620
8685
  if (!provider.listFiles) {
8621
8686
  return {
8622
8687
  type: "Error" /* Error */,
@@ -8637,16 +8702,16 @@ ${files.join(`
8637
8702
  <list_files_truncated>${limitReached}</list_files_truncated>`
8638
8703
  };
8639
8704
  };
8640
- var isAvailable5 = (provider) => {
8705
+ var isAvailable6 = (provider) => {
8641
8706
  return !!provider.listFiles;
8642
8707
  };
8643
8708
  var listFiles_default = {
8644
- ...toolInfo5,
8645
- handler: handler5,
8646
- isAvailable: isAvailable5
8709
+ ...toolInfo6,
8710
+ handler: handler6,
8711
+ isAvailable: isAvailable6
8647
8712
  };
8648
8713
  // src/tools/readFile.ts
8649
- var toolInfo6 = {
8714
+ var toolInfo7 = {
8650
8715
  name: "read_file",
8651
8716
  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.",
8652
8717
  parameters: [
@@ -8678,7 +8743,7 @@ var toolInfo6 = {
8678
8743
  }
8679
8744
  ]
8680
8745
  };
8681
- var handler6 = async (provider, args) => {
8746
+ var handler7 = async (provider, args) => {
8682
8747
  if (!provider.readFile) {
8683
8748
  return {
8684
8749
  type: "Error" /* Error */,
@@ -8702,16 +8767,16 @@ var handler6 = async (provider, args) => {
8702
8767
  `)
8703
8768
  };
8704
8769
  };
8705
- var isAvailable6 = (provider) => {
8770
+ var isAvailable7 = (provider) => {
8706
8771
  return !!provider.readFile;
8707
8772
  };
8708
8773
  var readFile_default = {
8709
- ...toolInfo6,
8710
- handler: handler6,
8711
- isAvailable: isAvailable6
8774
+ ...toolInfo7,
8775
+ handler: handler7,
8776
+ isAvailable: isAvailable7
8712
8777
  };
8713
8778
  // src/tools/replaceInFile.ts
8714
- var toolInfo7 = {
8779
+ var toolInfo8 = {
8715
8780
  name: "replace_in_file",
8716
8781
  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.",
8717
8782
  parameters: [
@@ -8795,7 +8860,7 @@ return (
8795
8860
  }
8796
8861
  ]
8797
8862
  };
8798
- var handler7 = async (provider, args) => {
8863
+ var handler8 = async (provider, args) => {
8799
8864
  if (!provider.readFile || !provider.writeFile) {
8800
8865
  return {
8801
8866
  type: "Error" /* Error */,
@@ -8812,16 +8877,16 @@ var handler7 = async (provider, args) => {
8812
8877
  message: `<replace_in_file_path>${path}</replace_in_file_path>`
8813
8878
  };
8814
8879
  };
8815
- var isAvailable7 = (provider) => {
8880
+ var isAvailable8 = (provider) => {
8816
8881
  return !!provider.readFile && !!provider.writeFile;
8817
8882
  };
8818
8883
  var replaceInFile_default = {
8819
- ...toolInfo7,
8820
- handler: handler7,
8821
- isAvailable: isAvailable7
8884
+ ...toolInfo8,
8885
+ handler: handler8,
8886
+ isAvailable: isAvailable8
8822
8887
  };
8823
8888
  // src/tools/searchFiles.ts
8824
- var toolInfo8 = {
8889
+ var toolInfo9 = {
8825
8890
  name: "search_files",
8826
8891
  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.",
8827
8892
  parameters: [
@@ -8864,7 +8929,7 @@ var toolInfo8 = {
8864
8929
  }
8865
8930
  ]
8866
8931
  };
8867
- var handler8 = async (provider, args) => {
8932
+ var handler9 = async (provider, args) => {
8868
8933
  if (!provider.searchFiles) {
8869
8934
  return {
8870
8935
  type: "Error" /* Error */,
@@ -8887,16 +8952,16 @@ ${files.join(`
8887
8952
  `
8888
8953
  };
8889
8954
  };
8890
- var isAvailable8 = (provider) => {
8955
+ var isAvailable9 = (provider) => {
8891
8956
  return !!provider.searchFiles;
8892
8957
  };
8893
8958
  var searchFiles_default = {
8894
- ...toolInfo8,
8895
- handler: handler8,
8896
- isAvailable: isAvailable8
8959
+ ...toolInfo9,
8960
+ handler: handler9,
8961
+ isAvailable: isAvailable9
8897
8962
  };
8898
8963
  // src/tools/writeToFile.ts
8899
- var toolInfo9 = {
8964
+ var toolInfo10 = {
8900
8965
  name: "write_to_file",
8901
8966
  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.",
8902
8967
  parameters: [
@@ -8940,7 +9005,7 @@ export default App;
8940
9005
  }
8941
9006
  ]
8942
9007
  };
8943
- var handler9 = async (provider, args) => {
9008
+ var handler10 = async (provider, args) => {
8944
9009
  if (!provider.writeFile) {
8945
9010
  return {
8946
9011
  type: "Error" /* Error */,
@@ -8955,16 +9020,16 @@ var handler9 = async (provider, args) => {
8955
9020
  message: `<write_to_file_path>${path}</write_to_file_path><status>Success</status>`
8956
9021
  };
8957
9022
  };
8958
- var isAvailable9 = (provider) => {
9023
+ var isAvailable10 = (provider) => {
8959
9024
  return !!provider.writeFile;
8960
9025
  };
8961
9026
  var writeToFile_default = {
8962
- ...toolInfo9,
8963
- handler: handler9,
8964
- isAvailable: isAvailable9
9027
+ ...toolInfo10,
9028
+ handler: handler10,
9029
+ isAvailable: isAvailable10
8965
9030
  };
8966
9031
  // src/tools/handOver.ts
8967
- var toolInfo10 = {
9032
+ var toolInfo11 = {
8968
9033
  name: "hand_over",
8969
9034
  description: "Hand over the current task to another agent to complete",
8970
9035
  parameters: [
@@ -8988,7 +9053,7 @@ var toolInfo10 = {
8988
9053
  },
8989
9054
  {
8990
9055
  name: "files",
8991
- description: "The files relevant to the task",
9056
+ description: "The files relevant to the task. Comma separated paths",
8992
9057
  required: false,
8993
9058
  usageValue: "Relevant files"
8994
9059
  }
@@ -9017,7 +9082,7 @@ var toolInfo10 = {
9017
9082
  }
9018
9083
  ]
9019
9084
  };
9020
- var handler10 = async (_provider, args) => {
9085
+ var handler11 = async (_provider, args) => {
9021
9086
  const agentName = getString(args, "agent_name");
9022
9087
  const task = getString(args, "task");
9023
9088
  const context = getString(args, "context", undefined);
@@ -9030,16 +9095,16 @@ var handler10 = async (_provider, args) => {
9030
9095
  files
9031
9096
  };
9032
9097
  };
9033
- var isAvailable10 = (_provider) => {
9098
+ var isAvailable11 = (_provider) => {
9034
9099
  return true;
9035
9100
  };
9036
9101
  var handOver_default = {
9037
- ...toolInfo10,
9038
- handler: handler10,
9039
- isAvailable: isAvailable10
9102
+ ...toolInfo11,
9103
+ handler: handler11,
9104
+ isAvailable: isAvailable11
9040
9105
  };
9041
9106
  // src/tools/removeFile.ts
9042
- var toolInfo11 = {
9107
+ var toolInfo12 = {
9043
9108
  name: "remove_file",
9044
9109
  description: "Request to remove a file at the specified path.",
9045
9110
  parameters: [
@@ -9062,7 +9127,7 @@ var toolInfo11 = {
9062
9127
  }
9063
9128
  ]
9064
9129
  };
9065
- var handler11 = async (provider, args) => {
9130
+ var handler12 = async (provider, args) => {
9066
9131
  if (!provider.removeFile) {
9067
9132
  return {
9068
9133
  type: "Error" /* Error */,
@@ -9076,16 +9141,16 @@ var handler11 = async (provider, args) => {
9076
9141
  message: `<remove_file_path>${path}</remove_file_path><status>Success</status>`
9077
9142
  };
9078
9143
  };
9079
- var isAvailable11 = (provider) => {
9144
+ var isAvailable12 = (provider) => {
9080
9145
  return !!provider.removeFile;
9081
9146
  };
9082
9147
  var removeFile_default = {
9083
- ...toolInfo11,
9084
- handler: handler11,
9085
- isAvailable: isAvailable11
9148
+ ...toolInfo12,
9149
+ handler: handler12,
9150
+ isAvailable: isAvailable12
9086
9151
  };
9087
9152
  // src/tools/renameFile.ts
9088
- var toolInfo12 = {
9153
+ var toolInfo13 = {
9089
9154
  name: "rename_file",
9090
9155
  description: "Request to rename a file from source path to target path.",
9091
9156
  parameters: [
@@ -9118,7 +9183,7 @@ var toolInfo12 = {
9118
9183
  }
9119
9184
  ]
9120
9185
  };
9121
- var handler12 = async (provider, args) => {
9186
+ var handler13 = async (provider, args) => {
9122
9187
  if (!provider.renameFile) {
9123
9188
  return {
9124
9189
  type: "Error" /* Error */,
@@ -9133,14 +9198,42 @@ var handler12 = async (provider, args) => {
9133
9198
  message: `<rename_file_path>${targetPath}</rename_file_path><status>Success</status>`
9134
9199
  };
9135
9200
  };
9136
- var isAvailable12 = (provider) => {
9201
+ var isAvailable13 = (provider) => {
9137
9202
  return !!provider.renameFile;
9138
9203
  };
9139
9204
  var renameFile_default = {
9140
- ...toolInfo12,
9141
- handler: handler12,
9142
- isAvailable: isAvailable12
9205
+ ...toolInfo13,
9206
+ handler: handler13,
9207
+ isAvailable: isAvailable13
9208
+ };
9209
+ // src/tool.ts
9210
+ var ToolResponseType;
9211
+ ((ToolResponseType2) => {
9212
+ ToolResponseType2["Reply"] = "Reply";
9213
+ ToolResponseType2["Exit"] = "Exit";
9214
+ ToolResponseType2["Invalid"] = "Invalid";
9215
+ ToolResponseType2["Error"] = "Error";
9216
+ ToolResponseType2["Interrupted"] = "Interrupted";
9217
+ ToolResponseType2["HandOver"] = "HandOver";
9218
+ ToolResponseType2["Delegate"] = "Delegate";
9219
+ })(ToolResponseType ||= {});
9220
+ var getAvailableTools = (provider2, allTools2, hasAgent) => {
9221
+ const tools = [];
9222
+ for (const tool of allTools2) {
9223
+ if (!hasAgent) {
9224
+ switch (tool.name) {
9225
+ case handOver_default.name:
9226
+ case delegate_default.name:
9227
+ continue;
9228
+ }
9229
+ }
9230
+ if (tool.isAvailable(provider2)) {
9231
+ tools.push(tool);
9232
+ }
9233
+ }
9234
+ return tools;
9143
9235
  };
9236
+
9144
9237
  // src/Agent/parseAssistantMessage.ts
9145
9238
  function parseAssistantMessage(assistantMessage, tools, toolNamePrefix) {
9146
9239
  const parameterPrefix = `${toolNamePrefix}parameter_`;
@@ -9272,17 +9365,21 @@ ${tools.map((tool) => {
9272
9365
  }).join("")}
9273
9366
  # Tool Use Guidelines
9274
9367
 
9275
- 1. **In \`<thinking>\` tags**, assess what information you have and what you need to proceed.
9276
- 2. **Choose one tool at a time per message** based on the task and its description. Do not assume a tool’s outcome without explicit confirmation.
9277
- 3. **Formulate tool use only in the specified XML format** for each tool.
9278
- 4. **Wait for the user’s response** after each tool use. Do not proceed until you have their confirmation.
9279
- 5. The user’s response may include:
9280
- - Tool success or failure details
9281
- - Linter errors
9282
- - Terminal output or other relevant feedback
9283
- 6. **Never repeat or quote the entire tool command** in your final user-facing message. Summarize outcomes clearly and avoid echoing commands verbatim.
9284
- 7. **Respond concisely** and move the conversation forward. Do not re-issue the same command or re-trigger tool use without necessity.
9285
- 8. Follow these steps **iteratively**, confirming success and addressing issues as you go.
9368
+ 1. **Thinking Tags**: Use \`<thinking>\` tags to clearly outline your thought process *before* using any tools. This includes:
9369
+ * Assessing the current situation and available information.
9370
+ * Defining specific goals and a plan to achieve them.
9371
+ * Justifying the selection of a particular tool.
9372
+ * Explaining how you intend to use the tool and what you expect to achieve.
9373
+ 2. **Tool Selection**: Choose one tool at a time per message based on the task and its description. Do not assume a tool’s outcome without explicit confirmation.
9374
+ 3. **Formatting**: Formulate tool use only in the specified XML format for each tool.
9375
+ 4. **User Response**: Wait for the user’s response after each tool use. Do not proceed until you have their confirmation. The user’s response may include:
9376
+ * Tool success or failure details
9377
+ * Linter errors
9378
+ * Terminal output or other relevant feedback
9379
+ 5. **Conciseness**: Never repeat or quote the entire tool command in your final user-facing message. Summarize outcomes clearly and avoid echoing commands verbatim.
9380
+ 6. **Brevity**: Respond concisely and move the conversation forward. Do not re-issue the same command or re-trigger tool use without necessity.
9381
+ 7. **Iteration**: Follow these steps iteratively, confirming success and addressing issues as you go.
9382
+ 8. **Error Handling**: If a tool returns an error, analyze the error message and adjust your approach accordingly. Consider alternative tools or strategies to achieve the desired outcome.
9286
9383
 
9287
9384
  By adhering to these guidelines:
9288
9385
  - You maintain clarity without accidentally re-invoking tools.
@@ -9408,6 +9505,7 @@ var TaskEventKind;
9408
9505
  TaskEventKind2["ToolError"] = "ToolError";
9409
9506
  TaskEventKind2["ToolInterrupted"] = "ToolInterrupted";
9410
9507
  TaskEventKind2["ToolHandOver"] = "ToolHandOver";
9508
+ TaskEventKind2["ToolDelegate"] = "ToolDelegate";
9411
9509
  TaskEventKind2["UsageExceeded"] = "UsageExceeded";
9412
9510
  TaskEventKind2["EndTask"] = "EndTask";
9413
9511
  })(TaskEventKind ||= {});
@@ -9416,9 +9514,10 @@ class AgentBase {
9416
9514
  ai;
9417
9515
  config;
9418
9516
  handlers;
9517
+ messages = [];
9419
9518
  constructor(name, ai, config) {
9420
9519
  this.ai = ai;
9421
- if (config.agents && Object.keys(config.agents).length > 0) {
9520
+ if (config.agents && config.agents.length > 0) {
9422
9521
  const agents = agentsPrompt(config.agents, name);
9423
9522
  config.systemPrompt += `
9424
9523
  ${agents}`;
@@ -9430,89 +9529,79 @@ ${agents}`;
9430
9529
  }
9431
9530
  this.handlers = handlers;
9432
9531
  }
9433
- async startTask({
9434
- task,
9435
- context,
9436
- callback = () => {
9437
- }
9438
- }) {
9439
- const taskInfo = {
9440
- messages: [],
9441
- inputTokens: 0,
9442
- outputTokens: 0,
9443
- cacheWriteTokens: 0,
9444
- cacheReadTokens: 0,
9445
- totalCost: 0
9446
- };
9532
+ async#callback(event) {
9533
+ await this.config.callback?.(event);
9534
+ }
9535
+ async startTask({ task, context }) {
9447
9536
  let text = `<task>${task}</task>`;
9448
9537
  if (context) {
9449
9538
  text += `
9450
9539
  <context>${context}</context>`;
9451
9540
  }
9452
- callback({ kind: "StartTask" /* StartTask */, info: taskInfo, systemPrompt: this.config.systemPrompt });
9453
- return await this.#processLoop(text, taskInfo, callback);
9541
+ this.#callback({ kind: "StartTask" /* StartTask */, agent: this, systemPrompt: this.config.systemPrompt });
9542
+ return await this.#processLoop(text);
9454
9543
  }
9455
- async#processLoop(userMessage, taskInfo, callback) {
9544
+ async#processLoop(userMessage) {
9456
9545
  let nextRequest = userMessage;
9457
- while (nextRequest) {
9546
+ while (true) {
9458
9547
  if (this.ai.usageMeter.isLimitExceeded().result) {
9459
- callback({ kind: "UsageExceeded" /* UsageExceeded */, info: taskInfo });
9460
- return [{ type: "UsageExceeded" }, taskInfo];
9548
+ this.#callback({ kind: "UsageExceeded" /* UsageExceeded */, agent: this });
9549
+ return { type: "UsageExceeded" };
9461
9550
  }
9462
- const response = await this.#request(taskInfo, nextRequest, callback);
9463
- const [newMessage, exitReason] = await this.#handleResponse(taskInfo, response, callback);
9464
- if (exitReason) {
9465
- callback({ kind: "EndTask" /* EndTask */, info: taskInfo });
9466
- return [exitReason, taskInfo];
9551
+ const response = await this.#request(nextRequest);
9552
+ const resp = await this.#handleResponse(response);
9553
+ if ("exit" in resp) {
9554
+ this.#callback({ kind: "EndTask" /* EndTask */, agent: this, exitReason: resp.exit });
9555
+ return resp.exit;
9467
9556
  }
9468
- nextRequest = newMessage;
9557
+ nextRequest = resp.replay;
9469
9558
  }
9470
- callback({ kind: "EndTask" /* EndTask */, info: taskInfo });
9471
- return [{ type: "Exit" /* Exit */, message: "Task completed successfully" }, taskInfo];
9472
9559
  }
9473
- async continueTask(userMessage, taskInfo, callback = () => {
9474
- }) {
9475
- return await this.#processLoop(userMessage, taskInfo, callback);
9560
+ async continueTask(userMessage) {
9561
+ return await this.#processLoop(userMessage);
9476
9562
  }
9477
- async#request(info, userMessage, callback) {
9478
- await callback({ kind: "StartRequest" /* StartRequest */, info, userMessage });
9479
- info.messages.push({
9563
+ async#request(userMessage) {
9564
+ await this.#callback({ kind: "StartRequest" /* StartRequest */, agent: this, userMessage });
9565
+ this.messages.push({
9480
9566
  role: "user",
9481
9567
  content: userMessage
9482
9568
  });
9483
- const stream = this.ai.send(this.config.systemPrompt, info.messages);
9484
9569
  let currentAssistantMessage = "";
9485
- for await (const chunk of stream) {
9486
- switch (chunk.type) {
9487
- case "usage":
9488
- info.inputTokens = chunk.inputTokens ?? 0;
9489
- info.outputTokens = chunk.outputTokens ?? 0;
9490
- info.cacheWriteTokens = chunk.cacheWriteTokens ?? 0;
9491
- info.cacheReadTokens = chunk.cacheReadTokens ?? 0;
9492
- info.totalCost = chunk.totalCost;
9493
- await callback({ kind: "Usage" /* Usage */, info });
9494
- break;
9495
- case "text":
9496
- currentAssistantMessage += chunk.text;
9497
- await callback({ kind: "Text" /* Text */, info, newText: chunk.text });
9498
- break;
9499
- case "reasoning":
9500
- await callback({ kind: "Reasoning" /* Reasoning */, info, newText: chunk.text });
9501
- break;
9570
+ const retryCount = 3;
9571
+ for (let i = 0;i < retryCount; i++) {
9572
+ currentAssistantMessage = "";
9573
+ const stream = this.ai.send(this.config.systemPrompt, this.messages);
9574
+ for await (const chunk of stream) {
9575
+ switch (chunk.type) {
9576
+ case "usage":
9577
+ await this.#callback({ kind: "Usage" /* Usage */, agent: this });
9578
+ break;
9579
+ case "text":
9580
+ currentAssistantMessage += chunk.text;
9581
+ await this.#callback({ kind: "Text" /* Text */, agent: this, newText: chunk.text });
9582
+ break;
9583
+ case "reasoning":
9584
+ await this.#callback({ kind: "Reasoning" /* Reasoning */, agent: this, newText: chunk.text });
9585
+ break;
9586
+ }
9587
+ }
9588
+ if (currentAssistantMessage) {
9589
+ break;
9502
9590
  }
9591
+ console.debug(`Retrying request ${i + 1} of ${retryCount}`);
9503
9592
  }
9504
9593
  if (!currentAssistantMessage) {
9505
9594
  throw new Error("No assistant message received");
9506
9595
  }
9507
- info.messages.push({
9596
+ this.messages.push({
9508
9597
  role: "assistant",
9509
9598
  content: currentAssistantMessage
9510
9599
  });
9511
9600
  const ret = parseAssistantMessage(currentAssistantMessage, this.config.tools, this.config.toolNamePrefix);
9512
- await callback({ kind: "EndRequest" /* EndRequest */, info });
9601
+ await this.#callback({ kind: "EndRequest" /* EndRequest */, agent: this });
9513
9602
  return ret;
9514
9603
  }
9515
- async#handleResponse(info, response, callback) {
9604
+ async#handleResponse(response) {
9516
9605
  const toolReponses = [];
9517
9606
  outer:
9518
9607
  for (const content of response) {
@@ -9520,65 +9609,76 @@ ${agents}`;
9520
9609
  case "text":
9521
9610
  break;
9522
9611
  case "tool_use": {
9523
- await callback({ kind: "ToolUse" /* ToolUse */, info, tool: content.name });
9612
+ await this.#callback({ kind: "ToolUse" /* ToolUse */, agent: this, tool: content.name });
9524
9613
  const toolResp = await this.#invokeTool(content.name, content.params);
9525
9614
  switch (toolResp.type) {
9526
9615
  case "Reply" /* Reply */:
9527
- await callback({ kind: "ToolReply" /* ToolReply */, info, tool: content.name });
9616
+ await this.#callback({ kind: "ToolReply" /* ToolReply */, agent: this, tool: content.name });
9528
9617
  toolReponses.push({ tool: content.name, response: toolResp.message });
9529
9618
  break;
9530
9619
  case "Exit" /* Exit */:
9531
- return [undefined, toolResp];
9620
+ return { exit: toolResp };
9532
9621
  case "Invalid" /* Invalid */:
9533
- await callback({ kind: "ToolInvalid" /* ToolInvalid */, info, tool: content.name });
9622
+ await this.#callback({ kind: "ToolInvalid" /* ToolInvalid */, agent: this, tool: content.name });
9534
9623
  toolReponses.push({ tool: content.name, response: toolResp.message });
9535
9624
  break outer;
9536
9625
  case "Error" /* Error */:
9537
- await callback({ kind: "ToolError" /* ToolError */, info, tool: content.name });
9626
+ await this.#callback({ kind: "ToolError" /* ToolError */, agent: this, tool: content.name });
9538
9627
  toolReponses.push({ tool: content.name, response: toolResp.message });
9539
9628
  break outer;
9540
9629
  case "Interrupted" /* Interrupted */:
9541
- await callback({ kind: "ToolInterrupted" /* ToolInterrupted */, info, tool: content.name });
9542
- return [undefined, toolResp];
9630
+ await this.#callback({ kind: "ToolInterrupted" /* ToolInterrupted */, agent: this, tool: content.name });
9631
+ return { exit: toolResp };
9543
9632
  case "HandOver" /* HandOver */:
9544
- await callback({
9633
+ await this.#callback({
9545
9634
  kind: "ToolHandOver" /* ToolHandOver */,
9546
- info,
9635
+ agent: this,
9547
9636
  tool: content.name,
9548
9637
  agentName: toolResp.agentName,
9549
9638
  task: toolResp.task,
9550
9639
  context: toolResp.context,
9551
9640
  files: toolResp.files
9552
9641
  });
9553
- return [undefined, toolResp];
9642
+ return { exit: toolResp };
9643
+ case "Delegate" /* Delegate */:
9644
+ await this.#callback({
9645
+ kind: "ToolDelegate" /* ToolDelegate */,
9646
+ agent: this,
9647
+ tool: content.name,
9648
+ agentName: toolResp.agentName,
9649
+ task: toolResp.task,
9650
+ context: toolResp.context,
9651
+ files: toolResp.files
9652
+ });
9653
+ return { exit: toolResp };
9554
9654
  }
9555
9655
  break;
9556
9656
  }
9557
9657
  }
9558
9658
  }
9559
9659
  if (toolReponses.length === 0 && !this.config.interactive) {
9560
- return [responsePrompts.requireUseTool, undefined];
9660
+ return { replay: responsePrompts.requireUseTool };
9561
9661
  }
9562
9662
  const finalResp = toolReponses.map(({ tool, response: response2 }) => responsePrompts.toolResults(tool, response2)).join(`
9563
9663
 
9564
9664
  `);
9565
- return [finalResp, undefined];
9665
+ return { replay: finalResp };
9566
9666
  }
9567
9667
  async#invokeTool(name, args) {
9568
9668
  try {
9569
- const handler13 = this.handlers[name]?.handler;
9570
- if (!handler13) {
9669
+ const handler14 = this.handlers[name]?.handler;
9670
+ if (!handler14) {
9571
9671
  return {
9572
9672
  type: "Error" /* Error */,
9573
9673
  message: responsePrompts.errorInvokeTool(name, "Tool not found"),
9574
9674
  canRetry: false
9575
9675
  };
9576
9676
  }
9577
- const resp = await this.onBeforeInvokeTool(name, args);
9677
+ const resp = await this.onBeforeInvokeTool(this.handlers[name].name, args);
9578
9678
  if (resp) {
9579
9679
  return resp;
9580
9680
  }
9581
- return await handler13(this.config.provider, args);
9681
+ return await handler14(this.config.provider, args);
9582
9682
  } catch (error) {
9583
9683
  return {
9584
9684
  type: "Error" /* Error */,
@@ -9633,12 +9733,13 @@ class AnalyzerAgent extends AgentBase {
9633
9733
  askFollowupQuestion_default,
9634
9734
  attemptCompletion_default,
9635
9735
  handOver_default,
9736
+ delegate_default,
9636
9737
  listCodeDefinitionNames_default,
9637
9738
  listFiles_default,
9638
9739
  readFile_default,
9639
9740
  searchFiles_default
9640
9741
  ];
9641
- const tools = getAvailableTools(options.provider, agentTools);
9742
+ const tools = getAvailableTools(options.provider, agentTools, (options.agents?.length ?? 0) > 0);
9642
9743
  const toolNamePrefix = "tool_";
9643
9744
  const systemPrompt = fullSystemPrompt({
9644
9745
  os: options.os
@@ -9650,7 +9751,8 @@ class AnalyzerAgent extends AgentBase {
9650
9751
  provider: options.provider,
9651
9752
  interactive: options.interactive,
9652
9753
  agents: options.agents,
9653
- scripts: options.scripts
9754
+ scripts: options.scripts,
9755
+ callback: options.callback
9654
9756
  });
9655
9757
  }
9656
9758
  onBeforeInvokeTool() {
@@ -9679,7 +9781,7 @@ You are the **Architect** agent, responsible for:
9679
9781
  3. **File Reading** – Use the provided tools to gather information from these files.
9680
9782
  4. **Implementation Plan** – Draft a concise plan detailing steps, resources, and dependencies.
9681
9783
  5. **Review & Improve** – Evaluate and refine the plan.
9682
- 6. **Handover** – Provide the final plan, context, and files to the **Coder** agent.
9784
+ 6. **Handover/Delegate** – Provide the final plan, context, and files to the **Coder** agent.
9683
9785
 
9684
9786
  > **Note**: The **Architect** agent must not make any direct modifications. Your role is limited to creating the implementation plan and handing it over to the **Coder** agent, who will perform any actual changes.
9685
9787
 
@@ -9712,7 +9814,7 @@ You are the **Architect** agent, responsible for:
9712
9814
  - Check the plan for consistency, clarity, and feasibility.
9713
9815
  - Make adjustments or refinements to ensure accuracy and efficiency.
9714
9816
 
9715
- 6. **Handover**
9817
+ 6. **Handover/Delegate**
9716
9818
  - Deliver the final implementation plan, context, and relevant files to the **Coder** agent.
9717
9819
  - Provide any additional instructions or clarifications needed for successful implementation.
9718
9820
  ${toolUsePrompt(tools, toolNamePrefix)}
@@ -9731,12 +9833,13 @@ class ArchitectAgent extends AgentBase {
9731
9833
  askFollowupQuestion_default,
9732
9834
  attemptCompletion_default,
9733
9835
  handOver_default,
9836
+ delegate_default,
9734
9837
  listCodeDefinitionNames_default,
9735
9838
  listFiles_default,
9736
9839
  readFile_default,
9737
9840
  searchFiles_default
9738
9841
  ];
9739
- const tools = getAvailableTools(options.provider, agentTools);
9842
+ const tools = getAvailableTools(options.provider, agentTools, (options.agents?.length ?? 0) > 0);
9740
9843
  const toolNamePrefix = "tool_";
9741
9844
  const systemPrompt = fullSystemPrompt2({
9742
9845
  os: options.os
@@ -9748,7 +9851,8 @@ class ArchitectAgent extends AgentBase {
9748
9851
  provider: options.provider,
9749
9852
  interactive: options.interactive,
9750
9853
  agents: options.agents,
9751
- scripts: options.scripts
9854
+ scripts: options.scripts,
9855
+ callback: options.callback
9752
9856
  });
9753
9857
  }
9754
9858
  onBeforeInvokeTool() {
@@ -9765,8 +9869,161 @@ var architectAgentInfo = {
9765
9869
  ]
9766
9870
  };
9767
9871
 
9872
+ // src/Agent/CodeFixerAgent/prompts.ts
9873
+ var basePrompt = `You are a highly skilled software engineer specializing in debugging and fixing code issues. You have extensive experience with:
9874
+ - Type systems and type checking
9875
+ - Test frameworks and debugging test failures
9876
+ - Code quality tools and best practices
9877
+ - Systematic debugging approaches`;
9878
+ var codeFixingStrategies = `
9879
+ ====
9880
+
9881
+ CODE FIXING STRATEGIES
9882
+
9883
+ 1. Type Errors
9884
+ - Analyze type error messages carefully
9885
+ - Check type definitions and imports
9886
+ - Consider type assertions only as a last resort
9887
+ - Verify type compatibility across function boundaries
9888
+ - Look for null/undefined handling issues
9889
+
9890
+ 2. Test Failures
9891
+ - Examine test output and error messages
9892
+ - Check test setup and fixtures
9893
+ - Verify assertions and expectations
9894
+ - Look for async/timing issues
9895
+ - Consider edge cases and input validation
9896
+
9897
+ 3. Code Quality Issues
9898
+ - Follow project's coding standards
9899
+ - Address linter warnings systematically
9900
+ - Improve code readability
9901
+ - Fix potential runtime issues
9902
+ - Consider performance implications
9903
+
9904
+ 4. General Approach
9905
+ - Start with the most critical issues
9906
+ - Make minimal necessary changes
9907
+ - Verify fixes don't introduce new issues
9908
+ - Document complex fixes with comments
9909
+ - Track attempted solutions for each issue`;
9910
+ var retryGuidelines = `
9911
+ ====
9912
+
9913
+ RETRY GUIDELINES
9914
+
9915
+ 1. Before Retrying
9916
+ - Analyze previous attempt's failure
9917
+ - Consider alternative approaches
9918
+ - Check if similar issues were fixed
9919
+ - Verify no new issues were introduced
9920
+
9921
+ 2. When to Retry
9922
+ - Error message changed but issue persists
9923
+ - New information available about the root cause
9924
+ - Different fixing strategy available
9925
+ - Previous attempt partially successful
9926
+
9927
+ 3. When to Stop
9928
+ - Maximum retry limit reached
9929
+ - Same error occurs repeatedly
9930
+ - Fix would require major refactoring
9931
+ - Issue requires human intervention
9932
+
9933
+ 4. After Maximum Retries
9934
+ - Document attempted solutions
9935
+ - Explain why the issue remains
9936
+ - Suggest manual intervention steps
9937
+ - Report any partial improvements`;
9938
+ var fullSystemPrompt3 = (info, tools, toolNamePrefix, instructions, scripts, interactive) => `
9939
+ ${basePrompt}
9940
+ ${toolUsePrompt(tools, toolNamePrefix)}
9941
+ ${codeFixingStrategies}
9942
+ ${retryGuidelines}
9943
+ ${capabilities(toolNamePrefix)}
9944
+ ${systemInformation(info)}
9945
+ ${customInstructions(instructions)}
9946
+ ${customScripts(scripts)}
9947
+ ${interactiveMode(interactive)}`;
9948
+
9949
+ // src/Agent/CodeFixerAgent/index.ts
9950
+ class CodeFixerAgent extends AgentBase {
9951
+ #maxRetries;
9952
+ #retryCount = 0;
9953
+ constructor(options) {
9954
+ const combinedTools = [...options.additionalTools ?? [], ...Object.values(exports_allTools)];
9955
+ const tools = getAvailableTools(options.provider, combinedTools, (options.agents?.length ?? 0) > 0);
9956
+ const toolNamePrefix = "tool_";
9957
+ const systemPrompt = fullSystemPrompt3({
9958
+ os: options.os
9959
+ }, tools, toolNamePrefix, options.customInstructions ?? [], options.scripts ?? {}, options.interactive);
9960
+ super(codeFixerAgentInfo.name, options.ai, {
9961
+ systemPrompt,
9962
+ tools,
9963
+ toolNamePrefix,
9964
+ provider: options.provider,
9965
+ interactive: options.interactive,
9966
+ agents: options.agents,
9967
+ scripts: options.scripts,
9968
+ callback: options.callback
9969
+ });
9970
+ this.#maxRetries = options.maxRetries ?? 5;
9971
+ }
9972
+ async onBeforeInvokeTool(name, args) {
9973
+ if (name === attemptCompletion_default.name) {
9974
+ if (this.#retryCount > this.#maxRetries) {
9975
+ return;
9976
+ }
9977
+ this.#retryCount++;
9978
+ const executeCommand = this.config.provider.executeCommand;
9979
+ if (!executeCommand) {
9980
+ return;
9981
+ }
9982
+ const check = this.config.scripts?.check;
9983
+ const checkCommand = typeof check === "string" ? check : check?.command;
9984
+ if (checkCommand) {
9985
+ try {
9986
+ const { exitCode, stdout, stderr } = await executeCommand(checkCommand, false);
9987
+ if (exitCode !== 0) {
9988
+ return {
9989
+ type: "Reply" /* Reply */,
9990
+ message: responsePrompts.commandResult(checkCommand, exitCode, stdout, stderr)
9991
+ };
9992
+ }
9993
+ } catch (error) {
9994
+ console.warn(`Failed to check code using command: ${checkCommand}`, error);
9995
+ }
9996
+ }
9997
+ const test = this.config.scripts?.test;
9998
+ const testCommand = typeof test === "string" ? test : test?.command;
9999
+ if (testCommand) {
10000
+ try {
10001
+ const { exitCode, stdout, stderr } = await executeCommand(testCommand, false);
10002
+ if (exitCode !== 0) {
10003
+ return {
10004
+ type: "Reply" /* Reply */,
10005
+ message: responsePrompts.commandResult(testCommand, exitCode, stdout, stderr)
10006
+ };
10007
+ }
10008
+ } catch (error) {
10009
+ console.warn(`Failed to test code using command: ${testCommand}`, error);
10010
+ }
10011
+ }
10012
+ }
10013
+ }
10014
+ }
10015
+ var codeFixerAgentInfo = {
10016
+ name: "codefixer",
10017
+ responsibilities: [
10018
+ "Fixing type errors and type-related issues",
10019
+ "Resolving failing tests",
10020
+ "Addressing code quality issues",
10021
+ "Tracking and reporting unfixed issues"
10022
+ ]
10023
+ };
10024
+
9768
10025
  // src/Agent/CoderAgent/prompts.ts
9769
- var basePrompt = "You are a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.";
10026
+ var basePrompt2 = "You are a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.";
9770
10027
  var editingFilesPrompt = (toolNamePrefix) => `
9771
10028
  ====
9772
10029
 
@@ -9866,8 +10123,8 @@ You accomplish a given task iteratively, breaking it down into clear steps and w
9866
10123
  3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. Before calling a tool, do some analysis within <thinking></thinking> tags. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use.
9867
10124
  4. Once you've completed the user's task, you must use the ${toolNamePrefix}attempt_completion tool to present the result of the task to the user.
9868
10125
  5. The user may provide feedback, which you can use to make improvements and try again. But DO NOT continue in pointless back and forth conversations, i.e. don't end your responses with questions or offers for further assistance.`;
9869
- var fullSystemPrompt3 = (info, tools, toolNamePrefix, instructions, scripts, interactive) => `
9870
- ${basePrompt}
10126
+ var fullSystemPrompt4 = (info, tools, toolNamePrefix, instructions, scripts, interactive) => `
10127
+ ${basePrompt2}
9871
10128
  ${toolUsePrompt(tools, toolNamePrefix)}
9872
10129
  ${editingFilesPrompt(toolNamePrefix)}
9873
10130
  ${capabilities(toolNamePrefix)}
@@ -9883,9 +10140,9 @@ ${interactiveMode(interactive)}
9883
10140
  class CoderAgent extends AgentBase {
9884
10141
  constructor(options) {
9885
10142
  const combinedTools = [...options.additionalTools ?? [], ...Object.values(exports_allTools)];
9886
- const tools = getAvailableTools(options.provider, combinedTools);
10143
+ const tools = getAvailableTools(options.provider, combinedTools, (options.agents?.length ?? 0) > 0);
9887
10144
  const toolNamePrefix = "tool_";
9888
- const systemPrompt = fullSystemPrompt3({
10145
+ const systemPrompt = fullSystemPrompt4({
9889
10146
  os: options.os
9890
10147
  }, tools, toolNamePrefix, options.customInstructions ?? [], options.scripts ?? {}, options.interactive);
9891
10148
  super(coderAgentInfo.name, options.ai, {
@@ -9895,10 +10152,14 @@ class CoderAgent extends AgentBase {
9895
10152
  provider: options.provider,
9896
10153
  interactive: options.interactive,
9897
10154
  agents: options.agents,
9898
- scripts: options.scripts
10155
+ scripts: options.scripts,
10156
+ callback: options.callback
9899
10157
  });
9900
10158
  }
9901
10159
  async onBeforeInvokeTool(name, args) {
10160
+ if (name !== attemptCompletion_default.name) {
10161
+ return;
10162
+ }
9902
10163
  const executeCommand = this.config.provider.executeCommand;
9903
10164
  if (!executeCommand) {
9904
10165
  return;
@@ -9956,46 +10217,66 @@ var coderAgentInfo = {
9956
10217
  // src/Agent/MultiAgent.ts
9957
10218
  class MultiAgent {
9958
10219
  #config;
9959
- #activeAgent = null;
10220
+ #agents = [];
9960
10221
  constructor(config) {
9961
10222
  this.#config = config;
9962
10223
  }
9963
- get model() {
9964
- return this.#activeAgent?.model;
10224
+ async#handleTaskResult(exitReason) {
10225
+ switch (exitReason.type) {
10226
+ case "HandOver" /* HandOver */: {
10227
+ this.#agents.pop();
10228
+ const newContext = await this.#config.getContext?.(exitReason.agentName, exitReason.context, exitReason.files);
10229
+ return await this.#startTask(exitReason.agentName, exitReason.task, newContext);
10230
+ }
10231
+ case "Delegate" /* Delegate */: {
10232
+ const newContext = await this.#config.getContext?.(exitReason.agentName, exitReason.context, exitReason.files);
10233
+ const delegateResult = await this.#startTask(exitReason.agentName, exitReason.task, newContext);
10234
+ switch (delegateResult.type) {
10235
+ case "HandOver" /* HandOver */:
10236
+ case "Delegate" /* Delegate */:
10237
+ console.warn("Unexpected exit reason", delegateResult);
10238
+ break;
10239
+ case "Interrupted" /* Interrupted */:
10240
+ return delegateResult;
10241
+ case "Exit" /* Exit */:
10242
+ return this.continueTask(delegateResult.message);
10243
+ }
10244
+ return delegateResult;
10245
+ }
10246
+ case "Interrupted" /* Interrupted */:
10247
+ case "Exit" /* Exit */:
10248
+ this.#agents.pop();
10249
+ return exitReason;
10250
+ default:
10251
+ return exitReason;
10252
+ }
9965
10253
  }
9966
- async#startTask(agentName, task, context, callback) {
9967
- this.#activeAgent = await this.#config.createAgent(agentName);
9968
- const [exitReason, info] = await this.#activeAgent.startTask({
10254
+ async#startTask(agentName, task, context) {
10255
+ const newAgent = await this.#config.createAgent(agentName);
10256
+ this.#agents.push(newAgent);
10257
+ const exitReason = await newAgent.startTask({
9969
10258
  task,
9970
- context,
9971
- callback
10259
+ context
9972
10260
  });
9973
- if (typeof exitReason === "string") {
9974
- return [exitReason, info];
9975
- }
9976
- if (exitReason.type === "HandOver") {
9977
- const context2 = await this.#config.getContext?.(agentName, exitReason.context, exitReason.files);
9978
- return await this.#startTask(exitReason.agentName, exitReason.task, context2, callback);
9979
- }
9980
- return [exitReason, info];
10261
+ return await this.#handleTaskResult(exitReason);
9981
10262
  }
9982
10263
  async startTask(options) {
9983
- if (this.#activeAgent) {
10264
+ if (this.#agents.length > 0) {
9984
10265
  throw new Error("An active agent already exists");
9985
10266
  }
9986
- return this.#startTask(options.agentName, options.task, options.context, options.callback);
10267
+ return this.#startTask(options.agentName, options.task, options.context);
9987
10268
  }
9988
- async continueTask(userMessage, taskInfo, callback = () => {
9989
- }) {
9990
- if (!this.#activeAgent) {
10269
+ async continueTask(userMessage) {
10270
+ if (!this.#agents.length) {
9991
10271
  throw new Error("No active agent");
9992
10272
  }
9993
- return this.#activeAgent.continueTask(userMessage, taskInfo, callback);
10273
+ const exitReason = await this.#agents[this.#agents.length - 1].continueTask(userMessage);
10274
+ return await this.#handleTaskResult(exitReason);
9994
10275
  }
9995
10276
  }
9996
10277
 
9997
10278
  // src/Agent/index.ts
9998
- var allAgents = [architectAgentInfo, coderAgentInfo, analyzerAgentInfo];
10279
+ var allAgents = [architectAgentInfo, coderAgentInfo, analyzerAgentInfo, codeFixerAgentInfo];
9999
10280
  // src/AiTool/createNewProject.ts
10000
10281
  var prompt = `You are an AiTool designed to assist users in creating new projects. Follow these guidelines:
10001
10282
 
@@ -10314,11 +10595,8 @@ var generateProjectConfig_default = {
10314
10595
  name: "generateProjectConfig",
10315
10596
  description: "Analyzes project files to generate polkacodes config sections",
10316
10597
  prompt: prompt4,
10317
- formatInput: (params) => {
10318
- return `<tool_input>
10319
- ${params.join(`
10320
- `)}
10321
- </tool_input>`;
10598
+ formatInput: () => {
10599
+ return "";
10322
10600
  },
10323
10601
  parseOutput: (output) => {
10324
10602
  return output.trim();
@@ -10336,15 +10614,14 @@ var executeTool = async (definition, ai, params) => {
10336
10614
  usage
10337
10615
  };
10338
10616
  };
10339
- var executeAgentTool = async (definition, agent, params, callback) => {
10617
+ var executeAgentTool = async (definition, agent, params) => {
10340
10618
  if (!definition.agent) {
10341
10619
  throw new Error("Agent not specified");
10342
10620
  }
10343
- const [exitReason] = await agent.startTask({
10621
+ const exitReason = await agent.startTask({
10344
10622
  agentName: definition.agent,
10345
10623
  task: definition.prompt,
10346
- context: definition.formatInput(params),
10347
- callback
10624
+ context: definition.formatInput(params)
10348
10625
  });
10349
10626
  if (exitReason.type === "Exit" /* Exit */) {
10350
10627
  return definition.parseOutput(exitReason.message);
@@ -10357,8 +10634,8 @@ var makeTool = (definition) => {
10357
10634
  };
10358
10635
  };
10359
10636
  var makeAgentTool = (definition) => {
10360
- return async (agent, params, callback) => {
10361
- return executeAgentTool(definition, agent, params, callback);
10637
+ return async (agent, params) => {
10638
+ return executeAgentTool(definition, agent, params);
10362
10639
  };
10363
10640
  };
10364
10641
  var generateGitCommitMessage = makeTool(generateGitCommitMessage_default);
@@ -10385,12 +10662,14 @@ export {
10385
10662
  executeTool,
10386
10663
  executeCommand_default as executeCommand,
10387
10664
  executeAgentTool,
10665
+ delegate_default as delegate,
10388
10666
  defaultModels,
10389
10667
  deepSeekModels,
10390
10668
  deepSeekDefaultModelId,
10391
10669
  createService,
10392
10670
  createNewProject,
10393
10671
  coderAgentInfo,
10672
+ codeFixerAgentInfo,
10394
10673
  attemptCompletion_default as attemptCompletion,
10395
10674
  askFollowupQuestion_default as askFollowupQuestion,
10396
10675
  architectAgentInfo,
@@ -10405,6 +10684,7 @@ export {
10405
10684
  MultiAgent,
10406
10685
  MockProvider,
10407
10686
  CoderAgent,
10687
+ CodeFixerAgent,
10408
10688
  ArchitectAgent,
10409
10689
  AnalyzerAgent,
10410
10690
  AiServiceProvider,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polka-codes/core",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "license": "AGPL-3.0",
5
5
  "type": "module",
6
6
  "exports": {