File size: 7,908 Bytes
05c5ed5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import {
  ObjectJsonSchema7,
  TipTapMentionJsonContent,
  TipTapMentionJsonContentPart,
} from "app-types/util";
import { JSONSchema7 } from "json-schema";
import {
  UINode,
  OutputSchemaSourceKey,
  WorkflowNodeData,
} from "./workflow.interface";
import { exclude, isString } from "lib/utils";
import { DBEdge, DBNode } from "app-types/workflow";
import { Edge } from "@xyflow/react";
import { GraphEvent } from "ts-edge";
import { UIMessage } from "ai";

export const defaultObjectJsonSchema: ObjectJsonSchema7 = {
  type: "object",
  properties: {},
};

export function findAccessibleNodeIds({
  nodeId,
  nodes,
  edges,
}: {
  nodeId: string;
  nodes: WorkflowNodeData[];
  edges: { target: string; source: string }[];
}): string[] {
  const accessibleNodes: string[] = [];
  const allNodeIds = nodes.map((node) => node.id);
  let currentNodes = [nodeId];
  while (currentNodes.length > 0) {
    const targets = [...currentNodes];
    currentNodes = [];
    for (const target of targets) {
      const sources = edges
        .filter(
          (edge) => edge.target === target && allNodeIds.includes(edge.source),
        )
        .map((edge) => edge.source);
      accessibleNodes.push(...sources);
      currentNodes.push(...sources);
    }
  }
  return accessibleNodes;
}

export function findJsonSchemaByPath(
  schema: ObjectJsonSchema7,
  path: string[],
): JSONSchema7 | undefined {
  const [key, ...rest] = path;
  if (rest.length === 0) {
    return schema.properties?.[key] as JSONSchema7;
  }
  return findJsonSchemaByPath(
    schema.properties![key] as ObjectJsonSchema7,
    rest,
  );
}

export function findAvailableSchemaBySource({
  nodeId,
  source,
  nodes,
  edges,
}: {
  nodeId: string;
  source: OutputSchemaSourceKey;
  nodes: WorkflowNodeData[];
  edges: { target: string; source: string }[];
}): {
  nodeName: string;
  path: string[];
  notFound?: boolean;
  type?: string;
} {
  const accessibleNodes = findAccessibleNodeIds({
    nodeId,
    nodes,
    edges,
  });
  const data = {
    nodeName: "ERROR",
    path: source.path,
    notFound: true,
    type: undefined as undefined | string,
  };
  if (!accessibleNodes.includes(source.nodeId)) return data;

  const sourceNode = nodes.find((node) => node.id === source.nodeId)!;
  if (!sourceNode) return data;
  data.nodeName = sourceNode.name;
  const schema = findJsonSchemaByPath(sourceNode.outputSchema, source.path);
  if (!schema) return data;
  data.notFound = false;
  data.type = isString(schema) ? schema : (schema?.type as string);

  return data;
}

export function convertUINodeToDBNode(
  workflowId: string,
  node: UINode,
): Omit<DBNode, "createdAt" | "updatedAt"> {
  return {
    id: node.id,
    workflowId,
    kind: node.data.kind,
    name: node.data.name,
    description: node.data.description || "",
    nodeConfig: exclude(node.data, ["id", "name", "description", "runtime"]),
    uiConfig: {
      position: node.position,
      type: node.type || "default",
    },
  };
}

export function convertDBNodeToUINode(node: DBNode): UINode {
  const uiNode: UINode = {
    id: node.id,
    ...(node.uiConfig as any),
    data: {
      ...(node.nodeConfig as any),
      id: node.id,
      name: node.name,
      description: node.description || "",
      kind: node.kind as any,
    },
    type: node.uiConfig.type || "default",
  };
  return uiNode;
}

export function convertUIEdgeToDBEdge(
  workflowId: string,
  edge: Edge,
): Omit<DBEdge, "createdAt" | "updatedAt"> {
  return {
    id: edge.id,
    source: edge.source,
    target: edge.target,
    uiConfig: {
      sourceHandle: edge.sourceHandle ?? undefined,
      targetHandle: edge.targetHandle ?? undefined,
      label: edge.label ?? undefined,
    },
    workflowId,
  };
}

