@polka-codes/core 0.9.39 → 0.9.41

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
@@ -29,16 +29,18 @@ var toolInfo = {
29
29
  {
30
30
  description: "Single clarifying question (no options)",
31
31
  input: {
32
- questions: { prompt: "What is the target deployment environment?" }
32
+ questions: [{ prompt: "What is the target deployment environment?" }]
33
33
  }
34
34
  },
35
35
  {
36
36
  description: "Single question with multiple-choice options",
37
37
  input: {
38
- questions: {
39
- prompt: "Which frontend framework are you using?",
40
- options: ["React", "Angular", "Vue", "Svelte"]
41
- }
38
+ questions: [
39
+ {
40
+ prompt: "Which frontend framework are you using?",
41
+ options: ["React", "Angular", "Vue", "Svelte"]
42
+ }
43
+ ]
42
44
  }
43
45
  },
44
46
  {
@@ -56,10 +58,12 @@ var toolInfo = {
56
58
  {
57
59
  description: "Binary (yes/no) confirmation",
58
60
  input: {
59
- questions: {
60
- prompt: "Is it acceptable to refactor existing tests to improve performance?",
61
- options: ["Yes", "No"]
62
- }
61
+ questions: [
62
+ {
63
+ prompt: "Is it acceptable to refactor existing tests to improve performance?",
64
+ options: ["Yes", "No"]
65
+ }
66
+ ]
63
67
  }
64
68
  }
65
69
  ]
@@ -87,9 +91,9 @@ var handler = async (provider, args) => {
87
91
  }
88
92
  const answers = [];
89
93
  for (const question of questions) {
90
- const { prompt: prompt3, options } = question;
91
- const answer = await provider.askFollowupQuestion(prompt3, options);
92
- answers.push(`<ask_followup_question_answer question="${prompt3}">
94
+ const { prompt: prompt2, options } = question;
95
+ const answer = await provider.askFollowupQuestion(prompt2, options);
96
+ answers.push(`<ask_followup_question_answer question="${prompt2}">
93
97
  ${answer}
94
98
  </ask_followup_question_answer>`);
95
99
  }
@@ -262,11 +266,11 @@ var handler4 = async (provider, args) => {
262
266
  }
263
267
  };
264
268
  }
265
- const { command: command2, requiresApproval } = toolInfo4.parameters.parse(args);
269
+ const { command, requiresApproval } = toolInfo4.parameters.parse(args);
266
270
  try {
267
- console.log("Executing command:", command2, "Requires approval:", requiresApproval);
268
- const result = await provider.executeCommand(command2, requiresApproval);
269
- let message = `<command>${command2}</command>
271
+ console.log("Executing command:", command, "Requires approval:", requiresApproval);
272
+ const result = await provider.executeCommand(command, requiresApproval);
273
+ let message = `<command>${command}</command>
270
274
  <command_exit_code>${result.exitCode}</command_exit_code>
271
275
  `;
272
276
  if (result.summary) {
@@ -1778,14 +1782,14 @@ The following additional instructions are provided by the user, and should be fo
1778
1782
  ${joined}`;
1779
1783
  };
1780
1784
  var customScripts = (commands) => {
1781
- const joined = Object.entries(commands).map(([name, command2]) => {
1782
- if (typeof command2 === "string") {
1785
+ const joined = Object.entries(commands).map(([name, command]) => {
1786
+ if (typeof command === "string") {
1783
1787
  return `- ${name}
1784
- - Command: \`${command2}\``;
1788
+ - Command: \`${command}\``;
1785
1789
  }
1786
1790
  return `- ${name}
1787
- - Command: \`${command2.command}\`
1788
- - Description: ${command2.description}`;
1791
+ - Command: \`${command.command}\`
1792
+ - Description: ${command.description}`;
1789
1793
  }).join("\n");
1790
1794
  if (joined.trim() === "") {
1791
1795
  return "";
@@ -1870,7 +1874,7 @@ Avoid unnecessary escape characters or special characters.
1870
1874
  ];
1871
1875
  }
1872
1876
  },
1873
- commandResult: (command2, exitCode, stdout, stderr) => `<command>${command2}</command>
1877
+ commandResult: (command, exitCode, stdout, stderr) => `<command>${command}</command>
1874
1878
  <command_exit_code>${exitCode}</command_exit_code>
1875
1879
  <command_stdout>
1876
1880
  ${stdout}
