llmist 1.0.0 → 1.2.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.
@@ -1346,215 +1346,242 @@ var init_exceptions = __esm({
1346
1346
  }
1347
1347
  });
1348
1348
 
1349
- // src/gadgets/executor.ts
1350
- var GadgetExecutor;
1351
- var init_executor = __esm({
1352
- "src/gadgets/executor.ts"() {
1349
+ // src/gadgets/schema-introspector.ts
1350
+ function getDef(schema) {
1351
+ return schema._def;
1352
+ }
1353
+ function getTypeName(schema) {
1354
+ const def = getDef(schema);
1355
+ return def?.type ?? def?.typeName;
1356
+ }
1357
+ function getShape(schema) {
1358
+ const def = getDef(schema);
1359
+ if (typeof def?.shape === "function") {
1360
+ return def.shape();
1361
+ }
1362
+ return def?.shape;
1363
+ }
1364
+ var SchemaIntrospector;
1365
+ var init_schema_introspector = __esm({
1366
+ "src/gadgets/schema-introspector.ts"() {
1353
1367
  "use strict";
1354
- init_logger();
1355
- init_exceptions();
1356
- GadgetExecutor = class {
1357
- constructor(registry, onHumanInputRequired, logger, defaultGadgetTimeoutMs) {
1358
- this.registry = registry;
1359
- this.onHumanInputRequired = onHumanInputRequired;
1360
- this.defaultGadgetTimeoutMs = defaultGadgetTimeoutMs;
1361
- this.logger = logger ?? createLogger({ name: "llmist:executor" });
1368
+ SchemaIntrospector = class {
1369
+ schema;
1370
+ cache = /* @__PURE__ */ new Map();
1371
+ constructor(schema) {
1372
+ this.schema = schema;
1362
1373
  }
1363
- logger;
1364
1374
  /**
1365
- * Creates a promise that rejects with a TimeoutException after the specified timeout.
1375
+ * Get the expected type at a JSON pointer path.
1376
+ *
1377
+ * @param pointer - JSON pointer path without leading / (e.g., "config/timeout", "items/0")
1378
+ * @returns Type hint for coercion decision
1366
1379
  */
1367
- createTimeoutPromise(gadgetName, timeoutMs) {
1368
- return new Promise((_, reject) => {
1369
- setTimeout(() => {
1370
- reject(new TimeoutException(gadgetName, timeoutMs));
1371
- }, timeoutMs);
1372
- });
1380
+ getTypeAtPath(pointer) {
1381
+ const cached = this.cache.get(pointer);
1382
+ if (cached !== void 0) {
1383
+ return cached;
1384
+ }
1385
+ const result = this.resolveTypeAtPath(pointer);
1386
+ this.cache.set(pointer, result);
1387
+ return result;
1373
1388
  }
1374
- // Execute a gadget call asynchronously
1375
- async execute(call) {
1376
- const startTime = Date.now();
1377
- this.logger.debug("Executing gadget", {
1378
- gadgetName: call.gadgetName,
1379
- invocationId: call.invocationId,
1380
- parameters: call.parameters
1381
- });
1382
- const rawParameters = call.parameters ?? {};
1383
- let validatedParameters = rawParameters;
1384
- try {
1385
- const gadget = this.registry.get(call.gadgetName);
1386
- if (!gadget) {
1387
- this.logger.error("Gadget not found", { gadgetName: call.gadgetName });
1388
- return {
1389
- gadgetName: call.gadgetName,
1390
- invocationId: call.invocationId,
1391
- parameters: call.parameters ?? {},
1392
- error: `Gadget '${call.gadgetName}' not found in registry`,
1393
- executionTimeMs: Date.now() - startTime
1394
- };
1395
- }
1396
- if (call.parseError || !call.parameters) {
1397
- this.logger.error("Gadget parameter parse error", {
1398
- gadgetName: call.gadgetName,
1399
- parseError: call.parseError,
1400
- rawParameters: call.parametersRaw
1401
- });
1402
- return {
1403
- gadgetName: call.gadgetName,
1404
- invocationId: call.invocationId,
1405
- parameters: {},
1406
- error: call.parseError ?? "Failed to parse parameters",
1407
- executionTimeMs: Date.now() - startTime
1408
- };
1409
- }
1410
- if (gadget.parameterSchema) {
1411
- const validationResult = gadget.parameterSchema.safeParse(rawParameters);
1412
- if (!validationResult.success) {
1413
- const formattedIssues = validationResult.error.issues.map((issue) => {
1414
- const path = issue.path.join(".") || "root";
1415
- return `${path}: ${issue.message}`;
1416
- }).join("; ");
1417
- const validationError = `Invalid parameters: ${formattedIssues}`;
1418
- this.logger.error("Gadget parameter validation failed", {
1419
- gadgetName: call.gadgetName,
1420
- error: validationError
1421
- });
1422
- return {
1423
- gadgetName: call.gadgetName,
1424
- invocationId: call.invocationId,
1425
- parameters: rawParameters,
1426
- error: validationError,
1427
- executionTimeMs: Date.now() - startTime
1428
- };
1389
+ /**
1390
+ * Internal method to resolve type at path without caching.
1391
+ */
1392
+ resolveTypeAtPath(pointer) {
1393
+ if (!pointer) {
1394
+ return this.getBaseType(this.schema);
1395
+ }
1396
+ const segments = pointer.split("/");
1397
+ let current = this.schema;
1398
+ for (const segment of segments) {
1399
+ current = this.unwrapSchema(current);
1400
+ const typeName = getTypeName(current);
1401
+ if (typeName === "object" || typeName === "ZodObject") {
1402
+ const shape = getShape(current);
1403
+ if (!shape || !(segment in shape)) {
1404
+ return "unknown";
1429
1405
  }
1430
- validatedParameters = validationResult.data;
1431
- }
1432
- const timeoutMs = gadget.timeoutMs ?? this.defaultGadgetTimeoutMs;
1433
- let result;
1434
- if (timeoutMs && timeoutMs > 0) {
1435
- this.logger.debug("Executing gadget with timeout", {
1436
- gadgetName: call.gadgetName,
1437
- timeoutMs
1438
- });
1439
- result = await Promise.race([
1440
- Promise.resolve(gadget.execute(validatedParameters)),
1441
- this.createTimeoutPromise(call.gadgetName, timeoutMs)
1442
- ]);
1406
+ current = shape[segment];
1407
+ } else if (typeName === "array" || typeName === "ZodArray") {
1408
+ if (!/^\d+$/.test(segment)) {
1409
+ return "unknown";
1410
+ }
1411
+ const def = getDef(current);
1412
+ const elementType = def?.element ?? def?.type;
1413
+ if (!elementType) {
1414
+ return "unknown";
1415
+ }
1416
+ current = elementType;
1417
+ } else if (typeName === "tuple" || typeName === "ZodTuple") {
1418
+ if (!/^\d+$/.test(segment)) {
1419
+ return "unknown";
1420
+ }
1421
+ const index = parseInt(segment, 10);
1422
+ const def = getDef(current);
1423
+ const items = def?.items;
1424
+ if (!items || index >= items.length) {
1425
+ return "unknown";
1426
+ }
1427
+ current = items[index];
1428
+ } else if (typeName === "record" || typeName === "ZodRecord") {
1429
+ const def = getDef(current);
1430
+ const valueType = def?.valueType;
1431
+ if (!valueType) {
1432
+ return "unknown";
1433
+ }
1434
+ current = valueType;
1443
1435
  } else {
1444
- result = await Promise.resolve(gadget.execute(validatedParameters));
1436
+ return "unknown";
1445
1437
  }
1446
- const executionTimeMs = Date.now() - startTime;
1447
- this.logger.info("Gadget executed successfully", {
1448
- gadgetName: call.gadgetName,
1449
- invocationId: call.invocationId,
1450
- executionTimeMs
1451
- });
1452
- this.logger.debug("Gadget result", {
1453
- gadgetName: call.gadgetName,
1454
- invocationId: call.invocationId,
1455
- parameters: validatedParameters,
1456
- result,
1457
- executionTimeMs
1458
- });
1459
- return {
1460
- gadgetName: call.gadgetName,
1461
- invocationId: call.invocationId,
1462
- parameters: validatedParameters,
1463
- result,
1464
- executionTimeMs
1465
- };
1466
- } catch (error) {
1467
- if (error instanceof BreakLoopException) {
1468
- this.logger.info("Gadget requested loop termination", {
1469
- gadgetName: call.gadgetName,
1470
- message: error.message
1471
- });
1472
- return {
1473
- gadgetName: call.gadgetName,
1474
- invocationId: call.invocationId,
1475
- parameters: validatedParameters,
1476
- result: error.message,
1477
- breaksLoop: true,
1478
- executionTimeMs: Date.now() - startTime
1479
- };
1438
+ }
1439
+ return this.getBaseType(current);
1440
+ }
1441
+ /**
1442
+ * Unwrap schema modifiers (optional, default, nullable, branded, etc.)
1443
+ * to get to the underlying type.
1444
+ */
1445
+ unwrapSchema(schema) {
1446
+ let current = schema;
1447
+ let iterations = 0;
1448
+ const maxIterations = 20;
1449
+ while (iterations < maxIterations) {
1450
+ const typeName = getTypeName(current);
1451
+ const wrapperTypes = [
1452
+ "optional",
1453
+ "nullable",
1454
+ "default",
1455
+ "catch",
1456
+ "branded",
1457
+ "readonly",
1458
+ "pipeline",
1459
+ "ZodOptional",
1460
+ "ZodNullable",
1461
+ "ZodDefault",
1462
+ "ZodCatch",
1463
+ "ZodBranded",
1464
+ "ZodReadonly",
1465
+ "ZodPipeline"
1466
+ ];
1467
+ if (typeName && wrapperTypes.includes(typeName)) {
1468
+ const def = getDef(current);
1469
+ const inner = def?.innerType ?? def?.in ?? def?.type;
1470
+ if (!inner || inner === current) break;
1471
+ current = inner;
1472
+ iterations++;
1473
+ continue;
1480
1474
  }
1481
- if (error instanceof TimeoutException) {
1482
- this.logger.error("Gadget execution timed out", {
1483
- gadgetName: call.gadgetName,
1484
- timeoutMs: error.timeoutMs,
1485
- executionTimeMs: Date.now() - startTime
1486
- });
1487
- return {
1488
- gadgetName: call.gadgetName,
1489
- invocationId: call.invocationId,
1490
- parameters: validatedParameters,
1491
- error: error.message,
1492
- executionTimeMs: Date.now() - startTime
1493
- };
1475
+ break;
1476
+ }
1477
+ return current;
1478
+ }
1479
+ /**
1480
+ * Get the primitive type hint from an unwrapped schema.
1481
+ */
1482
+ getBaseType(schema) {
1483
+ const unwrapped = this.unwrapSchema(schema);
1484
+ const typeName = getTypeName(unwrapped);
1485
+ switch (typeName) {
1486
+ // Primitive types
1487
+ case "string":
1488
+ case "ZodString":
1489
+ return "string";
1490
+ case "number":
1491
+ case "ZodNumber":
1492
+ case "bigint":
1493
+ case "ZodBigInt":
1494
+ return "number";
1495
+ case "boolean":
1496
+ case "ZodBoolean":
1497
+ return "boolean";
1498
+ // Literal types - check the literal value type
1499
+ case "literal":
1500
+ case "ZodLiteral": {
1501
+ const def = getDef(unwrapped);
1502
+ const values = def?.values;
1503
+ const value = values?.[0] ?? def?.value;
1504
+ if (typeof value === "string") return "string";
1505
+ if (typeof value === "number" || typeof value === "bigint")
1506
+ return "number";
1507
+ if (typeof value === "boolean") return "boolean";
1508
+ return "unknown";
1494
1509
  }
1495
- if (error instanceof HumanInputException) {
1496
- this.logger.info("Gadget requested human input", {
1497
- gadgetName: call.gadgetName,
1498
- question: error.question
1499
- });
1500
- if (this.onHumanInputRequired) {
1501
- try {
1502
- const answer = await this.onHumanInputRequired(error.question);
1503
- this.logger.debug("Human input received", {
1504
- gadgetName: call.gadgetName,
1505
- answerLength: answer.length
1506
- });
1507
- return {
1508
- gadgetName: call.gadgetName,
1509
- invocationId: call.invocationId,
1510
- parameters: validatedParameters,
1511
- result: answer,
1512
- executionTimeMs: Date.now() - startTime
1513
- };
1514
- } catch (inputError) {
1515
- this.logger.error("Human input callback error", {
1516
- gadgetName: call.gadgetName,
1517
- error: inputError instanceof Error ? inputError.message : String(inputError)
1518
- });
1519
- return {
1520
- gadgetName: call.gadgetName,
1521
- invocationId: call.invocationId,
1522
- parameters: validatedParameters,
1523
- error: inputError instanceof Error ? inputError.message : String(inputError),
1524
- executionTimeMs: Date.now() - startTime
1525
- };
1526
- }
1527
- }
1528
- this.logger.warn("Human input required but no callback provided", {
1529
- gadgetName: call.gadgetName
1530
- });
1531
- return {
1532
- gadgetName: call.gadgetName,
1533
- invocationId: call.invocationId,
1534
- parameters: validatedParameters,
1535
- error: "Human input required but not available (stdin is not interactive)",
1536
- executionTimeMs: Date.now() - startTime
1537
- };
1510
+ // Enum - always string keys
1511
+ case "enum":
1512
+ case "ZodEnum":
1513
+ case "nativeEnum":
1514
+ case "ZodNativeEnum":
1515
+ return "string";
1516
+ // Union - return 'unknown' to let auto-coercion decide
1517
+ // Since multiple types are valid, we can't definitively say what the LLM intended
1518
+ // Auto-coercion will handle common cases (numbers, booleans) appropriately
1519
+ case "union":
1520
+ case "ZodUnion":
1521
+ return "unknown";
1522
+ // Discriminated union - complex, return unknown
1523
+ case "discriminatedUnion":
1524
+ case "ZodDiscriminatedUnion":
1525
+ return "unknown";
1526
+ // Intersection - check both sides
1527
+ case "intersection":
1528
+ case "ZodIntersection": {
1529
+ const def = getDef(unwrapped);
1530
+ const left = def?.left;
1531
+ const right = def?.right;
1532
+ if (!left || !right) return "unknown";
1533
+ const leftType = this.getBaseType(left);
1534
+ const rightType = this.getBaseType(right);
1535
+ if (leftType === rightType) return leftType;
1536
+ if (leftType === "string" || rightType === "string") return "string";
1537
+ return "unknown";
1538
1538
  }
1539
- const executionTimeMs = Date.now() - startTime;
1540
- this.logger.error("Gadget execution failed", {
1541
- gadgetName: call.gadgetName,
1542
- error: error instanceof Error ? error.message : String(error),
1543
- executionTimeMs
1544
- });
1545
- return {
1546
- gadgetName: call.gadgetName,
1547
- invocationId: call.invocationId,
1548
- parameters: validatedParameters,
1549
- error: error instanceof Error ? error.message : String(error),
1550
- executionTimeMs
1551
- };
1539
+ // Effects/transforms - return unknown to let Zod handle it
1540
+ case "effects":
1541
+ case "ZodEffects":
1542
+ return "unknown";
1543
+ // Lazy - can't resolve without evaluating
1544
+ case "lazy":
1545
+ case "ZodLazy":
1546
+ return "unknown";
1547
+ // Complex types - return unknown
1548
+ case "object":
1549
+ case "ZodObject":
1550
+ case "array":
1551
+ case "ZodArray":
1552
+ case "tuple":
1553
+ case "ZodTuple":
1554
+ case "record":
1555
+ case "ZodRecord":
1556
+ case "map":
1557
+ case "ZodMap":
1558
+ case "set":
1559
+ case "ZodSet":
1560
+ case "function":
1561
+ case "ZodFunction":
1562
+ case "promise":
1563
+ case "ZodPromise":
1564
+ case "date":
1565
+ case "ZodDate":
1566
+ return "unknown";
1567
+ // Unknown/any/never/void/undefined/null
1568
+ case "unknown":
1569
+ case "ZodUnknown":
1570
+ case "any":
1571
+ case "ZodAny":
1572
+ case "never":
1573
+ case "ZodNever":
1574
+ case "void":
1575
+ case "ZodVoid":
1576
+ case "undefined":
1577
+ case "ZodUndefined":
1578
+ case "null":
1579
+ case "ZodNull":
1580
+ return "unknown";
1581
+ default:
1582
+ return "unknown";
1552
1583
  }
1553
1584
  }
1554
- // Execute multiple gadget calls in parallel
1555
- async executeAll(calls) {
1556
- return Promise.all(calls.map((call) => this.execute(call)));
1557
- }
1558
1585
  };
1559
1586
  }
1560
1587
  });
@@ -1564,6 +1591,7 @@ function parseBlockParams(content, options) {
1564
1591
  const argPrefix = options?.argPrefix ?? GADGET_ARG_PREFIX;
1565
1592
  const result = {};
1566
1593
  const seenPointers = /* @__PURE__ */ new Set();
1594
+ const introspector = options?.schema ? new SchemaIntrospector(options.schema) : void 0;
1567
1595
  const parts = content.split(argPrefix);
1568
1596
  for (let i = 1; i < parts.length; i++) {
1569
1597
  const part = parts[i];
@@ -1575,7 +1603,7 @@ function parseBlockParams(content, options) {
1575
1603
  throw new Error(`Duplicate pointer: ${pointer2}`);
1576
1604
  }
1577
1605
  seenPointers.add(pointer2);
1578
- setByPointer(result, pointer2, "");
1606
+ setByPointer(result, pointer2, "", introspector);
1579
1607
  }
1580
1608
  continue;
1581
1609
  }
@@ -1591,15 +1619,30 @@ function parseBlockParams(content, options) {
1591
1619
  throw new Error(`Duplicate pointer: ${pointer}`);
1592
1620
  }
1593
1621
  seenPointers.add(pointer);
1594
- setByPointer(result, pointer, value);
1622
+ setByPointer(result, pointer, value, introspector);
1595
1623
  }
1596
1624
  return result;
1597
1625
  }
1598
- function coerceValue(value) {
1626
+ function coerceValue(value, expectedType) {
1599
1627
  if (value.includes("\n")) {
1600
1628
  return value;
1601
1629
  }
1602
1630
  const trimmed = value.trim();
1631
+ if (expectedType === "string") {
1632
+ return value;
1633
+ }
1634
+ if (expectedType === "boolean") {
1635
+ if (trimmed === "true") return true;
1636
+ if (trimmed === "false") return false;
1637
+ return value;
1638
+ }
1639
+ if (expectedType === "number") {
1640
+ const num = Number(trimmed);
1641
+ if (!isNaN(num) && isFinite(num) && trimmed !== "") {
1642
+ return num;
1643
+ }
1644
+ return value;
1645
+ }
1603
1646
  if (trimmed === "true") return true;
1604
1647
  if (trimmed === "false") return false;
1605
1648
  if (trimmed !== "" && /^-?\d+(\.\d+)?$/.test(trimmed)) {
@@ -1610,7 +1653,7 @@ function coerceValue(value) {
1610
1653
  }
1611
1654
  return value;
1612
1655
  }
1613
- function setByPointer(obj, pointer, value) {
1656
+ function setByPointer(obj, pointer, value, introspector) {
1614
1657
  const segments = pointer.split("/");
1615
1658
  let current = obj;
1616
1659
  for (let i = 0; i < segments.length - 1; i++) {
@@ -1638,7 +1681,8 @@ function setByPointer(obj, pointer, value) {
1638
1681
  }
1639
1682
  }
1640
1683
  const lastSegment = segments[segments.length - 1];
1641
- const coercedValue = coerceValue(value);
1684
+ const expectedType = introspector?.getTypeAtPath(pointer);
1685
+ const coercedValue = coerceValue(value, expectedType);
1642
1686
  if (Array.isArray(current)) {
1643
1687
  const index = parseInt(lastSegment, 10);
1644
1688
  if (isNaN(index) || index < 0) {
@@ -1656,6 +1700,7 @@ var init_block_params = __esm({
1656
1700
  "src/gadgets/block-params.ts"() {
1657
1701
  "use strict";
1658
1702
  init_constants();
1703
+ init_schema_introspector();
1659
1704
  }
1660
1705
  });
1661
1706
 
@@ -1706,17 +1751,12 @@ var init_parser = __esm({
1706
1751
  return { actualName: gadgetName, invocationId: `gadget_${++globalInvocationCounter}` };
1707
1752
  }
1708
1753
  /**
1709
- * Truncate verbose parse errors to avoid context overflow.
1710
- * Keeps first meaningful line and limits total length.
1754
+ * Extract the error message from a parse error.
1755
+ * Preserves full message since the error formatter adds contextual help
1756
+ * that benefits from precise, detailed error information.
1711
1757
  */
1712
- truncateParseError(error, format) {
1713
- const message = error instanceof Error ? error.message : String(error);
1714
- const firstLine = message.split("\n")[0];
1715
- const maxLen = 200;
1716
- if (firstLine.length <= maxLen) {
1717
- return firstLine;
1718
- }
1719
- return `${firstLine.slice(0, maxLen)}... (${message.length} chars total)`;
1758
+ extractParseError(error) {
1759
+ return error instanceof Error ? error.message : String(error);
1720
1760
  }
1721
1761
  /**
1722
1762
  * Parse parameter string using block format
@@ -1726,7 +1766,7 @@ var init_parser = __esm({
1726
1766
  try {
1727
1767
  return { parameters: parseBlockParams(cleaned, { argPrefix: this.argPrefix }) };
1728
1768
  } catch (error) {
1729
- return { parseError: this.truncateParseError(error, "block") };
1769
+ return { parseError: this.extractParseError(error) };
1730
1770
  }
1731
1771
  }
1732
1772
  // Feed a chunk of text and get parsed events
@@ -1841,6 +1881,366 @@ var init_parser = __esm({
1841
1881
  }
1842
1882
  });
1843
1883
 
1884
+ // src/gadgets/error-formatter.ts
1885
+ var GadgetErrorFormatter;
1886
+ var init_error_formatter = __esm({
1887
+ "src/gadgets/error-formatter.ts"() {
1888
+ "use strict";
1889
+ init_constants();
1890
+ GadgetErrorFormatter = class {
1891
+ argPrefix;
1892
+ startPrefix;
1893
+ endPrefix;
1894
+ constructor(options = {}) {
1895
+ this.argPrefix = options.argPrefix ?? GADGET_ARG_PREFIX;
1896
+ this.startPrefix = options.startPrefix ?? GADGET_START_PREFIX;
1897
+ this.endPrefix = options.endPrefix ?? GADGET_END_PREFIX;
1898
+ }
1899
+ /**
1900
+ * Format a Zod validation error with full gadget instructions.
1901
+ *
1902
+ * @param gadgetName - Name of the gadget that was called
1903
+ * @param zodError - The Zod validation error
1904
+ * @param gadget - The gadget instance (for generating instructions)
1905
+ * @returns Formatted error message with usage instructions
1906
+ */
1907
+ formatValidationError(gadgetName, zodError, gadget) {
1908
+ const parts = [];
1909
+ parts.push(`Error: Invalid parameters for '${gadgetName}':`);
1910
+ for (const issue of zodError.issues) {
1911
+ const path = issue.path.join(".") || "root";
1912
+ parts.push(` - ${path}: ${issue.message}`);
1913
+ }
1914
+ parts.push("");
1915
+ parts.push("Gadget Usage:");
1916
+ parts.push(gadget.getInstruction(this.argPrefix));
1917
+ return parts.join("\n");
1918
+ }
1919
+ /**
1920
+ * Format a parse error with block format reference.
1921
+ *
1922
+ * @param gadgetName - Name of the gadget that was called
1923
+ * @param parseError - The parse error message
1924
+ * @param gadget - The gadget instance if found (for generating instructions)
1925
+ * @returns Formatted error message with format reference
1926
+ */
1927
+ formatParseError(gadgetName, parseError, gadget) {
1928
+ const parts = [];
1929
+ parts.push(`Error: Failed to parse parameters for '${gadgetName}':`);
1930
+ parts.push(` ${parseError}`);
1931
+ if (gadget) {
1932
+ parts.push("");
1933
+ parts.push("Gadget Usage:");
1934
+ parts.push(gadget.getInstruction(this.argPrefix));
1935
+ }
1936
+ parts.push("");
1937
+ parts.push("Block Format Reference:");
1938
+ parts.push(` ${this.startPrefix}${gadgetName}`);
1939
+ parts.push(` ${this.argPrefix}parameterName`);
1940
+ parts.push(" parameter value here");
1941
+ parts.push(` ${this.endPrefix}`);
1942
+ return parts.join("\n");
1943
+ }
1944
+ /**
1945
+ * Format a registry error (gadget not found) with available gadgets list.
1946
+ *
1947
+ * @param gadgetName - Name of the gadget that was not found
1948
+ * @param availableGadgets - List of available gadget names
1949
+ * @returns Formatted error message with available gadgets
1950
+ */
1951
+ formatRegistryError(gadgetName, availableGadgets) {
1952
+ const parts = [];
1953
+ parts.push(`Error: Gadget '${gadgetName}' not found.`);
1954
+ if (availableGadgets.length > 0) {
1955
+ parts.push("");
1956
+ parts.push(`Available gadgets: ${availableGadgets.join(", ")}`);
1957
+ } else {
1958
+ parts.push("");
1959
+ parts.push("No gadgets are currently registered.");
1960
+ }
1961
+ return parts.join("\n");
1962
+ }
1963
+ };
1964
+ }
1965
+ });
1966
+
1967
+ // src/gadgets/executor.ts
1968
+ var GadgetExecutor;
1969
+ var init_executor = __esm({
1970
+ "src/gadgets/executor.ts"() {
1971
+ "use strict";
1972
+ init_constants();
1973
+ init_logger();
1974
+ init_block_params();
1975
+ init_error_formatter();
1976
+ init_exceptions();
1977
+ init_parser();
1978
+ GadgetExecutor = class {
1979
+ constructor(registry, onHumanInputRequired, logger, defaultGadgetTimeoutMs, errorFormatterOptions) {
1980
+ this.registry = registry;
1981
+ this.onHumanInputRequired = onHumanInputRequired;
1982
+ this.defaultGadgetTimeoutMs = defaultGadgetTimeoutMs;
1983
+ this.logger = logger ?? createLogger({ name: "llmist:executor" });
1984
+ this.errorFormatter = new GadgetErrorFormatter(errorFormatterOptions);
1985
+ this.argPrefix = errorFormatterOptions?.argPrefix ?? GADGET_ARG_PREFIX;
1986
+ }
1987
+ logger;
1988
+ errorFormatter;
1989
+ argPrefix;
1990
+ /**
1991
+ * Creates a promise that rejects with a TimeoutException after the specified timeout.
1992
+ */
1993
+ createTimeoutPromise(gadgetName, timeoutMs) {
1994
+ return new Promise((_, reject) => {
1995
+ setTimeout(() => {
1996
+ reject(new TimeoutException(gadgetName, timeoutMs));
1997
+ }, timeoutMs);
1998
+ });
1999
+ }
2000
+ // Execute a gadget call asynchronously
2001
+ async execute(call) {
2002
+ const startTime = Date.now();
2003
+ this.logger.debug("Executing gadget", {
2004
+ gadgetName: call.gadgetName,
2005
+ invocationId: call.invocationId,
2006
+ parameters: call.parameters
2007
+ });
2008
+ const rawParameters = call.parameters ?? {};
2009
+ let validatedParameters = rawParameters;
2010
+ try {
2011
+ const gadget = this.registry.get(call.gadgetName);
2012
+ if (!gadget) {
2013
+ this.logger.error("Gadget not found", { gadgetName: call.gadgetName });
2014
+ const availableGadgets = this.registry.getNames();
2015
+ return {
2016
+ gadgetName: call.gadgetName,
2017
+ invocationId: call.invocationId,
2018
+ parameters: call.parameters ?? {},
2019
+ error: this.errorFormatter.formatRegistryError(call.gadgetName, availableGadgets),
2020
+ executionTimeMs: Date.now() - startTime
2021
+ };
2022
+ }
2023
+ if (call.parseError || !call.parameters) {
2024
+ this.logger.error("Gadget parameter parse error", {
2025
+ gadgetName: call.gadgetName,
2026
+ parseError: call.parseError,
2027
+ rawParameters: call.parametersRaw
2028
+ });
2029
+ const parseErrorMessage = call.parseError ?? "Failed to parse parameters";
2030
+ return {
2031
+ gadgetName: call.gadgetName,
2032
+ invocationId: call.invocationId,
2033
+ parameters: {},
2034
+ error: this.errorFormatter.formatParseError(call.gadgetName, parseErrorMessage, gadget),
2035
+ executionTimeMs: Date.now() - startTime
2036
+ };
2037
+ }
2038
+ let schemaAwareParameters = rawParameters;
2039
+ const hasBlockFormat = call.parametersRaw?.includes(this.argPrefix);
2040
+ if (gadget.parameterSchema && hasBlockFormat) {
2041
+ try {
2042
+ const cleanedRaw = stripMarkdownFences(call.parametersRaw);
2043
+ const initialParse = parseBlockParams(cleanedRaw, { argPrefix: this.argPrefix });
2044
+ const parametersWereModified = !this.deepEquals(rawParameters, initialParse);
2045
+ if (parametersWereModified) {
2046
+ this.logger.debug("Parameters modified by interceptor, skipping re-parse", {
2047
+ gadgetName: call.gadgetName
2048
+ });
2049
+ schemaAwareParameters = rawParameters;
2050
+ } else {
2051
+ schemaAwareParameters = parseBlockParams(cleanedRaw, {
2052
+ argPrefix: this.argPrefix,
2053
+ schema: gadget.parameterSchema
2054
+ });
2055
+ this.logger.debug("Re-parsed parameters with schema", {
2056
+ gadgetName: call.gadgetName,
2057
+ original: rawParameters,
2058
+ schemaAware: schemaAwareParameters
2059
+ });
2060
+ }
2061
+ } catch (error) {
2062
+ this.logger.warn("Schema-aware re-parsing failed, using original parameters", {
2063
+ gadgetName: call.gadgetName,
2064
+ error: error instanceof Error ? error.message : String(error)
2065
+ });
2066
+ schemaAwareParameters = rawParameters;
2067
+ }
2068
+ }
2069
+ if (gadget.parameterSchema) {
2070
+ const validationResult = gadget.parameterSchema.safeParse(schemaAwareParameters);
2071
+ if (!validationResult.success) {
2072
+ const validationError = this.errorFormatter.formatValidationError(
2073
+ call.gadgetName,
2074
+ validationResult.error,
2075
+ gadget
2076
+ );
2077
+ this.logger.error("Gadget parameter validation failed", {
2078
+ gadgetName: call.gadgetName,
2079
+ issueCount: validationResult.error.issues.length
2080
+ });
2081
+ return {
2082
+ gadgetName: call.gadgetName,
2083
+ invocationId: call.invocationId,
2084
+ parameters: schemaAwareParameters,
2085
+ error: validationError,
2086
+ executionTimeMs: Date.now() - startTime
2087
+ };
2088
+ }
2089
+ validatedParameters = validationResult.data;
2090
+ } else {
2091
+ validatedParameters = schemaAwareParameters;
2092
+ }
2093
+ const timeoutMs = gadget.timeoutMs ?? this.defaultGadgetTimeoutMs;
2094
+ let result;
2095
+ if (timeoutMs && timeoutMs > 0) {
2096
+ this.logger.debug("Executing gadget with timeout", {
2097
+ gadgetName: call.gadgetName,
2098
+ timeoutMs
2099
+ });
2100
+ result = await Promise.race([
2101
+ Promise.resolve(gadget.execute(validatedParameters)),
2102
+ this.createTimeoutPromise(call.gadgetName, timeoutMs)
2103
+ ]);
2104
+ } else {
2105
+ result = await Promise.resolve(gadget.execute(validatedParameters));
2106
+ }
2107
+ const executionTimeMs = Date.now() - startTime;
2108
+ this.logger.info("Gadget executed successfully", {
2109
+ gadgetName: call.gadgetName,
2110
+ invocationId: call.invocationId,
2111
+ executionTimeMs
2112
+ });
2113
+ this.logger.debug("Gadget result", {
2114
+ gadgetName: call.gadgetName,
2115
+ invocationId: call.invocationId,
2116
+ parameters: validatedParameters,
2117
+ result,
2118
+ executionTimeMs
2119
+ });
2120
+ return {
2121
+ gadgetName: call.gadgetName,
2122
+ invocationId: call.invocationId,
2123
+ parameters: validatedParameters,
2124
+ result,
2125
+ executionTimeMs
2126
+ };
2127
+ } catch (error) {
2128
+ if (error instanceof BreakLoopException) {
2129
+ this.logger.info("Gadget requested loop termination", {
2130
+ gadgetName: call.gadgetName,
2131
+ message: error.message
2132
+ });
2133
+ return {
2134
+ gadgetName: call.gadgetName,
2135
+ invocationId: call.invocationId,
2136
+ parameters: validatedParameters,
2137
+ result: error.message,
2138
+ breaksLoop: true,
2139
+ executionTimeMs: Date.now() - startTime
2140
+ };
2141
+ }
2142
+ if (error instanceof TimeoutException) {
2143
+ this.logger.error("Gadget execution timed out", {
2144
+ gadgetName: call.gadgetName,
2145
+ timeoutMs: error.timeoutMs,
2146
+ executionTimeMs: Date.now() - startTime
2147
+ });
2148
+ return {
2149
+ gadgetName: call.gadgetName,
2150
+ invocationId: call.invocationId,
2151
+ parameters: validatedParameters,
2152
+ error: error.message,
2153
+ executionTimeMs: Date.now() - startTime
2154
+ };
2155
+ }
2156
+ if (error instanceof HumanInputException) {
2157
+ this.logger.info("Gadget requested human input", {
2158
+ gadgetName: call.gadgetName,
2159
+ question: error.question
2160
+ });
2161
+ if (this.onHumanInputRequired) {
2162
+ try {
2163
+ const answer = await this.onHumanInputRequired(error.question);
2164
+ this.logger.debug("Human input received", {
2165
+ gadgetName: call.gadgetName,
2166
+ answerLength: answer.length
2167
+ });
2168
+ return {
2169
+ gadgetName: call.gadgetName,
2170
+ invocationId: call.invocationId,
2171
+ parameters: validatedParameters,
2172
+ result: answer,
2173
+ executionTimeMs: Date.now() - startTime
2174
+ };
2175
+ } catch (inputError) {
2176
+ this.logger.error("Human input callback error", {
2177
+ gadgetName: call.gadgetName,
2178
+ error: inputError instanceof Error ? inputError.message : String(inputError)
2179
+ });
2180
+ return {
2181
+ gadgetName: call.gadgetName,
2182
+ invocationId: call.invocationId,
2183
+ parameters: validatedParameters,
2184
+ error: inputError instanceof Error ? inputError.message : String(inputError),
2185
+ executionTimeMs: Date.now() - startTime
2186
+ };
2187
+ }
2188
+ }
2189
+ this.logger.warn("Human input required but no callback provided", {
2190
+ gadgetName: call.gadgetName
2191
+ });
2192
+ return {
2193
+ gadgetName: call.gadgetName,
2194
+ invocationId: call.invocationId,
2195
+ parameters: validatedParameters,
2196
+ error: "Human input required but not available (stdin is not interactive)",
2197
+ executionTimeMs: Date.now() - startTime
2198
+ };
2199
+ }
2200
+ const executionTimeMs = Date.now() - startTime;
2201
+ this.logger.error("Gadget execution failed", {
2202
+ gadgetName: call.gadgetName,
2203
+ error: error instanceof Error ? error.message : String(error),
2204
+ executionTimeMs
2205
+ });
2206
+ return {
2207
+ gadgetName: call.gadgetName,
2208
+ invocationId: call.invocationId,
2209
+ parameters: validatedParameters,
2210
+ error: error instanceof Error ? error.message : String(error),
2211
+ executionTimeMs
2212
+ };
2213
+ }
2214
+ }
2215
+ // Execute multiple gadget calls in parallel
2216
+ async executeAll(calls) {
2217
+ return Promise.all(calls.map((call) => this.execute(call)));
2218
+ }
2219
+ /**
2220
+ * Deep equality check for objects/arrays.
2221
+ * Used to detect if parameters were modified by an interceptor.
2222
+ */
2223
+ deepEquals(a, b) {
2224
+ if (a === b) return true;
2225
+ if (a === null || b === null) return a === b;
2226
+ if (typeof a !== typeof b) return false;
2227
+ if (typeof a !== "object") return a === b;
2228
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
2229
+ if (Array.isArray(a) && Array.isArray(b)) {
2230
+ if (a.length !== b.length) return false;
2231
+ return a.every((val, i) => this.deepEquals(val, b[i]));
2232
+ }
2233
+ const aObj = a;
2234
+ const bObj = b;
2235
+ const aKeys = Object.keys(aObj);
2236
+ const bKeys = Object.keys(bObj);
2237
+ if (aKeys.length !== bKeys.length) return false;
2238
+ return aKeys.every((key) => this.deepEquals(aObj[key], bObj[key]));
2239
+ }
2240
+ };
2241
+ }
2242
+ });
2243
+
1844
2244
  // src/agent/hook-validators.ts
1845
2245
  function validateBeforeLLMCallAction(action) {
1846
2246
  if (!action || typeof action !== "object" || !("action" in action)) {
@@ -2032,7 +2432,8 @@ var init_stream_processor = __esm({
2032
2432
  options.registry,
2033
2433
  options.onHumanInputRequired,
2034
2434
  this.logger.getSubLogger({ name: "executor" }),
2035
- options.defaultGadgetTimeoutMs
2435
+ options.defaultGadgetTimeoutMs,
2436
+ { argPrefix: options.gadgetArgPrefix }
2036
2437
  );
2037
2438
  }
2038
2439
  /**
@@ -5498,6 +5899,8 @@ export {
5498
5899
  getProvider,
5499
5900
  getModelId,
5500
5901
  init_model_shortcuts,
5902
+ validateGadgetSchema,
5903
+ init_schema_validator,
5501
5904
  GadgetRegistry,
5502
5905
  init_registry,
5503
5906
  DEFAULT_PROMPTS,
@@ -5509,6 +5912,8 @@ export {
5509
5912
  createLogger,
5510
5913
  defaultLogger,
5511
5914
  init_logger,
5915
+ schemaToJSONSchema,
5916
+ init_schema_to_json,
5512
5917
  BaseGadget,
5513
5918
  init_gadget,
5514
5919
  createGadget,
@@ -5526,10 +5931,10 @@ export {
5526
5931
  BreakLoopException,
5527
5932
  HumanInputException,
5528
5933
  init_exceptions,
5529
- GadgetExecutor,
5530
- init_executor,
5531
5934
  StreamParser,
5532
5935
  init_parser,
5936
+ GadgetExecutor,
5937
+ init_executor,
5533
5938
  StreamProcessor,
5534
5939
  init_stream_processor,
5535
5940
  FALLBACK_CHARS_PER_TOKEN,
@@ -5557,4 +5962,4 @@ export {
5557
5962
  AgentBuilder,
5558
5963
  init_builder
5559
5964
  };
5560
- //# sourceMappingURL=chunk-T24KLXY4.js.map
5965
+ //# sourceMappingURL=chunk-KORMY3CD.js.map