@misterscan/sesi 1.1.1

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 (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +191 -0
  3. package/bin/sesi.js +56 -0
  4. package/dist/ai-runtime.d.ts +15 -0
  5. package/dist/ai-runtime.d.ts.map +1 -0
  6. package/dist/ai-runtime.js +214 -0
  7. package/dist/ai-runtime.js.map +1 -0
  8. package/dist/builtins.d.ts +7 -0
  9. package/dist/builtins.d.ts.map +1 -0
  10. package/dist/builtins.js +473 -0
  11. package/dist/builtins.js.map +1 -0
  12. package/dist/index.d.ts +3 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +72 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/interpreter.d.ts +36 -0
  17. package/dist/interpreter.d.ts.map +1 -0
  18. package/dist/interpreter.js +495 -0
  19. package/dist/interpreter.js.map +1 -0
  20. package/dist/lexer.d.ts +26 -0
  21. package/dist/lexer.d.ts.map +1 -0
  22. package/dist/lexer.js +340 -0
  23. package/dist/lexer.js.map +1 -0
  24. package/dist/parser.d.ts +55 -0
  25. package/dist/parser.d.ts.map +1 -0
  26. package/dist/parser.js +1022 -0
  27. package/dist/parser.js.map +1 -0
  28. package/dist/types.d.ts +304 -0
  29. package/dist/types.d.ts.map +1 -0
  30. package/dist/types.js +63 -0
  31. package/dist/types.js.map +1 -0
  32. package/docs/ARCHITECTURE.md +430 -0
  33. package/docs/BUILTINS.md +577 -0
  34. package/docs/COMPARISON.md +334 -0
  35. package/docs/DISTRIBUTED_SYSTEMS.md +71 -0
  36. package/docs/IMAGE_GENERATION.md +76 -0
  37. package/docs/IMPLEMENTATION_SUMMARY.md +533 -0
  38. package/docs/QUICKSTART.md +351 -0
  39. package/docs/README.md +191 -0
  40. package/docs/ROADMAP.md +408 -0
  41. package/docs/SPECIFICATION.md +462 -0
  42. package/docs/SYSTEMS_REASONING.md +522 -0
  43. package/examples/01_hello.sesi +2 -0
  44. package/examples/02_variables.sesi +11 -0
  45. package/examples/03_functions.sesi +6 -0
  46. package/examples/04_conditionals.sesi +6 -0
  47. package/examples/05_loops.sesi +12 -0
  48. package/examples/06_arrays_objects.sesi +18 -0
  49. package/examples/07_prompts.sesi +10 -0
  50. package/examples/08_model_call.sesi +5 -0
  51. package/examples/09_structured_output.sesi +7 -0
  52. package/examples/10_code_generation.sesi +5 -0
  53. package/examples/11_memory_conversation.sesi +16 -0
  54. package/examples/12_classification.sesi +8 -0
  55. package/examples/13_data_pipeline.sesi +35 -0
  56. package/examples/14_folder_explainer.sesi +58 -0
  57. package/examples/15_image_generation.sesi +17 -0
  58. package/main/atm_deposit.sesi +37 -0
  59. package/main/atm_withdraw.sesi +37 -0
  60. package/main/data.txt +1 -0
  61. package/main/math_aggregator.sesi +15 -0
  62. package/main/math_generator.sesi +7 -0
  63. package/main/math_processor.sesi +23 -0
  64. package/main/orchestrator.sesi +15 -0
  65. package/main/playground.sesi +1 -0
  66. package/main/setup_swarm.sesi +5 -0
  67. package/main/start.sesi +13 -0
  68. package/main/tax_calculator.sesi +15 -0
  69. package/main/tests/compare.sesi +23 -0
  70. package/main/tests/compare.ts +104 -0
  71. package/main/tests/debug.sesi +1 -0
  72. package/main/tests/demo.sesi +24 -0
  73. package/main/tests/primitive_validation.sesi +18 -0
  74. package/main/tests/test_connection.sesi +4 -0
  75. package/main/tests/test_failure_debug.sesi +2 -0
  76. package/main/tests/test_image.sesi +3 -0
  77. package/main/tests/test_parser_config.sesi +2 -0
  78. package/main/tests/test_syntax.sesi +3 -0
  79. package/main/tests/test_tool_call.sesi +14 -0
  80. package/main/tests/try.sesi +7 -0
  81. package/main/vault.sesi +15 -0
  82. package/package.json +50 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Misterscan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,191 @@
1
+ <p align="center">
2
+ <img src="./sesi-logo.svg" alt="Sesi Logo" width="250" />
3
+ </p>
4
+
5
+ <h1 align="center">Sesi: A High-Performance Systems Language</h1>
6
+
7
+ <p align="center">
8
+ <em>Pronounced "say-see" — What you say, you'll see.</em>
9
+ </p>
10
+
11
+ <p align="center">
12
+ <img alt="License" src="https://img.shields.io/badge/license-MIT-blue.svg">
13
+ <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-Ready-blue?logo=typescript">
14
+ <img alt="Powered by Gemini" src="https://img.shields.io/badge/Powered%20By-Google%20Gemini-orange">
15
+ <img alt="Framework" src="https://img.shields.io/badge/Node.js-Engine-success?logo=node.js">
16
+ </p>
17
+
18
+ **Sesi** is a high-performance **Systems Language** designed for building resilient, stateful applications. It provides first-class primitives for process management, filesystem orchestration, and integrated reasoning—enabling developers to build complex logic with a fraction of the boilerplate required by traditional languages.
19
+
20
+ ## Quick Start
21
+
22
+ # Global Installation (Recommended)
23
+
24
+ Clone the repository:
25
+
26
+ ```bash
27
+ git clone https://github.com/Misterscan/Sesi.git
28
+ cd sesi-programming-lang
29
+ ```
30
+ You'll need a [Gemini API Key](https://aistudio.google.com/app/apikey). Create a `.env` file referencing your key:
31
+
32
+ ```env
33
+ GEMINI_API_KEY="AIzaSy..."
34
+ ```
35
+
36
+ You can install Sesi globally to use the `sesi` command anywhere on your system:
37
+
38
+ ```bash
39
+ # Install required dependencies
40
+ npm install
41
+
42
+ # Unlock the `sesi` command
43
+ npm install -g .
44
+ ```
45
+
46
+ Then run any program directly:
47
+
48
+ ```bash
49
+ # Standard script execution
50
+ sesi main/start.sesi
51
+
52
+ # Reasoning script example
53
+ sesi examples/08_model_call.sesi
54
+
55
+ # Run all examples
56
+ sesi examples.sesi
57
+ ```
58
+
59
+ # Local Execution (Development)
60
+
61
+ If you choose not install `sesi` globally, use the helper npm scripts:
62
+
63
+ ```bash
64
+ npm run example 01_hello.sesi
65
+ npm run example:ai 08_model_call.sesi
66
+ npm run example:all
67
+ ```
68
+
69
+ ## Language Overview
70
+
71
+ Sesi is designed for developers who want to:
72
+
73
+ - Write normal code (variables, functions, loops, etc.)
74
+ - Call Reasoning directly within code using `prompt` and `model` blocks
75
+ - Get structured outputs from Reasoning with type guarantees
76
+ - Build Reasoning agents with memory and multi-step reasoning
77
+ - Maintain full control and transparency
78
+
79
+ ## Example
80
+
81
+ ```sesi
82
+ // Basic computation
83
+ let x = 10
84
+ let y = 20
85
+ let result = x + y
86
+ print result // 30
87
+
88
+ // Reasoning-powered code generation
89
+ prompt generateCode {"Write a TypeScript function that reverses a string"}
90
+ let code = model("gemini-3.1-pro-preview") {generateCode}
91
+ print code
92
+ ```
93
+
94
+ ## Documentation
95
+
96
+ - [Getting Started](./QUICKSTART.md)
97
+ - [Examples](./examples/)
98
+ - [Language Specification](./docs/SPECIFICATION.md)
99
+ - [Language Comparison Showcase](./docs/COMPARISON.md)
100
+ - [Built-in Functions](./docs/BUILTINS.md)
101
+ - [Reasoning Guide](./docs/SYSTEMS_REASONING.md)
102
+ - [Distributed Systems](./docs/DISTRIBUTED_SYSTEMS.md)
103
+ - [Runtime Architecture](./docs/ARCHITECTURE.md)
104
+
105
+ ## AI Agent Context
106
+
107
+ The root-level `SKILLS.md` file is a workspace context file for AI agents. It records repo-specific constraints such as valid Sesi syntax expectations, execution conventions, and the intended meaning of directories like `main/` and `main/tests/`.
108
+
109
+ ## Project Structure
110
+
111
+ ```
112
+ sesi-programming-lang/
113
+ ├── SKILLS.md # AI-agent workspace context and repo guardrails
114
+ ├── index.html # Sesi-generated landing page
115
+ ├── eslint.config.mjs # ESLint configuration
116
+ ├── dist/ # Compiled TypeScript output
117
+ ├── example.js # Helper script to run basic examples
118
+ ├── example-ai.js # Helper script to run Reasoning examples
119
+ ├── package.json # Dependencies & scripts
120
+ ├── tsconfig.json # TypeScript configuration
121
+ ├── QUICKSTART.md # Quick start guide
122
+ ├── IMPLEMENTATION_SUMMARY.md # Progress and tracking
123
+ ├── src/
124
+ │ ├── types.ts # Type system & AST nodes
125
+ │ ├── lexer.ts # Tokenization
126
+ │ ├── parser.ts # AST generation
127
+ │ ├── interpreter.ts # Execution engine
128
+ │ ├── builtins.ts # Standard library
129
+ │ ├── ai-runtime.ts # Gemini integration
130
+ │ └── index.ts # Main entry point
131
+ ├── bin/
132
+ │ └── sesi.js # CLI executable
133
+ ├── examples/ # 15 sample programs demonstrating all features
134
+ ├── main/ # Main entry and specialized tests
135
+ │ ├── playground.sesi # Main playground script
136
+ │ ├── start.sesi # Beginner script
137
+ │ ├── build_website.sesi # Sesi-powered landing page generator
138
+ │ └── tests/ # Debug and syntax scripts
139
+ ├── tests/ # Test suite
140
+ └── docs/ # Documentation (ARCHITECTURE, BUILTINS, SPECIFICATION, etc.)
141
+ ```
142
+
143
+ ## Version 1.1 Features (Complete)
144
+
145
+ ### Core Language ✅
146
+
147
+ - **Variables & Bindings**: `let` for all bindings (const is deprecated).
148
+ - **Functions**: Side-effect driven functions with typed parameters.
149
+ - **Control Flow**: `if/else`, `while`, `for`, and `try/catch`.
150
+ - **Collections**: Robust Arrays and Objects.
151
+ - **Error Handling**: Structured `try/catch` for both runtime and Reasoning-level errors.
152
+
153
+ ### Reasoning-Native Features ✅
154
+
155
+ - `prompt` blocks for message composition
156
+ - `model()` calls with Reasoning provider configuration
157
+ - `image()` calls with specific ratio/size generation capabilities
158
+ - `structured_output()` for typed Reasoning responses
159
+ - `tool_call()` for function calling
160
+ - Basic memory for multi-turn reasoning
161
+ - `read_file()`, `write_file()`, `to_json()`, `write_image()`, and `list_dir()` for local file I/O
162
+ - **Native Orchestration**: `spawn()` and `exec()` for concurrent process management
163
+ - **Async Polling**: Native looping to auto-resume generation when hitting `MAX_TOKENS` limit
164
+ - **Utility Builtins**: `time()` and `random()` for robust coordination
165
+
166
+ ### Type System
167
+
168
+ - Static types: `number`, `string`, `bool`, `array<T>`, `object<T>`
169
+ - Type inference
170
+ - Union types for Reasoning response handling
171
+
172
+ ## Roadmap
173
+
174
+ ### V2: Advanced Reasoning
175
+
176
+ - Long-term memory and context management
177
+ - Parallel model calls
178
+ - Advanced error handling with Reasoning fallbacks
179
+ - Custom tool definitions
180
+ - Streaming responses
181
+
182
+ ### V3: Agents & Orchestration
183
+
184
+ - Agent definitions with state
185
+ - Tool composition and chaining
186
+ - Multi-agent collaboration
187
+ - Persistent knowledge bases
188
+
189
+ ## License
190
+
191
+ MIT
package/bin/sesi.js ADDED
@@ -0,0 +1,56 @@
1
+ require('@dotenvx/dotenvx').config();
2
+ const { runSesiFile } = require('../dist/index.js');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ const args = process.argv.slice(2);
7
+
8
+ if (args.length === 0) {
9
+ console.log(`
10
+ Sesi Programming Language v1.1.1
11
+
12
+ Usage:
13
+ sesi <file> Run a Sesi program
14
+ sesi --help Show this help
15
+
16
+ Examples:
17
+ sesi main/start.sesi
18
+ sesi examples/01_hello.sesi
19
+ `);
20
+ process.exit(0);
21
+ }
22
+
23
+ if (args[0] === '--help' || args[0] === '-h') {
24
+ console.log(`
25
+ Sesi Programming Language v1.1.1
26
+
27
+ Usage:
28
+ sesi <file> Run a Sesi program
29
+ sesi --help Show this help
30
+
31
+ Options:
32
+ --version Show version
33
+
34
+ Examples:
35
+ sesi main/start.sesi
36
+ sesi examples/01_hello.sesi
37
+ `);
38
+ process.exit(0);
39
+ }
40
+
41
+ if (args[0] === '--version') {
42
+ console.log('Sesi v1.1.1');
43
+ process.exit(0);
44
+ }
45
+
46
+ const filePath = args[0];
47
+
48
+ if (!fs.existsSync(filePath)) {
49
+ console.error(`Error: File not found: ${filePath}`);
50
+ process.exit(1);
51
+ }
52
+
53
+ runSesiFile(filePath).catch((error) => {
54
+ console.error('Fatal error:', error.message);
55
+ process.exit(1);
56
+ });
@@ -0,0 +1,15 @@
1
+ import { AIRequest, AIResponse, StructuredOutput } from './types';
2
+ export declare class AIRuntime {
3
+ private _client;
4
+ private conversationHistory;
5
+ constructor();
6
+ private get client();
7
+ callModel(request: AIRequest): Promise<AIResponse>;
8
+ parseStructuredOutput(response: string, schema: Record<string, any>): Promise<StructuredOutput>;
9
+ initializeMemory(memoryId: string, initialValue: string): void;
10
+ appendToMemory(memoryId: string, content: string): void;
11
+ getMemory(memoryId: string): string;
12
+ updateMemory(memoryId: string, content: string): void;
13
+ }
14
+ export declare const aiRuntime: AIRuntime;
15
+ //# sourceMappingURL=ai-runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-runtime.d.ts","sourceRoot":"","sources":["../src/ai-runtime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAElE,qBAAa,SAAS;IACpB,OAAO,CAAC,OAAO,CAAa;IAC5B,OAAO,CAAC,mBAAmB,CAAoC;;IAI/D,OAAO,KAAK,MAAM,GAajB;IAEK,SAAS,CAAC,OAAO,EAAE,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC;IA0JlD,qBAAqB,CACzB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC1B,OAAO,CAAC,gBAAgB,CAAC;IAkC5B,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,IAAI;IAI9D,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI;IAOvD,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM;IAMnC,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI;CAGtD;AAED,eAAO,MAAM,SAAS,WAAkB,CAAC"}
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.aiRuntime = exports.AIRuntime = void 0;
4
+ class AIRuntime {
5
+ constructor() {
6
+ this._client = null;
7
+ this.conversationHistory = new Map();
8
+ }
9
+ get client() {
10
+ if (!this._client) {
11
+ try {
12
+ const { GoogleGenAI } = require('@google/genai');
13
+ this._client = new GoogleGenAI({});
14
+ }
15
+ catch (error) {
16
+ throw new Error('Failed to initialize Gemini SDK. Ensure @google/genai is installed ' +
17
+ 'and GEMINI_API_KEY environment variable is set.\nDetails: ' + error.message);
18
+ }
19
+ }
20
+ return this._client;
21
+ }
22
+ async callModel(request) {
23
+ try {
24
+ const client = this.client;
25
+ // Inject current date/time for context
26
+ const timeContext = `[System context: Current date and time is ${new Date().toUTCString()}]\n\n`;
27
+ const fullPrompt = timeContext + request.prompt;
28
+ // Handle image generation models dynamically
29
+ if (request.model.includes('image')) {
30
+ const imageConfig = {};
31
+ if (request.ratio)
32
+ imageConfig.aspectRatio = request.ratio;
33
+ if (request.size)
34
+ imageConfig.imageSize = request.size;
35
+ const configObj = {
36
+ responseModalities: ["IMAGE"]
37
+ };
38
+ if (Object.keys(imageConfig).length > 0) {
39
+ configObj.imageConfig = imageConfig;
40
+ }
41
+ if (request.temperature !== undefined)
42
+ configObj.temperature = request.temperature;
43
+ if (request.maxTokens !== undefined)
44
+ configObj.maxOutputTokens = request.maxTokens;
45
+ if (request.topK !== undefined)
46
+ configObj.topK = request.topK;
47
+ if (request.topP !== undefined)
48
+ configObj.topP = request.topP;
49
+ const response = await client.models.generateContent({
50
+ model: request.model,
51
+ contents: request.prompt,
52
+ config: configObj
53
+ });
54
+ let base64String = null;
55
+ if (response.candidates && response.candidates.length > 0) {
56
+ for (const part of response.candidates[0].content.parts) {
57
+ if (part.inlineData) {
58
+ base64String = part.inlineData.data;
59
+ break;
60
+ }
61
+ }
62
+ }
63
+ if (!base64String) {
64
+ throw new Error("Image generation failed or returned no image output.");
65
+ }
66
+ return {
67
+ text: base64String, // Return the base64 string directly
68
+ finishReason: 'STOP',
69
+ usage: {
70
+ inputTokens: 0,
71
+ outputTokens: 0,
72
+ },
73
+ };
74
+ }
75
+ let accumulatedText = '';
76
+ let currentFinishReason = '';
77
+ let isComplete = false;
78
+ let totalInputTokens = 0;
79
+ let totalOutputTokens = 0;
80
+ let maxPolls = 10;
81
+ let currentPoll = 0;
82
+ const contents = [
83
+ { role: 'user', parts: [{ text: fullPrompt }] }
84
+ ];
85
+ while (!isComplete && currentPoll < maxPolls) {
86
+ const genConfig = {
87
+ temperature: request.temperature ?? 0.3,
88
+ maxOutputTokens: request.maxTokens ?? 2048,
89
+ topK: request.topK,
90
+ topP: request.topP,
91
+ };
92
+ if (request.tools) {
93
+ genConfig.tools = request.tools;
94
+ }
95
+ const response = await client.models.generateContent({
96
+ model: request.model,
97
+ contents: contents,
98
+ config: genConfig,
99
+ });
100
+ const candidate = response.candidates?.[0];
101
+ const rawFinishReason = candidate?.finishReason ?? response.finishReason ?? 'UNKNOWN';
102
+ const finishReason = String(rawFinishReason).toUpperCase();
103
+ // Handle tool calls
104
+ if (candidate?.content?.parts) {
105
+ for (const part of candidate.content.parts) {
106
+ if (part.call) {
107
+ return {
108
+ text: JSON.stringify(part.call),
109
+ finishReason: 'TOOL_CALL',
110
+ usage: {
111
+ inputTokens: response.usageMetadata?.promptTokenCount ?? 0,
112
+ outputTokens: response.usageMetadata?.candidatesTokenCount ?? 0,
113
+ },
114
+ };
115
+ }
116
+ }
117
+ }
118
+ let text = '';
119
+ if (candidate?.content?.parts) {
120
+ for (const part of candidate.content.parts) {
121
+ if (part.text) {
122
+ text += part.text;
123
+ }
124
+ }
125
+ }
126
+ accumulatedText += text;
127
+ totalInputTokens += response.usageMetadata?.promptTokenCount ?? 0;
128
+ totalOutputTokens += response.usageMetadata?.candidatesTokenCount ?? 0;
129
+ currentFinishReason = finishReason;
130
+ if (finishReason === 'MAX_TOKENS') {
131
+ // Add the model's partial response to the history and prompt it to continue
132
+ contents.push({ role: 'model', parts: [{ text: text }] });
133
+ contents.push({ role: 'user', parts: [{ text: 'Please continue exactly where you left off.' }] });
134
+ currentPoll++;
135
+ }
136
+ else if (finishReason === 'STOP') {
137
+ isComplete = true;
138
+ }
139
+ else {
140
+ if (!accumulatedText.trim()) {
141
+ throw new Error(`Returned no text output (finish reason: ${finishReason})`);
142
+ }
143
+ isComplete = true;
144
+ }
145
+ }
146
+ if (currentFinishReason !== 'STOP' && currentFinishReason !== 'MAX_TOKENS') {
147
+ throw new Error(`Generation did not complete successfully (finish reason: ${currentFinishReason})`);
148
+ }
149
+ return {
150
+ text: accumulatedText,
151
+ finishReason: currentFinishReason,
152
+ usage: {
153
+ inputTokens: totalInputTokens,
154
+ outputTokens: totalOutputTokens,
155
+ },
156
+ };
157
+ }
158
+ catch (error) {
159
+ throw new Error(`Sesi: ${error.message}`);
160
+ }
161
+ }
162
+ async parseStructuredOutput(response, schema) {
163
+ try {
164
+ // Try to extract JSON from the response
165
+ const jsonMatch = response.match(/\{[\s\S]*\}/);
166
+ if (jsonMatch) {
167
+ const parsed = JSON.parse(jsonMatch[0]);
168
+ // Validate against schema
169
+ const result = {};
170
+ for (const [key] of Object.entries(schema)) {
171
+ result[key] = parsed[key];
172
+ }
173
+ return result;
174
+ }
175
+ // If no JSON found, try to prompt model for structured output
176
+ const structuredPrompt = `Convert this response to JSON matching this schema:\n${JSON.stringify(schema)}\n\nResponse: ${response}`;
177
+ const structuredResponse = await this.callModel({
178
+ model: 'gemini-3.1-flash-lite',
179
+ prompt: structuredPrompt,
180
+ temperature: 0,
181
+ });
182
+ const jsonMatch2 = structuredResponse.text.match(/\{[\s\S]*\}/);
183
+ if (jsonMatch2) {
184
+ return JSON.parse(jsonMatch2[0]);
185
+ }
186
+ throw new Error('Could not parse structured output');
187
+ }
188
+ catch (error) {
189
+ console.error('Error parsing structured output:', error.message);
190
+ return {};
191
+ }
192
+ }
193
+ initializeMemory(memoryId, initialValue) {
194
+ this.conversationHistory.set(memoryId, [initialValue]);
195
+ }
196
+ appendToMemory(memoryId, content) {
197
+ if (!this.conversationHistory.has(memoryId)) {
198
+ this.conversationHistory.set(memoryId, []);
199
+ }
200
+ this.conversationHistory.get(memoryId).push(content);
201
+ }
202
+ getMemory(memoryId) {
203
+ const history = this.conversationHistory.get(memoryId);
204
+ if (!history)
205
+ return '';
206
+ return history.join('\n');
207
+ }
208
+ updateMemory(memoryId, content) {
209
+ this.conversationHistory.set(memoryId, [content]);
210
+ }
211
+ }
212
+ exports.AIRuntime = AIRuntime;
213
+ exports.aiRuntime = new AIRuntime();
214
+ //# sourceMappingURL=ai-runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-runtime.js","sourceRoot":"","sources":["../src/ai-runtime.ts"],"names":[],"mappings":";;;AAGA,MAAa,SAAS;IAIpB;QAHQ,YAAO,GAAQ,IAAI,CAAC;QACpB,wBAAmB,GAA0B,IAAI,GAAG,EAAE,CAAC;IAEhD,CAAC;IAEhB,IAAY,MAAM;QAChB,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,IAAI,CAAC;gBACH,MAAM,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC,eAAe,CAAC,CAA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AAC,OAAO;YAAE,OAAO,EAAE,CAAC;QACxB,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC;IAED,YAAY,CAAC,QAAgB,EAAE,OAAe;QAC5C,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IACpD,CAAC;CACF;AAxOD,8BAwOC;AAEY,QAAA,SAAS,GAAG,IAAI,SAAS,EAAE,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { RuntimeValue, RuntimeFunction } from './types';
2
+ export declare function getBuiltins(): Map<string, RuntimeFunction>;
3
+ export declare function isTruthy(value: RuntimeValue): boolean;
4
+ export declare function isEqual(a: RuntimeValue, b: RuntimeValue): boolean;
5
+ export declare function stringify(value: RuntimeValue): string;
6
+ export declare function compareValues(a: RuntimeValue, b: RuntimeValue): number;
7
+ //# sourceMappingURL=builtins.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builtins.d.ts","sourceRoot":"","sources":["../src/builtins.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAKxD,wBAAgB,WAAW,IAAI,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,CA6W1D;AAED,wBAAgB,QAAQ,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAIrD;AAED,wBAAgB,OAAO,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,YAAY,GAAG,OAAO,CAWjE;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,YAAY,GAAG,MAAM,CAmBrD;AAED,wBAAgB,aAAa,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,YAAY,GAAG,MAAM,CAQtE"}