@runtypelabs/cli 2.32.5 → 2.33.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 (2) hide show
  1. package/dist/index.js +173 -128
  2. package/package.json +9 -9
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  var __defProp = Object.defineProperty;
3
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
4
  var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
5
- get: (a, b2) => (typeof require !== "undefined" ? require : a)[b2]
5
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
6
  }) : x2)(function(x2) {
7
7
  if (typeof require !== "undefined") return require.apply(this, arguments);
8
8
  throw Error('Dynamic require of "' + x2 + '" is not supported');
@@ -1866,20 +1866,20 @@ function safeExtend(schema, shape) {
1866
1866
  });
1867
1867
  return clone(schema, def);
1868
1868
  }
1869
- function merge(a, b2) {
1869
+ function merge(a, b) {
1870
1870
  if (a._zod.def.checks?.length) {
1871
1871
  throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
1872
1872
  }
1873
1873
  const def = mergeDefs(a._zod.def, {
1874
1874
  get shape() {
1875
- const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape };
1875
+ const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
1876
1876
  assignProp(this, "shape", _shape);
1877
1877
  return _shape;
1878
1878
  },
1879
1879
  get catchall() {
1880
- return b2._zod.def.catchall;
1880
+ return b._zod.def.catchall;
1881
1881
  },
1882
- checks: b2._zod.def.checks ?? []
1882
+ checks: b._zod.def.checks ?? []
1883
1883
  });
1884
1884
  return clone(a, def);
1885
1885
  }
@@ -2082,7 +2082,7 @@ function hexToUint8Array(hex3) {
2082
2082
  return bytes;
2083
2083
  }
2084
2084
  function uint8ArrayToHex(bytes) {
2085
- return Array.from(bytes).map((b2) => b2.toString(16).padStart(2, "0")).join("");
2085
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
2086
2086
  }
