dirac-lang 0.1.96 → 0.1.98

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.
@@ -2,11 +2,11 @@ import {
2
2
  SessionServer,
3
3
  getSocketPath,
4
4
  isSessionRunning
5
- } from "./chunk-IFBJYN2F.js";
6
- import "./chunk-NUNYBLVJ.js";
7
- import "./chunk-ECAW4X46.js";
5
+ } from "./chunk-33DMGFRM.js";
6
+ import "./chunk-LAEYP4OQ.js";
8
7
  import "./chunk-SLGJRZ3P.js";
9
8
  import "./chunk-HRHAMPOB.js";
9
+ import "./chunk-ECAW4X46.js";
10
10
  import "./chunk-PPH7KYKH.js";
11
11
 
12
12
  // src/agent.ts
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  integrate
3
- } from "./chunk-NUNYBLVJ.js";
3
+ } from "./chunk-LAEYP4OQ.js";
4
4
  import {
5
5
  DiracParser
6
6
  } from "./chunk-HRHAMPOB.js";
@@ -1,6 +1,3 @@
1
- import {
2
- executeSubroutine
3
- } from "./chunk-ECAW4X46.js";
4
1
  import {
5
2
  executeIndexSubroutines,
6
3
  executeRegistryStats,
@@ -10,6 +7,9 @@ import {
10
7
  import {
11
8
  DiracParser
12
9
  } from "./chunk-HRHAMPOB.js";
10
+ import {
11
+ executeSubroutine
12
+ } from "./chunk-ECAW4X46.js";
13
13
  import {
14
14
  CustomLLMProvider,
15
15
  OllamaProvider,
@@ -487,12 +487,12 @@ async function executeIf(session, element) {
487
487
  const condition = await evaluatePredicate(session, conditionElement);
488
488
  if (condition) {
489
489
  if (thenElement) {
490
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-WNHDVVDD.js");
490
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-D6ZF3OJA.js");
491
491
  await integrateChildren2(session, thenElement);
492
492
  }
493
493
  } else {
494
494
  if (elseElement) {
495
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-WNHDVVDD.js");
495
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-D6ZF3OJA.js");
496
496
  await integrateChildren2(session, elseElement);
497
497
  }
498
498
  }
@@ -505,7 +505,7 @@ async function evaluatePredicate(session, predicateElement) {
505
505
  return await evaluateCondition(session, predicateElement);
506
506
  }
507
507
  const outputLengthBefore = session.output.length;
508
- const { integrate: integrate2 } = await import("./interpreter-WNHDVVDD.js");
508
+ const { integrate: integrate2 } = await import("./interpreter-D6ZF3OJA.js");
509
509
  await integrate2(session, predicateElement);
510
510
  const newOutputChunks = session.output.slice(outputLengthBefore);
511
511
  const result = newOutputChunks.join("").trim();
@@ -528,11 +528,11 @@ async function evaluateCondition(session, condElement) {
528
528
  }
529
529
  const outputLengthBefore = session.output.length;
530
530
  const args = [];
531
- const { integrate: integrate2 } = await import("./interpreter-WNHDVVDD.js");
531
+ const { integrate: integrate2 } = await import("./interpreter-D6ZF3OJA.js");
532
532
  for (const child of condElement.children) {
533
533
  if (child.tag.toLowerCase() === "arg") {
534
534
  const argOutputStart = session.output.length;
535
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-WNHDVVDD.js");
535
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-D6ZF3OJA.js");
536
536
  await integrateChildren2(session, child);
537
537
  const newChunks = session.output.slice(argOutputStart);
538
538
  const argValue = newChunks.join("");
@@ -1075,6 +1075,7 @@ ${result}
1075
1075
  console.error(`[LLM] Feedback iteration ${iteration}/${maxIterations}`);
1076
1076
  }
1077
1077
  let correctionMessages = [];
1078
+ let hasTagCorrections = false;
1078
1079
  let diracCode = result.trim();
1079
1080
  if (replaceTick && diracCode.startsWith("```")) {
1080
1081
  const match = diracCode.match(/^```(\w+)?\n?/m);
@@ -1086,16 +1087,20 @@ ${result}
1086
1087
  diracCode = diracCode.replace(/^```(?:xml|html|dirac)?\n?/m, "").replace(/\n?```$/m, "").trim();
1087
1088
  }
1088
1089
  }
1089
- const outputBefore = feedbackMode ? session.output.slice() : [];
1090
+ const outputBefore = session.output.length;
1090
1091
  try {
1092
+ console.error(`[LLM] Iteration ${iteration}: Parsing LLM response`);
1091
1093
  const parser = new DiracParser();
1092
1094
  let dynamicAST = parser.parse(diracCode);
1095
+ console.error(`[LLM] Iteration ${iteration}: Parse successful`);
1093
1096
  if (validateTags) {
1097
+ console.error(`[LLM] Iteration ${iteration}: Starting validation (autocorrect: ${autocorrect}, deepValidation: true)`);
1094
1098
  if (session.debug) {
1095
1099
  console.error(`[LLM] Validation enabled, autocorrect: ${autocorrect}`);
1096
1100
  }
1097
- const { validateDiracCode, applyCorrectedTags } = await import("./tag-validator-D7FH7P5F.js");
1098
- let validation = await validateDiracCode(session, dynamicAST, { autocorrect });
1101
+ const { validateDiracCode, applyCorrectedTags } = await import("./tag-validator-DS7OCXCG.js");
1102
+ let validation = await validateDiracCode(session, dynamicAST, { autocorrect, deepValidation: true });
1103
+ console.error(`[LLM] Iteration ${iteration}: Validation complete - valid: ${validation.valid}, errors: ${validation.errorMessages.length}`);
1099
1104
  if (session.debug) {
1100
1105
  console.error(`[LLM] Validation result: valid=${validation.valid}, results count=${validation.results.length}`);
1101
1106
  if (validation.results.length > 0) {
@@ -1112,10 +1117,15 @@ ${result}
1112
1117
  console.error(`[LLM] Applying corrections from initial ${validation.results.length} validation results`);
1113
1118
  for (const result2 of validation.results) {
1114
1119
  if (result2.corrected) {
1120
+ hasTagCorrections = true;
1115
1121
  correctionMessages.push(`Auto-corrected: <${result2.originalTag}> \u2192 <${result2.tagName}> (similarity: ${result2.similarity?.toFixed(2)})`);
1116
1122
  }
1117
1123
  if (result2.warnings.length > 0) {
1118
- correctionMessages.push(...result2.warnings);
1124
+ const nonScopeWarnings = result2.warnings.filter((w) => !w.startsWith("Scope:"));
1125
+ if (nonScopeWarnings.length > 0) {
1126
+ hasTagCorrections = true;
1127
+ correctionMessages.push(...nonScopeWarnings);
1128
+ }
1119
1129
  }
1120
1130
  }
1121
1131
  console.error("[LLM] Initial correction messages collected:", correctionMessages.length);
@@ -1124,12 +1134,14 @@ ${result}
1124
1134
  }
1125
1135
  dynamicAST = applyCorrectedTags(dynamicAST, validation.results);
1126
1136
  console.error("[LLM] Applied initial auto-corrections to AST");
1127
- validation = await validateDiracCode(session, dynamicAST, { autocorrect: false });
1137
+ validation = await validateDiracCode(session, dynamicAST, { autocorrect: false, deepValidation: true });
1128
1138
  console.error(`[LLM] Re-validation after corrections: valid=${validation.valid}`);
1129
1139
  }
1130
1140
  let retryCount = 0;
1141
+ console.error(`[LLM] Iteration ${iteration}: Entering retry loop (validation.valid: ${validation.valid}, maxRetries: ${maxRetries})`);
1131
1142
  while (!validation.valid && retryCount < maxRetries) {
1132
1143
  retryCount++;
1144
+ console.error(`[LLM] Iteration ${iteration}: Retry ${retryCount}/${maxRetries} - validation failed with errors:`, validation.errorMessages);
1133
1145
  if (session.debug) {
1134
1146
  console.error(`[LLM] Validation failed (attempt ${retryCount}/${maxRetries}):`, validation.errorMessages);
1135
1147
  }
@@ -1188,13 +1200,16 @@ ${result}
1188
1200
  }
1189
1201
  }
1190
1202
  dynamicAST = parser.parse(diracCode);
1191
- validation = await validateDiracCode(session, dynamicAST, { autocorrect });
1203
+ validation = await validateDiracCode(session, dynamicAST, { autocorrect, deepValidation: true });
1192
1204
  }
1193
1205
  if (!validation.valid) {
1206
+ console.error(`[LLM] Iteration ${iteration}: VALIDATION FAILED after ${maxRetries} retries. Throwing error.`);
1194
1207
  throw new Error(`Tag validation failed after ${maxRetries} retries:
1195
1208
  ${validation.errorMessages.join("\n")}`);
1196
1209
  }
1197
- if (correctionMessages.length > 0 && feedbackMode) {
1210
+ console.error(`[LLM] Iteration ${iteration}: Validation passed, checking for corrections (hasTagCorrections: ${hasTagCorrections}, correctionMessages: ${correctionMessages.length})`);
1211
+ if (hasTagCorrections && correctionMessages.length > 0 && feedbackMode) {
1212
+ console.error(`[LLM] Iteration ${iteration}: Has tag corrections, preparing feedback (confirmCorrections: ${confirmCorrections})`);
1198
1213
  const correctedCodeLines = [];
1199
1214
  for (const child of dynamicAST.children) {
1200
1215
  if (child.tag && child.tag !== "DIRAC-ROOT") {
@@ -1272,7 +1287,67 @@ ${correctedCode}
1272
1287
  }
1273
1288
  }
1274
1289
  }
1275
- await integrate(session, dynamicAST);
1290
+ console.error(`[LLM] Iteration ${iteration}: About to execute code`);
1291
+ let executionError = null;
1292
+ try {
1293
+ console.error(`[LLM] Iteration ${iteration}: Calling integrate()`);
1294
+ await integrate(session, dynamicAST);
1295
+ console.error(`[LLM] Iteration ${iteration}: integrate() completed successfully`);
1296
+ if (session.output.length === outputBefore) {
1297
+ setVariable(session, "__llm_silent_execution__", result, false);
1298
+ }
1299
+ } catch (execError) {
1300
+ executionError = execError instanceof Error ? execError.message : String(execError);
1301
+ console.error(`[LLM] Iteration ${iteration}: EXECUTION ERROR: ${executionError}`);
1302
+ console.error(`[LLM] Execution error: ${executionError}`);
1303
+ if (feedbackMode && iteration < maxIterations) {
1304
+ const errorFeedback = `System: Your code executed but encountered a runtime error:
1305
+ ${executionError}
1306
+
1307
+ Please fix the error and try again.`;
1308
+ dialogHistory.push({ role: "user", content: errorFeedback });
1309
+ if (contextVar) {
1310
+ setVariable(session, contextVar, JSON.stringify(dialogHistory), true);
1311
+ } else if (saveDialog) {
1312
+ setVariable(session, "__llm_dialog__", JSON.stringify(dialogHistory), true);
1313
+ }
1314
+ if (isOpenAI) {
1315
+ const response = await llmClient.chat.completions.create({
1316
+ model,
1317
+ max_tokens: maxTokens,
1318
+ temperature,
1319
+ messages: dialogHistory
1320
+ });
1321
+ result = response.choices[0]?.message?.content || "";
1322
+ } else if (isOllama) {
1323
+ const ollamaPrompt = dialogHistory.map((m) => `${m.role.charAt(0).toUpperCase() + m.role.slice(1)}: ${m.content}`).join("\n");
1324
+ result = await llmClient.complete(ollamaPrompt, {
1325
+ model,
1326
+ temperature,
1327
+ max_tokens: maxTokens
1328
+ });
1329
+ } else if (isCustom) {
1330
+ const customPrompt = dialogHistory.map((m) => `${m.role}: ${m.content}`).join("\n");
1331
+ result = await llmClient.complete(customPrompt, {
1332
+ model,
1333
+ temperature,
1334
+ max_tokens: maxTokens,
1335
+ messages: dialogHistory
1336
+ });
1337
+ } else {
1338
+ result = await callAnthropic(llmClient, model, maxTokens, temperature, dialogHistory);
1339
+ }
1340
+ dialogHistory.push({ role: "assistant", content: result });
1341
+ if (contextVar) {
1342
+ setVariable(session, contextVar, JSON.stringify(dialogHistory), true);
1343
+ } else if (saveDialog) {
1344
+ setVariable(session, "__llm_dialog__", JSON.stringify(dialogHistory), true);
1345
+ }
1346
+ continue;
1347
+ } else {
1348
+ throw execError;
1349
+ }
1350
+ }
1276
1351
  if (iteration === 1) {
1277
1352
  dumpGeneratedSubroutines(session, diracCode, userPrompt);
1278
1353
  }
@@ -1300,7 +1375,7 @@ ${correctedCode}
1300
1375
  }
1301
1376
  if (feedbackMode) {
1302
1377
  const outputAfter = session.output.slice();
1303
- const executionOutput = outputAfter.slice(outputBefore.length).join("");
1378
+ const executionOutput = outputAfter.slice(outputBefore).join("");
1304
1379
  if (executionOutput) {
1305
1380
  process.stdout.write(executionOutput);
1306
1381
  }
@@ -1370,13 +1445,72 @@ ${result}
1370
1445
  break;
1371
1446
  }
1372
1447
  } catch (parseError) {
1373
- if (session.debug) {
1374
- console.error(`[LLM] Failed to parse as Dirac, treating as text: ${parseError}`);
1448
+ console.error(`[LLM] Iteration ${iteration}: ERROR CAUGHT: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
1449
+ const errorMsg = parseError instanceof Error ? parseError.message : String(parseError);
1450
+ const isValidationError = errorMsg.includes("Tag validation failed") || errorMsg.includes("Attribute") || errorMsg.includes("contains <variable> tag");
1451
+ if (isValidationError && feedbackMode && iteration < maxIterations) {
1452
+ console.error(`[LLM] Iteration ${iteration}: VALIDATION ERROR - sending to LLM for correction`);
1453
+ const errorFeedback = `System: Your code had validation errors:
1454
+ ${errorMsg}
1455
+
1456
+ Please fix these errors and generate valid Dirac XML code. Remember:
1457
+ - Use \${varname} syntax in attributes instead of <variable name="..." /> tags
1458
+ - Only use allowed tags and attributes`;
1459
+ dialogHistory.push({ role: "user", content: errorFeedback });
1460
+ if (contextVar) {
1461
+ setVariable(session, contextVar, JSON.stringify(dialogHistory), true);
1462
+ } else if (saveDialog) {
1463
+ setVariable(session, "__llm_dialog__", JSON.stringify(dialogHistory), true);
1464
+ }
1465
+ if (isOpenAI) {
1466
+ const response = await llmClient.chat.completions.create({
1467
+ model,
1468
+ max_tokens: maxTokens,
1469
+ temperature,
1470
+ messages: dialogHistory
1471
+ });
1472
+ result = response.choices[0]?.message?.content || "";
1473
+ } else if (isOllama) {
1474
+ const ollamaPrompt = dialogHistory.map((m) => `${m.role.charAt(0).toUpperCase() + m.role.slice(1)}: ${m.content}`).join("\n");
1475
+ result = await llmClient.complete(ollamaPrompt, {
1476
+ model,
1477
+ temperature,
1478
+ max_tokens: maxTokens
1479
+ });
1480
+ } else if (isCustom) {
1481
+ const customPrompt = dialogHistory.map((m) => `${m.role}: ${m.content}`).join("\n");
1482
+ result = await llmClient.complete(customPrompt, {
1483
+ model,
1484
+ temperature,
1485
+ max_tokens: maxTokens,
1486
+ messages: dialogHistory
1487
+ });
1488
+ } else {
1489
+ result = await callAnthropic(llmClient, model, maxTokens, temperature, dialogHistory);
1490
+ }
1491
+ dialogHistory.push({ role: "assistant", content: result });
1492
+ if (contextVar) {
1493
+ setVariable(session, contextVar, JSON.stringify(dialogHistory), true);
1494
+ } else if (saveDialog) {
1495
+ setVariable(session, "__llm_dialog__", JSON.stringify(dialogHistory), true);
1496
+ }
1497
+ if (session.debug) {
1498
+ console.error(`[LLM] LLM correction response:
1499
+ ${result}
1500
+ `);
1501
+ }
1502
+ continue;
1503
+ } else {
1504
+ console.error(`[LLM] Iteration ${iteration}: PARSE ERROR (or no feedback): ${errorMsg}`);
1505
+ if (session.debug) {
1506
+ console.error(`[LLM] Failed to parse as Dirac, treating as text: ${parseError}`);
1507
+ }
1508
+ emit(session, result);
1509
+ break;
1375
1510
  }
1376
- emit(session, result);
1377
- break;
1378
1511
  }
1379
1512
  }
1513
+ console.error(`[LLM] Exited feedback loop after ${iteration} iterations`);
1380
1514
  } else {
1381
1515
  emit(session, result);
1382
1516
  }
@@ -1927,7 +2061,7 @@ async function executeTagCheck(session, element) {
1927
2061
  const executeTag = correctedTag || tagName;
1928
2062
  console.error(`[tag-check] Executing <${executeTag}/> as all checks passed and execute=true.`);
1929
2063
  const elementToExecute = correctedTag ? { ...child, tag: correctedTag } : child;
1930
- const { integrate: integrate2 } = await import("./interpreter-WNHDVVDD.js");
2064
+ const { integrate: integrate2 } = await import("./interpreter-D6ZF3OJA.js");
1931
2065
  await integrate2(session, elementToExecute);
1932
2066
  }
1933
2067
  }
@@ -1936,7 +2070,7 @@ async function executeTagCheck(session, element) {
1936
2070
  // src/tags/throw.ts
1937
2071
  async function executeThrow(session, element) {
1938
2072
  const exceptionName = element.attributes?.name || "exception";
1939
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-WNHDVVDD.js");
2073
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-D6ZF3OJA.js");
1940
2074
  const exceptionDom = {
1941
2075
  tag: "exception-content",
1942
2076
  attributes: { name: exceptionName },
@@ -1949,7 +2083,7 @@ async function executeThrow(session, element) {
1949
2083
  // src/tags/try.ts
1950
2084
  async function executeTry(session, element) {
1951
2085
  setExceptionBoundary(session);
1952
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-WNHDVVDD.js");
2086
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-D6ZF3OJA.js");
1953
2087
  await integrateChildren2(session, element);
1954
2088
  unsetExceptionBoundary(session);
1955
2089
  }
@@ -1959,7 +2093,7 @@ async function executeCatch(session, element) {
1959
2093
  const exceptionName = element.attributes?.name || "exception";
1960
2094
  const caughtCount = lookupException(session, exceptionName);
1961
2095
  if (caughtCount > 0) {
1962
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-WNHDVVDD.js");
2096
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-D6ZF3OJA.js");
1963
2097
  await integrateChildren2(session, element);
1964
2098
  }
1965
2099
  flushCurrentException(session);
@@ -1968,7 +2102,7 @@ async function executeCatch(session, element) {
1968
2102
  // src/tags/exception.ts
1969
2103
  async function executeException(session, element) {
1970
2104
  const exceptions = getCurrentExceptions(session);
1971
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-WNHDVVDD.js");
2105
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-D6ZF3OJA.js");
1972
2106
  for (const exceptionDom of exceptions) {
1973
2107
  await integrateChildren2(session, exceptionDom);
1974
2108
  }
@@ -2169,7 +2303,7 @@ async function executeLoadContext(session, element) {
2169
2303
  query = element.text.trim();
2170
2304
  }
2171
2305
  if (!query && element.children.length > 0) {
2172
- const { integrate: integrate2 } = await import("./interpreter-WNHDVVDD.js");
2306
+ const { integrate: integrate2 } = await import("./interpreter-D6ZF3OJA.js");
2173
2307
  const beforeOutput = session.output.length;
2174
2308
  for (const child of element.children) {
2175
2309
  await integrate2(session, child);
@@ -3013,7 +3147,7 @@ async function executeForeach(session, element) {
3013
3147
  const parser2 = new DiracParser2();
3014
3148
  try {
3015
3149
  const fromElement = parser2.parse(fromAttr);
3016
- const { integrate: integrate2 } = await import("./interpreter-WNHDVVDD.js");
3150
+ const { integrate: integrate2 } = await import("./interpreter-D6ZF3OJA.js");
3017
3151
  await integrate2(session, fromElement);
3018
3152
  } catch (e) {
3019
3153
  session.output = savedOutput;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  integrate
3
- } from "./chunk-NUNYBLVJ.js";
3
+ } from "./chunk-LAEYP4OQ.js";
4
4
  import {
5
5
  DiracParser
6
6
  } from "./chunk-HRHAMPOB.js";
package/dist/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  execute
4
- } from "./chunk-LGFNVEHY.js";
4
+ } from "./chunk-MYWEN36N.js";
5
5
  import {
6
6
  BraKetParser
7
- } from "./chunk-NUNYBLVJ.js";
8
- import "./chunk-ECAW4X46.js";
7
+ } from "./chunk-LAEYP4OQ.js";
9
8
  import "./chunk-SLGJRZ3P.js";
10
9
  import "./chunk-HRHAMPOB.js";
10
+ import "./chunk-ECAW4X46.js";
11
11
  import "./chunk-PPH7KYKH.js";
12
12
 
13
13
  // src/cli.ts
@@ -16,7 +16,7 @@ import "dotenv/config";
16
16
  // package.json
17
17
  var package_default = {
18
18
  name: "dirac-lang",
19
- version: "0.1.95",
19
+ version: "0.1.98",
20
20
  description: "LLM-Augmented Declarative Execution",
21
21
  type: "module",
22
22
  main: "dist/index.js",
@@ -150,7 +150,7 @@ async function main() {
150
150
  const args = process.argv.slice(2);
151
151
  const calledAs = process.argv[1];
152
152
  if (calledAs && calledAs.endsWith("/dish")) {
153
- const { DiracShell } = await import("./shell-N3TM23ZB.js");
153
+ const { DiracShell } = await import("./shell-KNEQHL3Y.js");
154
154
  const shellConfig = loadShellConfig(args);
155
155
  const shell = new DiracShell(shellConfig);
156
156
  await shell.start();
@@ -199,11 +199,11 @@ async function main() {
199
199
  if (args[0] === "agent") {
200
200
  const subcommand = args[1];
201
201
  if (subcommand === "daemon") {
202
- const { runAgentDaemon } = await import("./agent-SVKTURXE.js");
202
+ const { runAgentDaemon } = await import("./agent-5Q5MQOV2.js");
203
203
  await runAgentDaemon();
204
204
  return;
205
205
  }
206
- const { AgentCLI } = await import("./agent-SVKTURXE.js");
206
+ const { AgentCLI } = await import("./agent-5Q5MQOV2.js");
207
207
  const agent = new AgentCLI();
208
208
  switch (subcommand) {
209
209
  case "start":
@@ -230,8 +230,8 @@ async function main() {
230
230
  return;
231
231
  }
232
232
  if (args[0] === "shell") {
233
- const { DiracShell } = await import("./shell-N3TM23ZB.js");
234
- const { SessionServer, isSessionRunning, getSocketPath } = await import("./session-server-GPITH5QY.js");
233
+ const { DiracShell } = await import("./shell-KNEQHL3Y.js");
234
+ const { SessionServer, isSessionRunning, getSocketPath } = await import("./session-server-N53QIJO5.js");
235
235
  const { SessionClient } = await import("./session-client-3VTC5MLO.js");
236
236
  const daemonMode = args.includes("--daemon") || args.includes("-d");
237
237
  const agentMode = args.includes("--agent") || args.includes("-a");
@@ -277,7 +277,7 @@ async function main() {
277
277
  return;
278
278
  }
279
279
  if (args[0] === "daemon") {
280
- const { SessionServer } = await import("./session-server-GPITH5QY.js");
280
+ const { SessionServer } = await import("./session-server-N53QIJO5.js");
281
281
  const server = new SessionServer();
282
282
  await server.start();
283
283
  console.log("Session daemon started");
@@ -3,10 +3,10 @@ import {
3
3
  listCronJobs,
4
4
  stopAllCronJobs,
5
5
  stopCronJob
6
- } from "./chunk-NUNYBLVJ.js";
7
- import "./chunk-ECAW4X46.js";
6
+ } from "./chunk-LAEYP4OQ.js";
8
7
  import "./chunk-SLGJRZ3P.js";
9
8
  import "./chunk-HRHAMPOB.js";
9
+ import "./chunk-ECAW4X46.js";
10
10
  import "./chunk-PPH7KYKH.js";
11
11
  export {
12
12
  executeCron,
package/dist/index.js CHANGED
@@ -2,15 +2,15 @@ import {
2
2
  createLLMAdapter,
3
3
  execute,
4
4
  executeUserCommand
5
- } from "./chunk-LGFNVEHY.js";
5
+ } from "./chunk-MYWEN36N.js";
6
6
  import {
7
7
  integrate
8
- } from "./chunk-NUNYBLVJ.js";
9
- import "./chunk-ECAW4X46.js";
8
+ } from "./chunk-LAEYP4OQ.js";
10
9
  import "./chunk-SLGJRZ3P.js";
11
10
  import {
12
11
  DiracParser
13
12
  } from "./chunk-HRHAMPOB.js";
13
+ import "./chunk-ECAW4X46.js";
14
14
  import {
15
15
  createSession,
16
16
  getAvailableSubroutines,
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  integrate,
3
3
  integrateChildren
4
- } from "./chunk-NUNYBLVJ.js";
5
- import "./chunk-ECAW4X46.js";
4
+ } from "./chunk-LAEYP4OQ.js";
6
5
  import "./chunk-SLGJRZ3P.js";
7
6
  import "./chunk-HRHAMPOB.js";
7
+ import "./chunk-ECAW4X46.js";
8
8
  import "./chunk-PPH7KYKH.js";
9
9
  export {
10
10
  integrate,
@@ -3,10 +3,10 @@ import {
3
3
  cancelScheduledRun,
4
4
  executeRunAt,
5
5
  listScheduledRuns
6
- } from "./chunk-NUNYBLVJ.js";
7
- import "./chunk-ECAW4X46.js";
6
+ } from "./chunk-LAEYP4OQ.js";
8
7
  import "./chunk-SLGJRZ3P.js";
9
8
  import "./chunk-HRHAMPOB.js";
9
+ import "./chunk-ECAW4X46.js";
10
10
  import "./chunk-PPH7KYKH.js";
11
11
  export {
12
12
  cancelAllScheduledRuns,
@@ -3,10 +3,10 @@ import {
3
3
  listScheduledTasks,
4
4
  stopAllScheduledTasks,
5
5
  stopScheduledTask
6
- } from "./chunk-NUNYBLVJ.js";
7
- import "./chunk-ECAW4X46.js";
6
+ } from "./chunk-LAEYP4OQ.js";
8
7
  import "./chunk-SLGJRZ3P.js";
9
8
  import "./chunk-HRHAMPOB.js";
9
+ import "./chunk-ECAW4X46.js";
10
10
  import "./chunk-PPH7KYKH.js";
11
11
  export {
12
12
  executeSchedule,
@@ -0,0 +1,171 @@
1
+ // src/utils/scope-validator.ts
2
+ function extractParameterNames(element) {
3
+ const params = [];
4
+ for (const attr in element.attributes) {
5
+ if (attr.startsWith("param-")) {
6
+ const paramName = attr.slice(6);
7
+ params.push(paramName);
8
+ }
9
+ }
10
+ return params;
11
+ }
12
+ function extractVariableReferences(text) {
13
+ const pattern = /\$\{([a-zA-Z_][a-zA-Z0-9_-]*)\}/g;
14
+ const matches = [];
15
+ let match;
16
+ while ((match = pattern.exec(text)) !== null) {
17
+ matches.push(match[1]);
18
+ }
19
+ return matches;
20
+ }
21
+ var ScopeContext = class {
22
+ parameters;
23
+ // Declared parameters
24
+ declaredVariables;
25
+ // Variables declared with <defvar>
26
+ referencedVariables;
27
+ // Variables referenced with <variable> or ${}
28
+ referencedParameters;
29
+ // Parameters actually used
30
+ constructor(parameters) {
31
+ this.parameters = new Set(parameters);
32
+ this.declaredVariables = /* @__PURE__ */ new Set();
33
+ this.referencedVariables = /* @__PURE__ */ new Set();
34
+ this.referencedParameters = /* @__PURE__ */ new Set();
35
+ }
36
+ /**
37
+ * Check if a name is available in current scope
38
+ * Priority: parameters -> declared variables
39
+ */
40
+ isInScope(name) {
41
+ return this.parameters.has(name) || this.declaredVariables.has(name);
42
+ }
43
+ /**
44
+ * Record a variable declaration
45
+ */
46
+ declareVariable(name) {
47
+ this.declaredVariables.add(name);
48
+ }
49
+ /**
50
+ * Record a variable/parameter reference
51
+ */
52
+ referenceVariable(name) {
53
+ this.referencedVariables.add(name);
54
+ if (this.parameters.has(name)) {
55
+ this.referencedParameters.add(name);
56
+ }
57
+ }
58
+ };
59
+ function validateScope(element, scope, errors, warnings) {
60
+ if (element.tag === "defvar") {
61
+ const varName = element.attributes.name;
62
+ if (varName) {
63
+ scope.declareVariable(varName);
64
+ }
65
+ }
66
+ if (element.tag === "variable") {
67
+ const varName = element.attributes.name;
68
+ if (varName) {
69
+ scope.referenceVariable(varName);
70
+ if (!scope.isInScope(varName)) {
71
+ warnings.push(
72
+ `Variable reference '${varName}' not found in local scope (may be from parent scope)`
73
+ );
74
+ }
75
+ }
76
+ }
77
+ if (element.tag === "parameters") {
78
+ const select = element.attributes.select;
79
+ if (select && select.startsWith("@")) {
80
+ const paramName = select.slice(1);
81
+ scope.referenceVariable(paramName);
82
+ if (!scope.isInScope(paramName)) {
83
+ warnings.push(
84
+ `Parameter reference '${paramName}' not found in subroutine parameters`
85
+ );
86
+ }
87
+ }
88
+ }
89
+ for (const [attrName, attrValue] of Object.entries(element.attributes)) {
90
+ if (typeof attrValue === "string") {
91
+ const varRefs = extractVariableReferences(attrValue);
92
+ for (const varRef of varRefs) {
93
+ scope.referenceVariable(varRef);
94
+ if (!scope.isInScope(varRef)) {
95
+ warnings.push(
96
+ `Variable substitution '\${${varRef}}' in attribute not found in local scope (may be from parent scope)`
97
+ );
98
+ }
99
+ }
100
+ const dollarVarPattern = /\$([a-zA-Z_][a-zA-Z0-9_-]*)/g;
101
+ let dollarMatch;
102
+ while ((dollarMatch = dollarVarPattern.exec(attrValue)) !== null) {
103
+ const varName = dollarMatch[1];
104
+ scope.referenceVariable(varName);
105
+ }
106
+ }
107
+ }
108
+ for (const child of element.children) {
109
+ validateScope(child, scope, errors, warnings);
110
+ }
111
+ }
112
+ function validateSubroutineScope(subroutine) {
113
+ const errors = [];
114
+ const warnings = [];
115
+ const parameters = extractParameterNames(subroutine);
116
+ const scope = new ScopeContext(parameters);
117
+ for (const child of subroutine.children) {
118
+ validateScope(child, scope, errors, warnings);
119
+ }
120
+ const unusedParameters = parameters.filter((p) => !scope.referencedParameters.has(p));
121
+ if (unusedParameters.length > 0) {
122
+ warnings.push(
123
+ `Unused parameters: ${unusedParameters.join(", ")}`
124
+ );
125
+ }
126
+ const unusedVariables = Array.from(scope.declaredVariables).filter(
127
+ (v) => !scope.referencedVariables.has(v)
128
+ );
129
+ if (unusedVariables.length > 0) {
130
+ warnings.push(
131
+ `Unused variables: ${unusedVariables.join(", ")}`
132
+ );
133
+ }
134
+ const undefinedReferences = Array.from(scope.referencedVariables).filter(
135
+ (v) => !scope.isInScope(v)
136
+ );
137
+ const undefinedParameters = undefinedReferences.filter(
138
+ (v) => !scope.declaredVariables.has(v)
139
+ );
140
+ const undefinedVariables = undefinedReferences.filter(
141
+ (v) => scope.declaredVariables.has(v)
142
+ );
143
+ return {
144
+ valid: errors.length === 0,
145
+ errors,
146
+ warnings,
147
+ undefinedParameters,
148
+ undefinedVariables,
149
+ unusedParameters,
150
+ unusedVariables
151
+ };
152
+ }
153
+ function validateAllSubroutineScopes(ast) {
154
+ const results = /* @__PURE__ */ new Map();
155
+ function findSubroutines(element) {
156
+ if (element.tag === "subroutine") {
157
+ const name = element.attributes.name || "anonymous";
158
+ const result = validateSubroutineScope(element);
159
+ results.set(name, result);
160
+ }
161
+ for (const child of element.children) {
162
+ findSubroutines(child);
163
+ }
164
+ }
165
+ findSubroutines(ast);
166
+ return results;
167
+ }
168
+ export {
169
+ validateAllSubroutineScopes,
170
+ validateSubroutineScope
171
+ };
@@ -2,11 +2,11 @@ import {
2
2
  SessionServer,
3
3
  getSocketPath,
4
4
  isSessionRunning
5
- } from "./chunk-IFBJYN2F.js";
6
- import "./chunk-NUNYBLVJ.js";
7
- import "./chunk-ECAW4X46.js";
5
+ } from "./chunk-33DMGFRM.js";
6
+ import "./chunk-LAEYP4OQ.js";
8
7
  import "./chunk-SLGJRZ3P.js";
9
8
  import "./chunk-HRHAMPOB.js";
9
+ import "./chunk-ECAW4X46.js";
10
10
  import "./chunk-PPH7KYKH.js";
11
11
  export {
12
12
  SessionServer,
@@ -2,12 +2,12 @@
2
2
  import {
3
3
  BraKetParser,
4
4
  integrate
5
- } from "./chunk-NUNYBLVJ.js";
6
- import "./chunk-ECAW4X46.js";
5
+ } from "./chunk-LAEYP4OQ.js";
7
6
  import "./chunk-SLGJRZ3P.js";
8
7
  import {
9
8
  DiracParser
10
9
  } from "./chunk-HRHAMPOB.js";
10
+ import "./chunk-ECAW4X46.js";
11
11
  import {
12
12
  createSession
13
13
  } from "./chunk-PPH7KYKH.js";
@@ -358,7 +358,7 @@ var DiracShell = class {
358
358
  if (this.client) {
359
359
  this.client.disconnect();
360
360
  }
361
- import("./schedule-JY54UROJ.js").then(({ stopAllScheduledTasks }) => {
361
+ import("./schedule-3EJJHG3B.js").then(({ stopAllScheduledTasks }) => {
362
362
  stopAllScheduledTasks();
363
363
  console.log("\nGoodbye!");
364
364
  process.exit(0);
@@ -504,6 +504,15 @@ var DiracShell = class {
504
504
  if (this.session.output.length > 0) {
505
505
  console.log(this.session.output.join(""));
506
506
  }
507
+ const silentExecution = this.session.variables.find((v) => v.name === "__llm_silent_execution__");
508
+ if (silentExecution?.value) {
509
+ console.error(`
510
+ [LLM generated]
511
+ ${silentExecution.value}
512
+ `);
513
+ const idx = this.session.variables.findIndex((v) => v.name === "__llm_silent_execution__");
514
+ if (idx !== -1) this.session.variables.splice(idx, 1);
515
+ }
507
516
  } catch (error) {
508
517
  console.error("Error:", error instanceof Error ? error.message : String(error));
509
518
  if (this.config.debug && error instanceof Error && error.stack) {
@@ -763,7 +772,7 @@ Examples:
763
772
  break;
764
773
  case "tasks":
765
774
  try {
766
- const { listScheduledTasks } = await import("./schedule-JY54UROJ.js");
775
+ const { listScheduledTasks } = await import("./schedule-3EJJHG3B.js");
767
776
  const tasks = listScheduledTasks();
768
777
  if (tasks.length === 0) {
769
778
  console.log("No scheduled tasks running.");
@@ -782,7 +791,7 @@ Examples:
782
791
  console.log("Usage: :stop <task-name>");
783
792
  } else {
784
793
  try {
785
- const { stopScheduledTask } = await import("./schedule-JY54UROJ.js");
794
+ const { stopScheduledTask } = await import("./schedule-3EJJHG3B.js");
786
795
  const taskName = args[0];
787
796
  const stopped = stopScheduledTask(taskName);
788
797
  if (stopped) {
@@ -797,7 +806,7 @@ Examples:
797
806
  break;
798
807
  case "stopall":
799
808
  try {
800
- const { stopAllScheduledTasks } = await import("./schedule-JY54UROJ.js");
809
+ const { stopAllScheduledTasks } = await import("./schedule-3EJJHG3B.js");
801
810
  stopAllScheduledTasks();
802
811
  console.log("All scheduled tasks stopped.");
803
812
  } catch (error) {
@@ -806,7 +815,7 @@ Examples:
806
815
  break;
807
816
  case "crons":
808
817
  try {
809
- const { listCronJobs } = await import("./cron-YIBSPTLT.js");
818
+ const { listCronJobs } = await import("./cron-VCUFU2WU.js");
810
819
  const jobs = listCronJobs();
811
820
  if (jobs.length === 0) {
812
821
  console.log("No cron jobs running.");
@@ -826,7 +835,7 @@ Examples:
826
835
  console.log("Usage: :stopcron <job-name>");
827
836
  } else {
828
837
  try {
829
- const { stopCronJob } = await import("./cron-YIBSPTLT.js");
838
+ const { stopCronJob } = await import("./cron-VCUFU2WU.js");
830
839
  const jobName = args[0];
831
840
  const stopped = stopCronJob(jobName);
832
841
  if (stopped) {
@@ -841,7 +850,7 @@ Examples:
841
850
  break;
842
851
  case "stopallcrons":
843
852
  try {
844
- const { stopAllCronJobs } = await import("./cron-YIBSPTLT.js");
853
+ const { stopAllCronJobs } = await import("./cron-VCUFU2WU.js");
845
854
  stopAllCronJobs();
846
855
  console.log("All cron jobs stopped.");
847
856
  } catch (error) {
@@ -850,7 +859,7 @@ Examples:
850
859
  break;
851
860
  case "scheduled":
852
861
  try {
853
- const { listScheduledRuns } = await import("./run-at-H7RN6DOD.js");
862
+ const { listScheduledRuns } = await import("./run-at-P43PK5JU.js");
854
863
  const runs = listScheduledRuns();
855
864
  if (runs.length === 0) {
856
865
  console.log("No scheduled runs pending.");
@@ -870,7 +879,7 @@ Examples:
870
879
  console.log("Usage: :cancel <run-name>");
871
880
  } else {
872
881
  try {
873
- const { cancelScheduledRun } = await import("./run-at-H7RN6DOD.js");
882
+ const { cancelScheduledRun } = await import("./run-at-P43PK5JU.js");
874
883
  const runName = args[0];
875
884
  const cancelled = cancelScheduledRun(runName);
876
885
  if (cancelled) {
@@ -885,7 +894,7 @@ Examples:
885
894
  break;
886
895
  case "cancelall":
887
896
  try {
888
- const { cancelAllScheduledRuns } = await import("./run-at-H7RN6DOD.js");
897
+ const { cancelAllScheduledRuns } = await import("./run-at-P43PK5JU.js");
889
898
  cancelAllScheduledRuns();
890
899
  console.log("All scheduled runs cancelled.");
891
900
  } catch (error) {
@@ -47,8 +47,67 @@ async function getBestTagMatch(candidate, allowed) {
47
47
  });
48
48
  return { tag: allowed[bestIdx], score: bestScore };
49
49
  }
50
+ function validateParameterType(paramName, value, expectedType) {
51
+ if (!expectedType) {
52
+ return { valid: true };
53
+ }
54
+ const type = expectedType.split(":")[0].toLowerCase();
55
+ switch (type) {
56
+ case "boolean":
57
+ if (value !== "true" && value !== "false" && value !== "") {
58
+ return {
59
+ valid: false,
60
+ error: `Parameter '${paramName}' expects boolean (true/false), got: ${value}`
61
+ };
62
+ }
63
+ break;
64
+ case "number":
65
+ case "integer":
66
+ if (value !== "" && isNaN(Number(value))) {
67
+ return {
68
+ valid: false,
69
+ error: `Parameter '${paramName}' expects number, got: ${value}`
70
+ };
71
+ }
72
+ break;
73
+ case "string":
74
+ break;
75
+ default:
76
+ break;
77
+ }
78
+ return { valid: true };
79
+ }
80
+ function validateAttributeValue(attrName, value) {
81
+ if (value.includes("<variable")) {
82
+ return {
83
+ valid: false,
84
+ error: `Attribute '${attrName}' contains <variable> tag - use \${varname} syntax in attributes instead`
85
+ };
86
+ }
87
+ if (/<[a-zA-Z]/.test(value) && !value.includes("${")) {
88
+ return {
89
+ valid: false,
90
+ warning: `Attribute '${attrName}' appears to contain XML tags - attribute values should use \${} syntax for variables`
91
+ };
92
+ }
93
+ return { valid: true };
94
+ }
95
+ async function validateNestedTags(session, element, options = {}) {
96
+ const results = [];
97
+ for (const child of element.children) {
98
+ if (child.tag && child.tag.trim() !== "") {
99
+ const result = await validateTag(session, child, options);
100
+ results.push(result);
101
+ if (child.children && child.children.length > 0) {
102
+ const nestedResults = await validateNestedTags(session, child, options);
103
+ results.push(...nestedResults);
104
+ }
105
+ }
106
+ }
107
+ return results;
108
+ }
50
109
  async function validateTag(session, element, options = {}) {
51
- const { autocorrect = false, similarityCutoff = SIMILARITY_CUTOFF } = options;
110
+ const { autocorrect = false, similarityCutoff = SIMILARITY_CUTOFF, deepValidation = false } = options;
52
111
  console.error(`[VALIDATE] Tag: <${element.tag}>, autocorrect: ${autocorrect}, attributes:`, Object.keys(element.attributes));
53
112
  const { getAvailableSubroutines } = await import("./session-IH5LO7FS.js");
54
113
  const subroutines = getAvailableSubroutines(session);
@@ -61,7 +120,10 @@ async function validateTag(session, element, options = {}) {
61
120
  corrected: false,
62
121
  errors: [],
63
122
  warnings: [],
64
- attributeCorrections: {}
123
+ attributeCorrections: {},
124
+ typeErrors: [],
125
+ nestedValidation: [],
126
+ scopeValidation: void 0
65
127
  };
66
128
  if (allowed.has(tagName)) {
67
129
  console.error(`[VALIDATE] Tag <${tagName}> is valid`);
@@ -75,6 +137,10 @@ async function validateTag(session, element, options = {}) {
75
137
  }
76
138
  }
77
139
  for (const attr in element.attributes) {
140
+ if (tagName === "subroutine" && (attr.startsWith("param-") || attr.startsWith("meta-"))) {
141
+ console.error(`[VALIDATE] Skipping validation for wildcard attribute '${attr}' on <subroutine>`);
142
+ continue;
143
+ }
78
144
  if (!paramNames.includes(attr)) {
79
145
  console.error(`[VALIDATE] Unknown attribute '${attr}' on <${tagName}>`);
80
146
  if (autocorrect && paramNames.length > 0) {
@@ -108,6 +174,49 @@ async function validateTag(session, element, options = {}) {
108
174
  }
109
175
  }
110
176
  }
177
+ for (const attr in element.attributes) {
178
+ const param = sub.parameters.find((p) => p.name === attr);
179
+ const attrValue = element.attributes[attr];
180
+ const attrValueCheck = validateAttributeValue(attr, attrValue);
181
+ if (!attrValueCheck.valid && attrValueCheck.error) {
182
+ result.errors.push(attrValueCheck.error);
183
+ }
184
+ if (attrValueCheck.warning) {
185
+ result.warnings.push(attrValueCheck.warning);
186
+ }
187
+ if (param && param.type) {
188
+ const typeCheck = validateParameterType(attr, attrValue, param.type);
189
+ if (!typeCheck.valid && typeCheck.error) {
190
+ result.typeErrors.push(typeCheck.error);
191
+ result.errors.push(typeCheck.error);
192
+ }
193
+ }
194
+ }
195
+ if (deepValidation && tagName === "subroutine" && element.children && element.children.length > 0) {
196
+ console.error(`[VALIDATE] Deep validation of <subroutine name="${element.attributes.name}">`);
197
+ result.nestedValidation = await validateNestedTags(session, element, options);
198
+ for (const nestedResult of result.nestedValidation) {
199
+ if (!nestedResult.valid) {
200
+ result.warnings.push(`Nested tag <${nestedResult.originalTag}>: ${nestedResult.errors.join(", ")}`);
201
+ }
202
+ }
203
+ const { validateSubroutineScope } = await import("./scope-validator-TVQIOEAI.js");
204
+ result.scopeValidation = validateSubroutineScope(element);
205
+ console.error(`[VALIDATE] Scope validation for <subroutine name="${element.attributes.name}">:`, {
206
+ errors: result.scopeValidation.errors.length,
207
+ warnings: result.scopeValidation.warnings.length,
208
+ undefinedParams: result.scopeValidation.undefinedParameters,
209
+ undefinedVars: result.scopeValidation.undefinedVariables,
210
+ unusedParams: result.scopeValidation.unusedParameters,
211
+ unusedVars: result.scopeValidation.unusedVariables
212
+ });
213
+ if (result.scopeValidation.warnings.length > 0) {
214
+ result.warnings.push(...result.scopeValidation.warnings.map((w) => `Scope: ${w}`));
215
+ }
216
+ if (result.scopeValidation.errors.length > 0) {
217
+ result.errors.push(...result.scopeValidation.errors.map((e) => `Scope: ${e}`));
218
+ }
219
+ }
111
220
  }
112
221
  result.valid = result.errors.length === 0;
113
222
  } else {
@@ -160,6 +269,50 @@ async function validateTag(session, element, options = {}) {
160
269
  async function validateDiracCode(session, ast, options = {}) {
161
270
  const results = [];
162
271
  const errorMessages = [];
272
+ const typeErrors = [];
273
+ const localSubroutineNames = /* @__PURE__ */ new Set();
274
+ const localSubroutineElements = /* @__PURE__ */ new Map();
275
+ function extractLocalSubroutines(element) {
276
+ if (element.tag === "subroutine" && element.attributes.name) {
277
+ localSubroutineNames.add(element.attributes.name);
278
+ localSubroutineElements.set(element.attributes.name, element);
279
+ }
280
+ for (const child of element.children) {
281
+ extractLocalSubroutines(child);
282
+ }
283
+ }
284
+ extractLocalSubroutines(ast);
285
+ if (localSubroutineNames.size > 0) {
286
+ console.error(`[VALIDATE] Found ${localSubroutineNames.size} local subroutine definitions:`, Array.from(localSubroutineNames));
287
+ }
288
+ const tempSubroutines = [];
289
+ for (const subName of localSubroutineNames) {
290
+ const subElement = localSubroutineElements.get(subName);
291
+ const parameters = [];
292
+ for (const attr in subElement.attributes) {
293
+ if (attr.startsWith("param-")) {
294
+ const paramName = attr.slice(6);
295
+ const paramSpec = subElement.attributes[attr];
296
+ const parts = paramSpec.split(":");
297
+ parameters.push({
298
+ name: paramName,
299
+ type: parts[0] || "string",
300
+ required: parts[1] === "required",
301
+ description: parts[2] || "",
302
+ example: parts[3] || ""
303
+ });
304
+ }
305
+ }
306
+ console.error(`[VALIDATE] Temp subroutine '${subName}' has ${parameters.length} parameters:`, parameters.map((p) => p.name));
307
+ const tempSub = {
308
+ name: subName,
309
+ element: subElement,
310
+ boundary: session.variables.length,
311
+ parameters
312
+ };
313
+ session.subroutines.push(tempSub);
314
+ tempSubroutines.push(tempSub);
315
+ }
163
316
  async function validateElement(element) {
164
317
  if (element.tag && element.tag !== "dirac" && element.tag !== "DIRAC-ROOT" && element.tag.trim() !== "") {
165
318
  const result = await validateTag(session, element, options);
@@ -167,41 +320,53 @@ async function validateDiracCode(session, ast, options = {}) {
167
320
  if (!result.valid) {
168
321
  errorMessages.push(`<${result.originalTag}>: ${result.errors.join(", ")}`);
169
322
  }
323
+ if (result.typeErrors && result.typeErrors.length > 0) {
324
+ typeErrors.push(...result.typeErrors);
325
+ }
170
326
  }
171
327
  for (const child of element.children) {
172
328
  await validateElement(child);
173
329
  }
174
330
  }
175
331
  await validateElement(ast);
332
+ for (const tempSub of tempSubroutines) {
333
+ const index = session.subroutines.indexOf(tempSub);
334
+ if (index > -1) {
335
+ session.subroutines.splice(index, 1);
336
+ }
337
+ }
176
338
  return {
177
339
  valid: errorMessages.length === 0,
178
340
  results,
179
- errorMessages
341
+ errorMessages,
342
+ typeErrors
180
343
  };
181
344
  }
182
345
  function applyCorrectedTags(ast, results) {
183
346
  let resultIndex = 0;
184
347
  function correctElement(element) {
185
- if (element.tag && element.tag !== "dirac" && element.tag !== "DIRAC-ROOT" && element.tag.trim() !== "") {
348
+ const shouldProcess = element.tag && element.tag !== "dirac" && element.tag !== "DIRAC-ROOT" && element.tag.trim() !== "";
349
+ if (shouldProcess && resultIndex < results.length) {
186
350
  const result = results[resultIndex++];
187
- if (result) {
188
- if (result.corrected && result.tagName !== element.tag) {
189
- console.error(`[APPLY-CORRECTION] Tag: ${element.tag} \u2192 ${result.tagName}`);
190
- element = { ...element, tag: result.tagName };
191
- }
192
- if (result.attributeCorrections && Object.keys(result.attributeCorrections).length > 0) {
193
- console.error(`[APPLY-CORRECTION] Attributes on <${element.tag}>:`, result.attributeCorrections);
194
- const newAttributes = {};
195
- for (const [oldAttr, value] of Object.entries(element.attributes)) {
196
- const newAttr = result.attributeCorrections[oldAttr] || oldAttr;
197
- if (newAttr !== oldAttr) {
198
- console.error(`[APPLY-CORRECTION] ${oldAttr}="${value}" \u2192 ${newAttr}="${value}"`);
199
- }
200
- newAttributes[newAttr] = value;
351
+ console.error(`[APPLY-CORRECTION] Processing <${element.tag}> with result #${resultIndex - 1} for <${result.originalTag}>, corrected: ${result.corrected}`);
352
+ if (result.corrected && result.tagName !== element.tag) {
353
+ console.error(`[APPLY-CORRECTION] Tag: ${element.tag} \u2192 ${result.tagName}`);
354
+ element = { ...element, tag: result.tagName };
355
+ }
356
+ if (result.attributeCorrections && Object.keys(result.attributeCorrections).length > 0) {
357
+ console.error(`[APPLY-CORRECTION] Attributes on <${element.tag}>:`, result.attributeCorrections);
358
+ const newAttributes = {};
359
+ for (const [oldAttr, value] of Object.entries(element.attributes)) {
360
+ const newAttr = result.attributeCorrections[oldAttr] || oldAttr;
361
+ if (newAttr !== oldAttr) {
362
+ console.error(`[APPLY-CORRECTION] ${oldAttr}="${value}" \u2192 ${newAttr}="${value}"`);
201
363
  }
202
- element = { ...element, attributes: newAttributes };
364
+ newAttributes[newAttr] = value;
203
365
  }
366
+ element = { ...element, attributes: newAttributes };
204
367
  }
368
+ } else if (shouldProcess) {
369
+ console.error(`[APPLY-CORRECTION] WARNING: No result for <${element.tag}> at index ${resultIndex} (total results: ${results.length})`);
205
370
  }
206
371
  return {
207
372
  ...element,
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  integrate
3
- } from "./chunk-NUNYBLVJ.js";
4
- import "./chunk-ECAW4X46.js";
3
+ } from "./chunk-LAEYP4OQ.js";
5
4
  import "./chunk-SLGJRZ3P.js";
6
5
  import {
7
6
  DiracParser
8
7
  } from "./chunk-HRHAMPOB.js";
8
+ import "./chunk-ECAW4X46.js";
9
9
  import {
10
10
  createSession,
11
11
  getOutput
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dirac-lang",
3
- "version": "0.1.96",
3
+ "version": "0.1.98",
4
4
  "description": "LLM-Augmented Declarative Execution",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",