@kapeta/local-cluster-service 0.44.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/cjs/index.js +2 -0
  3. package/dist/cjs/src/codeGeneratorManager.d.ts +1 -0
  4. package/dist/cjs/src/codeGeneratorManager.js +12 -6
  5. package/dist/cjs/src/middleware/cors.d.ts +1 -0
  6. package/dist/cjs/src/middleware/kapeta.d.ts +1 -0
  7. package/dist/cjs/src/middleware/stringBody.d.ts +1 -0
  8. package/dist/cjs/src/storm/codegen.d.ts +40 -0
  9. package/dist/cjs/src/storm/codegen.js +210 -0
  10. package/dist/cjs/src/storm/event-parser.d.ts +70 -0
  11. package/dist/cjs/src/storm/event-parser.js +522 -0
  12. package/dist/cjs/src/storm/events.d.ts +126 -0
  13. package/dist/cjs/src/storm/events.js +6 -0
  14. package/dist/cjs/src/storm/routes.d.ts +7 -0
  15. package/dist/cjs/src/storm/routes.js +87 -0
  16. package/dist/cjs/src/storm/stormClient.d.ts +13 -0
  17. package/dist/cjs/src/storm/stormClient.js +80 -0
  18. package/dist/cjs/src/storm/stream.d.ts +45 -0
  19. package/dist/cjs/src/storm/stream.js +57 -0
  20. package/dist/esm/index.js +2 -0
  21. package/dist/esm/src/codeGeneratorManager.d.ts +1 -0
  22. package/dist/esm/src/codeGeneratorManager.js +12 -6
  23. package/dist/esm/src/middleware/cors.d.ts +1 -0
  24. package/dist/esm/src/middleware/kapeta.d.ts +1 -0
  25. package/dist/esm/src/middleware/stringBody.d.ts +1 -0
  26. package/dist/esm/src/storm/codegen.d.ts +40 -0
  27. package/dist/esm/src/storm/codegen.js +210 -0
  28. package/dist/esm/src/storm/event-parser.d.ts +70 -0
  29. package/dist/esm/src/storm/event-parser.js +522 -0
  30. package/dist/esm/src/storm/events.d.ts +126 -0
  31. package/dist/esm/src/storm/events.js +6 -0
  32. package/dist/esm/src/storm/routes.d.ts +7 -0
  33. package/dist/esm/src/storm/routes.js +87 -0
  34. package/dist/esm/src/storm/stormClient.d.ts +13 -0
  35. package/dist/esm/src/storm/stormClient.js +80 -0
  36. package/dist/esm/src/storm/stream.d.ts +45 -0
  37. package/dist/esm/src/storm/stream.js +57 -0
  38. package/index.ts +2 -0
  39. package/package.json +3 -3
  40. package/src/codeGeneratorManager.ts +17 -8
  41. package/src/storm/codegen.ts +266 -0
  42. package/src/storm/event-parser.ts +668 -0
  43. package/src/storm/events.ts +168 -0
  44. package/src/storm/routes.ts +111 -0
  45. package/src/storm/stormClient.ts +106 -0
  46. package/src/storm/stream.ts +96 -0
  47. package/src/utils/BlockInstanceRunner.ts +4 -2
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Copyright 2023 Kapeta Inc.
3
+ * SPDX-License-Identifier: BUSL-1.1
4
+ */
5
+ export type StormResourceType = 'API' | 'DATABASE' | 'CLIENT' | 'JWTPROVIDER' | 'JWTCONSUMER' | 'WEBFRAGMENT' | 'WEBPAGE' | 'SMTPCLIENT' | 'EXTERNAL_API' | 'SUBSCRIBER' | 'PUBLISHER' | 'QUEUE' | 'EXCHANGE';
6
+ export type StormBlockType = 'BACKEND' | 'FRONTEND' | 'GATEWAY' | 'MQ' | 'CLI' | 'DESKTOP';
7
+ export interface StormBlockInfo {
8
+ type: StormBlockType;
9
+ name: string;
10
+ description: string;
11
+ resources: {
12
+ type: StormResourceType;
13
+ name: string;
14
+ description: string;
15
+ }[];
16
+ }
17
+ export interface StormBlockInfoFilled extends StormBlockInfo {
18
+ apis: string[];
19
+ types: string[];
20
+ models: string[];
21
+ }
22
+ export interface StormEventCreateBlock {
23
+ type: 'CREATE_BLOCK';
24
+ reason: string;
25
+ created: number;
26
+ payload: StormBlockInfo;
27
+ }
28
+ export interface StormConnection {
29
+ fromComponent: string;
30
+ fromResource: string;
31
+ fromResourceType: StormResourceType;
32
+ toComponent: string;
33
+ toResource: string;
34
+ toResourceType: StormResourceType;
35
+ }
36
+ export interface StormEventCreateConnection {
37
+ type: 'CREATE_CONNECTION';
38
+ reason: string;
39
+ created: number;
40
+ payload: StormConnection;
41
+ }
42
+ export interface StormEventCreatePlanProperties {
43
+ type: 'CREATE_PLAN_PROPERTIES';
44
+ reason: string;
45
+ created: number;
46
+ payload: {
47
+ name: string;
48
+ description: string;
49
+ };
50
+ }
51
+ export interface StormEventInvalidResponse {
52
+ type: 'INVALID_RESPONSE';
53
+ reason: string;
54
+ created: number;
55
+ payload: {
56
+ error: string;
57
+ };
58
+ }
59
+ export interface StormEventPlanRetry {
60
+ type: 'PLAN_RETRY' | 'PLAN_RETRY_FAILED';
61
+ reason: string;
62
+ created: number;
63
+ payload: {
64
+ error: string;
65
+ };
66
+ }
67
+ export interface StormEventCreateDSL {
68
+ type: 'CREATE_API' | 'CREATE_TYPE' | 'CREATE_MODEL';
69
+ reason: string;
70
+ created: number;
71
+ payload: {
72
+ blockName: string;
73
+ content: string;
74
+ };
75
+ }
76
+ export interface StormEventError {
77
+ type: 'INVALID_RESPONSE' | 'ERROR_INTERNAL';
78
+ reason: string;
79
+ created: number;
80
+ payload: {
81
+ error: string;
82
+ };
83
+ }
84
+ export interface ScreenTemplate {
85
+ name: string;
86
+ template: string;
87
+ description: string;
88
+ url: string;
89
+ }
90
+ export interface StormEventScreen {
91
+ type: 'SCREEN';
92
+ reason: string;
93
+ created: number;
94
+ payload: {
95
+ blockName: string;
96
+ name: string;
97
+ template: string;
98
+ description: string;
99
+ url: string;
100
+ };
101
+ }
102
+ export interface StormEventScreenCandidate {
103
+ type: 'SCREEN_CANDIDATE';
104
+ reason: string;
105
+ created: number;
106
+ payload: {
107
+ name: string;
108
+ description: string;
109
+ url: string;
110
+ };
111
+ }
112
+ export interface StormEventFile {
113
+ type: 'FILE';
114
+ reason: string;
115
+ created: number;
116
+ payload: {
117
+ filename: string;
118
+ content: string;
119
+ blockRef: string;
120
+ };
121
+ }
122
+ export interface StormEventDone {
123
+ type: 'DONE';
124
+ created: number;
125
+ }
126
+ export type StormEvent = StormEventCreateBlock | StormEventCreateConnection | StormEventCreatePlanProperties | StormEventInvalidResponse | StormEventPlanRetry | StormEventCreateDSL | StormEventError | StormEventScreen | StormEventScreenCandidate | StormEventFile | StormEventDone;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright 2023 Kapeta Inc.
4
+ * SPDX-License-Identifier: BUSL-1.1
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Copyright 2023 Kapeta Inc.
3
+ * SPDX-License-Identifier: BUSL-1.1
4
+ */
5
+ /// <reference types="express" />
6
+ declare const router: import("express").Router;
7
+ export default router;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright 2023 Kapeta Inc.
4
+ * SPDX-License-Identifier: BUSL-1.1
5
+ */
6
+ var __importDefault = (this && this.__importDefault) || function (mod) {
7
+ return (mod && mod.__esModule) ? mod : { "default": mod };
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ const express_promise_router_1 = __importDefault(require("express-promise-router"));
11
+ const cors_1 = require("../middleware/cors");
12
+ const stringBody_1 = require("../middleware/stringBody");
13
+ const stormClient_1 = require("./stormClient");
14
+ const event_parser_1 = require("./event-parser");
15
+ const codegen_1 = require("./codegen");
16
+ const router = (0, express_promise_router_1.default)();
17
+ router.use('/', cors_1.corsHandler);
18
+ router.use('/', stringBody_1.stringBody);
19
+ router.post('/:handle/all', async (req, res) => {
20
+ const handle = req.params.handle;
21
+ try {
22
+ const stormOptions = await (0, event_parser_1.resolveOptions)();
23
+ const eventParser = new event_parser_1.StormEventParser(stormOptions);
24
+ const aiRequest = JSON.parse(req.stringBody ?? '{}');
25
+ const metaStream = await stormClient_1.stormClient.createMetadata(aiRequest.prompt, aiRequest.history);
26
+ res.set('Content-Type', 'application/x-ndjson');
27
+ metaStream.on('data', (data) => {
28
+ eventParser.addEvent(data);
29
+ });
30
+ await streamStormPartialResponse(metaStream, res);
31
+ if (!eventParser.isValid()) {
32
+ // We can't continue if the meta stream is invalid
33
+ res.write({
34
+ type: 'ERROR_INTERNAL',
35
+ payload: { error: eventParser.getError() },
36
+ reason: 'Failed to generate system',
37
+ created: Date.now(),
38
+ });
39
+ res.end();
40
+ return;
41
+ }
42
+ const result = eventParser.toResult(handle);
43
+ const stormCodegen = new codegen_1.StormCodegen(aiRequest.prompt, result.blocks, eventParser.getEvents());
44
+ const codegenStream = streamStormPartialResponse(stormCodegen.getStream(), res);
45
+ await stormCodegen.process();
46
+ await codegenStream;
47
+ sendDone(res);
48
+ }
49
+ catch (err) {
50
+ sendError(err, res);
51
+ }
52
+ });
53
+ function sendDone(res) {
54
+ res.write(JSON.stringify({
55
+ type: 'DONE',
56
+ created: Date.now(),
57
+ }) + '\n');
58
+ res.end();
59
+ }
60
+ function sendError(err, res) {
61
+ console.error('Failed to send prompt', err);
62
+ if (res.headersSent) {
63
+ res.write(JSON.stringify({
64
+ type: 'ERROR_INTERNAL',
65
+ created: Date.now(),
66
+ payload: { error: err.message },
67
+ reason: 'Failed while sending prompt',
68
+ }) + '\n');
69
+ }
70
+ else {
71
+ res.status(400).send({ error: err.message });
72
+ }
73
+ }
74
+ function streamStormPartialResponse(result, res) {
75
+ return new Promise((resolve, reject) => {
76
+ result.on('data', (data) => {
77
+ res.write(JSON.stringify(data) + '\n');
78
+ });
79
+ result.on('error', (err) => {
80
+ reject(err);
81
+ });
82
+ result.on('end', () => {
83
+ resolve();
84
+ });
85
+ });
86
+ }
87
+ exports.default = router;
@@ -0,0 +1,13 @@
1
+ import { ConversationItem, StormFileImplementationPrompt, StormStream, StormUIImplementationPrompt } from './stream';
2
+ export declare const STORM_ID = "storm";
3
+ declare class StormClient {
4
+ private readonly _baseUrl;
5
+ constructor();
6
+ private createOptions;
7
+ private send;
8
+ createMetadata(prompt: string, history?: ConversationItem[]): Promise<StormStream>;
9
+ createUIImplementation(prompt: StormUIImplementationPrompt, history?: ConversationItem[]): Promise<StormStream>;
10
+ createServiceImplementation(prompt: StormFileImplementationPrompt, history?: ConversationItem[]): Promise<StormStream>;
11
+ }
12
+ export declare const stormClient: StormClient;
13
+ export {};
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.stormClient = exports.STORM_ID = void 0;
7
+ /**
8
+ * Copyright 2023 Kapeta Inc.
9
+ * SPDX-License-Identifier: BUSL-1.1
10
+ */
11
+ const nodejs_api_client_1 = require("@kapeta/nodejs-api-client");
12
+ const utils_1 = require("../utils/utils");
13
+ const promises_1 = __importDefault(require("node:readline/promises"));
14
+ const node_stream_1 = require("node:stream");
15
+ const stream_1 = require("./stream");
16
+ exports.STORM_ID = 'storm';
17
+ class StormClient {
18
+ _baseUrl;
19
+ constructor() {
20
+ this._baseUrl = (0, utils_1.getRemoteUrl)('ai-service', 'https://ai.kapeta.com');
21
+ }
22
+ createOptions(path, method, body) {
23
+ const url = `${this._baseUrl}${path}`;
24
+ const headers = {
25
+ 'Content-Type': 'application/json',
26
+ };
27
+ const api = new nodejs_api_client_1.KapetaAPI();
28
+ if (api.hasToken()) {
29
+ //headers['Authorization'] = `Bearer ${api.getAccessToken()}`; //TODO: Enable authentication
30
+ }
31
+ return {
32
+ url,
33
+ method: method,
34
+ body: JSON.stringify(body),
35
+ headers,
36
+ };
37
+ }
38
+ async send(path, body, method = 'POST') {
39
+ const stringPrompt = typeof body.prompt === 'string' ? body.prompt : JSON.stringify(body.prompt);
40
+ const options = this.createOptions(path, method, {
41
+ prompt: stringPrompt,
42
+ history: body.history,
43
+ });
44
+ const out = new stream_1.StormStream(stringPrompt, body.history);
45
+ const response = await fetch(options.url, options);
46
+ if (response.status !== 200) {
47
+ throw new Error(`Got error response from ${options.url}: ${response.status}\nContent: ${await response.text()}`);
48
+ }
49
+ const jsonLStream = promises_1.default.createInterface(node_stream_1.Readable.fromWeb(response.body));
50
+ jsonLStream.on('line', (line) => {
51
+ out.addJSONLine(line);
52
+ });
53
+ jsonLStream.on('error', (error) => {
54
+ out.emit('error', error);
55
+ });
56
+ jsonLStream.on('close', () => {
57
+ out.end();
58
+ });
59
+ return out;
60
+ }
61
+ createMetadata(prompt, history) {
62
+ return this.send('/v2/all', {
63
+ history: history ?? [],
64
+ prompt: prompt,
65
+ });
66
+ }
67
+ createUIImplementation(prompt, history) {
68
+ return this.send('/v2/ui/merge', {
69
+ history: history ?? [],
70
+ prompt,
71
+ });
72
+ }
73
+ createServiceImplementation(prompt, history) {
74
+ return this.send('/v2/services/merge', {
75
+ history: history ?? [],
76
+ prompt,
77
+ });
78
+ }
79
+ }
80
+ exports.stormClient = new StormClient();
@@ -0,0 +1,45 @@
1
+ /// <reference types="node" />
2
+ /**
3
+ * Copyright 2023 Kapeta Inc.
4
+ * SPDX-License-Identifier: BUSL-1.1
5
+ */
6
+ import { EventEmitter } from 'node:events';
7
+ import { StormEvent } from './events';
8
+ import { AIFileTypes, GeneratedFile } from '@kapeta/codegen';
9
+ export declare class StormStream extends EventEmitter {
10
+ private history;
11
+ private lines;
12
+ constructor(prompt?: string, history?: ConversationItem[]);
13
+ addJSONLine(line: string): void;
14
+ end(): void;
15
+ on(event: 'end', listener: () => void): this;
16
+ on(event: 'error', listener: (e: Error) => void): this;
17
+ on(event: 'data', listener: (data: StormEvent) => void): this;
18
+ emit(event: 'end'): boolean;
19
+ emit(event: 'error', e: Error): boolean;
20
+ emit(event: 'data', data: StormEvent): boolean;
21
+ waitForDone(): Promise<void>;
22
+ }
23
+ export interface ConversationItem {
24
+ role: 'user' | 'model';
25
+ content: string;
26
+ }
27
+ export interface StormContextRequest<T = string> {
28
+ history?: ConversationItem[];
29
+ prompt: T;
30
+ }
31
+ export interface StormFileInfo extends GeneratedFile {
32
+ type: AIFileTypes;
33
+ }
34
+ export interface StormFileImplementationPrompt {
35
+ context: StormFileInfo[];
36
+ template: StormFileInfo;
37
+ prompt: string;
38
+ }
39
+ export interface StormUIImplementationPrompt {
40
+ events: StormEvent[];
41
+ templates: StormFileInfo[];
42
+ context: StormFileInfo[];
43
+ blockName: string;
44
+ prompt: string;
45
+ }
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StormStream = void 0;
4
+ /**
5
+ * Copyright 2023 Kapeta Inc.
6
+ * SPDX-License-Identifier: BUSL-1.1
7
+ */
8
+ const node_events_1 = require("node:events");
9
+ class StormStream extends node_events_1.EventEmitter {
10
+ history;
11
+ lines = [];
12
+ constructor(prompt = '', history) {
13
+ super();
14
+ this.history = history ?? [];
15
+ this.history.push({
16
+ role: 'user',
17
+ content: prompt,
18
+ });
19
+ }
20
+ addJSONLine(line) {
21
+ try {
22
+ this.lines.push(line);
23
+ const event = JSON.parse(line);
24
+ if (!event.created) {
25
+ event.created = Date.now();
26
+ }
27
+ this.emit('data', event);
28
+ }
29
+ catch (e) {
30
+ this.emit('error', e);
31
+ }
32
+ }
33
+ end() {
34
+ this.history.push({
35
+ role: 'model',
36
+ content: this.lines.join('\n'),
37
+ });
38
+ this.emit('end');
39
+ }
40
+ on(event, listener) {
41
+ return super.on(event, listener);
42
+ }
43
+ emit(eventName, ...args) {
44
+ return super.emit(eventName, ...args);
45
+ }
46
+ waitForDone() {
47
+ return new Promise((resolve, reject) => {
48
+ this.on('error', (err) => {
49
+ reject(err);
50
+ });
51
+ this.on('end', () => {
52
+ resolve();
53
+ });
54
+ });
55
+ }
56
+ }
57
+ exports.StormStream = StormStream;
package/index.ts CHANGED
@@ -24,6 +24,7 @@ import AttachmentRoutes from './src/attachments/routes';
24
24
  import TaskRoutes from './src/tasks/routes';
25
25
  import APIRoutes from './src/api';
26
26
  import AIRoutes from './src/ai/routes';
27
+ import StormRoutes from './src/storm/routes';
27
28
  import { isLinux } from './src/utils/utils';
28
29
  import request from 'request';
29
30
  import { repositoryManager } from './src/repositoryManager';
@@ -74,6 +75,7 @@ function createServer() {
74
75
  app.use('/tasks', TaskRoutes);
75
76
  app.use('/api', APIRoutes);
76
77
  app.use('/ai', AIRoutes);
78
+ app.use('/storm', StormRoutes);
77
79
 
78
80
  app.get('/status', async (req, res) => {
79
81
  res.send({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kapeta/local-cluster-service",
3
- "version": "0.44.0",
3
+ "version": "0.46.0",
4
4
  "description": "Manages configuration, ports and service discovery for locally running Kapeta systems",
5
5
  "type": "commonjs",
6
6
  "exports": {
@@ -50,9 +50,9 @@
50
50
  },
51
51
  "homepage": "https://github.com/kapetacom/local-cluster-service#readme",
52
52
  "dependencies": {
53
- "@kapeta/codegen": "^1.3.0",
53
+ "@kapeta/codegen": "^1.4.0",
54
54
  "@kapeta/config-mapper": "^1.2.1",
55
- "@kapeta/kaplang-core": "^1.14.2",
55
+ "@kapeta/kaplang-core": "^1.16.0",
56
56
  "@kapeta/local-cluster-config": "^0.4.2",
57
57
  "@kapeta/nodejs-api-client": ">=0.2.0 <2",
58
58
  "@kapeta/nodejs-process": "^1.2.0",
@@ -16,6 +16,22 @@ const TARGET_KIND = 'core/language-target';
16
16
  const BLOCK_TYPE_REGEX = /^core\/block-type.*/;
17
17
 
18
18
  class CodeGeneratorManager {
19
+ public async ensureTarget(targetKind: string) {
20
+ const targetRef = normalizeKapetaUri(targetKind);
21
+
22
+ // Automatically downloads target if not available
23
+ const targetAsset = await assetManager.getAsset(targetRef);
24
+
25
+ if (!targetAsset) {
26
+ console.error('Language target not found: %s', targetKind);
27
+ return false;
28
+ }
29
+
30
+ await this.ensureLanguageTargetInRegistry(targetAsset?.path, targetAsset?.version, targetAsset?.data);
31
+
32
+ return true;
33
+ }
34
+
19
35
  private async ensureLanguageTargetInRegistry(path: string, version: string, definition: Definition) {
20
36
  const key = `${definition.metadata.name}:${version}`;
21
37
 
@@ -81,17 +97,10 @@ class CodeGeneratorManager {
81
97
  return;
82
98
  }
83
99
 
84
- const targetRef = normalizeKapetaUri(yamlContent.spec.target?.kind);
85
-
86
- // Automatically downloads target if not available
87
- const targetAsset = await assetManager.getAsset(targetRef);
88
-
89
- if (!targetAsset) {
90
- console.error('Language target not found: %s', yamlContent.spec.target?.kind);
100
+ if (!(await this.ensureTarget(yamlContent.spec.target?.kind))) {
91
101
  return;
92
102
  }
93
103
 
94
- await this.ensureLanguageTargetInRegistry(targetAsset?.path, targetAsset?.version, targetAsset?.data);
95
104
  const baseDir = Path.dirname(yamlFile);
96
105
  console.log('Generating code for path: %s', baseDir);
97
106
  const codeGenerator = new BlockCodeGenerator(yamlContent as BlockDefinition);