@@ -1976,9 +1980,9 @@ ${instance.prompt}`;
1976
1980
  async #callback(event) {
1977
1981
  await this.config.callback?.(event);
1978
1982
  }
1979
- async start(prompt3) {
1983
+ async start(prompt2) {
1980
1984
  this.#callback({ kind: "StartTask" /* StartTask */, agent: this, systemPrompt: this.config.systemPrompt });
1981
- return await this.#processLoop(prompt3);
1985
+ return await this.#processLoop(prompt2);
1982
1986
  }
1983
1987
  async step(message) {
1984
1988
  if (this.#messages.length === 0) {
@@ -3000,21 +3004,21 @@ var CoderAgent = class extends AgentBase {
3000
3004
  return;
3001
3005
  }
3002
3006
  const script = this.config.scripts?.[scriptName];
3003
- const command2 = typeof script === "string" ? script : script?.command;
3004
- if (command2) {
3007
+ const command = typeof script === "string" ? script : script?.command;
3008
+ if (command) {
3005
3009
  try {
3006
- const { exitCode, stdout, stderr } = await executeCommand(command2, false);
3010
+ const { exitCode, stdout, stderr } = await executeCommand(command, false);
3007
3011
  if (exitCode !== 0 && shouldReplyWithError) {
3008
3012
  return {
3009
3013
  type: "Reply" /* Reply */,
3010
3014
  message: {
3011
3015
  type: "error-text",
3012
- value: responsePrompts.commandResult(command2, exitCode, stdout, stderr)
3016
+ value: responsePrompts.commandResult(command, exitCode, stdout, stderr)
3013
3017
  }
3014
3018
  };
3015
3019
  }
3016
3020
  } catch (error) {
3017
- console.warn(`Failed to run ${scriptName} using command: ${command2}`, error);
3021
+ console.warn(`Failed to run ${scriptName} using command: ${command}`, error);
3018
3022
  }
3019
3023
  }
3020
3024
  }
@@ -3055,24 +3059,24 @@ var MultiAgent = class {
3055
3059
  switch (exitReason.type) {
3056
3060
  case "HandOver" /* HandOver */: {
3057
3061
  this.#agents.pop();
3058
- const prompt3 = await this.#config.getPrompt?.(
3062
+ const prompt2 = await this.#config.getPrompt?.(
3059
3063
  exitReason.agentName,
3060
3064
  exitReason.task,
3061
3065
  exitReason.context,
3062
3066
  exitReason.files,
3063
3067
  this.#originalTask
3064
3068
  ) ?? exitReason.task;
3065
- return await this.#startTask(exitReason.agentName, prompt3);
3069
+ return await this.#startTask(exitReason.agentName, prompt2);
3066
3070
  }
3067
3071
  case "Delegate" /* Delegate */: {
3068
- const prompt3 = await this.#config.getPrompt?.(
3072
+ const prompt2 = await this.#config.getPrompt?.(
3069
3073
  exitReason.agentName,
3070
3074
  exitReason.task,
3071
3075
  exitReason.context,
3072
3076
  exitReason.files,
3073
3077
  this.#originalTask
3074
3078
  ) ?? exitReason.task;
3075
- const delegateResult = await this.#startTask(exitReason.agentName, prompt3);
3079
+ const delegateResult = await this.#startTask(exitReason.agentName, prompt2);
3076
3080
  switch (delegateResult.type) {
3077
3081
  case "HandOver" /* HandOver */:
3078
3082
  case "Delegate" /* Delegate */:
@@ -3488,64 +3492,6 @@ var createNewProject_default = {
3488
3492
  agent: "architect"
3489
3493
  };
3490
3494
 
3491
- // src/AiTool/generateProjectConfig.ts
3492
- var prompt2 = `
3493
- Role: Analyzer agent
3494
- Goal: Produce a valid polkacodes YAML configuration for the project.
3495
-
3496
- Workflow
3497
- 1. Scan project files with tool_read_file and identify:
3498
- - Package/build tool (npm, bun, pnpm, etc.)
3499
- - Test framework and patterns (snapshot tests, coverage, etc.)
3500
- - Formatter / linter and their rules
3501
- - Folder structure and naming conventions
3502
- - CI / development workflows
3503
-
3504
- 2. Build a YAML config with three root keys:
3505
-
3506
- \`\`\`yaml
3507
- scripts: # derive from package.json and CI
3508
- format: # code formatter
3509
- command: "<formatter cmd>"
3510
- description: "Format code"
3511
- check: # linter / type checker
3512
- command: "<linter cmd>"
3513
- description: "Static checks"
3514
- test: # test runner
3515
- command: "<test cmd>"
3516
- description: "Run tests"
3517
- # add any other meaningful project scripts
3518
-
3519
- rules: # bullet list of key conventions/tools
3520
-
3521
- excludeFiles: # only files likely to hold secrets
3522
- - ".env"
3523
- - ".env.*"
3524
- - ".npmrc"
3525
- # do NOT list build artifacts, lockfiles, or paths already in .gitignore
3526
- \`\`\`
3527
-
3528
- 3. Return the YAML exactly once, wrapped like:
3529
-
3530
- <tool_attempt_completion>
3531
- <tool_parameter_result>
3532
- # YAML (2-space indents, double-quoted commands)
3533
- </tool_parameter_result>
3534
- </tool_attempt_completion>
3535
- `;
3536
- var generateProjectConfig_default = {
3537
- name: "generateProjectConfig",
3538
- description: "Analyzes project files to generate polkacodes config sections",
3539
- prompt: prompt2,
3540
- formatInput: () => {
3541
- return "";
3542
- },
3543
- parseOutput: (output) => {
3544
- return output;
3545
- },
3546
- agent: "analyzer"
3547
- };
3548
-
3549
3495
  // src/AiTool/index.ts
