@polka-codes/core 0.9.24 → 0.9.26

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
@@ -27,13 +27,6 @@ __export(allTools_exports, {
27
27
  import { z } from "zod";
28
28
 
29
29
  // src/tool.ts
30
- var PermissionLevel = /* @__PURE__ */ ((PermissionLevel2) => {
31
- PermissionLevel2[PermissionLevel2["None"] = 0] = "None";
32
- PermissionLevel2[PermissionLevel2["Read"] = 1] = "Read";
33
- PermissionLevel2[PermissionLevel2["Write"] = 2] = "Write";
34
- PermissionLevel2[PermissionLevel2["Arbitrary"] = 3] = "Arbitrary";
35
- return PermissionLevel2;
36
- })(PermissionLevel || {});
37
30
  var ToolResponseType = /* @__PURE__ */ ((ToolResponseType2) => {
38
31
  ToolResponseType2["Reply"] = "Reply";
39
32
  ToolResponseType2["Exit"] = "Exit";
@@ -95,8 +88,7 @@ var toolInfo = {
95
88
  }
96
89
  }
97
90
  ]
98
- }),
99
- permissionLevel: 0 /* None */
91
+ })
100
92
  };
101
93
  var handler = async (provider, args) => {
102
94
  if (!provider.askFollowupQuestion) {
@@ -161,8 +153,7 @@ var toolInfo2 = {
161
153
  }
162
154
  }
163
155
  ]
164
- }),
165
- permissionLevel: 0 /* None */
156
+ })
166
157
  };
167
158
  var handler2 = async (provider, args) => {
168
159
  const parsed = toolInfo2.parameters.safeParse(args);
@@ -226,8 +217,7 @@ var toolInfo3 = {
226
217
  }
227
218
  }
228
219
  ]
229
- }),
230
- permissionLevel: 0 /* None */
220
+ })
231
221
  };
232
222
  var handler3 = async (_provider, args) => {
233
223
  const parsed = toolInfo3.parameters.safeParse(args);
@@ -285,8 +275,7 @@ var toolInfo4 = {
285
275
  }
286
276
  }
287
277
  ]
288
- }),
289
- permissionLevel: 3 /* Arbitrary */
278
+ })
290
279
  };
291
280
  var handler4 = async (provider, args) => {
292
281
  if (!provider.executeCommand) {
@@ -377,8 +366,7 @@ var toolInfo5 = {
377
366
  }
378
367
  }
379
368
  ]
380
- }),
381
- permissionLevel: 1 /* Read */
369
+ })
382
370
  };
383
371
  var handler5 = async (provider, args) => {
384
372
  if (!provider.fetchUrl) {
@@ -454,8 +442,7 @@ var toolInfo6 = {
454
442
  }
455
443
  }
456
444
  ]
457
- }),
458
- permissionLevel: 0 /* None */
445
+ })
459
446
  };
460
447
  var handler6 = async (_provider, args) => {
461
448
  const parsed = toolInfo6.parameters.safeParse(args);
@@ -520,8 +507,7 @@ var toolInfo7 = {
520
507
  }
521
508
  }
522
509
  ]
523
- }),
524
- permissionLevel: 1 /* Read */
510
+ })
525
511
  };
526
512
  var handler7 = async (provider, args) => {
527
513
  if (!provider.listFiles) {
@@ -563,8 +549,7 @@ var toolInfo8 = {
563
549
  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.",
564
550
  parameters: z8.object({
565
551
  url: z8.string().describe("The URL or local path of the file to read.")
566
- }),
567
- permissionLevel: 1 /* Read */
552
+ })
568
553
  };
569
554
  var handler8 = async (provider, args) => {
570
555
  if (!provider.readBinaryFile) {
@@ -647,8 +632,7 @@ var toolInfo9 = {
647
632
  }
648
633
  }
649
634
  ]
650
- }),
651
- permissionLevel: 1 /* Read */
635
+ })
652
636
  };
653
637
  var handler9 = async (provider, args) => {
654
638
  if (!provider.readFile) {
@@ -708,8 +692,7 @@ var toolInfo10 = {
708
692
  }
709
693
  }
710
694
  ]
711
- }),
712
- permissionLevel: 2 /* Write */
695
+ })
713
696
  };
714
697
  var handler10 = async (provider, args) => {
715
698
  if (!provider.removeFile) {
@@ -768,8 +751,7 @@ var toolInfo11 = {
768
751
  }
769
752
  }
770
753
  ]
771
- }),
772
- permissionLevel: 2 /* Write */
754
+ })
773
755
  };
774
756
  var handler11 = async (provider, args) => {
775
757
  if (!provider.renameFile) {
@@ -988,8 +970,7 @@ function oldFeature() {
988
970
  }
989
971
  }
990
972
  ]
991
- }),
992
- permissionLevel: 2 /* Write */
973
+ })
993
974
  };
