@koi-language/koi 1.0.6 → 1.1.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 (113) hide show
  1. package/README.md +4 -125
  2. package/examples/.build/agent-dialogue.ts +138 -0
  3. package/examples/.build/agent-dialogue.ts.map +1 -0
  4. package/examples/.build/chess.ts +77 -0
  5. package/examples/.build/chess.ts.map +1 -0
  6. package/examples/.build/delegation-test.ts +140 -0
  7. package/examples/.build/delegation-test.ts.map +1 -0
  8. package/examples/.build/dialog-demo.ts +77 -0
  9. package/examples/.build/dialog-demo.ts.map +1 -0
  10. package/examples/.build/hello-world.ts +77 -0
  11. package/examples/.build/hello-world.ts.map +1 -0
  12. package/examples/.build/lover-dialog-demo.ts +77 -0
  13. package/examples/.build/lover-dialog-demo.ts.map +1 -0
  14. package/examples/.build/package.json +3 -0
  15. package/examples/.build/registry-interactive-demo.ts +202 -0
  16. package/examples/.build/registry-interactive-demo.ts.map +1 -0
  17. package/examples/.build/registry-playbook-demo.ts +201 -0
  18. package/examples/.build/registry-playbook-demo.ts.map +1 -0
  19. package/examples/.build/tic-tac-toe.ts +77 -0
  20. package/examples/.build/tic-tac-toe.ts.map +1 -0
  21. package/examples/actions-demo.koi +8 -9
  22. package/examples/activists-dialogue.koi +75 -0
  23. package/examples/agent-dialogue.koi +66 -0
  24. package/examples/chess.koi +19 -0
  25. package/examples/counter.koi +20 -69
  26. package/examples/delegation-test.koi +16 -18
  27. package/examples/dialog-demo.koi +20 -0
  28. package/examples/hello-world.koi +7 -43
  29. package/examples/mcp-stdio-demo.koi +29 -0
  30. package/examples/memory-test.koi +49 -0
  31. package/examples/mobile-mcp-demo.koi +32 -0
  32. package/examples/multi-event-handler-test.koi +16 -18
  33. package/examples/pipeline.koi +15 -17
  34. package/examples/prompt-demo.koi +20 -0
  35. package/examples/{registry-playbook-email-compositor.koi → registry-interactive-demo.koi} +27 -27
  36. package/examples/registry-playbook-demo.koi +28 -28
  37. package/examples/skill-import-test.koi +7 -9
  38. package/examples/skills/.build/math-operations.ts +1656 -0
  39. package/examples/skills/.build/math-operations.ts.map +1 -0
  40. package/examples/skills/.build/package.json +3 -0
  41. package/examples/skills/.build/string-operations.ts +1643 -0
  42. package/examples/skills/.build/string-operations.ts.map +1 -0
  43. package/examples/skills/advanced/.build/index.ts +3223 -0
  44. package/examples/skills/advanced/.build/index.ts.map +1 -0
  45. package/examples/skills/advanced/.build/package.json +3 -0
  46. package/examples/skills/advanced/index.koi +3 -5
  47. package/examples/skills/math-operations.koi +1 -3
  48. package/examples/skills/string-operations.koi +1 -3
  49. package/examples/tic-tac-toe.koi +19 -0
  50. package/examples/utils/echo-mcp-server.js +141 -0
  51. package/examples/web-delegation-demo.koi +15 -17
  52. package/package.json +2 -1
  53. package/src/cli/koi.js +30 -41
  54. package/src/compiler/build-optimizer.js +204 -289
  55. package/src/compiler/cache-manager.js +1 -1
  56. package/src/compiler/import-resolver.js +5 -9
  57. package/src/compiler/parser.js +6072 -3476
  58. package/src/compiler/transpiler.js +346 -38
  59. package/src/grammar/koi.pegjs +302 -62
  60. package/src/runtime/actions/{format.js → call-llm.js} +37 -44
  61. package/src/runtime/actions/call-mcp.js +97 -0
  62. package/src/runtime/actions/if.js +179 -0
  63. package/src/runtime/actions/print.js +3 -1
  64. package/src/runtime/actions/prompt-user.js +75 -0
  65. package/src/runtime/actions/repeat.js +147 -0
  66. package/src/runtime/actions/shell.js +185 -0
  67. package/src/runtime/actions/while.js +205 -0
  68. package/src/runtime/agent.js +592 -178
  69. package/src/runtime/cli-display.js +26 -0
  70. package/src/runtime/cli-input.js +421 -0
  71. package/src/runtime/cli-logger.js +2 -5
  72. package/src/runtime/cli-markdown.js +61 -0
  73. package/src/runtime/cli-select.js +106 -0
  74. package/src/runtime/incremental-json-parser.js +27 -17
  75. package/src/runtime/index.js +1 -0
  76. package/src/runtime/llm-provider.js +1083 -572
  77. package/src/runtime/mcp-registry.js +141 -0
  78. package/src/runtime/mcp-stdio-client.js +334 -0
  79. package/src/runtime/planner.js +1 -1
  80. package/src/runtime/playbook-session.js +259 -0
  81. package/src/runtime/registry-backends/keyv-sqlite.js +1 -1
  82. package/src/runtime/registry-backends/local.js +1 -1
  83. package/src/runtime/router.js +22 -26
  84. package/src/runtime/runtime.js +7 -1
  85. package/examples/cache-test.koi +0 -29
  86. package/examples/calculator.koi +0 -61
  87. package/examples/clear-registry.js +0 -33
  88. package/examples/clear-registry.koi +0 -30
  89. package/examples/code-introspection-test.koi +0 -149
  90. package/examples/directory-import-test.koi +0 -84
  91. package/examples/hello-world-claude.koi +0 -52
  92. package/examples/hello.koi +0 -24
  93. package/examples/mcp-example.koi +0 -70
  94. package/examples/new-import-test.koi +0 -89
  95. package/examples/registry-demo.koi +0 -184
  96. package/examples/registry-playbook-email-compositor-2.koi +0 -140
  97. package/examples/sentiment.koi +0 -90
  98. package/examples/simple.koi +0 -48
  99. package/examples/task-chaining-demo.koi +0 -244
  100. package/examples/test-await.koi +0 -22
  101. package/examples/test-crypto-sha256.koi +0 -196
  102. package/examples/test-delegation.koi +0 -41
  103. package/examples/test-multi-team-routing.koi +0 -258
  104. package/examples/test-no-handler.koi +0 -35
  105. package/examples/test-npm-import.koi +0 -67
  106. package/examples/test-parse.koi +0 -10
  107. package/examples/test-peers-with-team.koi +0 -59
  108. package/examples/test-permissions-fail.koi +0 -20
  109. package/examples/test-permissions.koi +0 -36
  110. package/examples/test-simple-registry.koi +0 -31
  111. package/examples/test-typescript-import.koi +0 -64
  112. package/examples/test-uses-team-syntax.koi +0 -25
  113. package/examples/test-uses-team.koi +0 -31
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["index.koi"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;AAwBF","file":"index.koi.js"}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -3,8 +3,6 @@
3
3
  // Entry point that exports all skills from this directory
4
4
  // ============================================================
5
5
 
6
- package "skills.advanced"
7
-
8
6
  // Re-export from other files in this directory
9
7
  // (In a future version, we could support automatic re-export)
10
8
 
@@ -16,7 +14,7 @@ role DataScientist { can analyze }
16
14
  // Statistical Analysis Skill
17
15
  // ============================================================
18
16
 
19
- Skill StatisticalAnalysis {
17
+ skill StatisticalAnalysis {
20
18
  affordance """
21
19
  Perform statistical analysis including mean, median, standard deviation
22
20
  """
@@ -80,9 +78,9 @@ Skill StatisticalAnalysis {
80
78
  // Data Analysis Agent
81
79
  // ============================================================
82
80
 
83
- Agent DataAnalyzer : DataScientist {
81
+ agent DataAnalyzer : DataScientist {
84
82
  llm default = { provider: "openai", model: "gpt-4o-mini", temperature: 0.1, max_tokens: 400 }
85
- uses Skill StatisticalAnalysis
83
+ uses skill StatisticalAnalysis
86
84
 
87
85
  on analyze(args: Json) {
88
86
  playbook """
@@ -3,9 +3,7 @@
3
3
  // A reusable skill that provides math operations
4
4
  // ============================================================
5
5
 
6
- package "skills.math"
7
-
8
- Skill MathOperations {
6
+ skill MathOperations {
9
7
  affordance """
10
8
  Perform mathematical operations like addition, subtraction, multiplication, and division
11
9
  """
@@ -3,9 +3,7 @@
3
3
  // A reusable skill for string manipulation
4
4
  // ============================================================
5
5
 
6
- package "skills.string"
7
-
8
- Skill StringOperations {
6
+ skill StringOperations {
9
7
  affordance """
10
8
  Perform string operations like uppercase, lowercase, reverse, and length
11
9
  """
@@ -0,0 +1,19 @@
1
+ // Demo: Iteration Actions (repeat and while)
2
+ // Shows how to repeat actions fixed number of times or until condition
3
+
4
+ role Worker { can execute }
5
+
6
+ agent Assistant : Worker {
7
+ llm default = { provider: "openai", model: "gpt-5.2" }
8
+
9
+ on test_while(args: Json) {
10
+ playbook """
11
+ Play tic-tac-toe with the user.
12
+ On each turn you show the board, and the user says where to move with a combination like A2, B3
13
+ Then you make your move and show the board as it looks after your move.
14
+ End the game when someone wins or if the user expresses their wish to stop.
15
+ """
16
+ }
17
+ }
18
+
19
+ run Assistant.test_while({})
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Simple Echo MCP Server for testing Koi's MCP stdio integration.
5
+ * Communicates via JSON-RPC 2.0 over stdin/stdout.
6
+ *
7
+ * Tools:
8
+ * - echo: Echoes back the input message
9
+ * - reverse: Reverses the input string
10
+ * - uppercase: Converts input to uppercase
11
+ */
12
+
13
+ import { createInterface } from 'readline';
14
+
15
+ const SERVER_INFO = {
16
+ name: 'echo-mcp-server',
17
+ version: '1.0.0'
18
+ };
19
+
20
+ const TOOLS = [
21
+ {
22
+ name: 'echo',
23
+ description: 'Echo back the input message',
24
+ inputSchema: {
25
+ type: 'object',
26
+ properties: {
27
+ message: { type: 'string', description: 'The message to echo back' }
28
+ },
29
+ required: ['message']
30
+ }
31
+ },
32
+ {
33
+ name: 'reverse',
34
+ description: 'Reverse the input string',
35
+ inputSchema: {
36
+ type: 'object',
37
+ properties: {
38
+ text: { type: 'string', description: 'The text to reverse' }
39
+ },
40
+ required: ['text']
41
+ }
42
+ },
43
+ {
44
+ name: 'uppercase',
45
+ description: 'Convert text to uppercase',
46
+ inputSchema: {
47
+ type: 'object',
48
+ properties: {
49
+ text: { type: 'string', description: 'The text to convert to uppercase' }
50
+ },
51
+ required: ['text']
52
+ }
53
+ }
54
+ ];
55
+
56
+ function sendResponse(id, result) {
57
+ const response = JSON.stringify({ jsonrpc: '2.0', id, result });
58
+ process.stdout.write(response + '\n');
59
+ }
60
+
61
+ function sendError(id, code, message) {
62
+ const response = JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } });
63
+ process.stdout.write(response + '\n');
64
+ }
65
+
66
+ function handleRequest(message) {
67
+ const { id, method, params } = message;
68
+
69
+ switch (method) {
70
+ case 'initialize':
71
+ sendResponse(id, {
72
+ protocolVersion: '2024-11-05',
73
+ capabilities: { tools: {} },
74
+ serverInfo: SERVER_INFO
75
+ });
76
+ break;
77
+
78
+ case 'tools/list':
79
+ sendResponse(id, { tools: TOOLS });
80
+ break;
81
+
82
+ case 'tools/call': {
83
+ const toolName = params?.name;
84
+ const args = params?.arguments || {};
85
+
86
+ switch (toolName) {
87
+ case 'echo':
88
+ sendResponse(id, {
89
+ content: [{ type: 'text', text: JSON.stringify({ echo: args.message || '' }) }]
90
+ });
91
+ break;
92
+
93
+ case 'reverse':
94
+ const reversed = (args.text || '').split('').reverse().join('');
95
+ sendResponse(id, {
96
+ content: [{ type: 'text', text: JSON.stringify({ reversed }) }]
97
+ });
98
+ break;
99
+
100
+ case 'uppercase':
101
+ sendResponse(id, {
102
+ content: [{ type: 'text', text: JSON.stringify({ uppercased: (args.text || '').toUpperCase() }) }]
103
+ });
104
+ break;
105
+
106
+ default:
107
+ sendError(id, -32601, `Unknown tool: ${toolName}`);
108
+ }
109
+ break;
110
+ }
111
+
112
+ case 'notifications/initialized':
113
+ case 'notifications/cancelled':
114
+ // Notifications don't require a response
115
+ break;
116
+
117
+ default:
118
+ if (id !== undefined) {
119
+ sendError(id, -32601, `Method not found: ${method}`);
120
+ }
121
+ }
122
+ }
123
+
124
+ // Read JSON-RPC messages from stdin (newline-delimited)
125
+ const rl = createInterface({ input: process.stdin });
126
+
127
+ rl.on('line', (line) => {
128
+ const trimmed = line.trim();
129
+ if (!trimmed) return;
130
+
131
+ try {
132
+ const message = JSON.parse(trimmed);
133
+ handleRequest(message);
134
+ } catch (e) {
135
+ process.stderr.write(`[echo-mcp-server] Parse error: ${e.message}\n`);
136
+ }
137
+ });
138
+
139
+ rl.on('close', () => {
140
+ process.exit(0);
141
+ });
@@ -3,16 +3,14 @@
3
3
  // Demonstrates delegation with indentation and loop detection
4
4
  // ============================================================
5
5
 
6
- package "demo.koi.delegation"
7
-
8
6
  role Worker { can execute }
9
- role Assistant { can help }
7
+ role Assistant { can help, can delegate }
10
8
 
11
9
  // ============================================================
12
10
  // Skills - JavaScript functions agents can use
13
11
  // ============================================================
14
12
 
15
- Skill WebFetching {
13
+ skill WebFetching {
16
14
  affordance """
17
15
  Fetch content from web URLs
18
16
  """
@@ -60,9 +58,9 @@ Skill WebFetching {
60
58
  // Worker Agents with Specialized Capabilities
61
59
  // ============================================================
62
60
 
63
- Agent WebFetcher : Worker {
61
+ agent WebFetcher : Worker {
64
62
  llm default = { provider: "openai", model: "gpt-4o-mini", temperature: 0.2, max_tokens: 500 }
65
- uses Skill WebFetching
63
+ uses skill WebFetching
66
64
 
67
65
  on fetchWebPage(args: Json) {
68
66
  playbook """
@@ -73,7 +71,7 @@ Agent WebFetcher : Worker {
73
71
  }
74
72
  }
75
73
 
76
- Agent ContentSummarizer : Worker {
74
+ agent ContentSummarizer : Worker {
77
75
  llm default = { provider: "openai", model: "gpt-4o-mini", temperature: 0.3, max_tokens: 300 }
78
76
 
79
77
  on summarize(args: Json) {
@@ -86,7 +84,7 @@ Agent ContentSummarizer : Worker {
86
84
  }
87
85
  }
88
86
 
89
- Agent WordCounter : Worker {
87
+ agent WordCounter : Worker {
90
88
  llm default = { provider: "openai", model: "gpt-4o-mini", temperature: 0.1, max_tokens: 200 }
91
89
 
92
90
  on count(args: Json) {
@@ -102,10 +100,10 @@ Agent WordCounter : Worker {
102
100
  // Orchestrator Agent
103
101
  // ============================================================
104
102
 
105
- Agent TaskOrchestrator : Assistant {
103
+ agent TaskOrchestrator : Assistant {
106
104
  llm default = { provider: "openai", model: "gpt-4o-mini", temperature: 0.3, max_tokens: 800 }
107
105
 
108
- //no cambies este agente!!! Es el que se encarga de delegar la tarea. No cambies su playbook!!!!
106
+ //don't change this agent!!! It is the one responsible for delegating the task. Don't change its playbook!!!!
109
107
  on processWebTask(args: Json) {
110
108
  playbook """
111
109
  User request: ${args.request}
@@ -119,19 +117,19 @@ Agent TaskOrchestrator : Assistant {
119
117
  // Team
120
118
  // ============================================================
121
119
 
122
- Team WorkerTeam {
123
- orchestrator = TaskOrchestrator
124
- webFetcher = WebFetcher
125
- summarizer = ContentSummarizer
126
- counter = WordCounter
120
+ team WorkerTeam {
121
+ orchestrator: TaskOrchestrator
122
+ webFetcher: WebFetcher
123
+ summarizer: ContentSummarizer
124
+ counter: WordCounter
127
125
  }
128
126
 
129
127
  // ============================================================
130
128
  // Demo Runner
131
129
  // ============================================================
132
130
 
133
- Agent DemoRunner : Assistant {
134
- uses Team WorkerTeam
131
+ agent DemoRunner : Assistant {
132
+ uses team WorkerTeam
135
133
 
136
134
  on runDemo(args: Json) {
137
135
  console.log("╔════════════════════════════════════════════╗")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koi-language/koi",
3
- "version": "1.0.6",
3
+ "version": "1.1.0",
4
4
  "description": "Koi - Agent-first language. Calm orchestration.",
5
5
  "type": "module",
6
6
  "main": "src/runtime/index.js",
@@ -64,6 +64,7 @@
64
64
  "node-fetch": "^3.3.2",
65
65
  "openai": "^6.16.0",
66
66
  "peggy": "^5.0.6",
67
+ "prompts": "^2.4.2",
67
68
  "source-map": "^0.7.6",
68
69
  "tsx": "^4.21.0",
69
70
  "typescript": "^5.9.3",
package/src/cli/koi.js CHANGED
@@ -21,8 +21,8 @@ const COMMANDS = {
21
21
  };
22
22
 
23
23
  const FLAGS = {
24
- '--no-precalculate': 'Disable embedding pre-calculation (dynamic at runtime)',
25
- '--no-cache': 'Disable persistent cache (always regenerate embeddings)',
24
+ '--no-precalculate': 'Disable description pre-generation (dynamic at runtime)',
25
+ '--no-cache': 'Disable persistent cache (always regenerate descriptions)',
26
26
  '--verbose': 'Show detailed output',
27
27
  '--debug': 'Show all LLM prompts and responses',
28
28
  '--output, -o': 'Specify output file path',
@@ -87,14 +87,14 @@ function showCommandHelp(command) {
87
87
  switch (command) {
88
88
  case 'compile':
89
89
  console.log('koi compile - Compile Koi source to JavaScript\n');
90
- console.log('By default: Pre-computes embeddings and caches them for fast builds.');
90
+ console.log('By default: Pre-generates handler descriptions and caches them.');
91
91
  console.log('Use --no-precalculate or --no-cache to customize behavior.\n');
92
92
  console.log('Usage:');
93
93
  console.log(' koi compile <file.koi>');
94
94
  console.log(' koi compile -o <output.js> <file.koi>\n');
95
95
  console.log('Options:');
96
96
  console.log(' -o, --output <path> Output file path');
97
- console.log(' --no-precalculate Disable embedding pre-calculation (dynamic at runtime)');
97
+ console.log(' --no-precalculate Disable description pre-generation (dynamic at runtime)');
98
98
  console.log(' --no-cache Disable persistent cache (always regenerate)');
99
99
  console.log('\nExamples:');
100
100
  console.log(' koi compile examples/simple.koi # Default: pre-compute + cache');
@@ -105,11 +105,11 @@ function showCommandHelp(command) {
105
105
 
106
106
  case 'run':
107
107
  console.log('koi run - Compile and execute Koi programs\n');
108
- console.log('By default: Pre-computes embeddings and caches them.\n');
108
+ console.log('By default: Pre-generates handler descriptions and caches them.\n');
109
109
  console.log('Usage:');
110
110
  console.log(' koi run <file.koi>\n');
111
111
  console.log('Options:');
112
- console.log(' --no-precalculate Disable embedding pre-calculation');
112
+ console.log(' --no-precalculate Disable description pre-generation');
113
113
  console.log(' --no-cache Disable persistent cache');
114
114
  console.log(' --verbose Show detailed execution logs');
115
115
  console.log('\nExamples:');
@@ -132,8 +132,8 @@ function showCommandHelp(command) {
132
132
  console.log(' koi cache stats Show cache statistics');
133
133
  console.log(' koi cache clear Clear all cache');
134
134
  console.log(' koi cache clear <file> Clear cache for specific file\n');
135
- console.log('The cache stores pre-computed embeddings to avoid API calls.');
136
- console.log('Cache is stored in .koi-cache/ directory.\n');
135
+ console.log('The cache stores pre-generated handler descriptions to avoid API calls.');
136
+ console.log('Cache is stored in .koi/cache/ directory.\n');
137
137
  console.log('Examples:');
138
138
  console.log(' koi cache stats');
139
139
  console.log(' koi cache clear');
@@ -286,7 +286,7 @@ async function compileFile(sourcePath, outputPath = null, options = {}) {
286
286
  cacheData = cacheManager.get(source, sourcePath);
287
287
 
288
288
  if (cacheData && verbose) {
289
- cliLogger.success(`✅ Using cached embeddings (${cacheData.metadata.totalAffordances} affordances)`);
289
+ cliLogger.success(`✅ Using cached descriptions (${cacheData.metadata.totalAffordances} affordances)`);
290
290
  } else if (verbose) {
291
291
  cliLogger.clear();
292
292
  }
@@ -303,19 +303,19 @@ async function compileFile(sourcePath, outputPath = null, options = {}) {
303
303
  try {
304
304
  if (shouldCache) {
305
305
  if (verbose) {
306
- cliLogger.progress('🔄 Pre-computing embeddings...');
306
+ cliLogger.progress('🔄 Generating handler descriptions...');
307
307
  }
308
308
  cacheData = await optimizer.optimizeAST(ast, source, sourcePath);
309
309
  if (verbose) {
310
- cliLogger.success(`✅ Pre-computed ${cacheData.metadata.totalAffordances} embeddings`);
310
+ cliLogger.success(`✅ Generated ${cacheData.metadata.totalAffordances} descriptions`);
311
311
  }
312
312
  } else {
313
313
  if (verbose) {
314
- cliLogger.progress('🔄 Pre-computing embeddings (no cache)...');
314
+ cliLogger.progress('🔄 Generating handler descriptions (no cache)...');
315
315
  }
316
316
  cacheData = await optimizer.optimizeASTWithoutCache(ast);
317
317
  if (verbose) {
318
- cliLogger.success(`✅ Pre-computed ${cacheData.metadata.totalAffordances} embeddings`);
318
+ cliLogger.success(`✅ Generated ${cacheData.metadata.totalAffordances} descriptions`);
319
319
  }
320
320
  }
321
321
  } catch (error) {
@@ -323,12 +323,12 @@ async function compileFile(sourcePath, outputPath = null, options = {}) {
323
323
  cliLogger.clear();
324
324
  }
325
325
  console.error('⚠️ Build-time optimization failed:', error.message);
326
- console.error(' Continuing without pre-computed embeddings...\n');
326
+ console.error(' Continuing without pre-generated descriptions...\n');
327
327
  }
328
328
  }
329
329
  } else {
330
330
  if (options.verbose) {
331
- cliLogger.info('[Optimizer] Pre-calculation disabled. Runtime will generate embeddings dynamically.');
331
+ cliLogger.info('[Optimizer] Pre-generation disabled. Runtime will generate descriptions dynamically.');
332
332
  }
333
333
  }
334
334
 
@@ -347,7 +347,7 @@ async function compileFile(sourcePath, outputPath = null, options = {}) {
347
347
  }
348
348
 
349
349
  const basename = path.basename(sourcePath, '.koi');
350
- outputPath = path.join(buildDir, basename + '.js');
350
+ outputPath = path.join(buildDir, basename + '.ts');
351
351
  }
352
352
 
353
353
  // Transpile with output path so it can calculate correct runtime import path
@@ -398,14 +398,16 @@ async function runFile(sourcePath, options = {}) {
398
398
  const verbose = options.verbose || false;
399
399
  const debug = options.debug || false;
400
400
 
401
- // Show simple 1-line log if not verbose
401
+ // Show simple 1-line log if not verbose (cleared before child spawns)
402
402
  if (!verbose) {
403
- console.log(`🌊 Running ${sourcePath}`);
403
+ process.stdout.write(`🌊 Running ${sourcePath}`);
404
404
  }
405
405
 
406
406
  // Compile first
407
407
  const jsPath = await compileFile(sourcePath, null, options);
408
408
 
409
+ // "🌊 Running" message stays on screen until child's first cliLogger.progress() clears it
410
+
409
411
  // Run
410
412
  if (verbose) {
411
413
  console.log(`🚀 Executing: ${jsPath}\n`);
@@ -416,15 +418,19 @@ async function runFile(sourcePath, options = {}) {
416
418
  // This ensures each run uses the freshly compiled code
417
419
  const { spawn } = await import('child_process');
418
420
 
419
- // Prepare environment variables
421
+ // Prepare environment variables (pass COLUMNS so child knows terminal width)
420
422
  const env = { ...process.env };
423
+ if (process.stdout.columns) {
424
+ env.COLUMNS = String(process.stdout.columns);
425
+ }
421
426
  if (debug) {
422
427
  env.KOI_DEBUG_LLM = '1';
423
428
  }
424
429
 
425
- const child = spawn('node', [jsPath], {
430
+ const child = spawn('npx', ['tsx', jsPath], {
426
431
  stdio: 'inherit',
427
- env
432
+ env,
433
+ shell: true
428
434
  });
429
435
 
430
436
  return new Promise((resolve, reject) => {
@@ -489,7 +495,6 @@ async function initProject(projectName) {
489
495
  package "${projectName}"
490
496
 
491
497
  role Worker { can execute }
492
- role Lead { can delegate }
493
498
 
494
499
  // Agent with LLM playbook - generates creative greetings
495
500
  Agent Greeter : Worker {
@@ -505,28 +510,12 @@ Agent Greeter : Worker {
505
510
  - Add a motivational message or fun fact
506
511
  - Be brief (2-3 sentences)
507
512
 
508
- Use the return action with your greeting data:
509
- { "greeting": "your greeting here", "emoji": "an appropriate emoji" }
513
+ Return JSON: { "greeting": "your greeting here", "emoji": "an appropriate emoji" }
510
514
  """
511
515
  }
512
516
  }
513
517
 
514
- Team MainTeam {
515
- greeter = Greeter
516
- }
517
-
518
- // Orchestrator coordinates with team members
519
- Agent Orchestrator : Lead {
520
- uses Team MainTeam
521
-
522
- on start(args: Json) {
523
- const result = await send peers.event("greet").role(Worker).any()({ name: "World" }) timeout 30s
524
- console.log("Greeting:", result.greeting, result.emoji)
525
- return result
526
- }
527
- }
528
-
529
- run Orchestrator.start({})
518
+ run Greeter.greet({ name: "World" })
530
519
  `;
531
520
 
532
521
  fs.writeFileSync(path.join(projectPath, 'src', 'main.koi'), exampleCode);
@@ -602,7 +591,7 @@ Koi project - Agent-first language. Calm orchestration.
602
591
  .env
603
592
  dist/
604
593
  .build/
605
- .koi-cache/
594
+ .koi/
606
595
  *.js.map
607
596
  .DS_Store
608
597
  `;