3550
3496
  var executeTool = async (definition, ai, params, usageMeter) => {
3551
3497
  const resp = await generateText({
@@ -3598,706 +3544,7 @@ var makeAgentTool = (definition) => {
3598
3544
  return executeAgentTool(definition, options, params);
3599
3545
  };
3600
3546
  };
3601
- var generateProjectConfig = makeMultiAgentTool(generateProjectConfig_default);
3602
3547
  var createNewProject = makeMultiAgentTool(createNewProject_default);
3603
-
3604
- // src/workflow/agent.ts
3605
- import { toJSONSchema as toJSONSchema2 } from "zod/v4";
3606
-
3607
- // src/workflow/utils.ts
3608
- import { template } from "lodash";
3609
- var resolveTemplatedString = (templatedString, input) => {
3610
- if (typeof templatedString === "string") {
3611
- return templatedString;
3612
- }
3613
- if (templatedString.type === "function") {
3614
- return templatedString.fn(input);
3615
- }
3616
- return template(templatedString.template)(input);
3617
- };
3618
-
3619
- // src/workflow/agent.ts
3620
- var agentRegistry = {
3621
- analyzer: AnalyzerAgent,
3622
- architect: ArchitectAgent,
3623
- coder: CoderAgent,
3624
- codefixer: CodeFixerAgent
3625
- };
3626
- var WorkflowAgent = class extends AgentBase {
3627
- onBeforeInvokeTool(_name, _args) {
3628
- return Promise.resolve(void 0);
3629
- }
3630
- };
3631
- var makeAgentStepSpecHandler = (getModelFn) => ({
3632
- type: "agent",
3633
- handler(step2) {
3634
- return {
3635
- ...step2,
3636
- async run(input, context, resumedState) {
3637
- const logger = context.logger ?? console;
3638
- if (context.verbose && context.verbose >= 1) {
3639
- logger.log(`[agent-step] Running agent step '${step2.id}' with input:`, input);
3640
- }
3641
- try {
3642
- const model = await getModelFn(step2, context);
3643
- const parameters = context.parameters ?? {};
3644
- const usageMeter = parameters?.usageMeter ?? new UsageMeter();
3645
- const toolFormat = step2.toolFormat ?? parameters.toolFormat ?? "native";
3646
- const policies = parameters.policies ?? [];
3647
- const modelParameters = { ...parameters.modelParameters ?? {}, ...step2.modelParameters ?? {} };
3648
- if (resumedState?.usage) {
3649
- usageMeter.setUsage(resumedState.usage);
3650
- }
3651
- const getAgent = () => {
3652
- if (step2.agent) {
3653
- const agentName = step2.agent;
3654
- const AgentClass = agentRegistry[agentName];
3655
- if (!AgentClass) {
3656
- throw new Error(`Unknown agent: ${agentName}`);
3657
- }
3658
- if (context.verbose && context.verbose >= 1) {
3659
- logger.log(`[agent-step] Using agent: ${agentName}`);
3660
- }
3661
- return new AgentClass({
3662
- ai: model,
3663
- os: parameters.os ?? "linux",
3664
- provider: context.provider,
3665
- toolFormat,
3666
- additionalTools: step2.tools,
3667
- policies,
3668
- usageMeter,
3669
- parameters: modelParameters,
3670
- scripts: parameters.scripts,
3671
- callback: context.agentCallback,
3672
- requireToolUse: false,
3673
- retryCount: parameters.retryCount,
3674
- requestTimeoutSeconds: parameters.requestTimeoutSeconds
3675
- });
3676
- } else {
3677
- if (!step2.systemPrompt) {
3678
- throw new Error("No system prompt specified for the agent step.");
3679
- }
3680
- if (context.verbose && context.verbose >= 1) {
3681
- logger.log(`[agent-step] Using generic WorkflowAgent`);
3682
- }
3683
- const systemPrompt = resolveTemplatedString(step2.systemPrompt, input);
3684
- return new WorkflowAgent("agent", model, {
3685
- systemPrompt,
3686
- tools: step2.tools ?? [],
3687
- toolNamePrefix: toolFormat === "native" ? "" : "tool_",
3688
- provider: context.provider,
3689
- agents: [],
3690
- scripts: parameters.scripts,
3691
- callback: void 0,
3692
- policies,
3693
- toolFormat,
3694
- parameters: modelParameters,
3695
- usageMeter,
3696
- requireToolUse: false,
3697
- retryCount: parameters.retryCount,
3698
- requestTimeoutSeconds: parameters.requestTimeoutSeconds
3699
- });
3700
- }
3701
- };
3702
- const agent = getAgent();
3703
- if (resumedState?.messages) {
3704
- agent.setMessages(resumedState.messages);
3705
- }
3706
- const userContentArray = step2.messages.map((message) => {
3707
- if (typeof message === "string" || Array.isArray(message)) {
3708
- return message;
3709
- }
3710
- return resolveTemplatedString(message, input);
3711
- });
3712
- const combinedContentParts = [];
3713
- for (const content of userContentArray) {
3714
- if (typeof content === "string") {
3715
- combinedContentParts.push({ type: "text", text: content });
3716
- } else {
3717
- combinedContentParts.push(...content);
3718
- }
3719
- }
3720
- if (context.verbose && context.verbose >= 1) {
3721
- logger.log(`[agent-step] Starting agent with content:`, JSON.stringify(combinedContentParts, null, 2));
3722
- }
3723
- const exitReason = await agent.start(combinedContentParts);
3724
- if (context.verbose && context.verbose >= 1) {
3725
- logger.log(`[agent-step] Agent exited with reason:`, exitReason);
3726
- }
3727
- const handleExitReason = async (reason) => {
3728
- switch (reason.type) {
3729
- case "Pause":
3730
- return {
3731
- type: "paused",
3732
- state: {
3733
- messages: agent.messages,
3734
- usage: usageMeter.usage
3735
- }
3736
- };
3737
- case "UsageExceeded":
3738
- return { type: "error", error: new Error("Usage limit exceeded") };
3739
- case "Exit" /* Exit */: {
3740
- const raw = reason.message;
3741
- if (step2.parseOutput) {
3742
- const result = step2.parseOutput(raw);
3743
- if (result.success) {
3744
- if (step2.outputSchema) {
3745
- const validationResult = step2.outputSchema.safeParse(result.data);
3746
- if (validationResult.success) {
3747
- return { type: "success", output: validationResult.data };
3748
- }
3749
- let errorMessage2 = `Output validation failed: ${validationResult.error.toString()}`;
3750
- if (step2.outputSchema) {
3751
- errorMessage2 += `
3752
-
3753
- Expected JSON schema:
3754
- ${JSON.stringify(toJSONSchema2(step2.outputSchema), null, 2)}`;
3755
- }
3756
- const newReason2 = await agent.continueTask(errorMessage2);
3757
- return handleExitReason(newReason2);
3758
- }
3759
- return { type: "success", output: result.data };
3760
- }
3761
- let errorMessage = result.error ?? "Invalid format.";
3762
- if (step2.outputSchema) {
3763
- errorMessage += `
3764
-
3765
- Expected JSON schema:
3766
- ${JSON.stringify(toJSONSchema2(step2.outputSchema), null, 2)}`;
3767
- }
3768
- const newReason = await agent.continueTask(errorMessage);
3769
- return handleExitReason(newReason);
3770
- } else if (step2.outputSchema) {
3771
- try {
3772
- const output = JSON.parse(raw);
3773
- const validationResult = step2.outputSchema.safeParse(output);
3774
- if (validationResult.success) {
3775
- return { type: "success", output: validationResult.data };
3776
- }
3777
- let errorMessage = `Output validation failed: ${validationResult.error.toString()}`;
3778
- errorMessage += `
3779
-
3780
- Expected JSON schema:
3781
- ${JSON.stringify(toJSONSchema2(step2.outputSchema), null, 2)}`;
3782
- const newReason = await agent.continueTask(errorMessage);
3783
- return handleExitReason(newReason);
3784
- } catch (e) {
3785
- const error = e instanceof Error ? e : new Error(String(e));
3786
- let errorMessage = `Failed to parse agent output as JSON: ${error.message}`;
3787
- errorMessage += `
3788
-
3789
- Expected JSON schema:
3790
- ${JSON.stringify(toJSONSchema2(step2.outputSchema), null, 2)}`;
3791
- const newReason = await agent.continueTask(errorMessage);
3792
- return handleExitReason(newReason);
3793
- }
3794
- }
3795
- return { type: "success", output: reason };
3796
- }
3797
- case "HandOver" /* HandOver */:
3798
- case "Delegate" /* Delegate */:
3799
- return { type: "success", output: reason };
3800
- case "Aborted":
3801
- case "WaitForUserInput":
3802
- return { type: "error", error: new Error(`Agent exited for reason: ${reason.type}`) };
3803
- case "Interrupted" /* Interrupted */:
3804
- return { type: "error", error: new Error(JSON.stringify(reason.message)) };
3805
- default:
3806
- return {
3807
- type: "error",
3808
- error: new Error(`Agent exited for an unhandled reason: ${JSON.stringify(reason)}`)
3809
- };
3810
- }
3811
- };
3812
- return await handleExitReason(exitReason);
3813
- } catch (e) {
3814
- return { type: "error", error: e instanceof Error ? e : new Error(String(e)) };
3815
- }
3816
- }
3817
- };
3818
- }
3819
- });
3820
-
3821
- // src/workflow/builder.ts
3822
- var StepsBuilder = class {
3823
- #steps = [];
3824
- build() {
3825
- if (this.#steps.length === 0) {
3826
- throw new Error("A workflow must have at least one step.");
3827
- }
3828
- const rootStep = this.#steps.length > 1 ? {
3829
- id: "root",
3830
- type: "sequential",
3831
- steps: this.#steps
3832
- } : this.#steps[0];
3833
- return rootStep;
3834
- }
3835
- step(step2) {
3836
- this.#steps.push(step2);
3837
- return this;
3838
- }
3839
- parallel(id, step2) {
3840
- return this.step({
3841
- id,
3842
- type: "parallel",
3843
- step: step2
3844
- });
3845
- }
3846
- loop(id, config) {
3847
- return this.step({
3848
- ...config,
3849
- id,
3850
- type: "loop"
3851
- });
3852
- }
3853
- custom(idOrSpec, run2) {
3854
- if (typeof idOrSpec === "string") {
3855
- if (!run2) {
3856
- throw new Error('Custom step "run" function must be provided.');
3857
- }
3858
- return this.step({
3859
- id: idOrSpec,
3860
- type: "custom",
3861
- run: run2
3862
- });
3863
- }
3864
- return this.step(idOrSpec);
3865
- }
3866
- workflow(id, config) {
3867
- return this.step({
3868
- ...config,
3869
- id,
3870
- type: "workflow"
3871
- });
3872
- }
3873
- agent(id, spec) {
3874
- return this.step({
3875
- ...spec,
3876
- id,
3877
- type: "agent"
3878
- });
3879
- }
3880
- branch(id, config) {
3881
- return this.step({
3882
- ...config,
3883
- id,
3884
- type: "branch"
3885
- });
3886
- }
3887
- };
3888
- var builder = () => {
3889
- return new StepsBuilder();
3890
- };
3891
-
3892
- // src/workflow/command.ts
3893
- var commandStepSpecHandler = {
3894
- type: "command",
3895
- handler(step2) {
3896
- return {
3897
- ...step2,
3898
- async run(input, context) {
3899
- try {
3900
- if (!context.provider.executeCommand) {
3901
- throw new Error("executeCommand is not available in the provider");
3902
- }
3903
- const command2 = step2.command.map((arg) => resolveTemplatedString(arg, input));
3904
- const commandString = command2.map((arg) => {
3905
- if (/[^A-Za-z0-9_/:=-]/.test(arg)) {
3906
- return `"${arg.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
3907
- }
3908
- return arg;
3909
- }).join(" ");
3910
- const result = await context.provider.executeCommand(commandString, false);
3911
- const output = {};
3912
- if (step2.outputs?.includes("stdout")) {
3913
- output.stdout = result.stdout;
3914
- }
3915
- if (step2.outputs?.includes("stderr")) {
3916
- output.stderr = result.stderr;
3917
- }
3918
- if (step2.outputs?.includes("exitCode")) {
3919
- output.exitCode = result.exitCode;
3920
- }
3921
- return { type: "success", output };
3922
- } catch (e) {
3923
- return { type: "error", error: e instanceof Error ? e : new Error(String(e)) };
3924
- }
3925
- }
3926
- };
3927
- }
3928
- };
3929
- var command = (id, ...command2) => ({
3930
- id,
3931
- type: "command",
3932
- command: command2
3933
- });
3934
-
3935
- // src/workflow/runStep.ts
3936
- var runStep = async (step2, input, context, resumedState, allOutputs) => {
3937
- const logger = context.logger ?? console;
3938
- if (context.verbose && context.verbose >= 1) {
3939
- logger.log(`[workflow] running step: ${step2.id}`);
3940
- logger.log(`[workflow] input: ${JSON.stringify(input, null, 2)}`);
3941
- }
3942
- try {
3943
- const validatedInput = step2.inputSchema?.parse(input) ?? input;
3944
- const result = await step2.run({ ...validatedInput, $: allOutputs }, context, resumedState);
3945
- if (context.verbose && context.verbose >= 1) {
3946
- logger.log(`[workflow] step result: ${step2.id}`, JSON.stringify(result, null, 2));
3947
- }
3948
- if (result.type === "success") {
3949
- const validatedOutput = step2.outputSchema?.parse(result.output) ?? result.output;
3950
- return {
3951
- ...result,
3952
- output: validatedOutput
3953
- };
3954
- }
3955
- return result;
3956
- } catch (error) {
3957
- if (context.verbose && context.verbose >= 1) {
3958
- logger.error(`[workflow] step error: ${step2.id}`, error);
3959
- }
3960
- return { type: "error", error };
3961
- }
3962
- };
3963
-
3964
- // src/workflow/workflow.ts
3965
- var run = async (workflow, context, handler15, input) => {
3966
- const rootStep = handler15(workflow.step, handler15);
3967
- const result = await runStep(rootStep, input, context, void 0, {});
3968
- switch (result.type) {
3969
- case "paused":
3970
- return {
3971
- type: "paused",
3972
- state: result.state
3973
- };
3974
- case "error":
3975
- return {
3976
- type: "error",
3977
- error: result.error
3978
- };
3979
- case "success":
3980
- return {
3981
- type: "success",
3982
- output: result.output
3983
- };
3984
- }
3985
- };
3986
- var resume = async (workflow, context, handler15, state, input) => {
3987
- const rootStep = handler15(workflow.step, handler15);
3988
- const result = await runStep(rootStep, input, context, state, {});
3989
- switch (result.type) {
3990
- case "paused":
3991
- return {
3992
- type: "paused",
3993
- state: result.state
3994
- };
3995
- case "error":
3996
- return {
3997
- type: "error",
3998
- error: result.error
3999
- };
4000
- case "success":
4001
- return {
4002
- type: "success",
4003
- output: result.output
4004
- };
4005
- }
4006
- };
4007
-
4008
- // src/workflow/steps.ts
4009
- var combineHandlers = (...handlers) => {
4010
- const allHandlers = {};
4011
- for (const handler15 of handlers) {
4012
- if (allHandlers[handler15.type]) {
4013
- throw new Error(`Handler with type ${handler15.type} already exists`);
4014
- }
4015
- allHandlers[handler15.type] = handler15;
4016
- }
4017
- return (step2, rootHandler) => {
4018
- const handler15 = allHandlers[step2.type];
4019
- if (!handler15) {
4020
- throw new Error(`No handler found for step type: ${step2.type}`);
4021
- }
4022
- return handler15.handler(step2, rootHandler);
4023
- };
4024
- };
4025
- var sequentialStepSpecHandler = {
4026
- type: "sequential",
4027
- handler(step2, rootHandler) {
4028
- const steps = step2.steps.map((subStep) => rootHandler(subStep, rootHandler));
4029
- return {
4030
- ...step2,
4031
- async run(input, context, resumedState) {
4032
- let currentInput = input;
4033
- const allOutputs = resumedState ? resumedState.allOutputs : {};
4034
- const startStepIndex = resumedState ? resumedState.stepIndex : 0;
4035
- for (let i = startStepIndex; i < steps.length; i++) {
4036
- const subStep = steps[i];
4037
- const stateToPass = i === startStepIndex && resumedState ? resumedState.stepState : void 0;
4038
- const result = await runStep(subStep, currentInput, context, stateToPass, allOutputs);
4039
- switch (result.type) {
4040
- case "paused":
4041
- return {
4042
- type: "paused",
4043
- state: { stepIndex: i, stepState: result.state, allOutputs }
4044
- };
4045
- case "error":
4046
- return result;
4047
- // Propagate error
4048
- case "success":
4049
- if (subStep.id) {
4050
- allOutputs[subStep.id] = result.output;
4051
- }
4052
- currentInput = result.output;
4053
- break;
4054
- }
4055
- }
4056
- return { type: "success", output: currentInput };
4057
- }
4058
- };
4059
- }
4060
- };
4061
- var parallelStepSpecHandler = {
4062
- type: "parallel",
4063
- handler(step2, rootHandler) {
4064
- const innerStep = rootHandler(step2.step, rootHandler);
4065
- return {
4066
- ...step2,
4067
- async run(input, context, resumedState) {
4068
- const items = input.items ?? [];
4069
- const promises = items.map((innerInput, index) => {
4070
- const previousResult = resumedState?.[index];
4071
- if (previousResult) {
4072
- if (previousResult.type === "paused") {
4073
- return runStep(innerStep, innerInput, context, previousResult.state, input.$);
4074
- }
4075
- return previousResult;
4076
- }
4077
- return runStep(innerStep, innerInput, context, void 0, input.$);
4078
- });
4079
- const results = await Promise.all(promises);
4080
- const errors = results.filter((r) => r.type === "error");
4081
- if (errors.length > 0) {
4082
- return {
4083
- type: "error",
4084
- error: new Error(`Multiple errors: ${errors.map((e) => e.error).join(", ")}`)
4085
- };
4086
- }
4087
- const isPaused = results.some((r) => r.type === "paused");
4088
- if (isPaused) {
4089
- return { type: "paused", state: results };
4090
- }
4091
- const outputs = results.map((r) => r.output);
4092
- return { type: "success", output: { results: outputs } };
4093
- }
4094
- };
4095
- }
4096
- };
4097
- var loopStepSpecHandler = {
4098
- type: "loop",
4099
- handler(step2, rootHandler) {
4100
- const innerStep = rootHandler(step2.step, rootHandler);
4101
- return {
4102
- ...step2,
4103
- async run(input, context, resumedState) {
4104
- const allOutputs = input.$ ?? {};
4105
- const initialInput = { ...input };
4106
- delete initialInput.$;
4107
- const results = resumedState ? [...resumedState.results] : [];
4108
- let iteration = resumedState?.iteration ?? results.length;
4109
- let accumulator = resumedState?.accumulator;
4110
- if (step2.accumulator && accumulator === void 0) {
4111
- const initialAccumulator = step2.accumulator.initial;
4112
- accumulator = typeof initialAccumulator === "function" ? initialAccumulator() : initialAccumulator;
4113
- }
4114
- const hasPredicates = Boolean(step2.while || step2.until);
4115
- const effectiveMaxIterations = step2.maxIterations ?? (hasPredicates ? void 0 : 1);
4116
- const createState = () => ({
4117
- iteration,
4118
- input: initialInput,
4119
- results,
4120
- last: results[results.length - 1],
4121
- accumulator
4122
- });
4123
- const completeSuccess = () => {
4124
- const output = { results };
4125
- if (results.length > 0) {
4126
- output.last = results[results.length - 1];
4127
- }
4128
- if (accumulator !== void 0 && step2.accumulator) {
4129
- output.accumulator = accumulator;
4130
- }
4131
- return { type: "success", output };
4132
- };
4133
- const shouldContinue = async () => {
4134
- const state = createState();
4135
- if (step2.until) {
4136
- const shouldStop = await step2.until(state, context);
4137
- if (shouldStop) {
4138
- return false;
4139
- }
4140
- }
4141
- if (step2.while) {
4142
- return Boolean(await step2.while(state, context));
4143
- }
4144
- return true;
4145
- };
4146
- let pendingResumeState = resumedState;
4147
- while (true) {
4148
- if (!hasPredicates && effectiveMaxIterations !== void 0 && iteration >= effectiveMaxIterations) {
4149
- return completeSuccess();
4150
- }
4151
- if (hasPredicates) {
4152
- const canContinue = await shouldContinue();
4153
- if (!canContinue) {
4154
- return completeSuccess();
4155
- }
4156
- if (step2.maxIterations !== void 0 && iteration >= step2.maxIterations) {
4157
- return {
4158
- type: "error",
4159
- error: new Error(`Loop exceeded max iterations: ${step2.maxIterations}`)
4160
- };
4161
- }
4162
- }
4163
- const stateBeforeRun = createState();
4164
- const iterationInput = step2.mapInput ? await step2.mapInput(stateBeforeRun, context) : stateBeforeRun.last ?? initialInput;
4165
- const resumeStateForInner = pendingResumeState && pendingResumeState.iteration === iteration ? pendingResumeState.stepState : void 0;
4166
- const result = await runStep(innerStep, iterationInput, context, resumeStateForInner, allOutputs);
4167
- if (result.type === "paused") {
4168
- return {
4169
- type: "paused",
4170
- state: {
4171
- iteration,
4172
- stepState: result.state,
4173
- results,
4174
- accumulator
4175
- }
4176
- };
4177
- }
4178
- if (result.type === "error") {
4179
- return result;
4180
- }
4181
- results[iteration] = result.output;
4182
- if (step2.accumulator) {
4183
- const updated = await step2.accumulator.update(
4184
- {
4185
- ...stateBeforeRun,
4186
- results,
4187
- last: result.output,
4188
- accumulator,
4189
- result: result.output
4190
- },
4191
- context
4192
- );
4193
- accumulator = updated;
4194
- }
4195
- iteration += 1;
4196
- pendingResumeState = void 0;
4197
- }
4198
- }
4199
- };
4200
- }
4201
- };
4202
- var workflowStepSpecHandler = {
4203
- type: "workflow",
4204
- handler(step2, rootHandler) {
4205
- return {
4206
- ...step2,
4207
- async run(input, context, resumedState) {
4208
- const { $, ...rest } = input;
4209
- void $;
4210
- const defaultWorkflowInput = rest;
4211
- const workflowInput = step2.mapInput ? await step2.mapInput(input, context) : defaultWorkflowInput;
4212
- const workflowState = resumedState && "workflowState" in resumedState ? resumedState.workflowState : resumedState;
4213
- const result = workflowState ? await resume(step2.workflow, context, rootHandler, workflowState, workflowInput) : await run(step2.workflow, context, rootHandler, workflowInput);
4214
- if (result.type === "paused") {
4215
- return { type: "paused", state: { workflowState: result.state, workflowInput } };
4216
- }
4217
- if (result.type === "error") {
4218
- return { type: "error", error: result.error };
4219
- }
4220
- const finalOutput = step2.mapOutput ? await step2.mapOutput(
4221
- {
4222
- input,
4223
- workflowInput,
4224
- workflowOutput: result.output
4225
- },
4226
- context
4227
- ) : result.output;
4228
- return { type: "success", output: finalOutput };
4229
- }
4230
- };
4231
- }
4232
- };
4233
- var branchStepSpecHandler = {
4234
- type: "branch",
4235
- handler(step2, rootHandler) {
4236
- const branches = step2.branches.map((branch) => ({
4237
- ...branch,
4238
- step: rootHandler(branch.step, rootHandler)
4239
- }));
4240
- const otherwise = step2.otherwise ? rootHandler(step2.otherwise, rootHandler) : void 0;
4241
- return {
4242
- ...step2,
4243
- async run(input, context, resumedState) {
4244
- const allOutputs = input.$ ?? {};
4245
- let branchIndex = resumedState?.branchIndex;
4246
- let stepToRun;
4247
- if (branchIndex === void 0) {
4248
- for (let i = 0; i < branches.length; i++) {
4249
- const shouldRun = await branches[i].when(input, context);
4250
- if (shouldRun) {
4251
- branchIndex = i;
4252
- break;
4253
- }
4254
- }
4255
- if (branchIndex === void 0 && otherwise) {
4256
- branchIndex = branches.length;
4257
- }
4258
- }
4259
- if (branchIndex !== void 0) {
4260
- if (branchIndex < branches.length) {
4261
- stepToRun = branches[branchIndex].step;
4262
- } else if (branchIndex === branches.length && otherwise) {
4263
- stepToRun = otherwise;
4264
- }
4265
- }
4266
- if (!stepToRun) {
4267
- return {
4268
- type: "error",
4269
- error: new Error("No branch predicate matched and no otherwise branch provided")
4270
- };
4271
- }
4272
- const result = await runStep(
4273
- stepToRun,
4274
- input,
4275
- context,
4276
- branchIndex === resumedState?.branchIndex ? resumedState?.stepState : void 0,
4277
- allOutputs
4278
- );
4279
- if (result.type === "paused") {
4280
- return { type: "paused", state: { branchIndex, stepState: result.state } };
4281
- }
4282
- return result;
4283
- }
4284
- };
4285
- }
4286
- };
4287
- var customStepSpecHandler = {
4288
- type: "custom",
4289
- handler(step2) {
4290
- return {
4291
- ...step2,
4292
- async run(input, context, resumedState) {
4293
- return step2.run(input, context, resumedState);
4294
- }
4295
- };
4296
- }
4297
- };
4298
- function step(id, run2) {
4299
- return { id, type: "custom", run: run2 };
4300
- }
4301
3548
  export {
4302
3549
  AgentBase,
4303
3550
  AnalyzerAgent,
@@ -4318,35 +3565,25 @@ export {
4318
3565
  architectAgentInfo,
4319
3566
  askFollowupQuestion_default as askFollowupQuestion,
4320
3567
  attemptCompletion_default as attemptCompletion,
4321
- branchStepSpecHandler,
4322
- builder,
4323
3568
  capabilities,
4324
3569
  codeFixerAgentInfo,
4325
3570
  coderAgentInfo,
4326
- combineHandlers,
4327
- command,
4328
- commandStepSpecHandler,
4329
3571
  configSchema,
4330
3572
  createNewProject,
4331
3573
  customInstructions,
4332
3574
  customScripts,
4333
- customStepSpecHandler,
4334
3575
  delegate_default as delegate,
4335
3576
  executeAgentTool,
4336
3577
  executeCommand_default as executeCommand,
4337
3578
  executeMultiAgentTool,
4338
3579
  executeTool,
4339
3580
  fetchUrl_default as fetchUrl,
4340
- generateProjectConfig,
4341
3581
  getAvailableTools,
4342
3582
  handOver_default as handOver,
4343
3583
  listFiles_default as listFiles,
4344
- loopStepSpecHandler,
4345
- makeAgentStepSpecHandler,
4346
3584
  makeAgentTool,
4347
3585
  makeMultiAgentTool,
4348
3586
  makeTool,
4349
- parallelStepSpecHandler,
4350
3587
  parseAssistantMessage,
4351
3588
  parseJsonFromMarkdown,
4352
3589
  readBinaryFile_default as readBinaryFile,
@@ -4356,13 +3593,8 @@ export {
4356
3593
  replaceInFile_default as replaceInFile,
4357
3594
  replaceInFile as replaceInFileHelper,
4358
3595
  responsePrompts,
4359
- resume,
4360
- run,
4361
3596
  searchFiles_default as searchFiles,
4362
- sequentialStepSpecHandler,
4363
- step,
4364
3597
  systemInformation,
4365
3598
  toolUsePrompt,
4366
- workflowStepSpecHandler,
4367
3599
  writeToFile_default as writeToFile
4368
3600
  };