994
975
  var handler12 = async (provider, args) => {
995
976
  if (!provider.readFile || !provider.writeFile) {
@@ -1101,8 +1082,7 @@ var toolInfo13 = {
1101
1082
  }
1102
1083
  }
1103
1084
  ]
1104
- }),
1105
- permissionLevel: 1 /* Read */
1085
+ })
1106
1086
  };
1107
1087
  var handler13 = async (provider, args) => {
1108
1088
  if (!provider.searchFiles) {
@@ -1190,8 +1170,7 @@ export default App;
1190
1170
  }
1191
1171
  }
1192
1172
  ]
1193
- }),
1194
- permissionLevel: 2 /* Write */
1173
+ })
1195
1174
  };
1196
1175
  var handler14 = async (provider, args) => {
1197
1176
  if (!provider.writeFile) {
@@ -1270,7 +1249,6 @@ var getAvailableTools = ({
1270
1249
  provider,
1271
1250
  allTools,
1272
1251
  hasAgent,
1273
- permissionLevel,
1274
1252
  interactive
1275
1253
  }) => {
1276
1254
  const filteredTools = interactive ? allTools : allTools.filter((tool) => tool.name !== askFollowupQuestion_default.name);
@@ -1283,7 +1261,7 @@ var getAvailableTools = ({
1283
1261
  continue;
1284
1262
  }
1285
1263
  }
1286
- if (tool.isAvailable(provider) && tool.permissionLevel <= permissionLevel) {
1264
+ if (tool.isAvailable(provider)) {
1287
1265
  tools.push(tool);
1288
1266
  }
1289
1267
  }
@@ -2333,14 +2311,23 @@ Retrying request ${i + 2} of ${retryCount}`);
2333
2311
  return { type: "exit", reason: { type: "Pause", responses: toolResponses } };
2334
2312
  }
2335
2313
  if (toolResponses.length === 0) {
2314
+ if (this.config.requireToolUse) {
2315
+ return {
2316
+ type: "reply",
2317
+ message: [
2318
+ {
2319
+ role: "user",
2320
+ content: responsePrompts.requireUseToolNative
2321
+ }
2322
+ ]
2323
+ };
2324
+ }
2336
2325
  return {
2337
- type: "reply",
2338
- message: [
2339
- {
2340
- role: "user",
2341
- content: responsePrompts.requireUseToolNative
2342
- }
2343
- ]
2326
+ type: "exit",
2327
+ reason: {
2328
+ type: "Exit" /* Exit */,
2329
+ message: response.filter((c) => c.type === "text").map((c) => c.content).join("")
2330
+ }
2344
2331
  };
2345
2332
  }
2346
2333
  const mediaUserMessage = medias.length > 0 ? [
@@ -2384,14 +2371,23 @@ Retrying request ${i + 2} of ${retryCount}`);
2384
2371
  };
2385
2372
  }
2386
2373
  if (toolResponses.length === 0) {
2374
+ if (this.config.requireToolUse) {
2375
+ return {
2376
+ type: "reply",
2377
+ message: [
2378
+ {
2379
+ role: "user",
2380
+ content: responsePrompts.requireUseTool
2381
+ }
2382
+ ]
2383
+ };
2384
+ }
2387
2385
  return {
2388
- type: "reply",
2389
- message: [
2390
- {
2391
- role: "user",
2392
- content: responsePrompts.requireUseTool
2393
- }
2394
- ]
2386
+ type: "exit",
2387
+ reason: {
2388
+ type: "Exit" /* Exit */,
2389
+ message: response.filter((c) => c.type === "text").map((c) => c.content).join("")
2390
+ }
2395
2391
  };
2396
2392
  }
2397
2393
  const finalResp = toolResponses.filter((resp) => resp.type === "response").flatMap(({ tool, response: response2 }) => responsePrompts.toolResults(tool, response2));
@@ -2481,14 +2477,14 @@ ${customScripts(scripts)}
2481
2477
  `;
2482
2478
 
2483
2479
  // src/Agent/AnalyzerAgent/index.ts
2480
+ var agentTools = [askFollowupQuestion_default, attemptCompletion_default, delegate_default, fetchUrl_default, handOver_default, listFiles_default, readBinaryFile_default, readFile_default, searchFiles_default];
2484
2481
  var AnalyzerAgent = class extends AgentBase {
2485
2482
  constructor(options) {
2486
- const combinedTools = [...options.additionalTools ?? [], ...Object.values(allTools_exports)];
2483
+ const combinedTools = [...options.additionalTools ?? [], ...agentTools];
2487
2484
  const tools = getAvailableTools({
2488
2485
  provider: options.provider,
2489
2486
  allTools: combinedTools,
2490
2487
  hasAgent: (options.agents?.length ?? 0) > 0,
2491
- permissionLevel: 1 /* Read */,
2492
2488
  interactive: true
2493
2489
  });
2494
2490
  const toolNamePrefix = options.toolFormat === "native" ? "" : "tool_";
@@ -2515,7 +2511,8 @@ var AnalyzerAgent = class extends AgentBase {
2515
2511
  toolFormat: options.toolFormat,
2516
2512
  parameters: options.parameters ?? {},
2517
2513
  usageMeter: options.usageMeter ?? new UsageMeter(),
2518
- requestTimeoutSeconds: options.requestTimeoutSeconds
2514
+ requestTimeoutSeconds: options.requestTimeoutSeconds,
2515
+ requireToolUse: options.requireToolUse ?? true
2519
2516
  });
2520
2517
  }
2521
2518
  onBeforeInvokeTool() {
@@ -2579,14 +2576,14 @@ ${customScripts(scripts)}
2579
2576
  `;