export function convertDBEdgeToUIEdge(edge: DBEdge): Edge {
  return {
    id: edge.id,
    source: edge.source,
    target: edge.target,
    ...edge.uiConfig,
  };
}

// Workflow Stream Processing Functions
export const WORKFLOW_STREAM_DELIMITER = "\n";
export const WORKFLOW_STREAM_PREFIX = "WF_EVENT:";

export function encodeWorkflowEvent(event: GraphEvent): string {
  const eventData = {
    timestamp: Date.now(),
    ...event,
  };
  return `${WORKFLOW_STREAM_PREFIX}${JSON.stringify(eventData)}${WORKFLOW_STREAM_DELIMITER}`;
}

export function decodeWorkflowEvents(buffer: string): {
  events: GraphEvent[];
  remainingBuffer: string;
} {
  const lines = buffer.split(WORKFLOW_STREAM_DELIMITER);
  const remainingBuffer = lines.pop() || "";
  const events: GraphEvent[] = [];

  for (const line of lines) {
    if (line.startsWith(WORKFLOW_STREAM_PREFIX)) {
      try {
        const eventJson = line.slice(WORKFLOW_STREAM_PREFIX.length);
        const event = JSON.parse(eventJson);
        events.push(event);
      } catch (error) {
        console.error("Failed to parse workflow event:", line, error);
      }
    }
  }

  return { events, remainingBuffer };
}

export function convertTiptapJsonToText({
  json,
  mentionParser,
  getOutput,
}: {
  json: TipTapMentionJsonContent;
  mentionParser?: (
    part: Extract<TipTapMentionJsonContentPart, { type: "mention" }>,
  ) => string;
  getOutput: (key: OutputSchemaSourceKey) => any;
}): string {
  const parser =
    mentionParser ||
    ((part) => {
      const key = JSON.parse(part.attrs.label) as OutputSchemaSourceKey;
      const mentionItem = getOutput(key) || "";
      const value =
        typeof mentionItem == "object"
          ? JSON.stringify(mentionItem)
          : String(mentionItem);
      return value;
    });
  // Recursively process TipTap JSON content
  const processContent = (content: any[]): string => {
    return content
      .flatMap((item) => {
        if (!item) return "";

        // Handle paragraph
        if (item.type === "paragraph") {
          if (!item.content) return "";
          return processContent(item.content);
        }

        // Handle text
        if (item.type === "text") {
          return item.text || "";
        }

        // Handle mention
        if (item.type === "mention") {
          return parser(item);
        }

        // Handle hard break
        if (item.type === "hardBreak") {
          return "\n\n";
        }

        // Handle bullet list
        if (item.type === "bulletList") {
          if (!item.content) return "";
          return (
            item.content
              .map((listItem: any) => {
                const itemContent = processContent(listItem.content || []);
                return `• ${itemContent.trim()}`;
              })
              .join("\n") + "\n"
          );
        }

        // Handle list item
        if (item.type === "listItem") {
          if (!item.content) return "";
          return processContent(item.content);
        }

        // Recursively process other elements with content
        if (item.content) {
          return processContent(item.content);
        }

        return "";
      })
      .join("")
      .trim();
  };

  return processContent(json.content || []) || "";
}

export function convertTiptapJsonToAiMessage({
  role,
  getOutput,
  json,
}: {
  role: "user" | "assistant" | "system";
  getOutput: (key: OutputSchemaSourceKey) => any;
  json?: TipTapMentionJsonContent;
}): Omit<UIMessage, "id"> {
  if (!json)
    return {
      role,
      parts: [],
    };

  const text = convertTiptapJsonToText({
    json,
    getOutput,
    mentionParser: (part) => {
      const key = JSON.parse(part.attrs.label) as OutputSchemaSourceKey;
      const mentionItem = getOutput(key) || "";
      const value =
        typeof mentionItem == "object"
          ? "\n```json\n" + JSON.stringify(mentionItem, null, 2) + "\n```\n"
          : mentionItem
            ? String(mentionItem)
            : "";
      return value;
    },
  });

  return {
    role,
    parts: [
      {
        type: "text",
        text,
      },
    ],
  };
}