@polka-codes/core 0.9.77 → 0.9.79

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.
@@ -158,6 +158,10 @@ export { createContext }
158
158
  export { createContext as createContext_alias_1 }
159
159
  export { createContext as createContext_alias_2 }
160
160
 
161
+ declare function createDynamicWorkflow<TTools extends ToolRegistry = DynamicWorkflowRegistry>(definition: WorkflowFile | string, options?: DynamicWorkflowRunnerOptions): (workflowId: string, input: Record<string, any>, context: WorkflowContext<TTools>) => Promise<any>;
162
+ export { createDynamicWorkflow }
163
+ export { createDynamicWorkflow as createDynamicWorkflow_alias_1 }
164
+
161
165
  declare const _default: {
162
166
  handler: ToolHandler<{
163
167
  readonly name: "askFollowupQuestion";
@@ -556,6 +560,68 @@ export { _default_9 as readFile_alias_1 }
556
560
  */
557
561
  export declare function dirname(path: string): string;
558
562
 
563
+ declare type DynamicStepRuntimeContext<TTools extends ToolRegistry> = {
564
+ workflowId: string;
565
+ stepId: string;
566
+ input: Record<string, any>;
567
+ state: Record<string, any>;
568
+ tools: WorkflowTools<TTools>;
569
+ logger: Logger;
570
+ step: StepFn;
571
+ runWorkflow: (workflowId: string, input?: Record<string, any>) => Promise<any>;
572
+ toolInfo: Readonly<FullToolInfo[]> | undefined;
573
+ };
574
+ export { DynamicStepRuntimeContext }
575
+ export { DynamicStepRuntimeContext as DynamicStepRuntimeContext_alias_1 }
576
+
577
+ declare type DynamicWorkflowParseResult = {
578
+ success: true;
579
+ definition: WorkflowFile;
580
+ } | {
581
+ success: false;
582
+ error: string;
583
+ };
584
+ export { DynamicWorkflowParseResult }
585
+ export { DynamicWorkflowParseResult as DynamicWorkflowParseResult_alias_1 }
586
+
587
+ declare type DynamicWorkflowRegistry = ToolRegistry & {
588
+ runWorkflow: RunWorkflowTool;
589
+ };
590
+ export { DynamicWorkflowRegistry }
591
+ export { DynamicWorkflowRegistry as DynamicWorkflowRegistry_alias_1 }
592
+
593
+ declare type DynamicWorkflowRunnerOptions = {
594
+ /**
595
+ * Tool definitions used when a step does not have persisted `code`
596
+ * and needs to be executed via `agentWorkflow`.
597
+ */
598
+ toolInfo?: Readonly<FullToolInfo[]>;
599
+ /**
600
+ * Model id forwarded to `agentWorkflow` for agent-executed steps.
601
+ */
602
+ model?: string;
603
+ /**
604
+ * Maximum round trips for agent-executed steps.
605
+ */
606
+ maxToolRoundTrips?: number;
607
+ /**
608
+ * Opt-in to execute persisted step `code` strings.
609
+ * When false, steps without code must be agent-executed.
610
+ */
611
+ allowUnsafeCodeExecution?: boolean;
612
+ /**
613
+ * Customize per-step system prompt for agent-executed steps.
614
+ */
615
+ stepSystemPrompt?: (args: {
616
+ workflowId: string;
617
+ step: WorkflowStepDefinition;
618
+ input: any;
619
+ state: any;
620
+ }) => string;
621
+ };
622
+ export { DynamicWorkflowRunnerOptions }
623
+ export { DynamicWorkflowRunnerOptions as DynamicWorkflowRunnerOptions_alias_1 }
624
+
559
625
  declare type ExitReason = {
560
626
  type: 'UsageExceeded';
561
627
  messages: JsonModelMessage[];
@@ -603,6 +669,57 @@ declare type FullToolInfo = ToolInfo & {
603
669
  export { FullToolInfo }
604
670
  export { FullToolInfo as FullToolInfo_alias_1 }
605
671
 
672
+ declare type GenerateWorkflowCodeInput = z.infer<typeof GenerateWorkflowCodeInputSchema>;
673
+ export { GenerateWorkflowCodeInput }
674
+ export { GenerateWorkflowCodeInput as GenerateWorkflowCodeInput_alias_1 }
675
+
676
+ declare const GenerateWorkflowCodeInputSchema: z.ZodObject<{
677
+ workflow: z.ZodObject<{
678
+ workflows: z.ZodRecord<z.ZodString, z.ZodObject<{
679
+ task: z.ZodString;
680
+ inputs: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
681
+ id: z.ZodString;
682
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
683
+ default: z.ZodOptional<z.ZodNullable<z.ZodAny>>;
684
+ }, z.core.$strip>>>>;
685
+ steps: z.ZodArray<z.ZodObject<{
686
+ id: z.ZodString;
687
+ tools: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
688
+ task: z.ZodString;
689
+ output: z.ZodOptional<z.ZodNullable<z.ZodString>>;
690
+ expected_outcome: z.ZodOptional<z.ZodNullable<z.ZodString>>;
691
+ code: z.ZodOptional<z.ZodNullable<z.ZodString>>;
692
+ outputSchema: z.ZodOptional<z.ZodNullable<z.ZodAny>>;
693
+ }, z.core.$strip>>;
694
+ output: z.ZodOptional<z.ZodNullable<z.ZodString>>;
695
+ }, z.core.$strip>>;
696
+ }, z.core.$strip>;
697
+ }, z.core.$strip>;
698
+ export { GenerateWorkflowCodeInputSchema }
699
+ export { GenerateWorkflowCodeInputSchema as GenerateWorkflowCodeInputSchema_alias_1 }
700
+
701
+ declare const generateWorkflowCodeWorkflow: WorkflowFn<GenerateWorkflowCodeInput, WorkflowFile, AgentToolRegistry>;
702
+ export { generateWorkflowCodeWorkflow }
703
+ export { generateWorkflowCodeWorkflow as generateWorkflowCodeWorkflow_alias_1 }
704
+
705
+ declare type GenerateWorkflowDefinitionInput = z.infer<typeof GenerateWorkflowDefinitionInputSchema>;
706
+ export { GenerateWorkflowDefinitionInput }
707
+ export { GenerateWorkflowDefinitionInput as GenerateWorkflowDefinitionInput_alias_1 }
708
+
709
+ declare const GenerateWorkflowDefinitionInputSchema: z.ZodObject<{
710
+ prompt: z.ZodString;
711
+ availableTools: z.ZodOptional<z.ZodArray<z.ZodObject<{
712
+ name: z.ZodString;
713
+ description: z.ZodString;
714
+ }, z.core.$strip>>>;
715
+ }, z.core.$strip>;
716
+ export { GenerateWorkflowDefinitionInputSchema }
717
+ export { GenerateWorkflowDefinitionInputSchema as GenerateWorkflowDefinitionInputSchema_alias_1 }
718
+
719
+ declare const generateWorkflowDefinitionWorkflow: WorkflowFn<GenerateWorkflowDefinitionInput, WorkflowFile, AgentToolRegistry>;
720
+ export { generateWorkflowDefinitionWorkflow }
721
+ export { generateWorkflowDefinitionWorkflow as generateWorkflowDefinitionWorkflow_alias_1 }
722
+
606
723
  declare type GetTodoItemOutput = TodoItem & {
607
724
  subItems: {
608
725
  id: string;
@@ -877,6 +994,10 @@ declare type ModelInfo = {
877
994
  export { ModelInfo }
878
995
  export { ModelInfo as ModelInfo_alias_1 }
879
996
 
997
+ declare function parseDynamicWorkflowDefinition(source: string): DynamicWorkflowParseResult;
998
+ export { parseDynamicWorkflowDefinition }
999
+ export { parseDynamicWorkflowDefinition as parseDynamicWorkflowDefinition_alias_1 }
1000
+
880
1001
  declare const parseJsonFromMarkdown: (markdown: string) => ParseOutputResult<any>;
881
1002
  export { parseJsonFromMarkdown }
882
1003
  export { parseJsonFromMarkdown as parseJsonFromMarkdown_alias_1 }
@@ -941,6 +1062,16 @@ declare const ruleSchema: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
941
1062
  export { ruleSchema }
942
1063
  export { ruleSchema as ruleSchema_alias_1 }
943
1064
 
1065
+ declare type RunWorkflowTool = {
1066
+ input: {
1067
+ workflowId: string;
1068
+ input?: any;
1069
+ };
1070
+ output: any;
1071
+ };
1072
+ export { RunWorkflowTool }
1073
+ export { RunWorkflowTool as RunWorkflowTool_alias_1 }
1074
+
944
1075
  declare interface StepFn {
945
1076
  <T>(name: string, fn: () => Promise<T>): Promise<T>;
946
1077
  <T>(name: string, options: StepOptions, fn: () => Promise<T>): Promise<T>;
@@ -1540,11 +1671,91 @@ export { WorkflowContext }
1540
1671
  export { WorkflowContext as WorkflowContext_alias_1 }
1541
1672
  export { WorkflowContext as WorkflowContext_alias_2 }
1542
1673
 
1674
+ declare type WorkflowDefinition = z.infer<typeof WorkflowDefinitionSchema>;
1675
+ export { WorkflowDefinition }
1676
+ export { WorkflowDefinition as WorkflowDefinition_alias_1 }
1677
+
1678
+ declare const WorkflowDefinitionSchema: z.ZodObject<{
1679
+ task: z.ZodString;
1680
+ inputs: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
1681
+ id: z.ZodString;
1682
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1683
+ default: z.ZodOptional<z.ZodNullable<z.ZodAny>>;
1684
+ }, z.core.$strip>>>>;
1685
+ steps: z.ZodArray<z.ZodObject<{
1686
+ id: z.ZodString;
1687
+ tools: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
1688
+ task: z.ZodString;
1689
+ output: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1690
+ expected_outcome: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1691
+ code: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1692
+ outputSchema: z.ZodOptional<z.ZodNullable<z.ZodAny>>;
1693
+ }, z.core.$strip>>;
1694
+ output: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1695
+ }, z.core.$strip>;
1696
+ export { WorkflowDefinitionSchema }
1697
+ export { WorkflowDefinitionSchema as WorkflowDefinitionSchema_alias_1 }
1698
+
1699
+ declare type WorkflowFile = z.infer<typeof WorkflowFileSchema>;
1700
+ export { WorkflowFile }
1701
+ export { WorkflowFile as WorkflowFile_alias_1 }
1702
+
1703
+ declare const WorkflowFileSchema: z.ZodObject<{
1704
+ workflows: z.ZodRecord<z.ZodString, z.ZodObject<{
1705
+ task: z.ZodString;
1706
+ inputs: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
1707
+ id: z.ZodString;
1708
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1709
+ default: z.ZodOptional<z.ZodNullable<z.ZodAny>>;
1710
+ }, z.core.$strip>>>>;
1711
+ steps: z.ZodArray<z.ZodObject<{
1712
+ id: z.ZodString;
1713
+ tools: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
1714
+ task: z.ZodString;
1715
+ output: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1716
+ expected_outcome: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1717
+ code: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1718
+ outputSchema: z.ZodOptional<z.ZodNullable<z.ZodAny>>;
1719
+ }, z.core.$strip>>;
1720
+ output: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1721
+ }, z.core.$strip>>;
1722
+ }, z.core.$strip>;
1723
+ export { WorkflowFileSchema }
1724
+ export { WorkflowFileSchema as WorkflowFileSchema_alias_1 }
1725
+
1543
1726
  declare type WorkflowFn<TInput, TOutput, TTools extends ToolRegistry> = (input: TInput, context: WorkflowContext<TTools>) => Promise<TOutput>;
1544
1727
  export { WorkflowFn }
1545
1728
  export { WorkflowFn as WorkflowFn_alias_1 }
1546
1729
  export { WorkflowFn as WorkflowFn_alias_2 }
1547
1730
 
1731
+ declare type WorkflowInputDefinition = z.infer<typeof WorkflowInputDefinitionSchema>;
1732
+ export { WorkflowInputDefinition }
1733
+ export { WorkflowInputDefinition as WorkflowInputDefinition_alias_1 }
1734
+
1735
+ declare const WorkflowInputDefinitionSchema: z.ZodObject<{
1736
+ id: z.ZodString;
1737
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1738
+ default: z.ZodOptional<z.ZodNullable<z.ZodAny>>;
1739
+ }, z.core.$strip>;
1740
+ export { WorkflowInputDefinitionSchema }
1741
+ export { WorkflowInputDefinitionSchema as WorkflowInputDefinitionSchema_alias_1 }
1742
+
1743
+ declare type WorkflowStepDefinition = z.infer<typeof WorkflowStepDefinitionSchema>;
1744
+ export { WorkflowStepDefinition }
1745
+ export { WorkflowStepDefinition as WorkflowStepDefinition_alias_1 }
1746
+
1747
+ declare const WorkflowStepDefinitionSchema: z.ZodObject<{
1748
+ id: z.ZodString;
1749
+ tools: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
1750
+ task: z.ZodString;
1751
+ output: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1752
+ expected_outcome: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1753
+ code: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1754
+ outputSchema: z.ZodOptional<z.ZodNullable<z.ZodAny>>;
1755
+ }, z.core.$strip>;
1756
+ export { WorkflowStepDefinitionSchema }
1757
+ export { WorkflowStepDefinitionSchema as WorkflowStepDefinitionSchema_alias_1 }
1758
+
1548
1759
  declare type WorkflowTools<TTools extends ToolRegistry> = {
1549
1760
  [K in keyof TTools]: (input: TTools[K]['input']) => Promise<TTools[K]['output']>;
1550
1761
  };
package/dist/index.d.ts CHANGED
@@ -60,6 +60,27 @@ export { UsageMeter_alias_1 as UsageMeter } from './_tsup-dts-rollup.js';
60
60
  export { AgentWorkflowInput } from './_tsup-dts-rollup.js';
61
61
  export { AgentToolRegistry } from './_tsup-dts-rollup.js';
62
62
  export { agentWorkflow } from './_tsup-dts-rollup.js';
63
+ export { parseDynamicWorkflowDefinition } from './_tsup-dts-rollup.js';
64
+ export { createDynamicWorkflow } from './_tsup-dts-rollup.js';
65
+ export { RunWorkflowTool } from './_tsup-dts-rollup.js';
66
+ export { DynamicWorkflowRegistry } from './_tsup-dts-rollup.js';
67
+ export { DynamicWorkflowParseResult } from './_tsup-dts-rollup.js';
68
+ export { DynamicStepRuntimeContext } from './_tsup-dts-rollup.js';
69
+ export { DynamicWorkflowRunnerOptions } from './_tsup-dts-rollup.js';
70
+ export { GenerateWorkflowDefinitionInputSchema } from './_tsup-dts-rollup.js';
71
+ export { GenerateWorkflowDefinitionInput } from './_tsup-dts-rollup.js';
72
+ export { GenerateWorkflowCodeInputSchema } from './_tsup-dts-rollup.js';
73
+ export { GenerateWorkflowCodeInput } from './_tsup-dts-rollup.js';
74
+ export { generateWorkflowDefinitionWorkflow } from './_tsup-dts-rollup.js';
75
+ export { generateWorkflowCodeWorkflow } from './_tsup-dts-rollup.js';
76
+ export { WorkflowInputDefinitionSchema } from './_tsup-dts-rollup.js';
77
+ export { WorkflowStepDefinitionSchema } from './_tsup-dts-rollup.js';
78
+ export { WorkflowDefinitionSchema } from './_tsup-dts-rollup.js';
79
+ export { WorkflowFileSchema } from './_tsup-dts-rollup.js';
80
+ export { WorkflowInputDefinition } from './_tsup-dts-rollup.js';
81
+ export { WorkflowStepDefinition } from './_tsup-dts-rollup.js';
82
+ export { WorkflowDefinition } from './_tsup-dts-rollup.js';
83
+ export { WorkflowFile } from './_tsup-dts-rollup.js';
63
84
  export { JsonImagePart } from './_tsup-dts-rollup.js';
64
85
  export { JsonFilePart } from './_tsup-dts-rollup.js';
65
86
  export { JsonUserModelMessage } from './_tsup-dts-rollup.js';
package/dist/index.js CHANGED
@@ -1823,6 +1823,14 @@ var agentWorkflow = async (input, { step, tools, logger }) => {
1823
1823
  value: `Tool '${toolCall.toolName}' not found.`
1824
1824
  }
1825
1825
  });
1826
+ toolResults.push({
1827
+ toolCallId: toolCall.toolCallId,
1828
+ toolName: toolCall.toolName,
1829
+ output: {
1830
+ type: "error-text",
1831
+ value: `Error: Tool '${toolCall.toolName}' not found.`
1832
+ }
1833
+ });
1826
1834
  continue;
1827
1835
  }
1828
1836
  await event(`event-tool-use-${toolCall.toolName}-${toolCall.toolCallId}`, {
@@ -1896,6 +1904,478 @@ var agentWorkflow = async (input, { step, tools, logger }) => {
1896
1904
  throw new Error("Maximum number of tool round trips reached.");
1897
1905
  };
1898
1906
 
1907
+ // src/workflow/dynamic.ts
1908
+ import { parse } from "yaml";
1909
+ import { z as z22 } from "zod";
1910
+
1911
+ // src/workflow/dynamic-types.ts
1912
+ import { z as z21 } from "zod";
1913
+ var WorkflowInputDefinitionSchema = z21.object({
1914
+ id: z21.string(),
1915
+ description: z21.string().nullish(),
1916
+ default: z21.any().nullish()
1917
+ });
1918
+ var WorkflowStepDefinitionSchema = z21.object({
1919
+ id: z21.string(),
1920
+ tools: z21.array(z21.string()).nullish(),
1921
+ task: z21.string(),
1922
+ output: z21.string().nullish(),
1923
+ expected_outcome: z21.string().nullish(),
1924
+ /**
1925
+ * Persisted JavaScript/TypeScript (JS-compatible) async function body.
1926
+ * The code is wrapped as: `async (ctx) => { <code> }`.
1927
+ */
1928
+ code: z21.string().nullish(),
1929
+ /**
1930
+ * Optional JSON schema or other metadata for future structured outputs.
1931
+ * Not interpreted by core today.
1932
+ */
1933
+ outputSchema: z21.any().nullish()
1934
+ });
1935
+ var WorkflowDefinitionSchema = z21.object({
1936
+ task: z21.string(),
1937
+ inputs: z21.array(WorkflowInputDefinitionSchema).nullish(),
1938
+ steps: z21.array(WorkflowStepDefinitionSchema),
1939
+ output: z21.string().nullish()
1940
+ });
1941
+ var WorkflowFileSchema = z21.object({
1942
+ workflows: z21.record(z21.string(), WorkflowDefinitionSchema)
1943
+ });
1944
+
1945
+ // src/workflow/dynamic.ts
1946
+ function parseDynamicWorkflowDefinition(source) {
1947
+ try {
1948
+ const raw = parse(source);
1949
+ const validated = WorkflowFileSchema.safeParse(raw);
1950
+ if (!validated.success) {
1951
+ return { success: false, error: z22.prettifyError(validated.error) };
1952
+ }
1953
+ return { success: true, definition: validated.data };
1954
+ } catch (error) {
1955
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
1956
+ }
1957
+ }
1958
+ var AsyncFunction = Object.getPrototypeOf(async () => {
1959
+ }).constructor;
1960
+ function createRunWorkflowFn(args) {
1961
+ return async (subWorkflowId, subInput) => {
1962
+ const mergedInput = { ...args.input, ...args.state, ...subInput ?? {} };
1963
+ return await args.runInternal(subWorkflowId, mergedInput, args.context, args.state);
1964
+ };
1965
+ }
1966
+ function compileStep(stepDef, workflowId, compiledSteps) {
1967
+ const key = `${workflowId}.${stepDef.id}`;
1968
+ const existing = compiledSteps.get(key);
1969
+ if (existing) {
1970
+ return existing;
1971
+ }
1972
+ if (!stepDef.code) {
1973
+ throw new Error(`Step '${stepDef.id}' in workflow '${workflowId}' has no code`);
1974
+ }
1975
+ try {
1976
+ const fn = new AsyncFunction("ctx", stepDef.code);
1977
+ compiledSteps.set(key, fn);
1978
+ return fn;
1979
+ } catch (error) {
1980
+ throw new Error(
1981
+ `Failed to compile code for step '${stepDef.id}' in workflow '${workflowId}': ${error instanceof Error ? error.message : String(error)}`
1982
+ );
1983
+ }
1984
+ }
1985
+ async function executeStepWithAgent(stepDef, workflowId, input, state, context, options, runInternal) {
1986
+ const tools = context.tools;
1987
+ if (typeof tools.generateText !== "function" || typeof tools.invokeTool !== "function" || typeof tools.taskEvent !== "function") {
1988
+ throw new Error(
1989
+ `Step '${stepDef.id}' in workflow '${workflowId}' requires agent execution, but AgentToolRegistry tools are not available.`
1990
+ );
1991
+ }
1992
+ if (!options.toolInfo) {
1993
+ throw new Error(
1994
+ `Step '${stepDef.id}' in workflow '${workflowId}' requires agent execution, but no toolInfo was provided to DynamicWorkflowRunner.`
1995
+ );
1996
+ }
1997
+ const allowedToolNames = stepDef.tools;
1998
+ const toolsForAgent = allowedToolNames ? options.toolInfo.filter((t) => allowedToolNames.includes(t.name)) : [...options.toolInfo];
1999
+ if (!allowedToolNames || allowedToolNames.includes("runWorkflow")) {
2000
+ toolsForAgent.push({
2001
+ name: "runWorkflow",
2002
+ description: "Run a named sub-workflow defined in the current workflow file.",
2003
+ parameters: z22.object({
2004
+ workflowId: z22.string().describe("Sub-workflow id to run"),
2005
+ input: z22.any().nullish().describe("Optional input object for the sub-workflow")
2006
+ }),
2007
+ handler: async () => {
2008
+ return { type: "Error" /* Error */, message: { type: "error-text", value: "runWorkflow is virtual." } };
2009
+ }
2010
+ });
2011
+ }
2012
+ const allowedToolNameSet = new Set(toolsForAgent.map((t) => t.name));
2013
+ const systemPrompt = options.stepSystemPrompt?.({ workflowId, step: stepDef, input, state }) ?? [
2014
+ `You are an AI assistant executing a workflow step.`,
2015
+ "",
2016
+ "# Instructions",
2017
+ "- Execute the task defined in the user message.",
2018
+ "- Use the provided tools to accomplish the task.",
2019
+ "- Return the step output as valid JSON in markdown.",
2020
+ "- Do not ask for user input. If information is missing, make a reasonable assumption or fail."
2021
+ ].filter(Boolean).join("\n");
2022
+ const userContent = [
2023
+ `Workflow: ${workflowId}`,
2024
+ `Step: ${stepDef.id}`,
2025
+ `Task: ${stepDef.task}`,
2026
+ stepDef.expected_outcome ? `Expected outcome: ${stepDef.expected_outcome}` : "",
2027
+ `Workflow Input: ${JSON.stringify(input)}`,
2028
+ `Current State: ${JSON.stringify(state)}`
2029
+ ].filter(Boolean).join("\n");
2030
+ const runWorkflow = createRunWorkflowFn({ input, state, context, runInternal });
2031
+ const agentTools = {
2032
+ generateText: tools.generateText.bind(tools),
2033
+ taskEvent: tools.taskEvent.bind(tools),
2034
+ invokeTool: async ({ toolName, input: toolInput }) => {
2035
+ if (!allowedToolNameSet.has(toolName)) {
2036
+ return {
2037
+ type: "Error" /* Error */,
2038
+ message: { type: "error-text", value: `Tool '${toolName}' is not allowed in this step.` }
2039
+ };
2040
+ }
2041
+ if (toolName === "runWorkflow") {
2042
+ const subWorkflowId = toolInput?.workflowId;
2043
+ const subInput = toolInput?.input;
2044
+ if (typeof subWorkflowId !== "string") {
2045
+ return {
2046
+ type: "Error" /* Error */,
2047
+ message: { type: "error-text", value: "runWorkflow.workflowId must be a string." }
2048
+ };
2049
+ }
2050
+ try {
2051
+ const output = await runWorkflow(subWorkflowId, subInput);
2052
+ const jsonResult = { type: "json", value: output };
2053
+ return { type: "Reply" /* Reply */, message: jsonResult };
2054
+ } catch (error) {
2055
+ return {
2056
+ type: "Error" /* Error */,
2057
+ message: { type: "error-text", value: error instanceof Error ? error.message : String(error) }
2058
+ };
2059
+ }
2060
+ }
2061
+ return await tools.invokeTool({ toolName, input: toolInput });
2062
+ }
2063
+ };
2064
+ const result = await agentWorkflow(
2065
+ {
2066
+ tools: toolsForAgent,
2067
+ systemPrompt,
2068
+ userMessage: [{ role: "user", content: userContent }],
2069
+ maxToolRoundTrips: options.maxToolRoundTrips,
2070
+ model: options.model
2071
+ },
2072
+ { ...context, tools: agentTools }
2073
+ );
2074
+ if (result.type === "Exit") {
2075
+ if (result.object !== void 0) {
2076
+ return result.object;
2077
+ }
2078
+ const parsed = parseJsonFromMarkdown(result.message);
2079
+ if (parsed.success) {
2080
+ return parsed.data;
2081
+ }
2082
+ return result.message;
2083
+ }
2084
+ throw new Error(`Agent execution for step '${stepDef.id}' in workflow '${workflowId}' did not exit cleanly.`);
2085
+ }
2086
+ async function executeStep(stepDef, workflowId, input, state, context, options, compiledSteps, runInternal) {
2087
+ if (stepDef.code && options.allowUnsafeCodeExecution) {
2088
+ const fn = compileStep(stepDef, workflowId, compiledSteps);
2089
+ const runWorkflow = createRunWorkflowFn({ input, state, context, runInternal });
2090
+ const runtimeCtx = {
2091
+ workflowId,
2092
+ stepId: stepDef.id,
2093
+ input,
2094
+ state,
2095
+ tools: context.tools,
2096
+ logger: context.logger,
2097
+ step: context.step,
2098
+ runWorkflow,
2099
+ toolInfo: options.toolInfo
2100
+ };
2101
+ return await fn(runtimeCtx);
2102
+ }
2103
+ return await executeStepWithAgent(stepDef, workflowId, input, state, context, options, runInternal);
2104
+ }
2105
+ function createDynamicWorkflow(definition, options = {}) {
2106
+ if (typeof definition === "string") {
2107
+ const res = parseDynamicWorkflowDefinition(definition);
2108
+ if (!res.success) {
2109
+ throw new Error(res.error);
2110
+ }
2111
+ definition = res.definition;
2112
+ }
2113
+ const compiledSteps = /* @__PURE__ */ new Map();
2114
+ const runInternal = async (workflowId, input, context, inheritedState) => {
2115
+ const workflow = definition.workflows[workflowId];
2116
+ if (!workflow) {
2117
+ throw new Error(`Workflow '${workflowId}' not found`);
2118
+ }
2119
+ const state = { ...inheritedState };
2120
+ let lastOutput;
2121
+ for (const stepDef of workflow.steps) {
2122
+ const stepName = `${workflowId}.${stepDef.id}`;
2123
+ lastOutput = await context.step(stepName, async () => {
2124
+ return await executeStep(stepDef, workflowId, input, state, context, options, compiledSteps, runInternal);
2125
+ });
2126
+ const outputKey = stepDef.output ?? stepDef.id;
2127
+ state[outputKey] = lastOutput;
2128
+ }
2129
+ if (workflow.output) {
2130
+ return state[workflow.output];
2131
+ }
2132
+ return state;
2133
+ };
2134
+ return async (workflowId, input, context) => {
2135
+ return await runInternal(workflowId, input, context, {});
2136
+ };
2137
+ }
2138
+
2139
+ // src/workflow/dynamic-generator.workflow.ts
2140
+ import { z as z23 } from "zod";
2141
+ var GenerateWorkflowDefinitionInputSchema = z23.object({
2142
+ prompt: z23.string(),
2143
+ availableTools: z23.array(
2144
+ z23.object({
2145
+ name: z23.string(),
2146
+ description: z23.string()
2147
+ })
2148
+ ).optional()
2149
+ });
2150
+ var GenerateWorkflowCodeInputSchema = z23.object({
2151
+ workflow: WorkflowFileSchema
2152
+ });
2153
+ var WORKFLOW_DEFINITION_SYSTEM_PROMPT = `You are an expert workflow architect.
2154
+ Your task is to create a JSON workflow definition based on the user's request.
2155
+
2156
+ The workflow definition must follow this structure:
2157
+ {
2158
+ "workflows": {
2159
+ "workflowName": {
2160
+ "task": "Description of the workflow",
2161
+ "inputs": [
2162
+ { "id": "inputName", "description": "Description", "default": "optionalDefault" }
2163
+ ],
2164
+ "steps": [
2165
+ {
2166
+ "id": "stepId",
2167
+ "task": "Description of the step",
2168
+ "tools": ["toolName1", "toolName2"], // Optional list of tools needed
2169
+ "output": "outputVariableName", // Optional
2170
+ }
2171
+ ],
2172
+ "output": "outputVariableName" // Optional
2173
+ }
2174
+ }
2175
+ }
2176
+
2177
+ Constraints:
2178
+ - You MUST always include a workflow named 'main'. This is the entry point.
2179
+ - The 'main' workflow input must be either empty (no input) or a single string input.
2180
+ - Break down complex tasks into logical steps.
2181
+ - Define clear inputs and outputs.
2182
+
2183
+ Example 1:
2184
+ User: "Research a topic and summarize it."
2185
+ Output:
2186
+ \`\`\`json
2187
+ {
2188
+ "workflows": {
2189
+ "main": {
2190
+ "task": "Research a topic and provide a summary",
2191
+ "inputs": [
2192
+ { "id": "topic", "description": "The topic to research" }
2193
+ ],
2194
+ "steps": [
2195
+ {
2196
+ "id": "search",
2197
+ "task": "Search for information about the topic",
2198
+ "tools": ["search"],
2199
+ "output": "searchResults"
2200
+ },
2201
+ {
2202
+ "id": "summarize",
2203
+ "task": "Summarize the search results",
2204
+ "tools": ["generateText"],
2205
+ "output": "summary"
2206
+ }
2207
+ ],
2208
+ "output": "summary"
2209
+ }
2210
+ }
2211
+ }
2212
+ \`\`\`
2213
+
2214
+ Example 2:
2215
+ User: "Review urgent PRs. For each PR, run the review workflow."
2216
+ Output:
2217
+ \`\`\`json
2218
+ {
2219
+ "workflows": {
2220
+ "main": {
2221
+ "task": "Fetch urgent PRs and review them",
2222
+ "inputs": [],
2223
+ "steps": [
2224
+ {
2225
+ "id": "fetchPRs",
2226
+ "task": "Fetch list of urgent PRs",
2227
+ "tools": ["github_list_prs"],
2228
+ "output": "prs"
2229
+ },
2230
+ {
2231
+ "id": "reviewEachPR",
2232
+ "task": "Run review workflow for each PR",
2233
+ "tools": [],
2234
+ "output": "reviews"
2235
+ }
2236
+ ],
2237
+ "output": "reviews"
2238
+ },
2239
+ "reviewPR": {
2240
+ "task": "Review a single PR",
2241
+ "inputs": [
2242
+ { "id": "prId", "description": "ID of the PR to review" }
2243
+ ],
2244
+ "steps": [
2245
+ {
2246
+ "id": "getDiff",
2247
+ "task": "Get PR diff",
2248
+ "tools": ["github_get_diff"],
2249
+ "output": "diff"
2250
+ },
2251
+ {
2252
+ "id": "analyze",
2253
+ "task": "Analyze the diff",
2254
+ "tools": ["generateText"],
2255
+ "output": "analysis"
2256
+ }
2257
+ ],
2258
+ "output": "analysis"
2259
+ }
2260
+ }
2261
+ }
2262
+ \`\`\`
2263
+ `;
2264
+ var WORKFLOW_CODE_SYSTEM_PROMPT = `You are an expert TypeScript developer.
2265
+ Your task is to implement the TypeScript code for the steps in the provided workflow definition.
2266
+
2267
+ You will receive a JSON workflow definition where the "code" field is null.
2268
+ You must fill in the "code" field for each step with valid TypeScript code.
2269
+
2270
+ The code will be executed in an async function with the following signature:
2271
+ async (ctx) => {
2272
+ // Your code here
2273
+ }
2274
+
2275
+ The \`ctx\` object provides access to:
2276
+ - \`ctx.input\`: The workflow inputs.
2277
+ - \`ctx.state\`: A shared state object for passing data between steps.
2278
+ - \`ctx.tools\`: An object containing available tools.
2279
+ - \`ctx.runWorkflow\`: (workflowId: string, input?: any) => Promise<any>. Use this to run other workflows.
2280
+
2281
+ Guidelines:
2282
+ - Use \`await\` for asynchronous operations.
2283
+ - Return the output value of the step.
2284
+ - Access inputs via \`ctx.input.inputName\`.
2285
+ - Access previous step outputs via \`ctx.state.stepOutputName\`.
2286
+ - Use \`ctx.tools.invokeTool({ toolName: 'name', input: { ... } })\` to call tools.
2287
+ - Use \`ctx.tools.generateText({ messages: [...] })\` for LLM calls.
2288
+ - Use \`ctx.tools.invokeTool({ toolName: 'runAgent', input: { prompt: '...' } })\` for complex sub-tasks that require multiple steps or tools. Prefer this over \`generateText\` for advanced tasks.
2289
+
2290
+ Example Code for a step:
2291
+ \`\`\`typescript
2292
+ const searchResults = await ctx.tools.invokeTool({
2293
+ toolName: 'search',
2294
+ input: { query: ctx.input.topic }
2295
+ });
2296
+ return searchResults;
2297
+ \`\`\`
2298
+
2299
+ Example Code for LLM step:
2300
+ \`\`\`typescript
2301
+ const summary = await ctx.tools.generateText({
2302
+ messages: [
2303
+ { role: 'system', content: 'Summarize the following text.' },
2304
+ { role: 'user', content: ctx.state.searchResults }
2305
+ ]
2306
+ });
2307
+ return summary;
2308
+ \`\`\`
2309
+
2310
+ Example Code for runAgent:
2311
+ \`\`\`typescript
2312
+ const result = await ctx.tools.invokeTool({
2313
+ toolName: 'runAgent',
2314
+ input: {
2315
+ prompt: 'Research the history of the internet and write a summary.',
2316
+ tools: ['search', 'generateText']
2317
+ }
2318
+ });
2319
+ return result;
2320
+ \`\`\`
2321
+
2322
+ Example Code for invoking a sub-workflow:
2323
+ \`\`\`typescript
2324
+ const results = [];
2325
+ for (const pr of ctx.state.prs) {
2326
+ const review = await ctx.runWorkflow('reviewPR', { prId: pr.id });
2327
+ results.push(review);
2328
+ }
2329
+ return results;
2330
+ \`\`\`
2331
+
2332
+ Return the complete workflow JSON with the "code" fields populated.
2333
+ `;
2334
+ var generateWorkflowDefinitionWorkflow = async (input, ctx) => {
2335
+ let systemPrompt = WORKFLOW_DEFINITION_SYSTEM_PROMPT;
2336
+ if (input.availableTools && input.availableTools.length > 0) {
2337
+ const toolsList = input.availableTools.map((t) => `- ${t.name}: ${t.description}`).join("\n");
2338
+ systemPrompt += `
2339
+
2340
+ Available Tools:
2341
+ ${toolsList}
2342
+
2343
+ Use these tools when appropriate.`;
2344
+ }
2345
+ const result = await ctx.step("generate-workflow-definition", async () => {
2346
+ return agentWorkflow(
2347
+ {
2348
+ systemPrompt,
2349
+ userMessage: [{ role: "user", content: input.prompt }],
2350
+ tools: [],
2351
+ outputSchema: WorkflowFileSchema
2352
+ },
2353
+ ctx
2354
+ );
2355
+ });
2356
+ if (result.type === "Exit" && result.object) {
2357
+ return result.object;
2358
+ }
2359
+ throw new Error("Failed to generate workflow definition");
2360
+ };
2361
+ var generateWorkflowCodeWorkflow = async (input, ctx) => {
2362
+ const result = await ctx.step("generate-workflow-code", async () => {
2363
+ return agentWorkflow(
2364
+ {
2365
+ systemPrompt: WORKFLOW_CODE_SYSTEM_PROMPT,
2366
+ userMessage: [{ role: "user", content: JSON.stringify(input.workflow, null, 2) }],
2367
+ tools: [],
2368
+ outputSchema: WorkflowFileSchema
2369
+ },
2370
+ ctx
2371
+ );
2372
+ });
2373
+ if (result.type === "Exit" && result.object) {
2374
+ return result.object;
2375
+ }
2376
+ throw new Error("Failed to generate workflow code");
2377
+ };
2378
+
1899
2379
  // src/workflow/json-ai-types.ts
1900
2380
  var toJsonDataContent = (data) => {
1901
2381
  if (data instanceof URL) {
@@ -2094,6 +2574,8 @@ var makeStepFn = () => {
2094
2574
  };
2095
2575
  };
2096
2576
  export {
2577
+ GenerateWorkflowCodeInputSchema,
2578
+ GenerateWorkflowDefinitionInputSchema,
2097
2579
  MockProvider,
2098
2580
  TaskEventKind,
2099
2581
  TodoItemSchema,
@@ -2102,19 +2584,27 @@ export {
2102
2584
  UpdateTodoItemInputSchema,
2103
2585
  UpdateTodoItemOutputSchema,
2104
2586
  UsageMeter,
2587
+ WorkflowDefinitionSchema,
2588
+ WorkflowFileSchema,
2589
+ WorkflowInputDefinitionSchema,
2590
+ WorkflowStepDefinitionSchema,
2105
2591
  agentWorkflow,
2106
2592
  askFollowupQuestion_default as askFollowupQuestion,
2107
2593
  computeRateLimitBackoffSeconds,
2108
2594
  configSchema,
2109
2595
  createContext,
2596
+ createDynamicWorkflow,
2110
2597
  executeCommand_default as executeCommand,
2111
2598
  fetchUrl_default as fetchUrl,
2112
2599
  fromJsonModelMessage,
2600
+ generateWorkflowCodeWorkflow,
2601
+ generateWorkflowDefinitionWorkflow,
2113
2602
  getTodoItem_default as getTodoItem,
2114
2603
  listFiles_default as listFiles,
2115
2604
  listMemoryTopics_default as listMemoryTopics,
2116
2605
  listTodoItems_default as listTodoItems,
2117
2606
  makeStepFn,
2607
+ parseDynamicWorkflowDefinition,
2118
2608
  parseJsonFromMarkdown,
2119
2609
  providerModelSchema,
2120
2610
  readBinaryFile_default as readBinaryFile,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polka-codes/core",
3
- "version": "0.9.77",
3
+ "version": "0.9.79",
4
4
  "license": "AGPL-3.0",
5
5
  "author": "github@polka.codes",
6
6
  "type": "module",