2580
2577
 
2581
2578
  // src/Agent/ArchitectAgent/index.ts
2579
+ var agentTools2 = [askFollowupQuestion_default, attemptCompletion_default, delegate_default, fetchUrl_default, handOver_default, listFiles_default, readBinaryFile_default, readFile_default, searchFiles_default];
2582
2580
  var ArchitectAgent = class extends AgentBase {
2583
2581
  constructor(options) {
2584
- const combinedTools = [...options.additionalTools ?? [], ...Object.values(allTools_exports)];
2582
+ const combinedTools = [...options.additionalTools ?? [], ...agentTools2];
2585
2583
  const tools = getAvailableTools({
2586
2584
  provider: options.provider,
2587
2585
  allTools: combinedTools,
2588
2586
  hasAgent: (options.agents?.length ?? 0) > 0,
2589
- permissionLevel: 1 /* Read */,
2590
2587
  interactive: true
2591
2588
  });
2592
2589
  const toolNamePrefix = options.toolFormat === "native" ? "" : "tool_";
@@ -2613,7 +2610,8 @@ var ArchitectAgent = class extends AgentBase {
2613
2610
  toolFormat: options.toolFormat,
2614
2611
  parameters: options.parameters ?? {},
2615
2612
  usageMeter: options.usageMeter ?? new UsageMeter(),
2616
- requestTimeoutSeconds: options.requestTimeoutSeconds
2613
+ requestTimeoutSeconds: options.requestTimeoutSeconds,
2614
+ requireToolUse: options.requireToolUse ?? true
2617
2615
  });
2618
2616
  }
2619
2617
  onBeforeInvokeTool() {
@@ -2716,7 +2714,6 @@ var CodeFixerAgent = class extends AgentBase {
2716
2714
  provider: options.provider,
2717
2715
  allTools: combinedTools,
2718
2716
  hasAgent: (options.agents?.length ?? 0) > 0,
2719
- permissionLevel: 3 /* Arbitrary */,
2720
2717
  interactive: true
2721
2718
  });
2722
2719
  const toolNamePrefix = options.toolFormat === "native" ? "" : "tool_";
@@ -2744,7 +2741,8 @@ var CodeFixerAgent = class extends AgentBase {
2744
2741
  toolFormat: options.toolFormat,
2745
2742
  parameters: options.parameters ?? {},
2746
2743
  usageMeter: options.usageMeter ?? new UsageMeter(),
2747
- requestTimeoutSeconds: options.requestTimeoutSeconds
2744
+ requestTimeoutSeconds: options.requestTimeoutSeconds,
2745
+ requireToolUse: options.requireToolUse ?? true
2748
2746
  });
2749
2747
  this.#maxRetries = options.maxRetries ?? 5;
2750
2748
  }
@@ -2929,7 +2927,6 @@ var CoderAgent = class extends AgentBase {
2929
2927
  provider: options.provider,
2930
2928
  allTools: combinedTools,
2931
2929
  hasAgent: (options.agents?.length ?? 0) > 0,
2932
- permissionLevel: 3 /* Arbitrary */,
2933
2930
  interactive: true
2934
2931
  });
2935
2932
  const toolNamePrefix = options.toolFormat === "native" ? "" : "tool_";
@@ -2956,7 +2953,8 @@ var CoderAgent = class extends AgentBase {
2956
2953
  toolFormat: options.toolFormat,
2957
2954
  parameters: options.parameters ?? {},
2958
2955
  usageMeter: options.usageMeter ?? new UsageMeter(),
2959
- requestTimeoutSeconds: options.requestTimeoutSeconds
2956
+ requestTimeoutSeconds: options.requestTimeoutSeconds,
2957
+ requireToolUse: options.requireToolUse ?? true
2960
2958
  });
2961
2959
  }
2962
2960
  async #runScript(scriptName, shouldReplyWithError) {
@@ -3733,7 +3731,7 @@ var toolInfo15 = {
3733
3731
  return val;
3734
3732
  }, z17.boolean().optional().default(false)).describe("Get staged changes instead of unstaged changes."),