2087
2087
  var Class = class {
2088
2088
  constructor(..._args) {
@@ -2219,7 +2219,7 @@ function toDotPath(_path) {
2219
2219
  }
2220
2220
  function prettifyError(error51) {
2221
2221
  const lines = [];
2222
- const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length);
2222
+ const issues = [...error51.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
2223
2223
  for (const issue2 of issues) {
2224
2224
  lines.push(`\u2716 ${issue2.message}`);
2225
2225
  if (issue2.path?.length)
@@ -4194,19 +4194,19 @@ var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, d
4194
4194
  return handleIntersectionResults(payload, left, right);
4195
4195
  };
4196
4196
  });
4197
- function mergeValues(a, b2) {
4198
- if (a === b2) {
4197
+ function mergeValues(a, b) {
4198
+ if (a === b) {
4199
4199
  return { valid: true, data: a };
4200
4200
  }
4201
- if (a instanceof Date && b2 instanceof Date && +a === +b2) {
4201
+ if (a instanceof Date && b instanceof Date && +a === +b) {
4202
4202
  return { valid: true, data: a };
4203
4203
  }
4204
- if (isPlainObject(a) && isPlainObject(b2)) {
4205
- const bKeys = Object.keys(b2);
4204
+ if (isPlainObject(a) && isPlainObject(b)) {
4205
+ const bKeys = Object.keys(b);
4206
4206
  const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
4207
- const newObj = { ...a, ...b2 };
4207
+ const newObj = { ...a, ...b };
4208
4208
  for (const key of sharedKeys) {
4209
- const sharedValue = mergeValues(a[key], b2[key]);
4209
+ const sharedValue = mergeValues(a[key], b[key]);
4210
4210
  if (!sharedValue.valid) {
4211
4211
  return {
4212
4212
  valid: false,
@@ -4217,14 +4217,14 @@ function mergeValues(a, b2) {
4217
4217
  }
4218
4218
  return { valid: true, data: newObj };
4219
4219
  }
4220
- if (Array.isArray(a) && Array.isArray(b2)) {
4221
- if (a.length !== b2.length) {
4220
+ if (Array.isArray(a) && Array.isArray(b)) {
4221
+ if (a.length !== b.length) {
4222
4222
  return { valid: false, mergeErrorPath: [] };
4223
4223
  }
4224
4224
  const newArray = [];
4225
4225
  for (let index = 0; index < a.length; index++) {
4226
4226
  const itemA = a[index];
4227
- const itemB = b2[index];
4227
+ const itemB = b[index];
4228
4228
  const sharedValue = mergeValues(itemA, itemB);
4229
4229
  if (!sharedValue.valid) {
4230
4230
  return {
@@ -12863,14 +12863,14 @@ var intersectionProcessor = (schema, ctx, json2, params) => {
12863
12863
  ...params,
12864
12864
  path: [...params.path, "allOf", 0]
12865
12865
  });
12866
- const b2 = process2(def.right, ctx, {
12866
+ const b = process2(def.right, ctx, {
12867
12867
  ...params,
12868
12868
  path: [...params.path, "allOf", 1]
12869
12869
  });
12870
12870
  const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
12871
12871
  const allOf = [
12872
12872
  ...isSimpleIntersection(a) ? a.allOf : [a],
12873
- ...isSimpleIntersection(b2) ? b2.allOf : [b2]
12873
+ ...isSimpleIntersection(b) ? b.allOf : [b]
12874
12874
  ];
12875
12875
  json2.allOf = allOf;
12876
12876
  };
@@ -21096,28 +21096,28 @@ function formatPath(path20) {
21096
21096
  return acc ? `${acc}.${key}` : key;
21097
21097
  }, "");
21098
21098
  }
21099
- function compareIssuePath(a, b2) {
21100
- if (!a && !b2) return 0;
21099
+ function compareIssuePath(a, b) {
21100
+ if (!a && !b) return 0;
21101
21101
  if (!a) return 1;
21102
- if (!b2) return -1;
21103
- return a.localeCompare(b2);
21102
+ if (!b) return -1;
21103
+ return a.localeCompare(b);
21104
21104
  }
21105
21105
  function sortIssues(issues) {
21106
- return [...issues].sort((a, b2) => {
21106
+ return [...issues].sort((a, b) => {
21107
21107
  const aStepIndex = a.step?.index ?? Number.MAX_SAFE_INTEGER;
21108
- const bStepIndex = b2.step?.index ?? Number.MAX_SAFE_INTEGER;
21108
+ const bStepIndex = b.step?.index ?? Number.MAX_SAFE_INTEGER;
21109
21109
  if (aStepIndex !== bStepIndex) {
21110
21110
  return aStepIndex - bStepIndex;
21111
21111
  }
21112
- const pathCompare = compareIssuePath(a.path, b2.path);
21112
+ const pathCompare = compareIssuePath(a.path, b.path);
21113
21113
  if (pathCompare !== 0) {
21114
21114
  return pathCompare;
21115
21115
  }
21116
- const codeCompare = a.code.localeCompare(b2.code);
21116
+ const codeCompare = a.code.localeCompare(b.code);
21117
21117
  if (codeCompare !== 0) {
21118
21118
  return codeCompare;
21119
21119
  }
21120
- return a.message.localeCompare(b2.message);
21120
+ return a.message.localeCompare(b.message);
21121
21121
  });
21122
21122
  }
21123
21123
  function addIssue(level, issue2, buckets) {
@@ -22749,15 +22749,16 @@ var runtimeArtifactManifestSchema = external_exports.object({
22749
22749
  var KNOWN_FLOW_STEP_TYPES = new Set(FLOW_STEP_TYPES);
22750
22750
  var API_INPROCESS_CAPABILITY_MATRIX = {
22751
22751
  target: "api-inprocess",
22752
- // Bumped 2026-07-31: adds the §A1 `unmaterializedPromptToolRefs` fold (prompt
22753
- // `toolIds` classes with no runtime lane). Carries forward 2026-07-30: the
22754
- // IMPLICIT platform-default fallback candidate no longer folds (see
22755
- // `implicitPlatformFallback` below). Carries forward
22752
+ // Bumped 2026-08-03: adds the §A1 `promptCodeModeTools` fold (a prompt step's
22753
+ // `config.tools.codeModeConfig` has no runtime flow-lane port). Carries
22754
+ // forward 2026-07-31: the `unmaterializedPromptToolRefs` fold. Carries
22755
+ // forward 2026-07-30: the IMPLICIT platform-default fallback candidate no
22756
+ // longer folds (see `implicitPlatformFallback` below). Carries forward
22756
22757
  // 2026-07-29.4: api-hosted runtime fulfills managed fetch methods through
22757
22758
  // ManagedFetchExecutor (the managed-fetch fact remains for attribution). The
22758
22759
  // EXPLICIT Layer-2 fallback fold and the remaining parity-audit folds are
22759
22760
  // unchanged.
22760
- version: "2026-07-31.1",
22761
+ version: "2026-08-03.1",
22761
22762
  unsupportedStepTypes: ["wait-until", "crawl"],
22762
22763
  unsupportedFeatures: {
22763
22764
  approvalSteps: true,
@@ -22788,6 +22789,15 @@ var API_INPROCESS_CAPABILITY_MATRIX = {
22788
22789
  unsupportedTransformExecution: true,
22789
22790
  promptMcpServers: true,
22790
22791
  promptArtifacts: true,
22792
+ // §A1 parity-audit BRIDGE fold (2026-08-03): a PROMPT step's
22793
+ // `config.tools.codeModeConfig` with a non-empty `toolPool`. The
22794
+ // `transformDataCodeModeTools` fold above covers only a TRANSFORM-DATA
22795
+ // step's `config.tools` bag; a prompt step's code_mode synthesizer (the
22796
+ // legacy `buildSynthesizedCodeModeTool`) has no runtime flow-lane port, so
22797
+ // an unfolded prompt would run on the runtime lane with its code_mode tool
22798
+ // pool silently absent. Routes to legacy until the prompt-step code_mode
22799
+ // synthesizer is ported.
22800
+ promptCodeModeTools: true,
22791
22801
  // SUPPORTED as of the fallback-chain port: the runtime flow engine now
22792
22802
  // executes EXPLICIT author-configured Layer-2 chains and synthesizes their
22793
22803
  // `usedFallback` / `fallbackModel` / `fallbackExecutions` attribution, so
@@ -45830,7 +45840,7 @@ var TOOL_CATALOG_FOR_FLOW_GENERATION = (() => {
45830
45840
  const toolName = tool.id.replace(`orthogonal:${slug}:`, "");
45831
45841
  vendorGroups.get(slug).push(toolName);
45832
45842
  }
45833
- const orthogonalLines = Array.from(vendorGroups.entries()).sort(([a], [b2]) => a.localeCompare(b2)).map(([slug, tools]) => {
45843
+ const orthogonalLines = Array.from(vendorGroups.entries()).sort(([a], [b]) => a.localeCompare(b)).map(([slug, tools]) => {
45834
45844
  const vendorName = ORTHOGONAL_API_NAMES[slug] ?? slug;
45835
45845
  return `- **${vendorName}** (\`platform:orthogonal:${slug}:<tool>\`): ${tools.join(", ")}`;
45836
45846
  });
@@ -49562,7 +49572,8 @@ import chalk6 from "chalk";
49562
49572
  import React3 from "react";
49563
49573
  import { render as render3 } from "ink";
49564
49574
  import { useState as useState4, useEffect as useEffect5 } from "react";
49565
- import { writeFileSync } from "fs";
49575
+ import { writeFileSync, mkdirSync } from "fs";
49576
+ import { dirname as dirname2 } from "path";
49566
49577
 
49567
49578
  // src/lib/terminal-image.ts
49568
49579
  var ESC = "\x1B";
@@ -50361,6 +50372,31 @@ recordsCommand.command("export").description("Export records to a file").option(
50361
50372
  process.exit(1);
50362
50373
  }
50363
50374
  });
50375
+ recordsCommand.command("typegen").description(
50376
+ "Generate TypeScript types for your schematized record collections. Writes a .d.ts that augments the @runtypelabs/sdk RecordCollections map so client.records.from(slug) types record metadata. Commit the file and re-run this in CI, diffing against the committed copy (e.g. `runtype records typegen -o runtype-records.d.ts && git diff --exit-code runtype-records.d.ts`), to catch collection-schema drift."
50377
+ ).option(
50378
+ "-o, --output <file>",
50379
+ "Write the declarations to a file (default: print to stdout)"
50380
+ ).action(async (options) => {
50381
+ const apiKey = await ensureAuth();
50382
+ if (!apiKey) return;
50383
+ const client = createCliClient(apiKey);
50384
+ try {
50385
+ const dts = await client.collections.typegen();
50386
+ if (options.output) {
50387
+ const dir = dirname2(options.output);
50388
+ if (dir && dir !== ".") mkdirSync(dir, { recursive: true });
50389
+ writeFileSync(options.output, dts);
50390
+ console.log(chalk6.green(`Wrote record collection types to ${options.output}`));
50391
+ return;
50392
+ }
50393
+ process.stdout.write(dts);
50394
+ } catch (error51) {
50395
+ const message = error51 instanceof Error ? error51.message : "Unknown error";
50396
+ console.error(chalk6.red(`Failed to generate record types: ${message}`));
50397
+ process.exit(1);
50398
+ }
50399
+ });
50364
50400
  function csvEscape(value) {
50365
50401
  const text = neutralizeCsvFormula(value);
50366
50402
  if (text.includes(",") || text.includes('"') || text.includes("\n")) {
@@ -51471,18 +51507,18 @@ batchCommand.command("summary").description("Show a summary of active and recent
51471
51507
  console.log(` Recently completed: ${data.recentlyCompleted}`);
51472
51508
  if (data.batches.length > 0) {
51473
51509
  console.log(chalk9.cyan("\nActive Batches:"));
51474
- for (const b2 of data.batches) {
51510
+ for (const b of data.batches) {
51475
51511
  console.log(
51476
- ` ${chalk9.green(b2.id)} ${b2.flowName ?? ""} \u2014 ${b2.status} (${b2.processedRecords}/${b2.totalRecords}, ${b2.progress}%)`
51512
+ ` ${chalk9.green(b.id)} ${b.flowName ?? ""} \u2014 ${b.status} (${b.processedRecords}/${b.totalRecords}, ${b.progress}%)`
51477
51513
  );
51478
51514
  }
51479
51515
  }
51480
51516
  if (data.recent.length > 0) {
51481
51517
  console.log(chalk9.cyan("\nRecently Completed:"));
51482
- for (const b2 of data.recent) {
51483
- const statusColor = b2.status === "completed" ? chalk9.green(b2.status) : chalk9.red(b2.status);
51518
+ for (const b of data.recent) {
51519
+ const statusColor = b.status === "completed" ? chalk9.green(b.status) : chalk9.red(b.status);
51484
51520
  console.log(
51485
- ` ${chalk9.green(b2.id)} ${b2.flowName ?? ""} \u2014 ${statusColor} (${b2.processedRecords}/${b2.totalRecords})`
51521
+ ` ${chalk9.green(b.id)} ${b.flowName ?? ""} \u2014 ${statusColor} (${b.processedRecords}/${b.totalRecords})`
51486
51522
  );
51487
51523
  }
51488
51524
  }
@@ -51511,18 +51547,18 @@ batchCommand.command("summary").description("Show a summary of active and recent
51511
51547
  { label: "Active", value: data.activeBatches, color: "green" },
51512
51548
  { label: "Recently completed", value: data.recentlyCompleted }
51513
51549
  ];
51514
- for (const b2 of data.batches) {
51550
+ for (const b of data.batches) {
51515
51551
  fields.push({
51516
- label: b2.id,
51517
- value: `${b2.flowName ?? ""} \u2014 ${b2.status} (${b2.processedRecords}/${b2.totalRecords}, ${b2.progress}%)`,
51552
+ label: b.id,
51553
+ value: `${b.flowName ?? ""} \u2014 ${b.status} (${b.processedRecords}/${b.totalRecords}, ${b.progress}%)`,
51518
51554
  color: "yellow"
51519
51555
  });
51520
51556
  }
51521
- for (const b2 of data.recent) {
51557
+ for (const b of data.recent) {
51522
51558
  fields.push({
51523
- label: b2.id,
51524
- value: `${b2.flowName ?? ""} \u2014 ${b2.status} (${b2.processedRecords}/${b2.totalRecords})`,
51525
- color: b2.status === "completed" ? "green" : "red"
51559
+ label: b.id,
51560
+ value: `${b.flowName ?? ""} \u2014 ${b.status} (${b.processedRecords}/${b.totalRecords})`,
51561
+ color: b.status === "completed" ? "green" : "red"
51526
51562
  });
51527
51563
  }
51528
51564
  setResultNode(React6.createElement(EntityCard, { fields }));
@@ -53292,9 +53328,9 @@ Histogram (${histogram.length} buckets):`));
53292
53328
  if (histogram.length === 0) {
53293
53329
  console.log(chalk15.gray(" No data"));
53294
53330
  } else {
53295
- for (const b2 of histogram) {
53296
- const errPart = b2.errors > 0 ? chalk15.red(` (${b2.errors} errors)`) : "";
53297
- console.log(` ${chalk15.dim(b2.bucket)} ${b2.count}${errPart}`);
53331
+ for (const b of histogram) {
53332
+ const errPart = b.errors > 0 ? chalk15.red(` (${b.errors} errors)`) : "";
53333
+ console.log(` ${chalk15.dim(b.bucket)} ${b.count}${errPart}`);
53298
53334
  }
53299
53335
  }
53300
53336
  } catch (error51) {
@@ -53316,7 +53352,7 @@ Histogram (${histogram.length} buckets):`));
53316
53352
  const stats = res.data;
53317
53353
  const histogram = stats.histogram ?? [];
53318
53354
  const histogramSummary = histogram.length === 0 ? "No data" : histogram.map(
53319
- (b2) => `${b2.bucket}: ${b2.count}${b2.errors > 0 ? ` (${b2.errors} err)` : ""}`
53355
+ (b) => `${b.bucket}: ${b.count}${b.errors > 0 ? ` (${b.errors} err)` : ""}`
53320
53356
  ).join("\n");
53321
53357
  setResultNode(
53322
53358
  React11.createElement(EntityCard, {
@@ -57362,7 +57398,7 @@ function extractTrackedFiles(snapshots, liveTools, planPath) {
57362
57398
  result.push({ path: planPath, type: "plan" });
57363
57399
  }
57364
57400
  const sorted = Array.from(fileMap.values()).sort(
57365
- (a, b2) => (b2.lastTouchedAt ?? 0) - (a.lastTouchedAt ?? 0)
57401
+ (a, b) => (b.lastTouchedAt ?? 0) - (a.lastTouchedAt ?? 0)
57366
57402
  );
57367
57403
  result.push(...sorted);
57368
57404
  return result;
@@ -58593,7 +58629,7 @@ function ModelPicker({ currentModel, onSelect, onCancel, models }) {
58593
58629
  [contentWidth]
58594
58630
  );
58595
58631
  const sorted = useMemo7(
58596
- () => [...availableModels].sort((a, b2) => a.group.localeCompare(b2.group)),
58632
+ () => [...availableModels].sort((a, b) => a.group.localeCompare(b.group)),
58597
58633
  [availableModels]
58598
58634
  );
58599
58635
  const filtered = useMemo7(() => {
@@ -62972,7 +63008,7 @@ function getSanitizedEnv() {
62972
63008
  return clean;
62973
63009
  }
62974
63010
  function redactSecrets(output, secrets) {
62975
- const sorted = secrets.filter((s) => s.length >= 8).sort((a, b2) => b2.length - a.length);
63011
+ const sorted = secrets.filter((s) => s.length >= 8).sort((a, b) => b.length - a.length);
62976
63012
  let redacted = output;
62977
63013
  for (const secret of sorted) {
62978
63014
  redacted = redacted.replaceAll(secret, "[REDACTED]");
@@ -63905,7 +63941,7 @@ function buildTree(dirPath, maxDepth, depth = 0) {
63905
63941
  return [`${" ".repeat(depth)}[error reading ${normalizeToolPath(dirPath)}: ${message}]`];
63906
63942
  }
63907
63943
  const lines = [];
63908
- for (const entry of entries.sort((a, b2) => a.name.localeCompare(b2.name))) {
63944
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
63909
63945
  const entryPath = path10.join(dirPath, entry.name);
63910
63946
  if (shouldIgnoreRepoEntry(entryPath)) continue;
63911
63947
  lines.push(`${" ".repeat(depth)}- ${entry.name}${entry.isDirectory() ? "/" : ""}`);
@@ -64160,7 +64196,7 @@ function createDefaultLocalTools(context) {
64160
64196
  });
64161
64197
  }
64162
64198
  });
64163
- const matches = candidates.sort((a, b2) => b2.score - a.score || a.text.localeCompare(b2.text)).map((candidate) => candidate.text).filter((text, index, array2) => array2.indexOf(text) === index).slice(0, maxResults);
64199
+ const matches = candidates.sort((a, b) => b.score - a.score || a.text.localeCompare(b.text)).map((candidate) => candidate.text).filter((text, index, array2) => array2.indexOf(text) === index).slice(0, maxResults);
64164
64200
  return matches.length > 0 ? matches.join("\n") : `No matches found for "${query}" under ${normalizeToolPath(startPath.resolvedPath)}`;
64165
64201
  }
64166
64202
  },
@@ -64209,7 +64245,7 @@ function createDefaultLocalTools(context) {
64209
64245
  });
64210
64246
  }
64211
64247
  });
64212
- const rankedMatches = matches.sort((a, b2) => b2.score - a.score || a.path.localeCompare(b2.path)).map((match) => match.path).slice(0, maxResults);
64248
+ const rankedMatches = matches.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path)).map((match) => match.path).slice(0, maxResults);
64213
64249
  return rankedMatches.length > 0 ? rankedMatches.join("\n") : `No files matched "${pattern}" under ${normalizeToolPath(startPath.resolvedPath)}`;
64214
64250
  }
64215
64251
  },
@@ -68464,8 +68500,8 @@ import React20 from "react";
68464
68500
  import { render as render20 } from "ink";
68465
68501
  import { useState as useState37, useEffect as useEffect31 } from "react";
68466
68502
  import { Text as Text34 } from "ink";
68467
- import { readFileSync as readFileSync16, writeFileSync as writeFileSync6, mkdirSync as mkdirSync8 } from "fs";
68468
- import { dirname as dirname8, relative as relative6, resolve as resolve10 } from "path";
68503
+ import { readFileSync as readFileSync16, writeFileSync as writeFileSync6, mkdirSync as mkdirSync9 } from "fs";
68504
+ import { dirname as dirname9, relative as relative6, resolve as resolve10 } from "path";
68469
68505
 
68470
68506
  // src/lib/eval-discovery.ts
68471
68507
  import { readdirSync as readdirSync6 } from "fs";
@@ -68732,14 +68768,14 @@ evalCommand.command("list").description("List eval batches").option("--flow <id>
68732
68768
  total,
68733
68769
  emptyMessage: "No eval batches found",
68734
68770
  renderCard: (item) => {
68735
- const b2 = item;
68736
- const name = b2.name || b2.id;
68737
- const progress = b2.totalRecords ? `${b2.completedRecords ?? 0}/${b2.totalRecords}` : "";
68738
- const statusColor = b2.status === "completed" ? "green" : "yellow";
68771
+ const b = item;
68772
+ const name = b.name || b.id;
68773
+ const progress = b.totalRecords ? `${b.completedRecords ?? 0}/${b.totalRecords}` : "";
68774
+ const statusColor = b.status === "completed" ? "green" : "yellow";
68739
68775
  return React20.createElement(
68740
68776
  Text34,
68741
68777
  { color: statusColor },
68742
- ` ${b2.id} ${name} [${b2.status}] ${progress}`
68778
+ ` ${b.id} ${name} [${b.status}] ${progress}`
68743
68779
  );
68744
68780
  }
68745
68781
  });
@@ -69021,7 +69057,7 @@ evalCommand.command("run [idOrDirPrefix]").description(
69021
69057
  try {
69022
69058
  const xml = buildJUnitXml(outcomes.map(toJUnitSuite));
69023
69059
  const outPath = resolve10(options.junit);
69024
- mkdirSync8(dirname8(outPath), { recursive: true });
69060
+ mkdirSync9(dirname9(outPath), { recursive: true });
69025
69061
  writeFileSync6(outPath, xml, "utf-8");
69026
69062
  console.log(chalk28.gray(`JUnit results written to ${options.junit}`));
69027
69063
  } catch (error51) {
@@ -69906,19 +69942,19 @@ import { execFileSync } from "child_process";
69906
69942
  // src/lib/persona-init.ts
69907
69943
  init_credential_store();
69908
69944
 
69909
- // ../../node_modules/.pnpm/@runtypelabs+persona@4.14.0/node_modules/@runtypelabs/persona/dist/codegen.js
69910
- var w = "4.14.0";
69911
- var S = w;
69912
- function b(e) {
69913
- return e?.cdnBase?.trim().replace(/\/+$/, "").replace(/[\\'"<>`]/g, (r) => `%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`) || `https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${S}/dist`;
69945
+ // ../../node_modules/.pnpm/@runtypelabs+persona@4.15.0/node_modules/@runtypelabs/persona/dist/codegen.js
69946
+ var S = "4.15.0";
69947
+ var x = S;
69948
+ function $(e) {
69949
+ return e?.cdnBase?.trim().replace(/\/+$/, "").replace(/[\\'"<>`]/g, (r) => `%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`) || `https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${x}/dist`;
69914
69950
  }
69915
69951
  function u(e) {
69916
69952
  if (e !== void 0) return typeof e == "string" ? e : Array.isArray(e) ? `[${e.map((i) => i.toString()).join(", ")}]` : e.toString();
69917
69953
  }
69918
- function I(e) {
69954
+ function v(e) {
69919
69955
  if (e) return { getHeaders: u(e.getHeaders), onFeedback: u(e.onFeedback), onCopy: u(e.onCopy), requestMiddleware: u(e.requestMiddleware), actionHandlers: u(e.actionHandlers), actionParsers: u(e.actionParsers), postprocessMessage: u(e.postprocessMessage), contextProviders: u(e.contextProviders), streamParser: u(e.streamParser) };
69920
69956
  }
69921
- var x = `({ text, message }: any) => {
69957
+ var A = `({ text, message }: any) => {
69922
69958
  const jsonSource = (message as any).rawContent || text || message.content;
69923
69959
  if (!jsonSource || typeof jsonSource !== 'string') return null;
69924
69960
  let cleanJson = jsonSource
@@ -69932,7 +69968,7 @@ var x = `({ text, message }: any) => {
69932
69968
  } catch (e) { return null; }
69933
69969
  return null;
69934
69970
  }`;
69935
- var A = `function(ctx) {
69971
+ var j = `function(ctx) {
69936
69972
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
69937
69973
  if (!jsonSource || typeof jsonSource !== 'string') return null;
69938
69974
  var cleanJson = jsonSource
@@ -69946,7 +69982,7 @@ var A = `function(ctx) {
69946
69982
  } catch (e) { return null; }
69947
69983
  return null;
69948
69984
  }`;
69949
- var j = `(action: any, context: any) => {
69985
+ var O = `(action: any, context: any) => {
69950
69986
  if (action.type !== 'nav_then_click') return;
69951
69987
  const payload = action.payload || action.raw || {};
69952
69988
  const url = payload?.page;
@@ -69964,7 +70000,7 @@ var j = `(action: any, context: any) => {
69964
70000
  window.location.href = targetUrl;
69965
70001
  return { handled: true, displayText: text };
69966
70002
  }`;
69967
- var O = `function(action, context) {
70003
+ var E = `function(action, context) {
69968
70004
  if (action.type !== 'nav_then_click') return;
69969
70005
  var payload = action.payload || action.raw || {};
69970
70006
  var url = payload.page;
@@ -69982,27 +70018,27 @@ var O = `function(action, context) {
69982
70018
  window.location.href = targetUrl;
69983
70019
  return { handled: true, displayText: text };
69984
70020
  }`;
69985
- var v = `(parsed: any) => {
70021
+ var _ = `(parsed: any) => {
69986
70022
  if (!parsed || typeof parsed !== 'object') return null;
69987
70023
  if (parsed.action === 'nav_then_click') return 'Navigating...';
69988
70024
  if (parsed.action === 'message') return parsed.text || '';
69989
70025
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
69990
70026
  return parsed.text || null;
69991
70027
  }`;
69992
- var _ = `function(parsed) {
70028
+ var T = `function(parsed) {
69993
70029
  if (!parsed || typeof parsed !== 'object') return null;
69994
70030
  if (parsed.action === 'nav_then_click') return 'Navigating...';
69995
70031
  if (parsed.action === 'message') return parsed.text || '';
69996
70032
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
69997
70033
  return parsed.text || null;
69998
70034
  }`;
69999
- function T(e) {
70035
+ function M(e) {
70000
70036
  if (!e) return null;
70001
70037
  let i = e.toString();
70002
70038
  return i.includes("createJsonStreamParser") || i.includes("partial-json") ? "json" : i.includes("createRegexJsonParser") || i.includes("regex") ? "regex-json" : i.includes("createXmlParser") || i.includes("<text>") ? "xml" : null;
70003
70039
  }
70004
70040
  function h(e) {
70005
- return e.parserType ?? T(e.streamParser) ?? "plain";
70041
+ return e.parserType ?? M(e.streamParser) ?? "plain";
70006
70042
  }
70007
70043
  function g(e, i) {
70008
70044
  let r = [];
@@ -70027,6 +70063,15 @@ function f(e, i) {
70027
70063
  return r;
70028
70064
  }
70029
70065
  function y(e, i) {
70066
+ if (!e.suggestions) return [];
70067
+ let r = JSON.stringify(e.suggestions, null, 2).split(`
70068
+ `);
70069
+ return r.map((s, a) => {
70070
+ let t = a === 0 ? `${i}suggestions: ` : i, n = a === r.length - 1 ? "," : "";
70071
+ return `${t}${s}${n}`;
70072
+ });
70073
+ }
70074
+ function C(e, i) {
70030
70075
  let r = [];
70031
70076
  if (e.layout) {
70032
70077
  let s = e.layout.header && Object.keys(e.layout.header).some((t) => t !== "render"), a = e.layout.messages && Object.keys(e.layout.messages).some((t) => t !== "renderUserMessage" && t !== "renderAssistantMessage");
@@ -70042,11 +70087,11 @@ function y(e, i) {
70042
70087
  }
70043
70088
  return r;
70044
70089
  }
70045
- function $(e, i) {
70090
+ function w(e, i) {
70046
70091
  let r = [];
70047
70092
  return e && (e.getHeaders && r.push(`${i}getHeaders: ${e.getHeaders},`), e.requestMiddleware && r.push(`${i}requestMiddleware: ${e.requestMiddleware},`), e.actionParsers && r.push(`${i}actionParsers: ${e.actionParsers},`), e.actionHandlers && r.push(`${i}actionHandlers: ${e.actionHandlers},`), e.contextProviders && r.push(`${i}contextProviders: ${e.contextProviders},`), e.streamParser && r.push(`${i}streamParser: ${e.streamParser},`)), r;
70048
70093
  }
70049
- function E(e, i, r) {
70094
+ function k(e, i, r) {
70050
70095
  Object.entries(i).forEach(([s, a]) => {
70051
70096
  if (!(a === void 0 || typeof a == "function")) {
70052
70097
  if (Array.isArray(a)) {
@@ -70054,7 +70099,7 @@ function E(e, i, r) {
70054
70099
  return;
70055
70100
  }
70056
70101
  if (a && typeof a == "object") {
70057
- e.push(`${r}${s}: {`), E(e, a, `${r} `), e.push(`${r}},`);
70102
+ e.push(`${r}${s}: {`), k(e, a, `${r} `), e.push(`${r}},`);
70058
70103
  return;
70059
70104
  }
70060
70105
  e.push(`${r}${s}: ${JSON.stringify(a)},`);
@@ -70062,18 +70107,18 @@ function E(e, i, r) {
70062
70107
  });
70063
70108
  }
70064
70109
  function d(e, i, r, s) {
70065
- r && (e.push(`${s}${i}: {`), E(e, r, `${s} `), e.push(`${s}},`));
70110
+ r && (e.push(`${s}${i}: {`), k(e, r, `${s} `), e.push(`${s}},`));
70066
70111
  }
70067
70112
  function c(e) {
70068
70113
  return (e?.target ?? "body").replace(/\\/g, "\\\\").replace(/'/g, "\\'");
70069
70114
  }
70070
- function M(e, i = "esm", r) {
70115
+ function R(e, i = "esm", r) {
70071
70116
  let s = { ...e };
70072
70117
  delete s.postprocessMessage, delete s.initialMessages;
70073
- let a = r ? { ...r, hooks: I(r.hooks) } : void 0;
70074
- return i === "esm" ? R(s, a) : i === "script-installer" ? N(s, a) : i === "script-advanced" ? F(s, a) : i === "react-component" ? W(s, a) : i === "react-advanced" ? H(s, a) : D(s, a);
70118
+ let a = r ? { ...r, hooks: v(r.hooks) } : void 0;
70119
+ return i === "esm" ? W(s, a) : i === "script-installer" ? D(s, a) : i === "script-advanced" ? F(s, a) : i === "react-component" ? H(s, a) : i === "react-advanced" ? N(s, a) : J(s, a);
70075
70120
  }
70076
- function R(e, i) {
70121
+ function W(e, i) {
70077
70122
  let r = i?.hooks, s = h(e), a = s !== "plain", t = ["import '@runtypelabs/persona/widget.css';", "import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';", "", "initAgentWidget({", ` target: '${c(i)}',`, " config: {"];
70078
70123
  return e.apiUrl && t.push(` apiUrl: "${e.apiUrl}",`), e.clientToken && t.push(` clientToken: "${e.clientToken}",`), e.agentId && t.push(` agentId: "${e.agentId}",`), e.target && t.push(` target: "${e.target}",`), e.flowId && t.push(` flowId: "${e.flowId}",`), a && t.push(` parserType: "${s}",`), e.theme && typeof e.theme == "object" && Object.keys(e.theme).length > 0 && d(t, "theme", e.theme, " "), e.launcher && d(t, "launcher", e.launcher, " "), e.copy && (t.push(" copy: {"), Object.entries(e.copy).forEach(([n, o]) => {
70079
70124
  t.push(` ${n}: "${o}",`);
@@ -70085,12 +70130,12 @@ function R(e, i) {
70085
70130
  typeof o == "string" ? t.push(` ${n}: "${o}",`) : typeof o == "boolean" && t.push(` ${n}: ${o},`);
70086
70131
  }), t.push(" },")), e.features && (t.push(" features: {"), Object.entries(e.features).forEach(([n, o]) => {
70087
70132
  t.push(` ${n}: ${o},`);
70088
- }), t.push(" },")), e.suggestionChips && e.suggestionChips.length > 0 && (t.push(" suggestionChips: ["), e.suggestionChips.forEach((n) => {
70133
+ }), t.push(" },")), t.push(...y(e, " ")), e.suggestionChips && e.suggestionChips.length > 0 && (t.push(" suggestionChips: ["), e.suggestionChips.forEach((n) => {
70089
70134
  t.push(` "${n}",`);
70090
- }), t.push(" ],")), e.suggestionChipsConfig && (t.push(" suggestionChipsConfig: {"), e.suggestionChipsConfig.fontFamily && t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`), e.suggestionChipsConfig.fontWeight && t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`), e.suggestionChipsConfig.paddingX && t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`), e.suggestionChipsConfig.paddingY && t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`), t.push(" },")), t.push(...g(e, " ")), t.push(...m(e, " ", r)), t.push(...f(e, " ")), t.push(...y(e, " ")), t.push(...$(r, " ")), e.debug && t.push(` debug: ${e.debug},`), r?.postprocessMessage ? t.push(` postprocessMessage: ${r.postprocessMessage}`) : t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"), t.push(" }"), t.push("});"), t.join(`
70135
+ }), t.push(" ],")), e.suggestionChipsConfig && (t.push(" suggestionChipsConfig: {"), e.suggestionChipsConfig.fontFamily && t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`), e.suggestionChipsConfig.fontWeight && t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`), e.suggestionChipsConfig.paddingX && t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`), e.suggestionChipsConfig.paddingY && t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`), t.push(" },")), t.push(...g(e, " ")), t.push(...m(e, " ", r)), t.push(...f(e, " ")), t.push(...C(e, " ")), t.push(...w(r, " ")), e.debug && t.push(` debug: ${e.debug},`), r?.postprocessMessage ? t.push(` postprocessMessage: ${r.postprocessMessage}`) : t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"), t.push(" }"), t.push("});"), t.join(`
70091
70136
  `);
70092
70137
  }
70093
- function W(e, i) {
70138
+ function H(e, i) {
70094
70139
  let r = i?.hooks, s = h(e), a = s !== "plain", t = ["// ChatWidget.tsx", "'use client'; // Required for Next.js - remove for Vite/CRA", "", "import { useEffect } from 'react';", "import '@runtypelabs/persona/widget.css';", "import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';", "import type { AgentWidgetInitHandle } from '@runtypelabs/persona';", "", "export function ChatWidget() {", " useEffect(() => {", " let handle: AgentWidgetInitHandle | null = null;", "", " handle = initAgentWidget({", ` target: '${c(i)}',`, " config: {"];
70095
70140
  return e.apiUrl && t.push(` apiUrl: "${e.apiUrl}",`), e.clientToken && t.push(` clientToken: "${e.clientToken}",`), e.agentId && t.push(` agentId: "${e.agentId}",`), e.target && t.push(` target: "${e.target}",`), e.flowId && t.push(` flowId: "${e.flowId}",`), a && t.push(` parserType: "${s}",`), e.theme && typeof e.theme == "object" && Object.keys(e.theme).length > 0 && d(t, "theme", e.theme, " "), e.launcher && d(t, "launcher", e.launcher, " "), e.copy && (t.push(" copy: {"), Object.entries(e.copy).forEach(([n, o]) => {
70096
70141
  t.push(` ${n}: "${o}",`);
@@ -70102,12 +70147,12 @@ function W(e, i) {
70102
70147
  typeof o == "string" ? t.push(` ${n}: "${o}",`) : typeof o == "boolean" && t.push(` ${n}: ${o},`);
70103
70148
  }), t.push(" },")), e.features && (t.push(" features: {"), Object.entries(e.features).forEach(([n, o]) => {
70104
70149
  t.push(` ${n}: ${o},`);
70105
- }), t.push(" },")), e.suggestionChips && e.suggestionChips.length > 0 && (t.push(" suggestionChips: ["), e.suggestionChips.forEach((n) => {
70150
+ }), t.push(" },")), t.push(...y(e, " ")), e.suggestionChips && e.suggestionChips.length > 0 && (t.push(" suggestionChips: ["), e.suggestionChips.forEach((n) => {
70106
70151
  t.push(` "${n}",`);
70107
- }), t.push(" ],")), e.suggestionChipsConfig && (t.push(" suggestionChipsConfig: {"), e.suggestionChipsConfig.fontFamily && t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`), e.suggestionChipsConfig.fontWeight && t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`), e.suggestionChipsConfig.paddingX && t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`), e.suggestionChipsConfig.paddingY && t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`), t.push(" },")), t.push(...g(e, " ")), t.push(...m(e, " ", r)), t.push(...f(e, " ")), t.push(...y(e, " ")), t.push(...$(r, " ")), e.debug && t.push(` debug: ${e.debug},`), r?.postprocessMessage ? t.push(` postprocessMessage: ${r.postprocessMessage}`) : t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"), t.push(" }"), t.push(" });"), t.push(""), t.push(" // Cleanup on unmount"), t.push(" return () => {"), t.push(" if (handle) {"), t.push(" handle.destroy();"), t.push(" }"), t.push(" };"), t.push(" }, []);"), t.push(""), t.push(" return null; // Widget injects itself into the DOM"), t.push("}"), t.push(""), t.push("// Usage in your app:"), t.push("// import { ChatWidget } from './components/ChatWidget';"), t.push("//"), t.push("// export default function App() {"), t.push("// return ("), t.push("// <div>"), t.push("// {/* Your app content */}"), t.push("// <ChatWidget />"), t.push("// </div>"), t.push("// );"), t.push("// }"), t.join(`
70152
+ }), t.push(" ],")), e.suggestionChipsConfig && (t.push(" suggestionChipsConfig: {"), e.suggestionChipsConfig.fontFamily && t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`), e.suggestionChipsConfig.fontWeight && t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`), e.suggestionChipsConfig.paddingX && t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`), e.suggestionChipsConfig.paddingY && t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`), t.push(" },")), t.push(...g(e, " ")), t.push(...m(e, " ", r)), t.push(...f(e, " ")), t.push(...C(e, " ")), t.push(...w(r, " ")), e.debug && t.push(` debug: ${e.debug},`), r?.postprocessMessage ? t.push(` postprocessMessage: ${r.postprocessMessage}`) : t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"), t.push(" }"), t.push(" });"), t.push(""), t.push(" // Cleanup on unmount"), t.push(" return () => {"), t.push(" if (handle) {"), t.push(" handle.destroy();"), t.push(" }"), t.push(" };"), t.push(" }, []);"), t.push(""), t.push(" return null; // Widget injects itself into the DOM"), t.push("}"), t.push(""), t.push("// Usage in your app:"), t.push("// import { ChatWidget } from './components/ChatWidget';"), t.push("//"), t.push("// export default function App() {"), t.push("// return ("), t.push("// <div>"), t.push("// {/* Your app content */}"), t.push("// <ChatWidget />"), t.push("// </div>"), t.push("// );"), t.push("// }"), t.join(`
70108
70153
  `);
70109
70154
  }
70110
- function H(e, i) {
70155
+ function N(e, i) {
70111
70156
  let r = i?.hooks, s = ["// ChatWidgetAdvanced.tsx", "'use client'; // Required for Next.js - remove for Vite/CRA", "", "import { useEffect } from 'react';", "import '@runtypelabs/persona/widget.css';", "import {", " initAgentWidget,", " createFlexibleJsonStreamParser,", " defaultJsonActionParser,", " defaultActionHandlers,", " markdownPostprocessor", "} from '@runtypelabs/persona';", "import type { AgentWidgetInitHandle } from '@runtypelabs/persona';", "", "const STORAGE_KEY = 'chat-widget-state';", "const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';", "", "// Types for DOM elements", "interface PageElement {", " type: string;", " tagName: string;", " selector: string;", " innerText: string;", " href?: string;", "}", "", "interface DOMContext {", " page_elements: PageElement[];", " page_element_count: number;", " element_types: Record<string, number>;", " page_url: string;", " page_title: string;", " timestamp: string;", "}", "", "// DOM context provider - extracts page elements for AI context", "const collectDOMContext = (): DOMContext => {", " const selectors = {", ` products: '[data-product-id], .product-card, .product-item, [role="article"]',`, ` buttons: 'button, [role="button"], .btn',`, " links: 'a[href]',", " inputs: 'input, textarea, select'", " };", "", " const elements: PageElement[] = [];", " Object.entries(selectors).forEach(([type, selector]) => {", " document.querySelectorAll(selector).forEach((element) => {", " if (!(element instanceof HTMLElement)) return;", " ", " // Exclude elements within the widget", " const widgetHost = element.closest('.persona-host');", " if (widgetHost) return;", " ", " const text = element.innerText?.trim();", " if (!text) return;", "", " const selectorString =", " element.id ? `#${element.id}` :", " element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :", " element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :", " element.tagName.toLowerCase();", "", " const elementData: PageElement = {", " type,", " tagName: element.tagName.toLowerCase(),", " selector: selectorString,", " innerText: text.substring(0, 200)", " };", "", " if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {", " elementData.href = element.href;", " }", "", " elements.push(elementData);", " });", " });", "", " const counts = elements.reduce((acc, el) => {", " acc[el.type] = (acc[el.type] || 0) + 1;", " return acc;", " }, {} as Record<string, number>);", "", " return {", " page_elements: elements.slice(0, 50),", " page_element_count: elements.length,", " element_types: counts,", " page_url: window.location.href,", " page_title: document.title,", " timestamp: new Date().toISOString()", " };", "};", "", "export function ChatWidgetAdvanced() {", " useEffect(() => {", " let handle: AgentWidgetInitHandle | null = null;", "", " // Load saved state", " const loadSavedMessages = () => {", " const savedState = localStorage.getItem(STORAGE_KEY);", " if (savedState) {", " try {", " const { messages } = JSON.parse(savedState);", " return messages || [];", " } catch (e) {", " console.error('Failed to load saved state:', e);", " }", " }", " return [];", " };", "", " handle = initAgentWidget({", ` target: '${c(i)}',`, " config: {"];
70112
70157
  return e.apiUrl && s.push(` apiUrl: "${e.apiUrl}",`), e.clientToken && s.push(` clientToken: "${e.clientToken}",`), e.agentId && s.push(` agentId: "${e.agentId}",`), e.target && s.push(` target: "${e.target}",`), e.flowId && s.push(` flowId: "${e.flowId}",`), e.theme && typeof e.theme == "object" && Object.keys(e.theme).length > 0 && d(s, "theme", e.theme, " "), e.launcher && d(s, "launcher", e.launcher, " "), e.copy && (s.push(" copy: {"), Object.entries(e.copy).forEach(([a, t]) => {
70113
70158
  s.push(` ${a}: "${t}",`);
@@ -70119,14 +70164,14 @@ function H(e, i) {
70119
70164
  typeof t == "string" ? s.push(` ${a}: "${t}",`) : typeof t == "boolean" && s.push(` ${a}: ${t},`);
70120
70165
  }), s.push(" },")), e.features && (s.push(" features: {"), Object.entries(e.features).forEach(([a, t]) => {
70121
70166
  s.push(` ${a}: ${t},`);
70122
- }), s.push(" },")), e.suggestionChips && e.suggestionChips.length > 0 && (s.push(" suggestionChips: ["), e.suggestionChips.forEach((a) => {
70167
+ }), s.push(" },")), s.push(...y(e, " ")), e.suggestionChips && e.suggestionChips.length > 0 && (s.push(" suggestionChips: ["), e.suggestionChips.forEach((a) => {
70123
70168
  s.push(` "${a}",`);
70124
- }), s.push(" ],")), e.suggestionChipsConfig && (s.push(" suggestionChipsConfig: {"), e.suggestionChipsConfig.fontFamily && s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`), e.suggestionChipsConfig.fontWeight && s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`), e.suggestionChipsConfig.paddingX && s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`), e.suggestionChipsConfig.paddingY && s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`), s.push(" },")), s.push(...g(e, " ")), s.push(...m(e, " ", r)), s.push(...f(e, " ")), s.push(...y(e, " ")), r?.getHeaders && s.push(` getHeaders: ${r.getHeaders},`), r?.contextProviders && s.push(` contextProviders: ${r.contextProviders},`), e.debug && s.push(` debug: ${e.debug},`), s.push(" initialMessages: loadSavedMessages(),"), r?.streamParser ? s.push(` streamParser: ${r.streamParser},`) : (s.push(" // Flexible JSON stream parser for handling structured actions"), s.push(` streamParser: () => createFlexibleJsonStreamParser(${v}),`)), r?.actionParsers ? (s.push(" // Action parsers (custom merged with defaults)"), s.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`), s.push(" // Built-in parser for markdown-wrapped JSON"), s.push(` ${x}`), s.push(" ],")) : (s.push(" // Action parsers to detect JSON actions in responses"), s.push(" actionParsers: ["), s.push(" defaultJsonActionParser,"), s.push(" // Parser for markdown-wrapped JSON"), s.push(` ${x}`), s.push(" ],")), r?.actionHandlers ? (s.push(" // Action handlers (custom merged with defaults)"), s.push(` actionHandlers: [...(${r.actionHandlers}),`), s.push(" defaultActionHandlers.message,"), s.push(" defaultActionHandlers.messageAndClick,"), s.push(" // Built-in handler for nav_then_click action"), s.push(` ${j}`), s.push(" ],")) : (s.push(" // Action handlers for navigation and other actions"), s.push(" actionHandlers: ["), s.push(" defaultActionHandlers.message,"), s.push(" defaultActionHandlers.messageAndClick,"), s.push(" // Handler for nav_then_click action"), s.push(` ${j}`), s.push(" ],")), r?.postprocessMessage ? s.push(` postprocessMessage: ${r.postprocessMessage},`) : s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"), r?.requestMiddleware ? (s.push(" // Request middleware (custom merged with DOM context)"), s.push(" requestMiddleware: ({ payload, config }) => {"), s.push(` const customResult = (${r.requestMiddleware})({ payload, config });`), s.push(" const merged = customResult || payload;"), s.push(" return {"), s.push(" ...merged,"), s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"), s.push(" };"), s.push(" }")) : (s.push(" requestMiddleware: ({ payload }) => {"), s.push(" return {"), s.push(" ...payload,"), s.push(" metadata: collectDOMContext()"), s.push(" };"), s.push(" }")), s.push(" }"), s.push(" });"), s.push(""), s.push(" // Save state on message events"), s.push(" const handleMessage = () => {"), s.push(" const session = handle?.getSession?.();"), s.push(" if (session) {"), s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"), s.push(" messages: session.messages,"), s.push(" timestamp: new Date().toISOString()"), s.push(" }));"), s.push(" }"), s.push(" };"), s.push(""), s.push(" // Clear state on clear chat"), s.push(" const handleClearChat = () => {"), s.push(" localStorage.removeItem(STORAGE_KEY);"), s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"), s.push(" };"), s.push(""), s.push(" window.addEventListener('persona:message', handleMessage);"), s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"), s.push(""), s.push(" // Cleanup on unmount"), s.push(" return () => {"), s.push(" window.removeEventListener('persona:message', handleMessage);"), s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"), s.push(" if (handle) {"), s.push(" handle.destroy();"), s.push(" }"), s.push(" };"), s.push(" }, []);"), s.push(""), s.push(" return null; // Widget injects itself into the DOM"), s.push("}"), s.push(""), s.push("// Usage: Collects DOM context for AI-powered navigation"), s.push("// Features:"), s.push("// - Extracts page elements (products, buttons, links)"), s.push("// - Persists chat history across page loads"), s.push("// - Handles navigation actions (nav_then_click)"), s.push("// - Processes structured JSON actions from AI"), s.push("//"), s.push("// Example usage in Next.js:"), s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"), s.push("//"), s.push("// export default function RootLayout({ children }) {"), s.push("// return ("), s.push('// <html lang="en">'), s.push("// <body>"), s.push("// {children}"), s.push("// <ChatWidgetAdvanced />"), s.push("// </body>"), s.push("// </html>"), s.push("// );"), s.push("// }"), s.join(`
70169
+ }), s.push(" ],")), e.suggestionChipsConfig && (s.push(" suggestionChipsConfig: {"), e.suggestionChipsConfig.fontFamily && s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`), e.suggestionChipsConfig.fontWeight && s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`), e.suggestionChipsConfig.paddingX && s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`), e.suggestionChipsConfig.paddingY && s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`), s.push(" },")), s.push(...g(e, " ")), s.push(...m(e, " ", r)), s.push(...f(e, " ")), s.push(...C(e, " ")), r?.getHeaders && s.push(` getHeaders: ${r.getHeaders},`), r?.contextProviders && s.push(` contextProviders: ${r.contextProviders},`), e.debug && s.push(` debug: ${e.debug},`), s.push(" initialMessages: loadSavedMessages(),"), r?.streamParser ? s.push(` streamParser: ${r.streamParser},`) : (s.push(" // Flexible JSON stream parser for handling structured actions"), s.push(` streamParser: () => createFlexibleJsonStreamParser(${_}),`)), r?.actionParsers ? (s.push(" // Action parsers (custom merged with defaults)"), s.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`), s.push(" // Built-in parser for markdown-wrapped JSON"), s.push(` ${A}`), s.push(" ],")) : (s.push(" // Action parsers to detect JSON actions in responses"), s.push(" actionParsers: ["), s.push(" defaultJsonActionParser,"), s.push(" // Parser for markdown-wrapped JSON"), s.push(` ${A}`), s.push(" ],")), r?.actionHandlers ? (s.push(" // Action handlers (custom merged with defaults)"), s.push(` actionHandlers: [...(${r.actionHandlers}),`), s.push(" defaultActionHandlers.message,"), s.push(" defaultActionHandlers.messageAndClick,"), s.push(" // Built-in handler for nav_then_click action"), s.push(` ${O}`), s.push(" ],")) : (s.push(" // Action handlers for navigation and other actions"), s.push(" actionHandlers: ["), s.push(" defaultActionHandlers.message,"), s.push(" defaultActionHandlers.messageAndClick,"), s.push(" // Handler for nav_then_click action"), s.push(` ${O}`), s.push(" ],")), r?.postprocessMessage ? s.push(` postprocessMessage: ${r.postprocessMessage},`) : s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"), r?.requestMiddleware ? (s.push(" // Request middleware (custom merged with DOM context)"), s.push(" requestMiddleware: ({ payload, config }) => {"), s.push(` const customResult = (${r.requestMiddleware})({ payload, config });`), s.push(" const merged = customResult || payload;"), s.push(" return {"), s.push(" ...merged,"), s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"), s.push(" };"), s.push(" }")) : (s.push(" requestMiddleware: ({ payload }) => {"), s.push(" return {"), s.push(" ...payload,"), s.push(" metadata: collectDOMContext()"), s.push(" };"), s.push(" }")), s.push(" }"), s.push(" });"), s.push(""), s.push(" // Save state on message events"), s.push(" const handleMessage = () => {"), s.push(" const session = handle?.getSession?.();"), s.push(" if (session) {"), s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"), s.push(" messages: session.messages,"), s.push(" timestamp: new Date().toISOString()"), s.push(" }));"), s.push(" }"), s.push(" };"), s.push(""), s.push(" // Clear state on clear chat"), s.push(" const handleClearChat = () => {"), s.push(" localStorage.removeItem(STORAGE_KEY);"), s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"), s.push(" };"), s.push(""), s.push(" window.addEventListener('persona:message', handleMessage);"), s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"), s.push(""), s.push(" // Cleanup on unmount"), s.push(" return () => {"), s.push(" window.removeEventListener('persona:message', handleMessage);"), s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"), s.push(" if (handle) {"), s.push(" handle.destroy();"), s.push(" }"), s.push(" };"), s.push(" }, []);"), s.push(""), s.push(" return null; // Widget injects itself into the DOM"), s.push("}"), s.push(""), s.push("// Usage: Collects DOM context for AI-powered navigation"), s.push("// Features:"), s.push("// - Extracts page elements (products, buttons, links)"), s.push("// - Persists chat history across page loads"), s.push("// - Handles navigation actions (nav_then_click)"), s.push("// - Processes structured JSON actions from AI"), s.push("//"), s.push("// Example usage in Next.js:"), s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"), s.push("//"), s.push("// export default function RootLayout({ children }) {"), s.push("// return ("), s.push('// <html lang="en">'), s.push("// <body>"), s.push("// {children}"), s.push("// <ChatWidgetAdvanced />"), s.push("// </body>"), s.push("// </html>"), s.push("// );"), s.push("// }"), s.join(`
70125
70170
  `);
70126
70171
  }
70127
- function k(e) {
70172
+ function P(e) {
70128
70173
  let i = h(e), r = i !== "plain", s = {};
70129
- if (e.apiUrl && (s.apiUrl = e.apiUrl), e.clientToken && (s.clientToken = e.clientToken), e.agentId && (s.agentId = e.agentId), e.target && (s.target = e.target), e.flowId && (s.flowId = e.flowId), r && (s.parserType = i), e.theme && (s.theme = e.theme), e.launcher && (s.launcher = e.launcher), e.copy && (s.copy = e.copy), e.sendButton && (s.sendButton = e.sendButton), e.voiceRecognition && (s.voiceRecognition = e.voiceRecognition), e.statusIndicator && (s.statusIndicator = e.statusIndicator), e.features && (s.features = e.features), e.suggestionChips?.length > 0 && (s.suggestionChips = e.suggestionChips), e.suggestionChipsConfig && (s.suggestionChipsConfig = e.suggestionChipsConfig), e.debug && (s.debug = e.debug), e.toolCall) {
70174
+ if (e.apiUrl && (s.apiUrl = e.apiUrl), e.clientToken && (s.clientToken = e.clientToken), e.agentId && (s.agentId = e.agentId), e.target && (s.target = e.target), e.flowId && (s.flowId = e.flowId), r && (s.parserType = i), e.theme && (s.theme = e.theme), e.launcher && (s.launcher = e.launcher), e.copy && (s.copy = e.copy), e.sendButton && (s.sendButton = e.sendButton), e.voiceRecognition && (s.voiceRecognition = e.voiceRecognition), e.statusIndicator && (s.statusIndicator = e.statusIndicator), e.features && (s.features = e.features), e.suggestions && (s.suggestions = e.suggestions), e.suggestionChips?.length > 0 && (s.suggestionChips = e.suggestionChips), e.suggestionChipsConfig && (s.suggestionChipsConfig = e.suggestionChipsConfig), e.debug && (s.debug = e.debug), e.toolCall) {
70130
70175
  let a = {};
70131
70176
  Object.entries(e.toolCall).forEach(([t, n]) => {
70132
70177
  typeof n == "string" && (a[t] = n);
@@ -70156,8 +70201,8 @@ function k(e) {
70156
70201
  if (n !== "renderUserMessage" && n !== "renderAssistantMessage") if (n === "avatar" && typeof o == "object" && o !== null) t.avatar = o;
70157
70202
  else if (n === "timestamp" && typeof o == "object" && o !== null) {
70158
70203
  let p = {};
70159
- Object.entries(o).forEach(([l, C]) => {
70160
- l !== "format" && (typeof C == "string" || typeof C == "boolean") && (p[l] = C);
70204
+ Object.entries(o).forEach(([l, b]) => {
70205
+ l !== "format" && (typeof b == "string" || typeof b == "boolean") && (p[l] = b);
70161
70206
  }), Object.keys(p).length > 0 && (t.timestamp = p);
70162
70207
  } else (typeof o == "string" || typeof o == "boolean") && (t[n] = o);
70163
70208
  }), Object.keys(t).length > 0 && (a.messages = t);
@@ -70166,12 +70211,12 @@ function k(e) {
70166
70211
  }
70167
70212
  return s;
70168
70213
  }
70169
- function N(e, i) {
70170
- let r = k(e), a = !!(i?.windowKey || i?.target) ? { config: r, ...i?.windowKey ? { windowKey: i.windowKey } : {}, ...i?.target ? { target: i.target } : {} } : r, t = JSON.stringify(a, null, 0).replace(/'/g, "&#39;");
70171
- return `<script src="${b(i)}/install.global.js" data-config='${t}'></script>`;
70172
- }
70173
70214
  function D(e, i) {
70174
- let r = i?.hooks, s = h(e), a = s !== "plain", t = b(i), n = ["<!-- Load CSS -->", `<link rel="stylesheet" href="${t}/widget.css" />`, "", "<!-- Load JavaScript -->", `<script src="${t}/index.global.js"></script>`, "", "<!-- Initialize widget -->", "<script>", " var handle = window.AgentWidget.initAgentWidget({", ` target: '${c(i)}',`, ...i?.windowKey ? [` windowKey: '${i.windowKey}',`] : [], " config: {"];
70215
+ let r = P(e), a = !!(i?.windowKey || i?.target) ? { config: r, ...i?.windowKey ? { windowKey: i.windowKey } : {}, ...i?.target ? { target: i.target } : {} } : r, t = JSON.stringify(a, null, 0).replace(/'/g, "&#39;");
70216
+ return `<script src="${$(i)}/install.global.js" data-config='${t}'></script>`;
70217
+ }
70218
+ function J(e, i) {
70219
+ let r = i?.hooks, s = h(e), a = s !== "plain", t = $(i), n = ["<!-- Load CSS -->", `<link rel="stylesheet" href="${t}/widget.css" />`, "", "<!-- Load JavaScript -->", `<script src="${t}/index.global.js"></script>`, "", "<!-- Initialize widget -->", "<script>", " var handle = window.AgentWidget.initAgentWidget({", ` target: '${c(i)}',`, ...i?.windowKey ? [` windowKey: '${i.windowKey}',`] : [], " config: {"];
70175
70220
  return e.apiUrl && n.push(` apiUrl: "${e.apiUrl}",`), e.clientToken && n.push(` clientToken: "${e.clientToken}",`), e.agentId && n.push(` agentId: "${e.agentId}",`), e.target && n.push(` target: "${e.target}",`), e.flowId && n.push(` flowId: "${e.flowId}",`), a && n.push(` parserType: "${s}",`), e.theme && typeof e.theme == "object" && Object.keys(e.theme).length > 0 && d(n, "theme", e.theme, " "), e.launcher && d(n, "launcher", e.launcher, " "), e.copy && (n.push(" copy: {"), Object.entries(e.copy).forEach(([o, p]) => {
70176
70221
  n.push(` ${o}: "${p}",`);
70177
70222
  }), n.push(" },")), e.sendButton && (n.push(" sendButton: {"), Object.entries(e.sendButton).forEach(([o, p]) => {
@@ -70182,16 +70227,16 @@ function D(e, i) {
70182
70227
  typeof p == "string" ? n.push(` ${o}: "${p}",`) : typeof p == "boolean" && n.push(` ${o}: ${p},`);
70183
70228
  }), n.push(" },")), e.features && (n.push(" features: {"), Object.entries(e.features).forEach(([o, p]) => {
70184
70229
  n.push(` ${o}: ${p},`);
70185
- }), n.push(" },")), e.suggestionChips && e.suggestionChips.length > 0 && (n.push(" suggestionChips: ["), e.suggestionChips.forEach((o) => {
70230
+ }), n.push(" },")), n.push(...y(e, " ")), e.suggestionChips && e.suggestionChips.length > 0 && (n.push(" suggestionChips: ["), e.suggestionChips.forEach((o) => {
70186
70231
  n.push(` "${o}",`);
70187
- }), n.push(" ],")), e.suggestionChipsConfig && (n.push(" suggestionChipsConfig: {"), e.suggestionChipsConfig.fontFamily && n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`), e.suggestionChipsConfig.fontWeight && n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`), e.suggestionChipsConfig.paddingX && n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`), e.suggestionChipsConfig.paddingY && n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`), n.push(" },")), n.push(...g(e, " ")), n.push(...m(e, " ", r)), n.push(...f(e, " ")), n.push(...y(e, " ")), n.push(...$(r, " ")), e.debug && n.push(` debug: ${e.debug},`), r?.postprocessMessage ? n.push(` postprocessMessage: ${r.postprocessMessage}`) : n.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"), n.push(" }"), n.push(" });"), n.push("</script>"), n.join(`
70232
+ }), n.push(" ],")), e.suggestionChipsConfig && (n.push(" suggestionChipsConfig: {"), e.suggestionChipsConfig.fontFamily && n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`), e.suggestionChipsConfig.fontWeight && n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`), e.suggestionChipsConfig.paddingX && n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`), e.suggestionChipsConfig.paddingY && n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`), n.push(" },")), n.push(...g(e, " ")), n.push(...m(e, " ", r)), n.push(...f(e, " ")), n.push(...C(e, " ")), n.push(...w(r, " ")), e.debug && n.push(` debug: ${e.debug},`), r?.postprocessMessage ? n.push(` postprocessMessage: ${r.postprocessMessage}`) : n.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"), n.push(" }"), n.push(" });"), n.push("</script>"), n.join(`
70188
70233
  `);
70189
70234
  }
70190
70235
  function F(e, i) {
70191
- let r = i?.hooks, s = k(e), t = ["<script>", "(function() {", " 'use strict';", "", " // Configuration", ` var CONFIG = ${JSON.stringify(s, null, 2).split(`
70236
+ let r = i?.hooks, s = P(e), t = ["<script>", "(function() {", " 'use strict';", "", " // Configuration", ` var CONFIG = ${JSON.stringify(s, null, 2).split(`
70192
70237
  `).map((n, o) => o === 0 ? n : " " + n).join(`
70193
- `)};`, "", " // Constants", ` var CDN_BASE = '${b(i)}';`, " var STORAGE_KEY = 'chat-widget-state';", " var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';", "", " // DOM context provider - extracts page elements for AI context", " var domContextProvider = function() {", " var selectors = {", ` products: '[data-product-id], .product-card, .product-item, [role="article"]',`, ` buttons: 'button, [role="button"], .btn',`, " links: 'a[href]',", " inputs: 'input, textarea, select'", " };", "", " var elements = [];", " Object.entries(selectors).forEach(function(entry) {", " var type = entry[0], selector = entry[1];", " document.querySelectorAll(selector).forEach(function(element) {", " if (!(element instanceof HTMLElement)) return;", " var widgetHost = element.closest('.persona-host');", " if (widgetHost) return;", " var text = element.innerText ? element.innerText.trim() : '';", " if (!text) return;", "", " var selectorString = element.id ? '#' + element.id :", ` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`, ` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`, " element.tagName.toLowerCase();", "", " var elementData = {", " type: type,", " tagName: element.tagName.toLowerCase(),", " selector: selectorString,", " innerText: text.substring(0, 200)", " };", "", " if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {", " elementData.href = element.href;", " }", " elements.push(elementData);", " });", " });", "", " var counts = elements.reduce(function(acc, el) {", " acc[el.type] = (acc[el.type] || 0) + 1;", " return acc;", " }, {});", "", " return {", " page_elements: elements.slice(0, 50),", " page_element_count: elements.length,", " element_types: counts,", " page_url: window.location.href,", " page_title: document.title,", " timestamp: new Date().toISOString()", " };", " };", "", " // Load CSS dynamically", " var loadCSS = function() {", " if (document.querySelector('link[data-persona]')) return;", " var link = document.createElement('link');", " link.rel = 'stylesheet';", " link.href = CDN_BASE + '/widget.css';", " link.setAttribute('data-persona', 'true');", " document.head.appendChild(link);", " };", "", " // Load JS dynamically", " var loadJS = function(callback) {", " if (window.AgentWidget) { callback(); return; }", " var script = document.createElement('script');", " script.src = CDN_BASE + '/index.global.js';", " script.onload = callback;", " script.onerror = function() { console.error('Failed to load AgentWidget'); };", " document.head.appendChild(script);", " };", "", " // Create widget config with advanced features", " var createWidgetConfig = function(agentWidget) {", " var widgetConfig = Object.assign({}, CONFIG);", ""];
70194
- return r?.getHeaders && (t.push(` widgetConfig.getHeaders = ${r.getHeaders};`), t.push("")), r?.contextProviders && (t.push(` widgetConfig.contextProviders = ${r.contextProviders};`), t.push("")), r?.streamParser ? t.push(` widgetConfig.streamParser = ${r.streamParser};`) : (t.push(" // Flexible JSON stream parser for handling structured actions"), t.push(" widgetConfig.streamParser = function() {"), t.push(` return agentWidget.createFlexibleJsonStreamParser(${_});`), t.push(" };")), t.push(""), r?.actionParsers ? (t.push(" // Action parsers (custom merged with defaults)"), t.push(` var customParsers = ${r.actionParsers};`), t.push(" widgetConfig.actionParsers = customParsers.concat(["), t.push(" agentWidget.defaultJsonActionParser,"), t.push(` ${A}`), t.push(" ]);")) : (t.push(" // Action parsers to detect JSON actions in responses"), t.push(" widgetConfig.actionParsers = ["), t.push(" agentWidget.defaultJsonActionParser,"), t.push(` ${A}`), t.push(" ];")), t.push(""), r?.actionHandlers ? (t.push(" // Action handlers (custom merged with defaults)"), t.push(` var customHandlers = ${r.actionHandlers};`), t.push(" widgetConfig.actionHandlers = customHandlers.concat(["), t.push(" agentWidget.defaultActionHandlers.message,"), t.push(" agentWidget.defaultActionHandlers.messageAndClick,"), t.push(` ${O}`), t.push(" ]);")) : (t.push(" // Action handlers for navigation and other actions"), t.push(" widgetConfig.actionHandlers = ["), t.push(" agentWidget.defaultActionHandlers.message,"), t.push(" agentWidget.defaultActionHandlers.messageAndClick,"), t.push(` ${O}`), t.push(" ];")), t.push(""), r?.requestMiddleware ? (t.push(" // Request middleware (custom merged with DOM context)"), t.push(" widgetConfig.requestMiddleware = function(ctx) {"), t.push(` var customResult = (${r.requestMiddleware})(ctx);`), t.push(" var merged = customResult || ctx.payload;"), t.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"), t.push(" };")) : (t.push(" // Send DOM context with each request"), t.push(" widgetConfig.requestMiddleware = function(ctx) {"), t.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"), t.push(" };")), t.push(""), r?.postprocessMessage ? t.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`) : (t.push(" // Markdown postprocessor"), t.push(" widgetConfig.postprocessMessage = function(ctx) {"), t.push(" return agentWidget.markdownPostprocessor(ctx.text);"), t.push(" };")), t.push(""), (r?.onFeedback || r?.onCopy) && (t.push(" // Message action callbacks"), t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"), r?.onFeedback && t.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`), r?.onCopy && t.push(` widgetConfig.messageActions.onCopy = ${r.onCopy};`), t.push("")), t.push(" return widgetConfig;", " };", "", " // Initialize widget", " var init = function() {", " var agentWidget = window.AgentWidget;", " if (!agentWidget) {", " console.error('AgentWidget not loaded');", " return;", " }", "", " var widgetConfig = createWidgetConfig(agentWidget);", "", " // Load saved state", " var savedState = localStorage.getItem(STORAGE_KEY);", " if (savedState) {", " try {", " var parsed = JSON.parse(savedState);", " widgetConfig.initialMessages = parsed.messages || [];", " } catch (e) {", " console.error('Failed to load saved state:', e);", " }", " }", "", " // Initialize widget", " var handle = agentWidget.initAgentWidget({", ` target: '${c(i)}',`, " useShadowDom: false,", ...i?.windowKey ? [` windowKey: '${i.windowKey}',`] : [], " config: widgetConfig", " });", "", " // Save state on message events", " window.addEventListener('persona:message', function() {", " var session = handle.getSession ? handle.getSession() : null;", " if (session) {", " localStorage.setItem(STORAGE_KEY, JSON.stringify({", " messages: session.messages,", " timestamp: new Date().toISOString()", " }));", " }", " });", "", " // Clear state on clear chat", " window.addEventListener('persona:clear-chat', function() {", " localStorage.removeItem(STORAGE_KEY);", " localStorage.removeItem(PROCESSED_ACTIONS_KEY);", " });", " };", "", " // Wait for framework hydration to complete (Next.js, Nuxt, etc.)", " // This prevents the framework from removing dynamically added CSS during reconciliation", " var waitForHydration = function(callback) {", " var executed = false;", " ", " var execute = function() {", " if (executed) return;", " executed = true;", " callback();", " };", "", " var afterDom = function() {", " // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)", " if (typeof requestIdleCallback !== 'undefined') {", " requestIdleCallback(function() {", " // Double requestAnimationFrame ensures at least one full paint cycle completed", " requestAnimationFrame(function() {", " requestAnimationFrame(execute);", " });", " }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway", " } else {", " // Strategy 2: Fallback for Safari (no requestIdleCallback)", " // 300ms is typically enough for hydration on most pages", " setTimeout(execute, 300);", " }", " };", "", " if (document.readyState === 'loading') {", " document.addEventListener('DOMContentLoaded', afterDom);", " } else {", " // DOM already ready, but still wait for potential hydration", " afterDom();", " }", " };", "", " // Boot sequence: wait for hydration, then load CSS and JS, then initialize", " // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation", " waitForHydration(function() {", " loadCSS();", " loadJS(function() {", " init();", " });", " });", "})();", "</script>"), t.join(`
70238
+ `)};`, "", " // Constants", ` var CDN_BASE = '${$(i)}';`, " var STORAGE_KEY = 'chat-widget-state';", " var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';", "", " // DOM context provider - extracts page elements for AI context", " var domContextProvider = function() {", " var selectors = {", ` products: '[data-product-id], .product-card, .product-item, [role="article"]',`, ` buttons: 'button, [role="button"], .btn',`, " links: 'a[href]',", " inputs: 'input, textarea, select'", " };", "", " var elements = [];", " Object.entries(selectors).forEach(function(entry) {", " var type = entry[0], selector = entry[1];", " document.querySelectorAll(selector).forEach(function(element) {", " if (!(element instanceof HTMLElement)) return;", " var widgetHost = element.closest('.persona-host');", " if (widgetHost) return;", " var text = element.innerText ? element.innerText.trim() : '';", " if (!text) return;", "", " var selectorString = element.id ? '#' + element.id :", ` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`, ` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`, " element.tagName.toLowerCase();", "", " var elementData = {", " type: type,", " tagName: element.tagName.toLowerCase(),", " selector: selectorString,", " innerText: text.substring(0, 200)", " };", "", " if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {", " elementData.href = element.href;", " }", " elements.push(elementData);", " });", " });", "", " var counts = elements.reduce(function(acc, el) {", " acc[el.type] = (acc[el.type] || 0) + 1;", " return acc;", " }, {});", "", " return {", " page_elements: elements.slice(0, 50),", " page_element_count: elements.length,", " element_types: counts,", " page_url: window.location.href,", " page_title: document.title,", " timestamp: new Date().toISOString()", " };", " };", "", " // Load CSS dynamically", " var loadCSS = function() {", " if (document.querySelector('link[data-persona]')) return;", " var link = document.createElement('link');", " link.rel = 'stylesheet';", " link.href = CDN_BASE + '/widget.css';", " link.setAttribute('data-persona', 'true');", " document.head.appendChild(link);", " };", "", " // Load JS dynamically", " var loadJS = function(callback) {", " if (window.AgentWidget) { callback(); return; }", " var script = document.createElement('script');", " script.src = CDN_BASE + '/index.global.js';", " script.onload = callback;", " script.onerror = function() { console.error('Failed to load AgentWidget'); };", " document.head.appendChild(script);", " };", "", " // Create widget config with advanced features", " var createWidgetConfig = function(agentWidget) {", " var widgetConfig = Object.assign({}, CONFIG);", ""];
70239
+ return r?.getHeaders && (t.push(` widgetConfig.getHeaders = ${r.getHeaders};`), t.push("")), r?.contextProviders && (t.push(` widgetConfig.contextProviders = ${r.contextProviders};`), t.push("")), r?.streamParser ? t.push(` widgetConfig.streamParser = ${r.streamParser};`) : (t.push(" // Flexible JSON stream parser for handling structured actions"), t.push(" widgetConfig.streamParser = function() {"), t.push(` return agentWidget.createFlexibleJsonStreamParser(${T});`), t.push(" };")), t.push(""), r?.actionParsers ? (t.push(" // Action parsers (custom merged with defaults)"), t.push(` var customParsers = ${r.actionParsers};`), t.push(" widgetConfig.actionParsers = customParsers.concat(["), t.push(" agentWidget.defaultJsonActionParser,"), t.push(` ${j}`), t.push(" ]);")) : (t.push(" // Action parsers to detect JSON actions in responses"), t.push(" widgetConfig.actionParsers = ["), t.push(" agentWidget.defaultJsonActionParser,"), t.push(` ${j}`), t.push(" ];")), t.push(""), r?.actionHandlers ? (t.push(" // Action handlers (custom merged with defaults)"), t.push(` var customHandlers = ${r.actionHandlers};`), t.push(" widgetConfig.actionHandlers = customHandlers.concat(["), t.push(" agentWidget.defaultActionHandlers.message,"), t.push(" agentWidget.defaultActionHandlers.messageAndClick,"), t.push(` ${E}`), t.push(" ]);")) : (t.push(" // Action handlers for navigation and other actions"), t.push(" widgetConfig.actionHandlers = ["), t.push(" agentWidget.defaultActionHandlers.message,"), t.push(" agentWidget.defaultActionHandlers.messageAndClick,"), t.push(` ${E}`), t.push(" ];")), t.push(""), r?.requestMiddleware ? (t.push(" // Request middleware (custom merged with DOM context)"), t.push(" widgetConfig.requestMiddleware = function(ctx) {"), t.push(` var customResult = (${r.requestMiddleware})(ctx);`), t.push(" var merged = customResult || ctx.payload;"), t.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"), t.push(" };")) : (t.push(" // Send DOM context with each request"), t.push(" widgetConfig.requestMiddleware = function(ctx) {"), t.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"), t.push(" };")), t.push(""), r?.postprocessMessage ? t.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`) : (t.push(" // Markdown postprocessor"), t.push(" widgetConfig.postprocessMessage = function(ctx) {"), t.push(" return agentWidget.markdownPostprocessor(ctx.text);"), t.push(" };")), t.push(""), (r?.onFeedback || r?.onCopy) && (t.push(" // Message action callbacks"), t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"), r?.onFeedback && t.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`), r?.onCopy && t.push(` widgetConfig.messageActions.onCopy = ${r.onCopy};`), t.push("")), t.push(" return widgetConfig;", " };", "", " // Initialize widget", " var init = function() {", " var agentWidget = window.AgentWidget;", " if (!agentWidget) {", " console.error('AgentWidget not loaded');", " return;", " }", "", " var widgetConfig = createWidgetConfig(agentWidget);", "", " // Load saved state", " var savedState = localStorage.getItem(STORAGE_KEY);", " if (savedState) {", " try {", " var parsed = JSON.parse(savedState);", " widgetConfig.initialMessages = parsed.messages || [];", " } catch (e) {", " console.error('Failed to load saved state:', e);", " }", " }", "", " // Initialize widget", " var handle = agentWidget.initAgentWidget({", ` target: '${c(i)}',`, " useShadowDom: false,", ...i?.windowKey ? [` windowKey: '${i.windowKey}',`] : [], " config: widgetConfig", " });", "", " // Save state on message events", " window.addEventListener('persona:message', function() {", " var session = handle.getSession ? handle.getSession() : null;", " if (session) {", " localStorage.setItem(STORAGE_KEY, JSON.stringify({", " messages: session.messages,", " timestamp: new Date().toISOString()", " }));", " }", " });", "", " // Clear state on clear chat", " window.addEventListener('persona:clear-chat', function() {", " localStorage.removeItem(STORAGE_KEY);", " localStorage.removeItem(PROCESSED_ACTIONS_KEY);", " });", " };", "", " // Wait for framework hydration to complete (Next.js, Nuxt, etc.)", " // This prevents the framework from removing dynamically added CSS during reconciliation", " var waitForHydration = function(callback) {", " var executed = false;", " ", " var execute = function() {", " if (executed) return;", " executed = true;", " callback();", " };", "", " var afterDom = function() {", " // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)", " if (typeof requestIdleCallback !== 'undefined') {", " requestIdleCallback(function() {", " // Double requestAnimationFrame ensures at least one full paint cycle completed", " requestAnimationFrame(function() {", " requestAnimationFrame(execute);", " });", " }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway", " } else {", " // Strategy 2: Fallback for Safari (no requestIdleCallback)", " // 300ms is typically enough for hydration on most pages", " setTimeout(execute, 300);", " }", " };", "", " if (document.readyState === 'loading') {", " document.addEventListener('DOMContentLoaded', afterDom);", " } else {", " // DOM already ready, but still wait for potential hydration", " afterDom();", " }", " };", "", " // Boot sequence: wait for hydration, then load CSS and JS, then initialize", " // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation", " waitForHydration(function() {", " loadCSS();", " loadJS(function() {", " init();", " });", " });", "})();", "</script>"), t.join(`
70195
70240
  `);
70196
70241
  }
70197
70242
 
@@ -70231,14 +70276,14 @@ function buildWidgetConfig(input) {
70231
70276
  function generatePersonaInitSnippet(input, personaFormat) {
70232
70277
  const widgetConfig = buildWidgetConfig(input);
70233
70278
  const target = input.targetSelector?.trim();
70234
- return M(
70279
+ return R(
70235
70280
  widgetConfig,
70236
70281
  personaFormat,
70237
70282
  target ? { target } : void 0
70238
70283
  );
70239
70284
  }
70240
70285
  function getPersonaInstallerScriptUrl() {
70241
- const snippet = M(
70286
+ const snippet = R(
70242
70287
  {
70243
70288
  apiUrl: "https://api.runtype.com",
70244
70289
  clientToken: "ct_test_demo_00000000000000000000000000000000",
@@ -70417,7 +70462,7 @@ async function runPersonaInit(options) {
70417
70462
  // src/lib/persona-demo.ts
70418
70463
  import { createServer } from "http";
70419
70464
  import { createServer as createNetServer } from "net";
70420
- import { existsSync as existsSync13, mkdirSync as mkdirSync9, readFileSync as readFileSync17, writeFileSync as writeFileSync7 } from "fs";
70465
+ import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync17, writeFileSync as writeFileSync7 } from "fs";
70421
70466
  import path16 from "path";
70422
70467
  var PERSONA_DEMO_DEFAULT_DIR = "persona-demo";
70423
70468
  var PERSONA_DEMO_DEFAULT_PORT = 43110;
@@ -70453,7 +70498,7 @@ function ensurePersonaDemoCanWrite(directory, force) {
70453
70498
  }
70454
70499
  function writePersonaDemoPage(options) {
70455
70500
  ensurePersonaDemoCanWrite(options.directory, options.force);
70456
- mkdirSync9(options.directory, { recursive: true });
70501
+ mkdirSync10(options.directory, { recursive: true });
70457
70502
  const filePath = personaDemoIndexPath(options.directory);
70458
70503
  const readmePath = personaDemoReadmePath(options.directory);
70459
70504
  writeFileSync7(filePath, `${options.html.trim()}
@@ -74299,7 +74344,7 @@ import { Command as Command32 } from "commander";
74299
74344
  import chalk40 from "chalk";
74300
74345
 
74301
74346
  // src/lib/skills-install.ts
74302
- import { mkdirSync as mkdirSync11, readFileSync as readFileSync19, writeFileSync as writeFileSync9 } from "fs";
74347
+ import { mkdirSync as mkdirSync12, readFileSync as readFileSync19, writeFileSync as writeFileSync9 } from "fs";
74303
74348
  import path18 from "path";
74304
74349
  import readline4 from "readline";
74305
74350
  import chalk39 from "chalk";
@@ -74323,7 +74368,7 @@ function readSkillsInstallMetadata() {
74323
74368
  }
74324
74369
  function writeSkillsInstallMetadata(metadata) {
74325
74370
  try {
74326
- mkdirSync11(path18.dirname(metadataPath()), { recursive: true });
74371
+ mkdirSync12(path18.dirname(metadataPath()), { recursive: true });
74327
74372
  writeFileSync9(metadataPath(), JSON.stringify(metadata, null, 2));
74328
74373
  } catch {
74329
74374
  }
@@ -75950,7 +75995,7 @@ import { spawn as spawn2 } from "child_process";
75950
75995
  import {
75951
75996
  closeSync,
75952
75997
  existsSync as existsSync18,
75953
- mkdirSync as mkdirSync12,
75998
+ mkdirSync as mkdirSync13,
75954
75999
  openSync,
75955
76000
  readFileSync as readFileSync22,
75956
76001
  readdirSync as readdirSync8,
@@ -75961,7 +76006,7 @@ import {
75961
76006
  writeFileSync as writeFileSync10
75962
76007
  } from "fs";
75963
76008
  import { constants as osConstants } from "os";
75964
- import { dirname as dirname10, isAbsolute as isAbsolute4, join as join16, relative as relative8, resolve as resolve12, sep as sep6 } from "path";
76009
+ import { dirname as dirname11, isAbsolute as isAbsolute4, join as join16, relative as relative8, resolve as resolve12, sep as sep6 } from "path";
75965
76010
 
75966
76011
  // src/lib/update-check.ts
75967
76012
  import chalk44 from "chalk";
@@ -75988,10 +76033,10 @@ function parseVersion(version2) {
75988
76033
  }
75989
76034
  function compareVersions(left, right) {
75990
76035
  const a = parseVersion(left);
75991
- const b2 = parseVersion(right);
75992
- if (!a || !b2) return 0;
76036
+ const b = parseVersion(right);
76037
+ if (!a || !b) return 0;
75993
76038
  for (let index = 0; index < 3; index++) {
75994
- const diff = a[index] - b2[index];
76039
+ const diff = a[index] - b[index];
75995
76040
  if (diff !== 0) return diff;
75996
76041
  }
75997
76042
  return 0;
@@ -76149,7 +76194,7 @@ function getManagedCliState(homeDir = getRuntypeHomeDir()) {
76149
76194
  }
76150
76195
  }
76151
76196
  function writeManagedCliState(paths, state) {
76152
- mkdirSync12(paths.root, { recursive: true });
76197
+ mkdirSync13(paths.root, { recursive: true });
76153
76198
  const temporaryPath = `${paths.state}.${process.pid}.${Date.now()}.tmp`;
76154
76199
  try {
76155
76200
  writeFileSync10(temporaryPath, `${JSON.stringify(state, null, 2)}
@@ -76186,12 +76231,12 @@ function isPathInside(parent, child) {
76186
76231
  return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute4(relativePath);
76187
76232
  }
76188
76233
  function isSourceCheckout(entrypoint) {
76189
- let current = dirname10(entrypoint);
76234
+ let current = dirname11(entrypoint);
76190
76235
  for (let depth = 0; depth < 8; depth += 1) {
76191
76236
  if (existsSync18(join16(current, ".git")) || existsSync18(join16(current, "pnpm-workspace.yaml"))) {
76192
76237
  return true;
76193
76238
  }
76194
- const parent = dirname10(current);
76239
+ const parent = dirname11(current);
76195
76240
  if (parent === current) break;
76196
76241
  current = parent;
76197
76242
  }
@@ -76203,7 +76248,7 @@ function findProjectRoot(cwd) {
76203
76248
  if (existsSync18(join16(current, "package.json")) || existsSync18(join16(current, "pnpm-workspace.yaml"))) {
76204
76249
  return current;
76205
76250
  }
76206
- const parent = dirname10(current);
76251
+ const parent = dirname11(current);
76207
76252
  if (parent === current) return void 0;
76208
76253
  current = parent;
76209
76254
  }
@@ -76332,7 +76377,7 @@ var defaultCommandRunner = async (command, args, options = {}) => new Promise((r
76332
76377
  });
76333
76378
  });
76334
76379
  function acquireUpdateLock(paths, now) {
76335
- mkdirSync12(paths.root, { recursive: true });
76380
+ mkdirSync13(paths.root, { recursive: true });
76336
76381
  const tryAcquire = () => {
76337
76382
  try {
76338
76383
  const descriptor = openSync(paths.lock, "wx", 384);
@@ -76421,10 +76466,10 @@ async function installAndActivateCliVersion(version2, options = {}) {
76421
76466
  const temporaryRoot = join16(paths.versions, `.${version2}-${process.pid}-${now.getTime()}`);
76422
76467
  let installed = false;
76423
76468
  try {
76424
- mkdirSync12(paths.versions, { recursive: true });
76469
+ mkdirSync13(paths.versions, { recursive: true });
76425
76470
  if (!isHealthyManagedVersion(paths, version2)) {
76426
76471
  rmSync2(temporaryRoot, { force: true, recursive: true });
76427
- mkdirSync12(temporaryRoot, { recursive: true });
76472
+ mkdirSync13(temporaryRoot, { recursive: true });
76428
76473
  const npmCommand = options.npmCommand ?? (process.platform === "win32" ? "npm.cmd" : "npm");
76429
76474
  const installResult = await commandRunner(
76430
76475
  npmCommand,
@@ -76524,7 +76569,7 @@ function spawnAutoUpdateWorker(version2, context = {}) {
76524
76569
  const entrypoint = context.entrypoint ?? process.argv[1];
76525
76570
  if (!entrypoint || !existsSync18(entrypoint)) return false;
76526
76571
  const paths = getManagedCliPaths();
76527
- mkdirSync12(paths.root, { recursive: true });
76572
+ mkdirSync13(paths.root, { recursive: true });
76528
76573
  const logDescriptor = openSync(paths.log, "a", 384);
76529
76574
  try {
76530
76575
  const child = spawn2(process.execPath, [entrypoint, INTERNAL_AUTO_UPDATE_ARG, version2], {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runtypelabs/cli",
3
- "version": "2.32.5",
3
+ "version": "2.33.0",
4
4
  "description": "Command-line interface for Runtype AI platform",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -10,7 +10,7 @@
10
10
  "dependencies": {
11
11
  "@modelcontextprotocol/client": "2.0.0",
12
12
  "@modelcontextprotocol/core": "2.0.0",
13
- "add-mcp": "1.14.0",
13
+ "add-mcp": "2.0.0",
14
14
  "chalk": "^5.3.0",
15
15
  "commander": "^15.0.0",
16
16
  "conf": "^15.1.0",
@@ -23,27 +23,27 @@
23
23
  "micromatch": "^4.0.8",
24
24
  "oauth4webapi": "^3.8.5",
25
25
  "open": "^10.1.0",
26
- "react": "^19.2.4",
26
+ "react": "^19.2.8",
27
27
  "rosie-skills": "0.8.1",
28
28
  "yaml": "^2.9.0",
29
- "@runtypelabs/ink-components": "0.3.5",
30
- "@runtypelabs/sdk": "6.5.1",
31
- "@runtypelabs/terminal-animations": "0.2.2"
29
+ "@runtypelabs/ink-components": "0.3.6",
30
+ "@runtypelabs/sdk": "6.6.0",
31
+ "@runtypelabs/terminal-animations": "0.2.3"
32
32
  },
33
33
  "devDependencies": {
34
34
  "@modelcontextprotocol/server": "2.0.0",
35
- "@runtypelabs/persona": "4.14.0",
35
+ "@runtypelabs/persona": "4.15.0",
36
36
  "@types/express": "^5.0.6",
37
37
  "@types/micromatch": "^4.0.9",
38
38
  "@types/node": "^25.3.3",
39
- "@types/react": "^19.2.14",
39
+ "@types/react": "^19.2.17",
40
40
  "@vitest/coverage-v8": "^4.1.5",
41
41
  "ink-testing-library": "4.0.0",
42
42
  "tsup": "^8.0.2",
43
43
  "tsx": "^4.7.1",
44
44
  "typescript": "^6.0.3",
45
45
  "vitest": "^4.1.0",
46
- "@runtypelabs/shared": "3.13.0"
46
+ "@runtypelabs/shared": "3.15.0"
47
47
  },
48
48
  "engines": {
49
49
  "node": ">=22.12.0"