3735
3733
  commitRange: z17.string().optional().describe('The commit range to get the diff for (e.g., "main...HEAD").'),
3736
- file: z17.string().optional().describe("Get the diff for a specific file."),
3734
+ file: z17.string().describe("Get the diff for a specific file."),
3737
3735
  contextLines: z17.coerce.number().optional().default(5).describe("Number of context lines to include around changes."),
3738
3736
  includeLineNumbers: z17.preprocess((val) => {
3739
3737
  if (typeof val === "string") {
@@ -3743,8 +3741,7 @@ var toolInfo15 = {
3743
3741
  }
3744
3742
  return val;
3745
3743
  }, z17.boolean().optional().default(false)).describe("Annotate the diff with line numbers for additions and deletions.")
3746
- }),
3747
- permissionLevel: 1 /* Read */
3744
+ })
3748
3745
  };
3749
3746
  var handler15 = async (provider, args) => {
3750
3747
  if (!provider.executeCommand) {
@@ -3828,50 +3825,64 @@ var prompt5 = `
3828
3825
  You are a senior software engineer reviewing code changes.
3829
3826
 
3830
3827
  ## Critical Instructions
3831
- **ONLY review the actual changes shown in the diff.** Do not comment on existing code that wasn't modified.
3828
+ - **ONLY review the actual changes shown in the diff.** Do not comment on existing code that wasn't modified.
3829
+ - **ONLY run git_diff on files that are reviewable source/config files** per the "File Selection for git_diff" rules below. Do not pass excluded files to git_diff.
3830
+
3831
+ ## File Selection for git_diff
3832
+ Use <file_status> to decide which files to diff. Include only files likely to contain human-authored source or meaningful configuration.
3833
+
3834
+ Include (run git_diff):
3835
+ - Application/source code
3836
+ - UI/templates/assets code
3837
+ - Infra/config that affects behavior
3838
+
3839
+ Exclude (do NOT run git_diff; do not review):
3840
+ - Lockfiles
3841
+ - Generated/build artifacts & deps
3842
+ - Test artifacts/snapshots
3843
+ - Data and fixtures
3844
+ - Binary/media/minified/maps
3832
3845
 
3833
3846
  ## Viewing Changes
3834
- - **Use git_diff** to inspect the actual code changes for each relevant file.
3835
- - **Pull request**: use the provided commit range for the git_diff tool with contextLines: 5 and includeLineNumbers: true
3836
- - **Local changes**: diff staged or unstaged files using the git_diff tool with contextLines: 5 and includeLineNumbers: true
3837
- - The diff will include line number annotations: [Line N] for additions and [Line N removed] for deletions
3838
- - If a pull request is present you may receive:
3847
+ - For each included file, **use git_diff** to inspect the actual code changes:
3848
+ - **Pull request:** use the provided commit range for the git_diff tool with contextLines: 5 and includeLineNumbers: true, but only surface and review the included files.
3849
+ - **Local changes:** diff staged or unstaged included files using git_diff with contextLines: 5 and includeLineNumbers: true.
3850
+ - The diff will include line number annotations: [Line N] for additions and [Line N removed] for deletions.
3851
+ - You may receive:
3839
3852
  - <pr_title>
3840
3853
  - <pr_description>
3841
3854
  - <commit_messages>
3842
3855
  - A <review_instructions> tag tells you the focus of the review.
3843
- - File status information is provided in <file_status> - use this to understand which files were modified, added, deleted, or renamed.
3856
+ - Use <file_status> to understand which files were modified, added, deleted, or renamed and to apply the inclusion/exclusion rules above.
3844
3857
 
3845
3858
  ## Line Number Reporting
3846
- - **IMPORTANT**: Use the line numbers from the annotations in the diff output
3847
- - For additions: Look for [Line N] annotations after the + lines
3848
- - For deletions: Look for [Line N removed] annotations after the - lines
3849
- - For modifications: Report the line number of the new/current code (from [Line N] annotations)
3850
- - Report single lines as "N" and ranges as "N-M"
3859
+ - Use the line numbers from the annotations in the diff output.
3860
+ - For additions: use the number from the [Line N] annotation after the + line.
3861
+ - For deletions: use the number from the [Line N removed] annotation after the - line.
3862
+ - For modifications: report the line number of the new/current code (from [Line N]).
3863
+ - Report single lines as "N" and ranges as "N-M".
3851
3864
 
3852
3865
  ## Review Guidelines
3853
3866
  Focus exclusively on the changed lines (+ additions, - deletions, modified lines):
3854
- - **Specific issues**: Point to exact problems in the changed code with accurate line references from the annotations
3855
- - **Actionable fixes**: Provide concrete solutions, not vague suggestions
3856
- - **Clear reasoning**: Explain why each issue matters and how to fix it
3857
- - **Avoid generic advice**: No generic suggestions like "add more tests", "improve documentation", or "follow best practices" unless directly related to a specific problem in the diff
3867
+ - **Specific issues:** Point to exact problems in the changed code with accurate line references from the annotations.
3868
+ - **Actionable fixes:** Provide concrete solutions, not vague suggestions.
3869
+ - **Clear reasoning:** Explain why each issue matters and how to fix it.
3870
+ - **Avoid generic advice** unless directly tied to a specific problem visible in the diff.
3858
3871
 
3859
3872
  ## What NOT to review
3860
- - Existing unchanged code
3861
- - Overall project structure or architecture (unless directly impacted by changes)
3862
- - Generic best practices unrelated to the specific changes
3863
- - Missing features or functionality not part of this diff
3873
+ - Files excluded by the "File Selection for git_diff" rules (do not diff or comment on them).
3874
+ - Existing unchanged code.
3875
+ - Overall project structure/architecture unless directly impacted by the changes.
3876
+ - Missing features or functionality not part of this diff.
3864
3877
 
3865
3878
  ## Output Format
3866
- Do **not** include praise or positive feedback. Ignore generated files such as lock files.
3879
+ Do not include praise or positive feedback.
3867
3880
  Only include reviews for actual issues found in the changed code.
3868
3881
 
3869
3882
  Return your review as a JSON object inside a \`\`\`json block, wrapped like:
3870
- <tool_attempt_completion>
3871
- <tool_parameter_result>
3872
3883
  \`\`\`json
3873
3884
  {
3874
- "overview": "Summary of specific issues found in the diff changes, or 'No issues found' if the changes look good.",
3885
+ "overview": "Summary of specific issues found in the diff changes, 'No issues found', or 'No reviewable changes' if all modified files were excluded.",
3875
3886
  "specificReviews": [
3876
3887
  {
3877
3888
  "file": "path/filename.ext",
@@ -3881,8 +3892,6 @@ Return your review as a JSON object inside a \`\`\`json block, wrapped like:
3881
3892
  ]
3882
3893
  }
3883
3894
  \`\`\`
3884
- </tool_parameter_result>
3885
- </tool_attempt_completion>
3886
3895
  `;
3887
3896
  var reviewDiff_default = {
3888
3897
  name: "reviewDiff",
@@ -3942,7 +3951,8 @@ ${output}`,
3942
3951
  agent: (options) => {
3943
3952
  return new AnalyzerAgent({
3944
3953
  ...options,
3945
- additionalTools: [gitDiff_default]
3954
+ additionalTools: [gitDiff_default],
3955
+ requireToolUse: false
3946
3956
  });
3947
3957
  }
3948
3958
  };
@@ -4004,6 +4014,382 @@ var generateGithubPullRequestDetails = makeTool(generateGithubPullRequestDetails
4004
4014
  var reviewDiff = makeAgentTool(reviewDiff_default);
4005
4015
  var generateProjectConfig = makeMultiAgentTool(generateProjectConfig_default);
4006
4016
  var createNewProject = makeMultiAgentTool(createNewProject_default);
4017
+
4018
+ // src/workflow/utils.ts
4019
+ import { template } from "lodash";
4020
+ var resolveTemplatedString = (templatedString, input) => {
4021
+ if (typeof templatedString === "string") {
4022
+ return templatedString;
4023
+ }
4024
+ if (templatedString.type === "function") {
4025
+ return templatedString.fn(input);
4026
+ }
4027
+ return template(templatedString.template)(input);
4028
+ };
4029
+
4030
+ // src/workflow/agent.ts
4031
+ var agentRegistry = {
4032
+ analyzer: AnalyzerAgent,
4033
+ architect: ArchitectAgent,
4034
+ coder: CoderAgent,
4035
+ codefixer: CodeFixerAgent
4036
+ };
4037
+ var WorkflowAgent = class extends AgentBase {
4038
+ onBeforeInvokeTool(_name, _args) {
4039
+ return Promise.resolve(void 0);
4040
+ }
4041
+ };
4042
+ var makeAgentStepSpecHandler = (getModelFn) => ({
4043
+ type: "agent",
4044
+ handler(step) {
4045
+ return {
4046
+ ...step,
4047
+ async run(input, context, resumedState) {
4048
+ try {
4049
+ const model = await getModelFn(step, context);
4050
+ const parameters = context.parameters ?? {};
4051
+ const budget = step.budget ?? parameters?.budget;
4052
+ const maxMessages = step.maxMessages ?? parameters?.maxMessages;
4053
+ const usageMeter = new UsageMeter({}, { maxMessages, maxCost: budget });
4054
+ const toolFormat = step.toolFormat ?? parameters.toolFormat ?? "native";
4055
+ const policies = parameters.policies ?? [];
4056
+ const modelParameters = { ...parameters.modelParameters ?? {}, ...step.modelParameters ?? {} };
4057
+ if (resumedState?.usage) {
4058
+ usageMeter.setUsage(resumedState.usage);
4059
+ }
4060
+ const getAgent = () => {
4061
+ if ("agent" in step) {
4062
+ const agentName = step.agent;
4063
+ const AgentClass = agentRegistry[agentName];
4064
+ if (!AgentClass) {
4065
+ throw new Error(`Unknown agent: ${agentName}`);
4066
+ }
4067
+ const agentOptions = {
4068
+ ai: model,
4069
+ os: parameters.os ?? "linux",
4070
+ provider: context.provider,
4071
+ interactive: false,
4072
+ toolFormat,
4073
+ additionalTools: step.tools,
4074
+ policies,
4075
+ usageMeter,
4076
+ parameters: modelParameters,
4077
+ scripts: parameters.scripts
4078
+ };
4079
+ return new AgentClass(agentOptions);
4080
+ } else {
4081
+ const systemPrompt = resolveTemplatedString(step.systemPrompt, input);
4082
+ return new WorkflowAgent("agent", model, {
4083
+ systemPrompt,
4084
+ tools: step.tools,
4085
+ toolNamePrefix: toolFormat === "native" ? "" : "tool_",
4086
+ provider: context.provider,
4087
+ interactive: false,
4088
+ agents: [],
4089
+ scripts: parameters.scripts,
4090
+ callback: void 0,
4091
+ policies,
4092
+ toolFormat,
4093
+ parameters: modelParameters,
4094
+ usageMeter,
4095
+ requireToolUse: true
4096
+ });
4097
+ }
4098
+ };
4099
+ const agent = getAgent();
4100
+ if (resumedState?.messages) {
4101
+ agent.setMessages(resumedState.messages);
4102
+ }
4103
+ const userContentArray = step.messages.map((message) => {
4104
+ if (typeof message === "string" || Array.isArray(message)) {
4105
+ return message;
4106
+ }
4107
+ return resolveTemplatedString(message, input);
4108
+ });
4109
+ const combinedContentParts = [];
4110
+ for (const content of userContentArray) {
4111
+ if (typeof content === "string") {
4112
+ combinedContentParts.push({ type: "text", text: content });
4113
+ } else {
4114
+ combinedContentParts.push(...content);
4115
+ }
4116
+ }
4117
+ const exitReason = await agent.start(combinedContentParts);
4118
+ const handleExitReason = (reason) => {
4119
+ switch (reason.type) {
4120
+ case "Pause":
4121
+ return { type: "paused", state: { messages: agent.messages } };
4122
+ case "UsageExceeded":
4123
+ return { type: "error", error: new Error("Usage limit exceeded") };
4124
+ case "Exit" /* Exit */:
4125
+ case "HandOver" /* HandOver */:
4126
+ case "Delegate" /* Delegate */:
4127
+ return { type: "success", output: reason };
4128
+ case "Aborted":
4129
+ case "WaitForUserInput":
4130
+ return { type: "error", error: new Error(`Agent exited for reason: ${reason.type}`) };
4131
+ case "Interrupted" /* Interrupted */:
4132
+ return { type: "error", error: new Error(JSON.stringify(reason.message)) };
4133
+ default:
4134
+ return {
4135
+ type: "error",
4136
+ error: new Error(`Agent exited for an unhandled reason: ${JSON.stringify(reason)}`)
4137
+ };
4138
+ }
4139
+ };
4140
+ return handleExitReason(exitReason);
4141
+ } catch (e) {
4142
+ return { type: "error", error: e instanceof Error ? e : new Error(String(e)) };
4143
+ }
4144
+ }
4145
+ };
4146
+ }
4147
+ });
4148
+
4149
+ // src/workflow/builder.ts
4150
+ var StepsBuilder = class {
4151
+ #steps = [];
4152
+ build() {
4153
+ if (this.#steps.length === 0) {
4154
+ throw new Error("A workflow must have at least one step.");
4155
+ }
4156
+ const rootStep = this.#steps.length > 1 ? {
4157
+ id: "root",
4158
+ type: "sequential",
4159
+ steps: this.#steps
4160
+ } : this.#steps[0];
4161
+ return rootStep;
4162
+ }
4163
+ step(step) {
4164
+ this.#steps.push(step);
4165
+ return this;
4166
+ }
4167
+ parallel(id, step) {
4168
+ return this.step({
4169
+ id,
4170
+ type: "parallel",
4171
+ step
4172
+ });
4173
+ }
4174
+ custom(id, run2) {
4175
+ return this.step({
4176
+ id,
4177
+ type: "custom",
4178
+ run: run2
4179
+ });
4180
+ }
4181
+ agent(id, spec) {
4182
+ return this.step({
4183
+ ...spec,
4184
+ id,
4185
+ type: "agent"
4186
+ });
4187
+ }
4188
+ };
4189
+ var builder = () => {
4190
+ return new StepsBuilder();
4191
+ };
4192
+
4193
+ // src/workflow/command.ts
4194
+ var commandStepSpecHandler = {
4195
+ type: "command",
4196
+ handler(step) {
4197
+ return {
4198
+ ...step,
4199
+ async run(input, context) {
4200
+ try {
4201
+ if (!context.provider.executeCommand) {
4202
+ throw new Error("executeCommand is not available in the provider");
4203
+ }
4204
+ const command = step.command.map((arg) => resolveTemplatedString(arg, input));
4205
+ const commandString = command.map((arg) => {
4206
+ if (/[^A-Za-z0-9_/:=-]/.test(arg)) {
4207
+ return `"${arg.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
4208
+ }
4209
+ return arg;
4210
+ }).join(" ");
4211
+ const result = await context.provider.executeCommand(commandString, false);
4212
+ const output = {};
4213
+ if (step.outputs?.includes("stdout")) {
4214
+ output.stdout = result.stdout;
4215
+ }
4216
+ if (step.outputs?.includes("stderr")) {
4217
+ output.stderr = result.stderr;
4218
+ }
4219
+ if (step.outputs?.includes("exitCode")) {
4220
+ output.exitCode = result.exitCode;
4221
+ }
4222
+ return { type: "success", output };
4223
+ } catch (e) {
4224
+ return { type: "error", error: e instanceof Error ? e : new Error(String(e)) };
4225
+ }
4226
+ }
4227
+ };
4228
+ }
4229
+ };
4230
+
4231
+ // src/workflow/runStep.ts
4232
+ var runStep = async (step, input, context, resumedState, allOutputs) => {
4233
+ try {
4234
+ const validatedInput = step.inputSchema?.parse(input) ?? input;
4235
+ const result = await step.run({ ...validatedInput, $: allOutputs }, context, resumedState);
4236
+ if (result.type === "success") {
4237
+ const validatedOutput = step.outputSchema?.parse(result.output) ?? result.output;
4238
+ return {
4239
+ ...result,
4240
+ output: validatedOutput
4241
+ };
4242
+ }
4243
+ return result;
4244
+ } catch (error) {
4245
+ return { type: "error", error };
4246
+ }
4247
+ };
4248
+
4249
+ // src/workflow/steps.ts
4250
+ var combineHandlers = (...handlers) => {
4251
+ const allHandlers = {};
4252
+ for (const handler16 of handlers) {
4253
+ if (allHandlers[handler16.type]) {
4254
+ throw new Error(`Handler with type ${handler16.type} already exists`);
4255
+ }
4256
+ allHandlers[handler16.type] = handler16;
4257
+ }
4258
+ return (step, rootHandler) => {
4259
+ const handler16 = allHandlers[step.type];
4260
+ if (!handler16) {
4261
+ throw new Error(`No handler found for step type: ${step.type}`);
4262
+ }
4263
+ return handler16.handler(step, rootHandler);
4264
+ };
4265
+ };
4266
+ var sequentialStepSpecHandler = {
4267
+ type: "sequential",
4268
+ handler(step, rootHandler) {
4269
+ const steps = step.steps.map((subStep) => rootHandler(subStep, rootHandler));
4270
+ return {
4271
+ ...step,
4272
+ async run(input, context, resumedState) {
4273
+ let currentInput = input;
4274
+ const allOutputs = resumedState ? resumedState.allOutputs : {};
4275
+ const startStepIndex = resumedState ? resumedState.stepIndex : 0;
4276
+ for (let i = startStepIndex; i < steps.length; i++) {
4277
+ const subStep = steps[i];
4278
+ const stateToPass = i === startStepIndex && resumedState ? resumedState.stepState : void 0;
4279
+ const result = await runStep(subStep, currentInput, context, stateToPass, allOutputs);
4280
+ switch (result.type) {
4281
+ case "paused":
4282
+ return {
4283
+ type: "paused",
4284
+ state: { stepIndex: i, stepState: result.state, allOutputs }
4285
+ };
4286
+ case "error":
4287
+ return result;
4288
+ // Propagate error
4289
+ case "success":
4290
+ if (subStep.id) {
4291
+ allOutputs[subStep.id] = result.output;
4292
+ }
4293
+ currentInput = result.output;
4294
+ break;
4295
+ }
4296
+ }
4297
+ return { type: "success", output: currentInput };
4298
+ }
4299
+ };
4300
+ }
4301
+ };
4302
+ var parallelStepSpecHandler = {
4303
+ type: "parallel",
4304
+ handler(step, rootHandler) {
4305
+ const innerStep = rootHandler(step.step, rootHandler);
4306
+ return {
4307
+ ...step,
4308
+ async run(input, context, resumedState) {
4309
+ const items = input.items ?? [];
4310
+ const promises = items.map((innerInput, index) => {
4311
+ const previousResult = resumedState?.[index];
4312
+ if (previousResult) {
4313
+ if (previousResult.type === "paused") {
4314
+ return runStep(innerStep, innerInput, context, previousResult.state, input.$);
4315
+ }
4316
+ return previousResult;
4317
+ }
4318
+ return runStep(innerStep, innerInput, context, void 0, input.$);
4319
+ });
4320
+ const results = await Promise.all(promises);
4321
+ const errors = results.filter((r) => r.type === "error");
4322
+ if (errors.length > 0) {
4323
+ return {
4324
+ type: "error",
4325
+ error: new Error(`Multiple errors: ${errors.map((e) => e.error).join(", ")}`)
4326
+ };
4327
+ }
4328
+ const isPaused = results.some((r) => r.type === "paused");
4329
+ if (isPaused) {
4330
+ return { type: "paused", state: results };
4331
+ }
4332
+ const outputs = results.map((r) => r.output);
4333
+ return { type: "success", output: { results: outputs } };
4334
+ }
4335
+ };
4336
+ }
4337
+ };
4338
+ var customStepSpecHandler = {
4339
+ type: "custom",
4340
+ handler(step) {
4341
+ return {
4342
+ ...step,
4343
+ async run(input, context, resumedState) {
4344
+ return step.run(input, context, resumedState);
4345
+ }
4346
+ };
4347
+ }
4348
+ };
4349
+
4350
+ // src/workflow/workflow.ts
4351
+ var run = async (workflow, context, handler16, input) => {
4352
+ const rootStep = handler16(workflow.step, handler16);
4353
+ const result = await runStep(rootStep, input, context, void 0, {});
4354
+ switch (result.type) {
4355
+ case "paused":
4356
+ return {
4357
+ type: "paused",
4358
+ state: result.state
4359
+ };
4360
+ case "error":
4361
+ return {
4362
+ type: "error",
4363
+ error: result.error
4364
+ };
4365
+ case "success":
4366
+ return {
4367
+ type: "success",
4368
+ output: result.output
4369
+ };
4370
+ }
4371
+ };
4372
+ var resume = async (workflow, context, handler16, state, input) => {
4373
+ const rootStep = handler16(workflow.step, handler16);
4374
+ const result = await runStep(rootStep, input, context, state, {});
4375
+ switch (result.type) {
4376
+ case "paused":
4377
+ return {
4378
+ type: "paused",
4379
+ state: result.state
4380
+ };
4381
+ case "error":
4382
+ return {
4383
+ type: "error",
4384
+ error: result.error
4385
+ };
4386
+ case "success":
4387
+ return {
4388
+ type: "success",
4389
+ output: result.output
4390
+ };
4391
+ }
4392
+ };
4007
4393
  export {
4008
4394
  AgentBase,
4009
4395
  AnalyzerAgent,
@@ -4013,7 +4399,6 @@ export {
4013
4399
  EnableCachePolicy,
4014
4400
  MockProvider,
4015
4401
  MultiAgent,
4016
- PermissionLevel,
4017
4402
  Policies,
4018
4403
  TaskEventKind,
4019
4404
  ToolResponseType,
@@ -4026,13 +4411,17 @@ export {
4026
4411
  architectAgentInfo,
4027
4412
  askFollowupQuestion_default as askFollowupQuestion,
4028
4413
  attemptCompletion_default as attemptCompletion,
4414
+ builder,
4029
4415
  capabilities,
4030
4416
  codeFixerAgentInfo,
4031
4417
  coderAgentInfo,
4418
+ combineHandlers,
4419
+ commandStepSpecHandler,
4032
4420
  configSchema,
4033
4421
  createNewProject,
4034
4422
  customInstructions,
4035
4423
  customScripts,
4424
+ customStepSpecHandler,
4036
4425
  delegate_default as delegate,
4037
4426
  executeAgentTool,
4038
4427
  executeCommand_default as executeCommand,
@@ -4045,9 +4434,11 @@ export {
4045
4434
  getAvailableTools,
4046
4435
  handOver_default as handOver,
4047
4436
  listFiles_default as listFiles,
4437
+ makeAgentStepSpecHandler,
4048
4438
  makeAgentTool,
4049
4439
  makeMultiAgentTool,
4050
4440
  makeTool,
4441
+ parallelStepSpecHandler,
4051
4442
  parseAssistantMessage,
4052
4443
  readBinaryFile_default as readBinaryFile,
4053
4444
  readFile_default as readFile,
@@ -4056,8 +4447,11 @@ export {
4056
4447
  replaceInFile_default as replaceInFile,
4057
4448
  replaceInFile as replaceInFileHelper,
4058
4449
  responsePrompts,
4450
+ resume,
4059
4451
  reviewDiff,
4452
+ run,
4060
4453
  searchFiles_default as searchFiles,
4454
+ sequentialStepSpecHandler,
4061
4455
  systemInformation,
4062
4456
  toolUsePrompt,
4063
4457
  writeToFile_default as writeToFile