@runtypelabs/cli 2.32.5 → 2.33.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +748 -168
  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');
@@ -616,9 +616,6 @@ var OAuthManager = class {
616
616
  // src/auth/api-key-manager.ts
617
617
  import { RuntypeApiError } from "@runtypelabs/sdk";
618
618
 
619
- // src/lib/sdk-client.ts
620
- import { createClient } from "@runtypelabs/sdk";
621
-
622
619
  // ../shared/dist/chunk-ZUODFMLO.mjs
623
620
  var DEFAULT_MODELS_FOR_NEW_ACCOUNTS = [
624
621
  // Mixlayer models
@@ -1866,20 +1863,20 @@ function safeExtend(schema, shape) {
1866
1863
  });
1867
1864
  return clone(schema, def);
1868
1865
  }
1869
- function merge(a, b2) {
1866
+ function merge(a, b) {
1870
1867
  if (a._zod.def.checks?.length) {
1871
1868
  throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
1872
1869
  }
1873
1870
  const def = mergeDefs(a._zod.def, {
1874
1871
  get shape() {
1875
- const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape };
1872
+ const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
1876
1873
  assignProp(this, "shape", _shape);
1877
1874
  return _shape;
1878
1875
  },
1879
1876
  get catchall() {
1880
- return b2._zod.def.catchall;
1877
+ return b._zod.def.catchall;
1881
1878
  },
1882
- checks: b2._zod.def.checks ?? []
1879
+ checks: b._zod.def.checks ?? []
1883
1880
  });
1884
1881
  return clone(a, def);
1885
1882
  }
@@ -2082,7 +2079,7 @@ function hexToUint8Array(hex3) {
2082
2079
  return bytes;
2083
2080
  }
2084
2081
  function uint8ArrayToHex(bytes) {
2085
- return Array.from(bytes).map((b2) => b2.toString(16).padStart(2, "0")).join("");
2082
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
2086
2083
  }
2087
2084
  var Class = class {
2088
2085
  constructor(..._args) {
@@ -2219,7 +2216,7 @@ function toDotPath(_path) {
2219
2216
  }
2220
2217
  function prettifyError(error51) {
2221
2218
  const lines = [];
2222
- const issues = [...error51.issues].sort((a, b2) => (a.path ?? []).length - (b2.path ?? []).length);
2219
+ const issues = [...error51.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
2223
2220
  for (const issue2 of issues) {
2224
2221
  lines.push(`\u2716 ${issue2.message}`);
2225
2222
  if (issue2.path?.length)
@@ -4194,19 +4191,19 @@ var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, d
4194
4191
  return handleIntersectionResults(payload, left, right);
4195
4192
  };
4196
4193
  });
4197
- function mergeValues(a, b2) {
4198
- if (a === b2) {
4194
+ function mergeValues(a, b) {
4195
+ if (a === b) {
4199
4196
  return { valid: true, data: a };
4200
4197
  }
4201
- if (a instanceof Date && b2 instanceof Date && +a === +b2) {
4198
+ if (a instanceof Date && b instanceof Date && +a === +b) {
4202
4199
  return { valid: true, data: a };
4203
4200
  }
4204
- if (isPlainObject(a) && isPlainObject(b2)) {
4205
- const bKeys = Object.keys(b2);
4201
+ if (isPlainObject(a) && isPlainObject(b)) {
4202
+ const bKeys = Object.keys(b);
4206
4203
  const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
4207
- const newObj = { ...a, ...b2 };
4204
+ const newObj = { ...a, ...b };
4208
4205
  for (const key of sharedKeys) {
4209
- const sharedValue = mergeValues(a[key], b2[key]);
4206
+ const sharedValue = mergeValues(a[key], b[key]);
4210
4207
  if (!sharedValue.valid) {
4211
4208
  return {
4212
4209
  valid: false,
@@ -4217,14 +4214,14 @@ function mergeValues(a, b2) {
4217
4214
  }
4218
4215
  return { valid: true, data: newObj };
4219
4216
  }
4220
- if (Array.isArray(a) && Array.isArray(b2)) {
4221
- if (a.length !== b2.length) {
4217
+ if (Array.isArray(a) && Array.isArray(b)) {
4218
+ if (a.length !== b.length) {
4222
4219
  return { valid: false, mergeErrorPath: [] };
4223
4220
  }
4224
4221
  const newArray = [];
4225
4222
  for (let index = 0; index < a.length; index++) {
4226
4223
  const itemA = a[index];
4227
- const itemB = b2[index];
4224
+ const itemB = b[index];
4228
4225
  const sharedValue = mergeValues(itemA, itemB);
4229
4226
  if (!sharedValue.valid) {
4230
4227
  return {
@@ -12863,14 +12860,14 @@ var intersectionProcessor = (schema, ctx, json2, params) => {
12863
12860
  ...params,
12864
12861
  path: [...params.path, "allOf", 0]
12865
12862
  });
12866
- const b2 = process2(def.right, ctx, {
12863
+ const b = process2(def.right, ctx, {
12867
12864
  ...params,
12868
12865
  path: [...params.path, "allOf", 1]
12869
12866
  });
12870
12867
  const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
12871
12868
  const allOf = [
12872
12869
  ...isSimpleIntersection(a) ? a.allOf : [a],
12873
- ...isSimpleIntersection(b2) ? b2.allOf : [b2]
12870
+ ...isSimpleIntersection(b) ? b.allOf : [b]
12874
12871
  ];
12875
12872
  json2.allOf = allOf;
12876
12873
  };
@@ -15364,7 +15361,7 @@ var edgeContextPayloadSchema = external_exports.object({
15364
15361
  // ../shared/dist/chunk-SCJRL6LP.mjs
15365
15362
  var MAX_DURABLE_POLL_ATTEMPTS = 1e3;
15366
15363
 
15367
- // ../shared/dist/chunk-FSHR33DZ.mjs
15364
+ // ../shared/dist/chunk-MATCHJ7V.mjs
15368
15365
  function getNestedValue(obj, path20) {
15369
15366
  let normalizedPath = path20;
15370
15367
  normalizedPath = normalizedPath.replace(/^\$\.?/, "");
@@ -20376,14 +20373,14 @@ function normalizeVectorSearchConfig(config3) {
20376
20373
  }
20377
20374
  const providerInput = config3.provider || config3.vectorStore || "record";
20378
20375
  const vectorStore = providerInput === "record" ? "pgvector" : providerInput;
20379
- const vectorizeConfig = config3.vectorizeConfigId || config3.vectorizeNamespace ? {
20376
+ const vectorizeConfig = config3.vectorizeConfig || (config3.vectorizeConfigId || config3.vectorizeNamespace ? {
20380
20377
  configId: config3.vectorizeConfigId,
20381
20378
  namespace: config3.vectorizeNamespace
20382
- } : void 0;
20383
- const weaviateConfig = config3.weaviateClassName || config3.weaviateConfigId ? {
20379
+ } : void 0);
20380
+ const weaviateConfig = config3.weaviateConfig || (config3.weaviateClassName || config3.weaviateConfigId ? {
20384
20381
  configId: config3.weaviateConfigId,
20385
20382
  className: config3.weaviateClassName || ""
20386
- } : void 0;
20383
+ } : void 0);
20387
20384
  return {
20388
20385
  query: config3.query,
20389
20386
  embeddingModel: config3.embeddingModel,
@@ -20956,6 +20953,9 @@ function sanitizeCodeToolIdentifier(name) {
20956
20953
  if (/^[0-9]/.test(safe)) safe = "_" + safe;
20957
20954
  return safe;
20958
20955
  }
20956
+ function snakeToCamel(str) {
20957
+ return str.replace(/_([a-z])/g, (_2, letter) => letter.toUpperCase());
20958
+ }
20959
20959
  var flowStepValidationSchema = external_exports.object({
20960
20960
  // Optional stable client-supplied identifier. Preserved across saves so that
20961
20961
  // `flow_step_results.stepId` references stay valid and dashboard UI state
@@ -21018,6 +21018,12 @@ var KNOWN_TOOL_KEYS = /* @__PURE__ */ new Set([
21018
21018
  ...Object.keys(CAMEL_CASE_TOOL_KEYS),
21019
21019
  ...Object.keys(SNAKE_CASE_TOOL_KEYS)
21020
21020
  ]);
21021
+ for (const snakeKey of Object.keys(SNAKE_CASE_TOOL_KEYS)) {
21022
+ const camelKey = snakeToCamel(snakeKey);
21023
+ if (!(camelKey in CAMEL_CASE_TOOL_KEYS)) {
21024
+ throw new Error(`No camelCase tool key for snake_case key "${snakeKey}"`);
21025
+ }
21026
+ }
21021
21027
  var LEGACY_TOOL_KEY_SUGGESTIONS = {
21022
21028
  builtinTools: "toolIds"
21023
21029
  };
@@ -21096,28 +21102,28 @@ function formatPath(path20) {
21096
21102
  return acc ? `${acc}.${key}` : key;
21097
21103
  }, "");
21098
21104
  }
21099
- function compareIssuePath(a, b2) {
21100
- if (!a && !b2) return 0;
21105
+ function compareIssuePath(a, b) {
21106
+ if (!a && !b) return 0;
21101
21107
  if (!a) return 1;
21102
- if (!b2) return -1;
21103
- return a.localeCompare(b2);
21108
+ if (!b) return -1;
21109
+ return a.localeCompare(b);
21104
21110
  }
21105
21111
  function sortIssues(issues) {
21106
- return [...issues].sort((a, b2) => {
21112
+ return [...issues].sort((a, b) => {
21107
21113
  const aStepIndex = a.step?.index ?? Number.MAX_SAFE_INTEGER;
21108
- const bStepIndex = b2.step?.index ?? Number.MAX_SAFE_INTEGER;
21114
+ const bStepIndex = b.step?.index ?? Number.MAX_SAFE_INTEGER;
21109
21115
  if (aStepIndex !== bStepIndex) {
21110
21116
  return aStepIndex - bStepIndex;
21111
21117
  }
21112
- const pathCompare = compareIssuePath(a.path, b2.path);
21118
+ const pathCompare = compareIssuePath(a.path, b.path);
21113
21119
  if (pathCompare !== 0) {
21114
21120
  return pathCompare;
21115
21121
  }
21116
- const codeCompare = a.code.localeCompare(b2.code);
21122
+ const codeCompare = a.code.localeCompare(b.code);
21117
21123
  if (codeCompare !== 0) {
21118
21124
  return codeCompare;
21119
21125
  }
21120
- return a.message.localeCompare(b2.message);
21126
+ return a.message.localeCompare(b.message);
21121
21127
  });
21122
21128
  }
21123
21129
  function addIssue(level, issue2, buckets) {
@@ -22749,15 +22755,50 @@ var runtimeArtifactManifestSchema = external_exports.object({
22749
22755
  var KNOWN_FLOW_STEP_TYPES = new Set(FLOW_STEP_TYPES);
22750
22756
  var API_INPROCESS_CAPABILITY_MATRIX = {
22751
22757
  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
22756
- // 2026-07-29.4: api-hosted runtime fulfills managed fetch methods through
22757
- // ManagedFetchExecutor (the managed-fetch fact remains for attribution). The
22758
- // EXPLICIT Layer-2 fallback fold and the remaining parity-audit folds are
22759
- // unchanged.
22760
- version: "2026-07-31.1",
22758
+ // Bumped 2026-08-05.3: graduates `conditionalNestedExecuteAgentStep` to
22759
+ // SUPPORTED (the runtime-conditional-nested-execute-agent leg-2 port): a
22760
+ // conditional-nested `execute-agent` runs on the engine-owned nested path
22761
+ // (the shared `conditionalSubStepExecutor` re-enters `runContextStep`, whose
22762
+ // default engine path dispatches `executeExecuteAgent`), so it no longer folds
22763
+ // to legacy. The fact stays computed for decision attribution. Rollback lever:
22764
+ // revert this bit to `true`.
22765
+ // Bumped 2026-08-05.3: graduates `promptMcpServers` to SUPPORTED (the #6013
22766
+ // fold — the runtime FLOW lane now discovers `config.tools.mcpServers` on
22767
+ // prompt steps via `discoverMCPTools`, exactly like the agent lane, merging
22768
+ // each step's servers' tools into its `config.tools.runtimeTools` before the
22769
+ // prompt runs). The `hasPromptMcpServers` FACT is still computed for
22770
+ // decision attribution but no longer folds. Rollback lever: revert this bit
22771
+ // to `true`.
22772
+ // Bumped 2026-08-05.2: graduates `conditionalNestedPromptStep` to SUPPORTED
22773
+ // (the #6016 leg-1 port routes nested prompt sub-steps through the engine-owned
22774
+ // `runPromptStep` path instead of the portable executor's throw). The
22775
+ // `hasConditionalNestedPromptStep` FACT is still computed for decision
22776
+ // attribution but no longer folds. Rollback lever: revert this bit to `true`.
22777
+ // Bumped 2026-08-05.1: adds the #6023 leg 1 `customToolExecution` fold (a
22778
+ // custom runtime tool requesting code_mode / a non-JS language / a
22779
+ // container-backed sandbox provider the runtime's JS-only executor cannot
22780
+ // honor). Carries forward 2026-08-03: the §A1 `promptCodeModeTools` fold.
22781
+ // Carries forward 2026-07-31: the `unmaterializedPromptToolRefs` fold.
22782
+ // Carries forward 2026-07-30: the IMPLICIT platform-default fallback
22783
+ // candidate no longer folds (see `implicitPlatformFallback` below). Carries
22784
+ // forward 2026-07-29.4: api-hosted runtime fulfills managed fetch methods
22785
+ // through ManagedFetchExecutor (the managed-fetch fact remains for
22786
+ // attribution). The EXPLICIT Layer-2 fallback fold and the remaining
22787
+ // parity-audit folds are unchanged.
22788
+ // Bumped 2026-08-06.1: graduates `promptCodeModeTools` + the
22789
+ // `transformDataCodeModeTools` runtimeTools/toolIds cases (#6013) — the
22790
+ // runtime flow lane synthesizes `code_mode` and runs it (plus transform-data
22791
+ // tool pools) through the host `CodeModeExecutor`
22792
+ // (`SANDBOX.workerLoaderExecuteTransformWithTools`). The
22793
+ // `transformDataCodeModeTools` fact now folds only the `mcpServers` case.
22794
+ // Rollback lever: revert the two bits to `true` (plus their tests).
22795
+ // Bumped 2026-08-06.3: integration re-bump past the .1/.2 collisions — five
22796
+ // #6013/#6016 graduations (advisorTools, transformDataCodeModeTools,
22797
+ // promptCodeModeTools, promptMcpServers, promptArtifacts) landed on
22798
+ // independent branches that each claimed their own suffix, plus the
22799
+ // vendored-export re-fold pass. No bit changes with this bump; it exists so
22800
+ // the combined base carries one unambiguous version.
22801
+ version: "2026-08-06.3",
22761
22802
  unsupportedStepTypes: ["wait-until", "crawl"],
22762
22803
  unsupportedFeatures: {
22763
22804
  approvalSteps: true,
@@ -22765,8 +22806,18 @@ var API_INPROCESS_CAPABILITY_MATRIX = {
22765
22806
  claudeManagedAgent: true,
22766
22807
  inexpressibleVectorStep: true,
22767
22808
  unresolvableAgentRef: true,
22768
- conditionalNestedPromptStep: true,
22769
- conditionalNestedExecuteAgentStep: true,
22809
+ // SUPPORTED as of 2026-08-05 (#6016 leg 1): the runtime flow lane routes a
22810
+ // conditional-nested prompt through the engine-owned `runPromptStep` path
22811
+ // (nested prompt dispatch in flow-engine.ts), so a prompt inside a
22812
+ // conditional branch no longer folds to legacy.
22813
+ conditionalNestedPromptStep: false,
22814
+ // SUPPORTED as of 2026-08-05.3 (runtime-conditional-nested-execute-agent):
22815
+ // the runtime flow lane routes a conditional-nested `execute-agent` through
22816
+ // the engine-owned nested path (`conditionalSubStepExecutor` -> `runContextStep`
22817
+ // -> the default engine dispatch of `executeExecuteAgent`), so an execute-agent
22818
+ // inside a conditional branch no longer folds to legacy. The fact stays
22819
+ // computed for decision attribution. Rollback lever: revert this bit.
22820
+ conditionalNestedExecuteAgentStep: false,
22770
22821
  // SUPPORTED as of 2026-07-23 (slice 6 activation): the runtime flow lane
22771
22822
  // now PAUSES on definition-embedded client-executed (local / webmcp) tools
22772
22823
  // — `ClientToolRequiredError` → `step_await` / `flow_await` → durable KV
@@ -22776,7 +22827,13 @@ var API_INPROCESS_CAPABILITY_MATRIX = {
22776
22827
  // Rollback lever after retiring the flow request override: revert this bit
22777
22828
  // to `true` (the agent lane retains its separate rollout gate).
22778
22829
  clientExecutedTools: false,
22779
- advisorTools: true,
22830
+ // SUPPORTED as of 2026-08-06 (#6013 advisor port): the runtime flow lane
22831
+ // now executes advisor runtime tools server-side via nested model inference
22832
+ // (`RuntimeToolExecutor.runAdvisor`), so an advisor flow stays on the
22833
+ // runtime lane instead of folding to legacy. The `hasAdvisorTools` FACT is
22834
+ // still computed for decision attribution but no longer folds. Rollback
22835
+ // lever: flip this bit back to `true` (plus its test).
22836
+ advisorTools: false,
22780
22837
  // G2 SUPPORTED: api-hosted runtime delegates Firecrawl / Massive fetch-url
22781
22838
  // methods through ManagedFetchExecutor to the same API implementations the
22782
22839
  // legacy executor uses. Keep the fact computed for attribution, like
@@ -22784,10 +22841,48 @@ var API_INPROCESS_CAPABILITY_MATRIX = {
22784
22841
  unsupportedFetchMethod: false,
22785
22842
  // Remaining 2026-07-29 parity-audit BRIDGE folds (G4/G5/G10/G14): feature
22786
22843
  // classes the runtime flow lane still cannot faithfully run.
22787
- transformDataCodeModeTools: true,
22844
+ // SUPPORTED as of 2026-08-06 (#6013): a `transform-data` step whose
22845
+ // `config.tools` carries a runtime tool pool binds those tools through the
22846
+ // host `CodeModeExecutor` (`workerLoaderExecuteTransformWithTools`). The
22847
+ // `mcpServers`-only case STAYS folded via the narrow
22848
+ // `transformDataMcpServers` bit below (the runtime has no MCP discovery on
22849
+ // transform steps, so an MCP tool pool would silently lose its tools).
22850
+ // Rollback lever: revert this bit to `true` (plus its test).
22851
+ transformDataCodeModeTools: false,
22852
+ // #6013 narrow carve-out — the mcpServers-only transform code-mode case.
22853
+ // `transformDataHasCodeModeTools` now fires only on `config.tools.mcpServers`,
22854
+ // and this bit keeps that narrow case routed to legacy while the
22855
+ // runtimeTools/toolIds cases graduate (bit above flipped false).
22856
+ transformDataMcpServers: true,
22788
22857
  unsupportedTransformExecution: true,
22789
- promptMcpServers: true,
22790
- promptArtifacts: true,
22858
+ // #6023 leg 1 (2026-08-05): a custom runtime tool requesting code_mode / a
22859
+ // non-JS language / a container-backed sandbox provider has no runtime-lane
22860
+ // port — `runCustom` ignores all three and silently misexecutes as JS. Same
22861
+ // bridge class as `unsupportedTransformExecution` (G5), at the tool level.
22862
+ customToolExecution: true,
22863
+ // SUPPORTED as of 2026-08-05 (#6013 fold): the runtime FLOW lane now
22864
+ // discovers `config.tools.mcpServers` on prompt steps via `discoverMCPTools`
22865
+ // (mirroring the agent lane's agent-engine.ts wiring) and merges the
22866
+ // discovered tools into each prompt step's `config.tools.runtimeTools`
22867
+ // before it runs. Runtime discovery is the ONLY model-visible schema source
22868
+ // (real `tools/list` schemas + fresh auth — no export-time materialization,
22869
+ // which would ship empty schemas for allowedTools-gated servers). The
22870
+ // `hasPromptMcpServers` FACT is still computed for decision-attribution logs
22871
+ // but no longer folds. Rollback lever: revert this bit to `true`.
22872
+ promptMcpServers: false,
22873
+ // #6013 (G14, 2026-08-06): prompt-step artifact emission is ported to the
22874
+ // runtime lane (injection + emit_artifact_* execution + artifact_* frame
22875
+ // emission + strip). `hasPromptArtifacts` stays computed for decision
22876
+ // attribution. Rollback lever: set this back to `true` (plus its test).
22877
+ promptArtifacts: false,
22878
+ // SUPPORTED as of 2026-08-06 (#6013): the runtime flow lane synthesizes
22879
+ // the `code_mode` tool (byte-identical description/schema to legacy via the
22880
+ // shared builders) and executes it through the host `CodeModeExecutor`.
22881
+ // The `hasPromptCodeModeTools` FACT is still computed (for decision
22882
+ // attribution) but no longer folds. A pool referencing an unmaterialized
22883
+ // class still folds via the separate `unmaterializedPromptToolRefs` fact.
22884
+ // Rollback lever: revert this bit to `true` (plus its test).
22885
+ promptCodeModeTools: false,
22791
22886
  // SUPPORTED as of the fallback-chain port: the runtime flow engine now
22792
22887
  // executes EXPLICIT author-configured Layer-2 chains and synthesizes their
22793
22888
  // `usedFallback` / `fallbackModel` / `fallbackExecutions` attribution, so
@@ -22832,6 +22927,180 @@ var API_DURABLE_RESUME_CAPABILITY_MATRIX = {
22832
22927
  (stepType) => !DURABLE_HOSTED_STEP_TYPES.has(stepType)
22833
22928
  )
22834
22929
  };
22930
+ var VENDORED_EXPORT_CAPABILITY_MATRIX = {
22931
+ ...API_INPROCESS_CAPABILITY_MATRIX,
22932
+ target: "vendored-export",
22933
+ // Bumped 2026-08-06.3: one-pass re-decision of the restated fold block after
22934
+ // the five #6013/#6016 api-inprocess graduations (advisorTools,
22935
+ // transformDataCodeModeTools, promptCodeModeTools, promptMcpServers,
22936
+ // promptArtifacts) plus `conditionalNestedExecuteAgentStep`. Each restated
22937
+ // literal was re-classified against this file's own criterion — ENGINE-owned
22938
+ // (a self-contained container runs it) inherits the base `false`; HOST-SEAM
22939
+ // (fulfilled only by an api-wired optional executor a vendored container
22940
+ // lacks) becomes a documented entry in {@link VENDORED_EXPORT_REFOLDS}. The
22941
+ // two CodeModeExecutor-backed bits re-fold; the other four graduate here too.
22942
+ // Bumped 2026-08-06.2: re-folds `unsupportedFetchMethod` (see
22943
+ // VENDORED_EXPORT_REFOLDS) — api-inprocess supports managed fetch methods
22944
+ // only because the api host wires `ManagedFetchExecutor`; no export bundle
22945
+ // does, so a firecrawl/massive fetch-url step fails as-shipped.
22946
+ version: "2026-08-06.3",
22947
+ unsupportedStepTypes: [
22948
+ // ── Carried over from api-inprocess: durable-host-only step types. A
22949
+ // self-contained container has no durable host (BYOC §3.3 / S0 — the
22950
+ // exported runtime's `waitUntil` seam is unset; crawl needs the
22951
+ // `CrawlPendingError` durable pause). Graduation lever: wire a durable
22952
+ // store in the export (e.g. a Cloud SQL CheckpointStore) — then flip.
22953
+ "wait-until",
22954
+ "crawl",
22955
+ // ── Hosted-service / DB-backed record & email steps (BYOC §7.2). A
22956
+ // self-contained container has no hosted RecordStore / EmailSender; the
22957
+ // Hosted endpoints are PROPOSED, not built, and S0 shows send-email /
22958
+ // record steps fail in BOTH default and wired configs (no Bundled mode).
22959
+ // Graduation lever: build the Hosted endpoints OR ship a Bundled
22960
+ // RecordStore/EmailSender in the standard export — then remove.
22961
+ "send-email",
22962
+ "upsert-record",
22963
+ "update-record",
22964
+ "retrieve-record",
22965
+ "get-record",
22966
+ "list-records",
22967
+ "search",
22968
+ // ── Vector DB / embedding provider steps (BYOC §3.4 / §7.4). Only a
22969
+ // customer-wired VectorStore / EmbeddingProvider can host these; the
22970
+ // container ships neither. Graduation lever: bundle a pgvector
22971
+ // VectorStore + a provider-backed EmbeddingProvider in the export.
22972
+ "generate-embedding",
22973
+ "vector-search",
22974
+ "store-vector",
22975
+ // ── Hosted asset / PDF service steps (BYOC §7.2). store-asset /
22976
+ // generate-pdf are Hosted-only; no Bundled fulfillment. Graduation lever:
22977
+ // build the Hosted asset/PDF endpoints or ship a Bundled renderer/store.
22978
+ "store-asset",
22979
+ "generate-pdf",
22980
+ // ── Hosted memory-store steps (BYOC §3.4 / §7.2). Memory has Hosted/Custom
22981
+ // only, no Bundled mode. Graduation lever: a Bundled MemoryStore seam in
22982
+ // the export (or the Hosted memory endpoints).
22983
+ "save-memory",
22984
+ "recall-memory",
22985
+ "memory-summary",
22986
+ // ── template & transform-data: FAIL AS-SHIPPED (S0 §5.2.1 / §5.2.2). The
22987
+ // export does NOT bundle liquidjs / QuickJS, so a self-contained container
22988
+ // throws `TemplateRenderer not configured` / `SandboxNotConfiguredError`
22989
+ // out of the box; they only PASS once the container wires the Bundled
22990
+ // fulfillment (LiquidTemplateRenderer + QuickJSSafeCodeExecutor). Per the
22991
+ // fail-closed / keep-gates-truthful principle these stay UNSUPPORTED for
22992
+ // this v1. Graduation lever: bundle liquidjs + QuickJS as part of the
22993
+ // STANDARD export (default-wire the renderer and sandbox) — then flip both
22994
+ // to supported.
22995
+ "template",
22996
+ "transform-data"
22997
+ ],
22998
+ // Every api-inprocess feature fold carries over (shared engine, derived by
22999
+ // spreading the base). Each is restated below with its evidence + graduation
23000
+ // lever so the contract is self-documenting; values are pinned to the
23001
+ // api-inprocess semantics a container inherits, never loosened — except the
23002
+ // vendored-specific RE-FOLDS enumerated in {@link VENDORED_EXPORT_REFOLDS},
23003
+ // which are strictly stricter.
23004
+ unsupportedFeatures: {
23005
+ ...API_INPROCESS_CAPABILITY_MATRIX.unsupportedFeatures,
23006
+ approvalSteps: true,
23007
+ // api-inprocess fold; the runtime flow engine derives no approval config. Graduation: port the approval rail.
23008
+ batchInputMode: true,
23009
+ // api-inprocess fold; batch has no conversational context (BYOC §3.2).
23010
+ claudeManagedAgent: true,
23011
+ // api-inprocess fold; exported execute-agent rejects claude_managed/external (BYOC §3.6, D-030/D-031).
23012
+ inexpressibleVectorStep: true,
23013
+ // api-inprocess fold; no vector seam in a self-contained container.
23014
+ unresolvableAgentRef: true,
23015
+ // api-inprocess fold; execute-agent resolves only against the embedded registry (ADR 0014).
23016
+ // Nested-prompt dispatch is ENGINE-owned and works identically in a
23017
+ // container, so this stays SUPPORTED (false) exactly as api-inprocess has
23018
+ // it — a container does not re-fold what the engine runs itself.
23019
+ conditionalNestedPromptStep: false,
23020
+ // Conditional-nested `execute-agent` dispatch is ENGINE-owned exactly like
23021
+ // nested prompt above (`conditionalSubStepExecutor` -> `runContextStep` ->
23022
+ // `executeExecuteAgent`), so it inherits the base SUPPORTED (`false`) from
23023
+ // the spread. NOT restated as a literal: the 2026-08-06.3 re-decision pass
23024
+ // exists because a restated literal went stale when the base graduated.
23025
+ // Client-executed (local/webmcp) tools PAUSE natively on the runtime flow
23026
+ // lane; a self-contained container still pauses on them, so SUPPORTED
23027
+ // (false) — carried over verbatim.
23028
+ clientExecutedTools: false,
23029
+ // `advisorTools` inherits the base SUPPORTED (`false`): `RuntimeToolExecutor
23030
+ // .runAdvisor` resolves the advisor model through `PROVIDER_REGISTRY` +
23031
+ // `adapter.getSecret`/`getBinding` — the same machinery every prompt step
23032
+ // already uses — so a container that runs prompts runs advisors. No host
23033
+ // seam involved.
23034
+ // VENDORED RE-FOLD (not carried over): api-inprocess marks managed fetch
23035
+ // methods SUPPORTED (false) only because the api host wires
23036
+ // `ManagedFetchExecutor` — the seam exists precisely because the portable
23037
+ // runtime cannot own Firecrawl / Massive credentials, rollout gates, or
23038
+ // platform-spend metering. No export bundle wires it (the only
23039
+ // implementation is `ApiManagedFetchExecutor`, wired solely by
23040
+ // `apps/api/src/lib/runtime/playground-runtime.ts`), so a `fetch-url` step
23041
+ // with `fetchMethod: 'firecrawl' | 'massive'` falls through to the portable
23042
+ // base's not-supported error — and under the default `errorHandling:
23043
+ // 'continue'` that failure is SWALLOWED and downstream steps see null.
23044
+ // Declaring such a flow container-eligible is exactly the silent-misexecution
23045
+ // class the fail-closed posture (which folded template / transform-data for
23046
+ // the identical "passes only when hand-wired" reason) exists to prevent.
23047
+ // Graduation lever: ship a Bundled managed-fetch fulfillment in the standard
23048
+ // export (direct provider-credential fetch, or a hosted managed-fetch
23049
+ // endpoint) — then flip back to false and drop it from
23050
+ // {@link VENDORED_EXPORT_REFOLDS}. Plain `fetch-url` (no managed method)
23051
+ // stays supported; only the managed methods fold.
23052
+ unsupportedFetchMethod: true,
23053
+ // VENDORED RE-FOLD (not carried over): api-inprocess graduated a
23054
+ // `transform-data` step's runtimeTools/toolIds pool (#6013) only because the
23055
+ // api host wires `ApiCodeModeExecutor` → `SANDBOX
23056
+ // .workerLoaderExecuteTransformWithTools`. The seam exists precisely because
23057
+ // NONE of the runtime's four shipped `SafeCodeExecutor`s can bind pool tools
23058
+ // to sandboxed code, so an unwired container throws
23059
+ // `CodeModeExecutorNotConfiguredError` (`runtime-context-step-executor.ts`
23060
+ // fails closed on the transform-data path). Graduation lever: ship a Bundled
23061
+ // code-with-tools fulfillment in the standard export — then flip to false and
23062
+ // drop from {@link VENDORED_EXPORT_REFOLDS}.
23063
+ transformDataCodeModeTools: true,
23064
+ // The narrow mcpServers-only transform carve-out (#6013) is a base fold;
23065
+ // carried over as `true` and restated for the same reason (no MCP discovery
23066
+ // on transform steps).
23067
+ transformDataMcpServers: true,
23068
+ unsupportedTransformExecution: true,
23069
+ // api-inprocess fold (G5); carried over.
23070
+ customToolExecution: true,
23071
+ // api-inprocess fold (#6023 leg 1); carried over.
23072
+ // `promptMcpServers` inherits the base SUPPORTED (`false`). The runtime owns
23073
+ // MCP end to end for the shipped default transport: `discoverMCPTools` falls
23074
+ // back to its own `listServerTools` over `adapter.fetch` when no host
23075
+ // `MCPToolExecutor` is present, and `RuntimeToolExecutor.runMCP` has a
23076
+ // portable Streamable-HTTP JSON-RPC dispatch path on the same fallback. Only
23077
+ // `transport: 'rest'` requires the host executor, and that is a per-server
23078
+ // authoring choice this flow-level bit cannot express — the agent lane makes
23079
+ // the identical bet in a container today.
23080
+ // `promptArtifacts` inherits the base SUPPORTED (`false`): artifact emission
23081
+ // is pure `UnifiedEventEmitter` frame production plus builtin-tool injection
23082
+ // and strip, entirely inside the engine. (Persisting an artifact to hosted
23083
+ // storage is the separate `store-asset` STEP TYPE, which stays folded above.)
23084
+ // VENDORED RE-FOLD (not carried over): api-inprocess graduated a PROMPT
23085
+ // step's `codeModeConfig.toolPool` (#6013) on the same `ApiCodeModeExecutor`
23086
+ // seam as `transformDataCodeModeTools` above. The runtime synthesizes the
23087
+ // `code_mode` tool byte-identically, but firing it without a host executor
23088
+ // throws `CodeModeExecutorNotConfiguredError` (`tool-executor.ts` fails
23089
+ // closed rather than silently degrading the pool to plain model tools).
23090
+ // Under the default `errorHandling: 'continue'` that failure is swallowed —
23091
+ // the same silent-misexecution class the fail-closed posture exists to
23092
+ // prevent. Same graduation lever as the transform-data bit.
23093
+ promptCodeModeTools: true,
23094
+ // Explicit Layer-2 fallback chains are SUPPORTED (false) on the runtime
23095
+ // lane, engine-owned, so a container runs them — carried over verbatim.
23096
+ fallbackErrorHandling: false,
23097
+ // Implicit platform-default fallback SUPPORTED (false) — engine-owned
23098
+ // resilience; carried over verbatim (a container is not less capable).
23099
+ implicitPlatformFallback: false,
23100
+ unmaterializedPromptToolRefs: true
23101
+ // api-inprocess fold (§A1); carried over.
23102
+ }
23103
+ };
22835
23104
  var edgeAuthSnapshotSchema = external_exports.object({
22836
23105
  /**
22837
23106
  * Schema version. A plain positive int (not a literal) so a consumer pinned
@@ -37812,7 +38081,7 @@ var CORE_BUILTIN_TOOLS_REGISTRY = [
37812
38081
  {
37813
38082
  id: "sandbox:exec",
37814
38083
  name: "Sandbox Exec",
37815
- description: "Run a shell command in a Linux sandbox (Node 22, Python 3.12, git, pnpm). The sandbox persists across tool calls within the same execution \u2014 install packages, write files, then run them. Returns stdout, stderr, and exit code.",
38084
+ description: "Run a shell command in a Linux sandbox (Node 22, Python 3.12, git, pnpm). Commands run in /workspace; installed packages and files you write there stay available to later calls in the same execution, but the working directory does not carry over \u2014 every call starts in /workspace again. Chain a directory change inside one command (`cd app && npm test`) or use absolute paths; a lone `cd` does nothing. Returns stdout, stderr, and exit code.",
37816
38085
  category: BuiltInToolCategory.SANDBOX,
37817
38086
  toolGroup: BuiltInToolGroup.SANDBOX_USE,
37818
38087
  providers: [BuiltInToolProvider.MULTI],
@@ -37821,7 +38090,7 @@ var CORE_BUILTIN_TOOLS_REGISTRY = [
37821
38090
  properties: {
37822
38091
  command: {
37823
38092
  type: "string",
37824
- description: "Shell command to execute (runs in bash)"
38093
+ description: "Shell command to execute (runs in bash, cwd is /workspace)."
37825
38094
  },
37826
38095
  timeout: {
37827
38096
  type: "number",
@@ -37863,7 +38132,7 @@ var CORE_BUILTIN_TOOLS_REGISTRY = [
37863
38132
  {
37864
38133
  id: "sandbox:write_file",
37865
38134
  name: "Sandbox Write File",
37866
- description: "Write a file to the sandbox filesystem. Creates parent directories automatically. Use sandbox:exec to run files after writing them.",
38135
+ description: "Write a file to the sandbox filesystem. Creates parent directories automatically. Relative paths resolve against /workspace, the directory every sandbox call starts in. Files written there stay available to later calls in the same execution. Use sandbox:exec to run files after writing them.",
37867
38136
  category: BuiltInToolCategory.SANDBOX,
37868
38137
  toolGroup: BuiltInToolGroup.SANDBOX_USE,
37869
38138
  providers: [BuiltInToolProvider.MULTI],
@@ -37872,7 +38141,7 @@ var CORE_BUILTIN_TOOLS_REGISTRY = [
37872
38141
  properties: {
37873
38142
  path: {
37874
38143
  type: "string",
37875
- description: "File path in the sandbox (e.g., /home/user/app/index.js)"
38144
+ description: "File path in the sandbox (e.g. /workspace/app/index.js, or app/index.js relative to /workspace)"
37876
38145
  },
37877
38146
  content: {
37878
38147
  type: "string",
@@ -37888,7 +38157,7 @@ var CORE_BUILTIN_TOOLS_REGISTRY = [
37888
38157
  {
37889
38158
  id: "sandbox:read_file",
37890
38159
  name: "Sandbox Read File",
37891
- description: "Read a file from the sandbox filesystem. Returns the file content as a string.",
38160
+ description: "Read a file from the sandbox filesystem. Relative paths resolve against /workspace, the directory every sandbox call starts in. Returns the file content as a string.",
37892
38161
  category: BuiltInToolCategory.SANDBOX,
37893
38162
  toolGroup: BuiltInToolGroup.SANDBOX_USE,
37894
38163
  providers: [BuiltInToolProvider.MULTI],
@@ -37897,7 +38166,7 @@ var CORE_BUILTIN_TOOLS_REGISTRY = [
37897
38166
  properties: {
37898
38167
  path: {
37899
38168
  type: "string",
37900
- description: "File path to read"
38169
+ description: "File path to read (relative paths resolve against /workspace)"
37901
38170
  }
37902
38171
  },
37903
38172
  required: ["path"]
@@ -37934,7 +38203,7 @@ var CORE_BUILTIN_TOOLS_REGISTRY = [
37934
38203
  {
37935
38204
  id: "sandbox:git_checkout",
37936
38205
  name: "Sandbox Git Checkout",
37937
- description: "Clone a git repository into the sandbox. The repo is cloned into the current working directory.",
38206
+ description: "Clone a git repository into the sandbox. The repo is cloned under /workspace, the directory every sandbox call starts in; reach it afterward with an explicit path (`cd <repo> && ...`), since the working directory does not carry over between calls.",
37938
38207
  category: BuiltInToolCategory.SANDBOX,
37939
38208
  toolGroup: BuiltInToolGroup.SANDBOX_USE,
37940
38209
  providers: [BuiltInToolProvider.MULTI],
@@ -37983,7 +38252,7 @@ var CORE_BUILTIN_TOOLS_REGISTRY = [
37983
38252
  {
37984
38253
  id: "sandbox:session_exec",
37985
38254
  name: "Sandbox Session Exec",
37986
- description: "Run a shell command in a specific sandbox identified by sandboxId.",
38255
+ description: "Run a shell command in a specific sandbox identified by sandboxId. Commands run in /workspace; files stay available across calls but the working directory does not carry over \u2014 every call starts in /workspace again, so chain a directory change inside one command (`cd app && npm test`) or use absolute paths.",
37987
38256
  category: BuiltInToolCategory.SANDBOX,
37988
38257
  toolGroup: BuiltInToolGroup.SANDBOX_SESSION,
37989
38258
  providers: [BuiltInToolProvider.MULTI],
@@ -37996,7 +38265,7 @@ var CORE_BUILTIN_TOOLS_REGISTRY = [
37996
38265
  },
37997
38266
  command: {
37998
38267
  type: "string",
37999
- description: "Shell command to execute"
38268
+ description: "Shell command to execute (runs in bash, cwd is /workspace)."
38000
38269
  },
38001
38270
  timeout: {
38002
38271
  type: "number",
@@ -38185,7 +38454,7 @@ var CORE_BUILTIN_TOOLS_REGISTRY = [
38185
38454
  {
38186
38455
  id: "bash",
38187
38456
  name: "Bash",
38188
- description: "Run a shell command on your Linux computer (Node 22, Python 3.12, git, pnpm, uv, ripgrep preinstalled). Commands run in /workspace; files you write there are available to later commands, but system-level changes outside /workspace may not persist. Combined stdout/stderr is returned. Prefer searching over dumping: use `rg`/`grep` to find the lines you need and `head`/`tail`/`sed -n` to read slices. Output is capped. If the command is still running at timeout_ms, it is NOT killed: bash returns a durable process_id and partial output. When the result has a deliveryId, pass it as ack_delivery_id on the next bash_output poll so newer output can advance. Poll only new output with bash_output, stop it with kill_process, or inspect handles with list_processes. Use run_in_background=true to yield immediately.",
38457
+ description: "Run a shell command on your Linux computer (Node 22, Python 3.12, git, pnpm, uv, ripgrep preinstalled). Commands run in /workspace; files you write there are available to later commands, but system-level changes outside /workspace may not persist. Combined stdout/stderr is returned. Prefer searching over dumping: use `rg`/`grep` to find the lines you need and `head`/`tail`/`sed -n` to read slices. Output is capped. If the command is still running at timeout_ms, it is NOT killed: bash returns a durable process_id and partial output. When the result has a deliveryId, pass it as ack_delivery_id on the next bash_output poll so newer output can advance. Read only new output with bash_output (pass its wait_for_exit_ms to wait for the process rather than polling in a loop), stop it with kill_process, or inspect handles with list_processes. Use run_in_background=true to yield immediately.",
38189
38458
  category: BuiltInToolCategory.SANDBOX,
38190
38459
  toolGroup: BuiltInToolGroup.SANDBOX_AGENT,
38191
38460
  providers: [BuiltInToolProvider.MULTI],
@@ -38227,7 +38496,7 @@ var CORE_BUILTIN_TOOLS_REGISTRY = [
38227
38496
  {
38228
38497
  id: "bash_output",
38229
38498
  name: "Bash Output",
38230
- description: "Read only the new combined stdout/stderr produced after the last acknowledged delivery of a background bash process. Pass the previous successful bash or bash_output result's deliveryId as ack_delivery_id on the next poll; unacknowledged output is replayed so an API timeout cannot lose it. Acknowledge a terminal result's final delivery with one more poll so its bounded history record can retire. Returns status and an actual exitCode only after the process is terminal. Output is bounded and untrusted.",
38499
+ description: "Read only the new combined stdout/stderr produced after the last acknowledged delivery of a background bash process. Do NOT poll in a tight loop: pass wait_for_exit_ms to wait server-side for the process to finish, so one call replaces many. Pass the previous successful bash or bash_output result's deliveryId as ack_delivery_id on the next poll; unacknowledged output is replayed so an API timeout cannot lose it. Acknowledge a terminal result's final delivery with one more poll so its bounded history record can retire. Returns status and an actual exitCode only after the process is terminal. Output is bounded and untrusted.",
38231
38500
  category: BuiltInToolCategory.SANDBOX,
38232
38501
  toolGroup: BuiltInToolGroup.SANDBOX_AGENT,
38233
38502
  providers: [BuiltInToolProvider.MULTI],
@@ -38246,6 +38515,10 @@ var CORE_BUILTIN_TOOLS_REGISTRY = [
38246
38515
  description: "deliveryId from the most recent successful bash or bash_output result for this process. Acknowledges that batch before reading newer output. Omit when no deliveryId has been received.",
38247
38516
  minLength: 1,
38248
38517
  maxLength: 64
38518
+ },
38519
+ wait_for_exit_ms: {
38520
+ type: "number",
38521
+ description: "Milliseconds to wait for the process to exit before returning. Use this instead of repeated polling when you expect the command to finish soon: it returns as soon as the process exits, or immediately if output is already waiting or the process has already finished. It waits for EXIT, so a process that prints progress as it goes still returns only at exit or at this deadline. Clamped to at most 240000 and to the time left in the turn; defaults to 0 (return whatever is available now)."
38249
38522
  }
38250
38523
  },
38251
38524
  required: ["process_id"]
@@ -45043,7 +45316,7 @@ var FLOW_STEP_TYPE_METADATA = {
45043
45316
  configHints: "recordId, recordType, recordName, recordFilter ({ type, where: { field, op, value } }), outputVariable (returns one object \u2014 access as {{var.field}})"
45044
45317
  },
45045
45318
  "list-records": {
45046
- description: "Load an ARRAY of records from the Runtype record store by type, name, or a chip-style recordFilter (metadata + top-level columns: id, name, createdAt, updatedAt), ordered by updated_at desc. Always returns an array \u2014 even for a single match \u2014 so index it in templates ({{var.0.field}}). Default limit 50 (max 1000).",
45319
+ description: "Load an ARRAY of records from the Runtype record store by type, name, or a chip-style recordFilter (metadata + top-level columns: id, name, createdAt, updatedAt, schemaValid), ordered by updated_at desc. Always returns an array \u2014 even for a single match \u2014 so index it in templates ({{var.0.field}}). Default limit 50 (max 1000).",
45047
45320
  category: "data",
45048
45321
  isPrompt: false,
45049
45322
  configHints: "recordType, recordName, recordFilter ({ type, where: { field, op, value } }), limit (default 50, max 1000), onEmpty (succeed|fail), outputVariable (returns an array \u2014 index as {{var.0.field}})"
@@ -45830,7 +46103,7 @@ var TOOL_CATALOG_FOR_FLOW_GENERATION = (() => {
45830
46103
  const toolName = tool.id.replace(`orthogonal:${slug}:`, "");
45831
46104
  vendorGroups.get(slug).push(toolName);
45832
46105
  }
45833
- const orthogonalLines = Array.from(vendorGroups.entries()).sort(([a], [b2]) => a.localeCompare(b2)).map(([slug, tools]) => {
46106
+ const orthogonalLines = Array.from(vendorGroups.entries()).sort(([a], [b]) => a.localeCompare(b)).map(([slug, tools]) => {
45834
46107
  const vendorName = ORTHOGONAL_API_NAMES[slug] ?? slug;
45835
46108
  return `- **${vendorName}** (\`platform:orthogonal:${slug}:<tool>\`): ${tools.join(", ")}`;
45836
46109
  });
@@ -46016,7 +46289,7 @@ var FLOW_GENERATION_GUIDE = `## Flow Generation Guide
46016
46289
  - **conditional**: Branch logic. Either the binary shape (condition (JS expression), trueSteps, falseSteps) or N-way named branches (branches: [{ id, name, condition, steps }], evaluated first-match-wins, with otherwiseSteps as the fallback). Set outputVariable to merge whichever branch ran into one named result.
46017
46290
  - **fetch-url**: HTTP request. Config: http (url, method, headers, body), responseType, outputVariable. Optional fetchMethod: 'firecrawl' (structured extraction) or 'massive' (JS-rendered/blocked pages, with massive: { format, country, delay, expiration }) instead of a raw fetch
46018
46291
  - **api-call**: Structured API call. Config: http, auth, responseMapping, outputVariable
46019
- - **get-record**: Load a SINGLE record OBJECT. Config: recordId, OR recordType + recordName, OR recordFilter ({ type, where: { field, op, value } }) for richer metadata-aware queries; outputVariable. Reachable filter columns include id, name, createdAt, updatedAt plus any metadata key. Returns one object \u2014 access fields directly in templates (\`{{record.field}}\`). On multiple matches the first by updated_at desc wins; fails if none match.
46292
+ - **get-record**: Load a SINGLE record OBJECT. Config: recordId, OR recordType + recordName, OR recordFilter ({ type, where: { field, op, value } }) for richer metadata-aware queries; outputVariable. Reachable filter columns include id, name, createdAt, updatedAt, schemaValid (the collection-validation stamp) plus any metadata key. Returns one object \u2014 access fields directly in templates (\`{{record.field}}\`). On multiple matches the first by updated_at desc wins; fails if none match.
46020
46293
  - **list-records**: Load an ARRAY of records. Config: recordType, recordName, OR recordFilter ({ type, where: { field, op, value } }); limit (default 50, max 1000), onEmpty (succeed|fail, default succeed), outputVariable. Ordered by updated_at desc. Always writes an array \u2014 even for a single match \u2014 so index it in templates (\`{{records.0.field}}\` or \`{{records[0].field}}\`); object-style access (\`{{records.field}}\`) on the array resolves to undefined.
46021
46294
  - **retrieve-record**: DEPRECATED \u2014 use get-record (single object) or list-records (array). Still accepted at write and aliased at execution onto one of them; its return shape is inferred from the lookup method (recordId \u2192 object, type/name/filter \u2192 array), which is the ambiguity the successors remove.
46022
46295
  - **upsert-record**: Create/update a record keyed by \`(recordType, recordName)\` per owner. Config: recordType, **recordName** (REQUIRED for upsert semantics \u2014 without it each run creates a fresh \`\${recordType}-\${Date.now()}\` record), sourceVariable (the JSON metadata payload only \u2014 do NOT wrap as \`{ name, type, metadata }\`; the wrapper gets stored verbatim), outputVariable. See "Record-Keyed Upsert Patterns" in the build-product instructions for the full anti-pattern list (silent timestamped fallback, wrapped-source footgun, JSONB-blob aggregate races).
@@ -46845,7 +47118,15 @@ var FlowInputSchema = external_exports.object({
46845
47118
  name: external_exports.string().min(1).optional(),
46846
47119
  description: external_exports.string().optional(),
46847
47120
  steps: external_exports.array(external_exports.any()).optional(),
46848
- contentHash: external_exports.string().length(64).optional()
47121
+ contentHash: external_exports.string().length(64).optional(),
47122
+ // An inline/virtual flow may embed an agent registry (an `agents` map,
47123
+ // mirroring `ExportedFlowDefinition.agents`) so the lane-routing eligibility
47124
+ // analyzer and the runtime leg can resolve `execute-agent` refs against it
47125
+ // instead of folding a resolvable embedded ref to legacy (or failing with
47126
+ // AGENT_NOT_RESOLVED at execution). Optional and backward-compatible: flows
47127
+ // without embedded agents omit it, and the values pass through verbatim so
47128
+ // the full ExportedAgent shape survives the schema boundary.
47129
+ agents: external_exports.record(external_exports.string(), external_exports.any()).optional()
46849
47130
  }).refine(
46850
47131
  (data) => {
46851
47132
  const hasFlowId = !!data.id;
@@ -47384,7 +47665,12 @@ var RuntimeStoredRecordSchema = external_exports.object({
47384
47665
  userId: external_exports.string(),
47385
47666
  organizationId: external_exports.string().nullable(),
47386
47667
  createdAt: external_exports.string(),
47387
- updatedAt: external_exports.string()
47668
+ updatedAt: external_exports.string(),
47669
+ metadataSchema: external_exports.record(external_exports.string(), external_exports.unknown()).nullable().optional(),
47670
+ metadataLabels: external_exports.record(external_exports.string(), external_exports.string()).nullable().optional(),
47671
+ schemaValid: external_exports.boolean().nullable().optional(),
47672
+ messages: external_exports.array(external_exports.object({ role: external_exports.string(), content: external_exports.string() })).nullable().optional(),
47673
+ productSurfaceId: external_exports.string().nullable().optional()
47388
47674
  });
47389
47675
  var FILTER_FIELD_NAME_RE = /^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,63}$/;
47390
47676
  var runtimeRecordFilterConditionSchema = external_exports.object({
@@ -47704,6 +47990,167 @@ var appDataGrantSchema = external_exports.object({
47704
47990
  // this field directly.
47705
47991
  writePolicy: external_exports.enum(["app", "creator"]).optional()
47706
47992
  });
47993
+ var APP_CSP_DIRECTIVES = [
47994
+ "default-src",
47995
+ "script-src",
47996
+ "script-src-elem",
47997
+ "script-src-attr",
47998
+ "style-src",
47999
+ "style-src-elem",
48000
+ "style-src-attr",
48001
+ "img-src",
48002
+ "media-src",
48003
+ "font-src",
48004
+ "connect-src",
48005
+ "frame-src",
48006
+ "child-src",
48007
+ "worker-src",
48008
+ "object-src",
48009
+ "manifest-src",
48010
+ "form-action",
48011
+ "base-uri",
48012
+ "frame-ancestors"
48013
+ ];
48014
+ var APP_CSP_KEYWORD_SOURCES = [
48015
+ "'self'",
48016
+ "'none'",
48017
+ "'unsafe-inline'",
48018
+ "'unsafe-eval'",
48019
+ "'wasm-unsafe-eval'",
48020
+ "'strict-dynamic'",
48021
+ "'report-sample'"
48022
+ ];
48023
+ var APP_CSP_SCHEME_SOURCES = ["https:", "data:", "blob:", "wss:", "mediastream:"];
48024
+ var APP_CSP_HOST_SOURCE_PATTERN = /^(https|wss):\/\/(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*(:\d{1,5})?$/i;
48025
+ var APP_CSP_LIMITS = {
48026
+ maxSourcesPerDirective: 20,
48027
+ sourceMaxLength: 256
48028
+ };
48029
+ var APP_RESPONSE_HEADER_LIMITS = {
48030
+ maxEntries: 20,
48031
+ nameMaxLength: 128,
48032
+ valueMaxLength: 1024
48033
+ };
48034
+ var APP_RESPONSE_HEADER_NAME_PATTERN = /^[a-zA-Z0-9-]+$/;
48035
+ var APP_DENIED_RESPONSE_HEADERS = {
48036
+ "content-security-policy": 'Use the manifest "csp" field instead.',
48037
+ "content-type": "Content types are inferred from the file extension.",
48038
+ "content-length": "Runtype sets transport headers for the served response.",
48039
+ "content-encoding": "Runtype sets transport headers for the served response.",
48040
+ "transfer-encoding": "Runtype sets transport headers for the served response.",
48041
+ connection: "Runtype sets transport headers for the served response.",
48042
+ etag: "The ETag is derived from the stored bundle file.",
48043
+ "cache-control": "Runtype owns caching so activating an older version takes effect immediately.",
48044
+ "set-cookie": "Apps authenticate through the injected client token, not cookies.",
48045
+ "x-robots-tag": "Indexing follows the app's visibility setting.",
48046
+ "x-content-type-options": "Runtype always sends nosniff.",
48047
+ "strict-transport-security": "HSTS is set for the whole serving domain.",
48048
+ location: "Served bundle files are static content and never redirect."
48049
+ };
48050
+ function isAllowedAppCspDirective(name) {
48051
+ return APP_CSP_DIRECTIVES.includes(name);
48052
+ }
48053
+ function isValidAppCspSource(source) {
48054
+ if (source.length === 0 || source.length > APP_CSP_LIMITS.sourceMaxLength) return false;
48055
+ if (APP_CSP_KEYWORD_SOURCES.includes(source)) return true;
48056
+ if (APP_CSP_SCHEME_SOURCES.includes(source)) return true;
48057
+ return APP_CSP_HOST_SOURCE_PATTERN.test(source);
48058
+ }
48059
+ function appResponseHeaderDenialReason(name) {
48060
+ return APP_DENIED_RESPONSE_HEADERS[name.toLowerCase()] ?? null;
48061
+ }
48062
+ var APP_CSP_SOURCE_HELP = `Use a quoted keyword (${APP_CSP_KEYWORD_SOURCES.join(
48063
+ ", "
48064
+ )}), a scheme (${APP_CSP_SCHEME_SOURCES.join(", ")}), or an https/wss origin such as https://cdn.example.com`;
48065
+ var appCspOverridesSchema = external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).superRefine((overrides, ctx) => {
48066
+ for (const [directive, sources] of Object.entries(overrides)) {
48067
+ if (!isAllowedAppCspDirective(directive)) {
48068
+ ctx.addIssue({
48069
+ code: "custom",
48070
+ path: [directive],
48071
+ message: `Unsupported CSP directive "${directive}". Allowed directives: ${APP_CSP_DIRECTIVES.join(", ")}.`
48072
+ });
48073
+ continue;
48074
+ }
48075
+ if (sources.length === 0) {
48076
+ ctx.addIssue({
48077
+ code: "custom",
48078
+ path: [directive],
48079
+ message: `CSP directive "${directive}" needs at least one source. Use "'none'" to block everything.`
48080
+ });
48081
+ continue;
48082
+ }
48083
+ if (sources.length > APP_CSP_LIMITS.maxSourcesPerDirective) {
48084
+ ctx.addIssue({
48085
+ code: "custom",
48086
+ path: [directive],
48087
+ message: `CSP directive "${directive}" has ${sources.length} sources, which exceeds the ${APP_CSP_LIMITS.maxSourcesPerDirective}-source limit.`
48088
+ });
48089
+ continue;
48090
+ }
48091
+ for (const [index, source] of sources.entries()) {
48092
+ if (source.length > APP_CSP_LIMITS.sourceMaxLength) {
48093
+ ctx.addIssue({
48094
+ code: "custom",
48095
+ path: [directive, index],
48096
+ message: `CSP source in "${directive}" exceeds the ${APP_CSP_LIMITS.sourceMaxLength}-character limit.`
48097
+ });
48098
+ continue;
48099
+ }
48100
+ if (!isValidAppCspSource(source)) {
48101
+ ctx.addIssue({
48102
+ code: "custom",
48103
+ path: [directive, index],
48104
+ message: `CSP directive "${directive}" has an unsupported source "${source}". ${APP_CSP_SOURCE_HELP}.`
48105
+ });
48106
+ }
48107
+ }
48108
+ }
48109
+ });
48110
+ var appResponseHeaderOverridesSchema = external_exports.record(external_exports.string(), external_exports.string()).superRefine((headers, ctx) => {
48111
+ const entries = Object.entries(headers);
48112
+ if (entries.length > APP_RESPONSE_HEADER_LIMITS.maxEntries) {
48113
+ ctx.addIssue({
48114
+ code: "custom",
48115
+ message: `${entries.length} response headers exceeds the ${APP_RESPONSE_HEADER_LIMITS.maxEntries}-header limit.`
48116
+ });
48117
+ return;
48118
+ }
48119
+ for (const [name, value] of entries) {
48120
+ if (name.length > APP_RESPONSE_HEADER_LIMITS.nameMaxLength || !APP_RESPONSE_HEADER_NAME_PATTERN.test(name)) {
48121
+ ctx.addIssue({
48122
+ code: "custom",
48123
+ path: [name],
48124
+ message: `Response header name "${name}" is invalid. Use letters, digits, and hyphens only (max ${APP_RESPONSE_HEADER_LIMITS.nameMaxLength} characters).`
48125
+ });
48126
+ continue;
48127
+ }
48128
+ const denied = appResponseHeaderDenialReason(name);
48129
+ if (denied) {
48130
+ ctx.addIssue({
48131
+ code: "custom",
48132
+ path: [name],
48133
+ message: `Response header "${name}" is set by Runtype and cannot be overridden. ${denied}`
48134
+ });
48135
+ continue;
48136
+ }
48137
+ if (/[\r\n]/.test(value)) {
48138
+ ctx.addIssue({
48139
+ code: "custom",
48140
+ path: [name],
48141
+ message: `Response header "${name}" must not contain a carriage return or newline.`
48142
+ });
48143
+ continue;
48144
+ }
48145
+ if (value.length > APP_RESPONSE_HEADER_LIMITS.valueMaxLength) {
48146
+ ctx.addIssue({
48147
+ code: "custom",
48148
+ path: [name],
48149
+ message: `Response header "${name}" exceeds the ${APP_RESPONSE_HEADER_LIMITS.valueMaxLength}-character value limit.`
48150
+ });
48151
+ }
48152
+ }
48153
+ });
47707
48154
  var appManifestSchema = external_exports.object({
47708
48155
  name: external_exports.string().min(1).max(APP_MANIFEST_LIMITS.nameMaxLength),
47709
48156
  description: external_exports.string().max(2e3).optional(),
@@ -47712,7 +48159,9 @@ var appManifestSchema = external_exports.object({
47712
48159
  agents: external_exports.array(external_exports.string()).max(APP_MANIFEST_LIMITS.maxAgents).default([])
47713
48160
  }).strict().default({ flows: [], agents: [] }),
47714
48161
  data: external_exports.array(appDataGrantSchema).max(APP_MANIFEST_LIMITS.maxDataNamespaces).default([]),
47715
- auth: external_exports.enum(["none", "optional", "required"]).default("none")
48162
+ auth: external_exports.enum(["none", "optional", "required"]).default("none"),
48163
+ csp: appCspOverridesSchema.optional(),
48164
+ headers: appResponseHeaderOverridesSchema.optional()
47716
48165
  }).strict();
47717
48166
  var appRoutingDocSchema = external_exports.object({
47718
48167
  appId: external_exports.string(),
@@ -47729,6 +48178,20 @@ var appRoutingDocSchema = external_exports.object({
47729
48178
  apiUrl: external_exports.string(),
47730
48179
  clientToken: external_exports.string().nullable()
47731
48180
  }),
48181
+ /**
48182
+ * The active manifest's serving policy, copied forward on activation.
48183
+ * Optional so routing docs written before this field keep parsing.
48184
+ *
48185
+ * The SHAPE is validated here but the CONTENT deliberately is not: a doc
48186
+ * whose csp/headers fail the stricter manifest rules must still parse, or a
48187
+ * single bad value would take the whole app off the air. The edge runs
48188
+ * `sanitizeAppCspOverrides` / `sanitizeAppResponseHeaders` at header-build
48189
+ * time and falls back to the platform default for anything it rejects.
48190
+ */
48191
+ serving: external_exports.object({
48192
+ csp: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional(),
48193
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional()
48194
+ }).optional(),
47732
48195
  updatedAt: external_exports.string()
47733
48196
  });
47734
48197
  var SKILL_SCAN_HARD_BLOCK_CATEGORIES = [
@@ -47765,6 +48228,9 @@ function getDevPlanOverride() {
47765
48228
  return process.env.RUNTYPE_DEV_PLAN_OVERRIDE;
47766
48229
  }
47767
48230
 
48231
+ // src/lib/sdk-client.ts
48232
+ import { createClient } from "@runtypelabs/sdk";
48233
+
47768
48234
  // src/lib/cli-version.ts
47769
48235
  import { readFileSync as readFileSync2 } from "fs";
47770
48236
  import { dirname, join } from "path";
@@ -47829,6 +48295,24 @@ var isAuthMeResponse = (value) => {
47829
48295
  const record2 = value;
47830
48296
  return typeof record2.userId === "string";
47831
48297
  };
48298
+ var ApiKeyValidationUnavailableError = class extends Error {
48299
+ constructor(message, statusCode, options) {
48300
+ super(message, options);
48301
+ this.statusCode = statusCode;
48302
+ this.name = "ApiKeyValidationUnavailableError";
48303
+ }
48304
+ statusCode;
48305
+ };
48306
+ var describeUnverifiableStatus = (statusCode, apiUrl) => {
48307
+ const answered = `Could not verify the API key: the API at ${apiUrl} answered HTTP ${statusCode}`;
48308
+ if (statusCode === 403 || statusCode === 407) {
48309
+ return `${answered} (this can be an egress proxy or firewall blocking ${apiUrl}, not an invalid key)`;
48310
+ }
48311
+ if (statusCode >= 500) {
48312
+ return `${answered} (the API or something in front of it is failing, not an invalid key). Try again shortly.`;
48313
+ }
48314
+ return `${answered}, which is neither a success nor a credential rejection, so the key was not verified.`;
48315
+ };
47832
48316
  var ApiKeyManager = class {
47833
48317
  /**
47834
48318
  * Exchange a Clerk session JWT for a persistent API key.
@@ -47858,14 +48342,32 @@ var ApiKeyManager = class {
47858
48342
  }
47859
48343
  return result;
47860
48344
  }
48345
+ /**
48346
+ * Resolve whether the API accepts this key.
48347
+ *
48348
+ * `false` means strictly "the API looked at these credentials and rejected
48349
+ * them". Anything that leaves the key unchecked throws instead — the SDK
48350
+ * mints a `RuntypeApiError` for every non-2xx response, so returning false
48351
+ * for all of them reported an intercepting proxy's 403, a 407, or an API
48352
+ * 5xx as "Invalid API key" and sent people hunting for a credential problem
48353
+ * that did not exist.
48354
+ */
47861
48355
  async validateApiKey(apiKey, apiUrl) {
47862
- const client = createCliClient(apiKey, apiUrl);
48356
+ const resolvedApiUrl = apiUrl || getApiUrl();
48357
+ const client = createCliClient(apiKey, resolvedApiUrl);
47863
48358
  try {
47864
48359
  await client.get("/users/profile");
47865
48360
  return true;
47866
48361
  } catch (error51) {
47867
48362
  if (error51 instanceof RuntypeApiError) {
47868
- return false;
48363
+ if (error51.statusCode === 401) {
48364
+ return false;
48365
+ }
48366
+ throw new ApiKeyValidationUnavailableError(
48367
+ describeUnverifiableStatus(error51.statusCode, resolvedApiUrl),
48368
+ error51.statusCode,
48369
+ { cause: error51 }
48370
+ );
47869
48371
  }
47870
48372
  throw error51;
47871
48373
  }
@@ -48539,6 +49041,10 @@ var NON_TTY_LOGIN_GUIDANCE = {
48539
49041
  "Existing account: ask the user for an API key from the dashboard (Settings > API keys), then run: runtype auth login --api-key <key>"
48540
49042
  ]
48541
49043
  };
49044
+ var API_UNREACHABLE_NEXT = [
49045
+ "Confirm this environment can reach the Runtype API directly over HTTPS.",
49046
+ "If egress is restricted, allowlist api.runtype.com (staging: api.runtype-staging.com), then re-run: runtype auth login --api-key <key>"
49047
+ ];
48542
49048
  function refuseForcedTtyLogin(options) {
48543
49049
  if (options.tty === true && process.stdout.isTTY !== true) {
48544
49050
  console.error(
@@ -48651,6 +49157,21 @@ async function loginAction(options) {
48651
49157
  )
48652
49158
  );
48653
49159
  } catch (error51) {
49160
+ if (error51 instanceof ApiKeyValidationUnavailableError) {
49161
+ console.error(
49162
+ JSON.stringify(
49163
+ {
49164
+ status: "error",
49165
+ code: "api_unreachable",
49166
+ error: error51.message,
49167
+ next: API_UNREACHABLE_NEXT
49168
+ },
49169
+ null,
49170
+ 2
49171
+ )
49172
+ );
49173
+ process.exit(1);
49174
+ }
48654
49175
  const message = error51 instanceof Error ? error51.message : "Unknown error";
48655
49176
  console.error(JSON.stringify({ status: "error", error: message }, null, 2));
48656
49177
  process.exit(1);
@@ -49121,7 +49642,11 @@ async function ensureAuth(options) {
49121
49642
  if (isValid) {
49122
49643
  return envApiKey;
49123
49644
  }
49124
- } catch {
49645
+ } catch (error51) {
49646
+ if (error51 instanceof ApiKeyValidationUnavailableError) {
49647
+ console.error(chalk4.yellow(`
49648
+ ${error51.message}`));
49649
+ }
49125
49650
  }
49126
49651
  }
49127
49652
  const store = new CredentialStore();
@@ -49562,7 +50087,8 @@ import chalk6 from "chalk";
49562
50087
  import React3 from "react";
49563
50088
  import { render as render3 } from "ink";
49564
50089
  import { useState as useState4, useEffect as useEffect5 } from "react";
49565
- import { writeFileSync } from "fs";
50090
+ import { writeFileSync, mkdirSync } from "fs";
50091
+ import { dirname as dirname2 } from "path";
49566
50092
 
49567
50093
  // src/lib/terminal-image.ts
49568
50094
  var ESC = "\x1B";
@@ -50361,6 +50887,31 @@ recordsCommand.command("export").description("Export records to a file").option(
50361
50887
  process.exit(1);
50362
50888
  }
50363
50889
  });
50890
+ recordsCommand.command("typegen").description(
50891
+ "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."
50892
+ ).option(
50893
+ "-o, --output <file>",
50894
+ "Write the declarations to a file (default: print to stdout)"
50895
+ ).action(async (options) => {
50896
+ const apiKey = await ensureAuth();
50897
+ if (!apiKey) return;
50898
+ const client = createCliClient(apiKey);
50899
+ try {
50900
+ const dts = await client.collections.typegen();
50901
+ if (options.output) {
50902
+ const dir = dirname2(options.output);
50903
+ if (dir && dir !== ".") mkdirSync(dir, { recursive: true });
50904
+ writeFileSync(options.output, dts);
50905
+ console.log(chalk6.green(`Wrote record collection types to ${options.output}`));
50906
+ return;
50907
+ }
50908
+ process.stdout.write(dts);
50909
+ } catch (error51) {
50910
+ const message = error51 instanceof Error ? error51.message : "Unknown error";
50911
+ console.error(chalk6.red(`Failed to generate record types: ${message}`));
50912
+ process.exit(1);
50913
+ }
50914
+ });
50364
50915
  function csvEscape(value) {
50365
50916
  const text = neutralizeCsvFormula(value);
50366
50917
  if (text.includes(",") || text.includes('"') || text.includes("\n")) {
@@ -51471,18 +52022,18 @@ batchCommand.command("summary").description("Show a summary of active and recent
51471
52022
  console.log(` Recently completed: ${data.recentlyCompleted}`);
51472
52023
  if (data.batches.length > 0) {
51473
52024
  console.log(chalk9.cyan("\nActive Batches:"));
51474
- for (const b2 of data.batches) {
52025
+ for (const b of data.batches) {
51475
52026
  console.log(
51476
- ` ${chalk9.green(b2.id)} ${b2.flowName ?? ""} \u2014 ${b2.status} (${b2.processedRecords}/${b2.totalRecords}, ${b2.progress}%)`
52027
+ ` ${chalk9.green(b.id)} ${b.flowName ?? ""} \u2014 ${b.status} (${b.processedRecords}/${b.totalRecords}, ${b.progress}%)`
51477
52028
  );
51478
52029
  }
51479
52030
  }
51480
52031
  if (data.recent.length > 0) {
51481
52032
  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);
52033
+ for (const b of data.recent) {
52034
+ const statusColor = b.status === "completed" ? chalk9.green(b.status) : chalk9.red(b.status);
51484
52035
  console.log(
51485
- ` ${chalk9.green(b2.id)} ${b2.flowName ?? ""} \u2014 ${statusColor} (${b2.processedRecords}/${b2.totalRecords})`
52036
+ ` ${chalk9.green(b.id)} ${b.flowName ?? ""} \u2014 ${statusColor} (${b.processedRecords}/${b.totalRecords})`
51486
52037
  );
51487
52038
  }
51488
52039
  }
@@ -51511,18 +52062,18 @@ batchCommand.command("summary").description("Show a summary of active and recent
51511
52062
  { label: "Active", value: data.activeBatches, color: "green" },
51512
52063
  { label: "Recently completed", value: data.recentlyCompleted }
51513
52064
  ];
51514
- for (const b2 of data.batches) {
52065
+ for (const b of data.batches) {
51515
52066
  fields.push({
51516
- label: b2.id,
51517
- value: `${b2.flowName ?? ""} \u2014 ${b2.status} (${b2.processedRecords}/${b2.totalRecords}, ${b2.progress}%)`,
52067
+ label: b.id,
52068
+ value: `${b.flowName ?? ""} \u2014 ${b.status} (${b.processedRecords}/${b.totalRecords}, ${b.progress}%)`,
51518
52069
  color: "yellow"
51519
52070
  });
51520
52071
  }
51521
- for (const b2 of data.recent) {
52072
+ for (const b of data.recent) {
51522
52073
  fields.push({
51523
- label: b2.id,
51524
- value: `${b2.flowName ?? ""} \u2014 ${b2.status} (${b2.processedRecords}/${b2.totalRecords})`,
51525
- color: b2.status === "completed" ? "green" : "red"
52074
+ label: b.id,
52075
+ value: `${b.flowName ?? ""} \u2014 ${b.status} (${b.processedRecords}/${b.totalRecords})`,
52076
+ color: b.status === "completed" ? "green" : "red"
51526
52077
  });
51527
52078
  }
51528
52079
  setResultNode(React6.createElement(EntityCard, { fields }));
@@ -53292,9 +53843,9 @@ Histogram (${histogram.length} buckets):`));
53292
53843
  if (histogram.length === 0) {
53293
53844
  console.log(chalk15.gray(" No data"));
53294
53845
  } 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}`);
53846
+ for (const b of histogram) {
53847
+ const errPart = b.errors > 0 ? chalk15.red(` (${b.errors} errors)`) : "";
53848
+ console.log(` ${chalk15.dim(b.bucket)} ${b.count}${errPart}`);
53298
53849
  }
53299
53850
  }
53300
53851
  } catch (error51) {
@@ -53316,7 +53867,7 @@ Histogram (${histogram.length} buckets):`));
53316
53867
  const stats = res.data;
53317
53868
  const histogram = stats.histogram ?? [];
53318
53869
  const histogramSummary = histogram.length === 0 ? "No data" : histogram.map(
53319
- (b2) => `${b2.bucket}: ${b2.count}${b2.errors > 0 ? ` (${b2.errors} err)` : ""}`
53870
+ (b) => `${b.bucket}: ${b.count}${b.errors > 0 ? ` (${b.errors} err)` : ""}`
53320
53871
  ).join("\n");
53321
53872
  setResultNode(
53322
53873
  React11.createElement(EntityCard, {
@@ -53965,6 +54516,7 @@ function InitApp({ apiUrl, onComplete }) {
53965
54516
  const checkAndAuth = async () => {
53966
54517
  const store = new CredentialStore();
53967
54518
  const existingKey = await store.getApiKey();
54519
+ let storedKeyNotice = null;
53968
54520
  if (existingKey) {
53969
54521
  const apiKeyManager = new ApiKeyManager();
53970
54522
  try {
@@ -53983,14 +54535,15 @@ function InitApp({ apiUrl, onComplete }) {
53983
54535
  }));
53984
54536
  return;
53985
54537
  }
53986
- } catch {
54538
+ } catch (err) {
54539
+ storedKeyNotice = err instanceof Error ? err.message : String(err);
53987
54540
  }
53988
54541
  }
53989
54542
  setState((prev) => ({
53990
54543
  ...prev,
53991
54544
  step: 1,
53992
54545
  loading: true,
53993
- loadingLabel: "Opening browser to sign in..."
54546
+ loadingLabel: storedKeyNotice ? `${storedKeyNotice} Opening browser to sign in instead...` : "Opening browser to sign in..."
53994
54547
  }));
53995
54548
  try {
53996
54549
  const oauth = new OAuthManager({
@@ -54498,6 +55051,21 @@ var initCommand = new Command14("init").description("Set up Runtype CLI with gui
54498
55051
  )
54499
55052
  );
54500
55053
  } catch (error51) {
55054
+ if (error51 instanceof ApiKeyValidationUnavailableError) {
55055
+ console.error(
55056
+ JSON.stringify(
55057
+ {
55058
+ status: "error",
55059
+ code: "api_unreachable",
55060
+ error: error51.message,
55061
+ next: "If egress is restricted, allowlist api.runtype.com (staging: api.runtype-staging.com), then re-run: runtype init --api-key <key>"
55062
+ },
55063
+ null,
55064
+ 2
55065
+ )
55066
+ );
55067
+ process.exit(1);
55068
+ }
54501
55069
  const message = error51 instanceof Error ? error51.message : "Authentication failed";
54502
55070
  console.error(
54503
55071
  JSON.stringify({ status: "error", error: message }, null, 2)
@@ -57362,7 +57930,7 @@ function extractTrackedFiles(snapshots, liveTools, planPath) {
57362
57930
  result.push({ path: planPath, type: "plan" });
57363
57931
  }
57364
57932
  const sorted = Array.from(fileMap.values()).sort(
57365
- (a, b2) => (b2.lastTouchedAt ?? 0) - (a.lastTouchedAt ?? 0)
57933
+ (a, b) => (b.lastTouchedAt ?? 0) - (a.lastTouchedAt ?? 0)
57366
57934
  );
57367
57935
  result.push(...sorted);
57368
57936
  return result;
@@ -58593,7 +59161,7 @@ function ModelPicker({ currentModel, onSelect, onCancel, models }) {
58593
59161
  [contentWidth]
58594
59162
  );
58595
59163
  const sorted = useMemo7(
58596
- () => [...availableModels].sort((a, b2) => a.group.localeCompare(b2.group)),
59164
+ () => [...availableModels].sort((a, b) => a.group.localeCompare(b.group)),
58597
59165
  [availableModels]
58598
59166
  );
58599
59167
  const filtered = useMemo7(() => {
@@ -62972,7 +63540,7 @@ function getSanitizedEnv() {
62972
63540
  return clean;
62973
63541
  }
62974
63542
  function redactSecrets(output, secrets) {
62975
- const sorted = secrets.filter((s) => s.length >= 8).sort((a, b2) => b2.length - a.length);
63543
+ const sorted = secrets.filter((s) => s.length >= 8).sort((a, b) => b.length - a.length);
62976
63544
  let redacted = output;
62977
63545
  for (const secret of sorted) {
62978
63546
  redacted = redacted.replaceAll(secret, "[REDACTED]");
@@ -63905,7 +64473,7 @@ function buildTree(dirPath, maxDepth, depth = 0) {
63905
64473
  return [`${" ".repeat(depth)}[error reading ${normalizeToolPath(dirPath)}: ${message}]`];
63906
64474
  }
63907
64475
  const lines = [];
63908
- for (const entry of entries.sort((a, b2) => a.name.localeCompare(b2.name))) {
64476
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
63909
64477
  const entryPath = path10.join(dirPath, entry.name);
63910
64478
  if (shouldIgnoreRepoEntry(entryPath)) continue;
63911
64479
  lines.push(`${" ".repeat(depth)}- ${entry.name}${entry.isDirectory() ? "/" : ""}`);
@@ -64160,7 +64728,7 @@ function createDefaultLocalTools(context) {
64160
64728
  });
64161
64729
  }
64162
64730
  });
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);
64731
+ 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
64732
  return matches.length > 0 ? matches.join("\n") : `No matches found for "${query}" under ${normalizeToolPath(startPath.resolvedPath)}`;
64165
64733
  }
64166
64734
  },
@@ -64209,7 +64777,7 @@ function createDefaultLocalTools(context) {
64209
64777
  });
64210
64778
  }
64211
64779
  });
64212
- const rankedMatches = matches.sort((a, b2) => b2.score - a.score || a.path.localeCompare(b2.path)).map((match) => match.path).slice(0, maxResults);
64780
+ const rankedMatches = matches.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path)).map((match) => match.path).slice(0, maxResults);
64213
64781
  return rankedMatches.length > 0 ? rankedMatches.join("\n") : `No files matched "${pattern}" under ${normalizeToolPath(startPath.resolvedPath)}`;
64214
64782
  }
64215
64783
  },
@@ -68464,8 +69032,8 @@ import React20 from "react";
68464
69032
  import { render as render20 } from "ink";
68465
69033
  import { useState as useState37, useEffect as useEffect31 } from "react";
68466
69034
  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";
69035
+ import { readFileSync as readFileSync16, writeFileSync as writeFileSync6, mkdirSync as mkdirSync9 } from "fs";
69036
+ import { dirname as dirname9, relative as relative6, resolve as resolve10 } from "path";
68469
69037
 
68470
69038
  // src/lib/eval-discovery.ts
68471
69039
  import { readdirSync as readdirSync6 } from "fs";
@@ -68732,14 +69300,14 @@ evalCommand.command("list").description("List eval batches").option("--flow <id>
68732
69300
  total,
68733
69301
  emptyMessage: "No eval batches found",
68734
69302
  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";
69303
+ const b = item;
69304
+ const name = b.name || b.id;
69305
+ const progress = b.totalRecords ? `${b.completedRecords ?? 0}/${b.totalRecords}` : "";
69306
+ const statusColor = b.status === "completed" ? "green" : "yellow";
68739
69307
  return React20.createElement(
68740
69308
  Text34,
68741
69309
  { color: statusColor },
68742
- ` ${b2.id} ${name} [${b2.status}] ${progress}`
69310
+ ` ${b.id} ${name} [${b.status}] ${progress}`
68743
69311
  );
68744
69312
  }
68745
69313
  });
@@ -69021,7 +69589,7 @@ evalCommand.command("run [idOrDirPrefix]").description(
69021
69589
  try {
69022
69590
  const xml = buildJUnitXml(outcomes.map(toJUnitSuite));
69023
69591
  const outPath = resolve10(options.junit);
69024
- mkdirSync8(dirname8(outPath), { recursive: true });
69592
+ mkdirSync9(dirname9(outPath), { recursive: true });
69025
69593
  writeFileSync6(outPath, xml, "utf-8");
69026
69594
  console.log(chalk28.gray(`JUnit results written to ${options.junit}`));
69027
69595
  } catch (error51) {
@@ -69906,19 +70474,19 @@ import { execFileSync } from "child_process";
69906
70474
  // src/lib/persona-init.ts
69907
70475
  init_credential_store();
69908
70476
 
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`;
70477
+ // ../../node_modules/.pnpm/@runtypelabs+persona@4.15.0/node_modules/@runtypelabs/persona/dist/codegen.js
70478
+ var S = "4.15.0";
70479
+ var x = S;
70480
+ function $(e) {
70481
+ 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
70482
  }
69915
70483
  function u(e) {
69916
70484
  if (e !== void 0) return typeof e == "string" ? e : Array.isArray(e) ? `[${e.map((i) => i.toString()).join(", ")}]` : e.toString();
69917
70485
  }
69918
- function I(e) {
70486
+ function v(e) {
69919
70487
  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
70488
  }
69921
- var x = `({ text, message }: any) => {
70489
+ var A = `({ text, message }: any) => {
69922
70490
  const jsonSource = (message as any).rawContent || text || message.content;
69923
70491
  if (!jsonSource || typeof jsonSource !== 'string') return null;
69924
70492
  let cleanJson = jsonSource
@@ -69932,7 +70500,7 @@ var x = `({ text, message }: any) => {
69932
70500
  } catch (e) { return null; }
69933
70501
  return null;
69934
70502
  }`;
69935
- var A = `function(ctx) {
70503
+ var j = `function(ctx) {
69936
70504
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
69937
70505
  if (!jsonSource || typeof jsonSource !== 'string') return null;
69938
70506
  var cleanJson = jsonSource
@@ -69946,7 +70514,7 @@ var A = `function(ctx) {
69946
70514
  } catch (e) { return null; }
69947
70515
  return null;
69948
70516
  }`;
69949
- var j = `(action: any, context: any) => {
70517
+ var O = `(action: any, context: any) => {
69950
70518
  if (action.type !== 'nav_then_click') return;
69951
70519
  const payload = action.payload || action.raw || {};
69952
70520
  const url = payload?.page;
@@ -69964,7 +70532,7 @@ var j = `(action: any, context: any) => {
69964
70532
  window.location.href = targetUrl;
69965
70533
  return { handled: true, displayText: text };
69966
70534
  }`;
69967
- var O = `function(action, context) {
70535
+ var E = `function(action, context) {
69968
70536
  if (action.type !== 'nav_then_click') return;
69969
70537
  var payload = action.payload || action.raw || {};
69970
70538
  var url = payload.page;
@@ -69982,27 +70550,27 @@ var O = `function(action, context) {
69982
70550
  window.location.href = targetUrl;
69983
70551
  return { handled: true, displayText: text };
69984
70552
  }`;
69985
- var v = `(parsed: any) => {
70553
+ var _ = `(parsed: any) => {
69986
70554
  if (!parsed || typeof parsed !== 'object') return null;
69987
70555
  if (parsed.action === 'nav_then_click') return 'Navigating...';
69988
70556
  if (parsed.action === 'message') return parsed.text || '';
69989
70557
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
69990
70558
  return parsed.text || null;
69991
70559
  }`;
69992
- var _ = `function(parsed) {
70560
+ var T = `function(parsed) {
69993
70561
  if (!parsed || typeof parsed !== 'object') return null;
69994
70562
  if (parsed.action === 'nav_then_click') return 'Navigating...';
69995
70563
  if (parsed.action === 'message') return parsed.text || '';
69996
70564
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
69997
70565
  return parsed.text || null;
69998
70566
  }`;
69999
- function T(e) {
70567
+ function M(e) {
70000
70568
  if (!e) return null;
70001
70569
  let i = e.toString();
70002
70570
  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
70571
  }
70004
70572
  function h(e) {
70005
- return e.parserType ?? T(e.streamParser) ?? "plain";
70573
+ return e.parserType ?? M(e.streamParser) ?? "plain";
70006
70574
  }
70007
70575
  function g(e, i) {
70008
70576
  let r = [];
@@ -70027,6 +70595,15 @@ function f(e, i) {
70027
70595
  return r;
70028
70596
  }
70029
70597
  function y(e, i) {
70598
+ if (!e.suggestions) return [];
70599
+ let r = JSON.stringify(e.suggestions, null, 2).split(`
70600
+ `);
70601
+ return r.map((s, a) => {
70602
+ let t = a === 0 ? `${i}suggestions: ` : i, n = a === r.length - 1 ? "," : "";
70603
+ return `${t}${s}${n}`;
70604
+ });
70605
+ }
70606
+ function C(e, i) {
70030
70607
  let r = [];
70031
70608
  if (e.layout) {
70032
70609
  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 +70619,11 @@ function y(e, i) {
70042
70619
  }
70043
70620
  return r;
70044
70621
  }
70045
- function $(e, i) {
70622
+ function w(e, i) {
70046
70623
  let r = [];
70047
70624
  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
70625
  }
70049
- function E(e, i, r) {
70626
+ function k(e, i, r) {
70050
70627
  Object.entries(i).forEach(([s, a]) => {
70051
70628
  if (!(a === void 0 || typeof a == "function")) {
70052
70629
  if (Array.isArray(a)) {
@@ -70054,7 +70631,7 @@ function E(e, i, r) {
70054
70631
  return;
70055
70632
  }
70056
70633
  if (a && typeof a == "object") {
70057
- e.push(`${r}${s}: {`), E(e, a, `${r} `), e.push(`${r}},`);
70634
+ e.push(`${r}${s}: {`), k(e, a, `${r} `), e.push(`${r}},`);
70058
70635
  return;
70059
70636
  }
70060
70637
  e.push(`${r}${s}: ${JSON.stringify(a)},`);
@@ -70062,18 +70639,18 @@ function E(e, i, r) {
70062
70639
  });
70063
70640
  }
70064
70641
  function d(e, i, r, s) {
70065
- r && (e.push(`${s}${i}: {`), E(e, r, `${s} `), e.push(`${s}},`));
70642
+ r && (e.push(`${s}${i}: {`), k(e, r, `${s} `), e.push(`${s}},`));
70066
70643
  }
70067
70644
  function c(e) {
70068
70645
  return (e?.target ?? "body").replace(/\\/g, "\\\\").replace(/'/g, "\\'");
70069
70646
  }
70070
- function M(e, i = "esm", r) {
70647
+ function R(e, i = "esm", r) {
70071
70648
  let s = { ...e };
70072
70649
  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);
70650
+ let a = r ? { ...r, hooks: v(r.hooks) } : void 0;
70651
+ 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
70652
  }
70076
- function R(e, i) {
70653
+ function W(e, i) {
70077
70654
  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
70655
  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
70656
  t.push(` ${n}: "${o}",`);
@@ -70085,12 +70662,12 @@ function R(e, i) {
70085
70662
  typeof o == "string" ? t.push(` ${n}: "${o}",`) : typeof o == "boolean" && t.push(` ${n}: ${o},`);
70086
70663
  }), t.push(" },")), e.features && (t.push(" features: {"), Object.entries(e.features).forEach(([n, o]) => {
70087
70664
  t.push(` ${n}: ${o},`);
70088
- }), t.push(" },")), e.suggestionChips && e.suggestionChips.length > 0 && (t.push(" suggestionChips: ["), e.suggestionChips.forEach((n) => {
70665
+ }), t.push(" },")), t.push(...y(e, " ")), e.suggestionChips && e.suggestionChips.length > 0 && (t.push(" suggestionChips: ["), e.suggestionChips.forEach((n) => {
70089
70666
  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(`
70667
+ }), 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
70668
  `);
70092
70669
  }
70093
- function W(e, i) {
70670
+ function H(e, i) {
70094
70671
  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
70672
  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
70673
  t.push(` ${n}: "${o}",`);
@@ -70102,12 +70679,12 @@ function W(e, i) {
70102
70679
  typeof o == "string" ? t.push(` ${n}: "${o}",`) : typeof o == "boolean" && t.push(` ${n}: ${o},`);
70103
70680
  }), t.push(" },")), e.features && (t.push(" features: {"), Object.entries(e.features).forEach(([n, o]) => {
70104
70681
  t.push(` ${n}: ${o},`);
70105
- }), t.push(" },")), e.suggestionChips && e.suggestionChips.length > 0 && (t.push(" suggestionChips: ["), e.suggestionChips.forEach((n) => {
70682
+ }), t.push(" },")), t.push(...y(e, " ")), e.suggestionChips && e.suggestionChips.length > 0 && (t.push(" suggestionChips: ["), e.suggestionChips.forEach((n) => {
70106
70683
  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(`
70684
+ }), 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
70685
  `);
70109
70686
  }
70110
- function H(e, i) {
70687
+ function N(e, i) {
70111
70688
  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
70689
  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
70690
  s.push(` ${a}: "${t}",`);
@@ -70119,14 +70696,14 @@ function H(e, i) {
70119
70696
  typeof t == "string" ? s.push(` ${a}: "${t}",`) : typeof t == "boolean" && s.push(` ${a}: ${t},`);
70120
70697
  }), s.push(" },")), e.features && (s.push(" features: {"), Object.entries(e.features).forEach(([a, t]) => {
70121
70698
  s.push(` ${a}: ${t},`);
70122
- }), s.push(" },")), e.suggestionChips && e.suggestionChips.length > 0 && (s.push(" suggestionChips: ["), e.suggestionChips.forEach((a) => {
70699
+ }), s.push(" },")), s.push(...y(e, " ")), e.suggestionChips && e.suggestionChips.length > 0 && (s.push(" suggestionChips: ["), e.suggestionChips.forEach((a) => {
70123
70700
  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(`
70701
+ }), 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
70702
  `);
70126
70703
  }
70127
- function k(e) {
70704
+ function P(e) {
70128
70705
  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) {
70706
+ 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
70707
  let a = {};
70131
70708
  Object.entries(e.toolCall).forEach(([t, n]) => {
70132
70709
  typeof n == "string" && (a[t] = n);
@@ -70156,8 +70733,8 @@ function k(e) {
70156
70733
  if (n !== "renderUserMessage" && n !== "renderAssistantMessage") if (n === "avatar" && typeof o == "object" && o !== null) t.avatar = o;
70157
70734
  else if (n === "timestamp" && typeof o == "object" && o !== null) {
70158
70735
  let p = {};
70159
- Object.entries(o).forEach(([l, C]) => {
70160
- l !== "format" && (typeof C == "string" || typeof C == "boolean") && (p[l] = C);
70736
+ Object.entries(o).forEach(([l, b]) => {
70737
+ l !== "format" && (typeof b == "string" || typeof b == "boolean") && (p[l] = b);
70161
70738
  }), Object.keys(p).length > 0 && (t.timestamp = p);
70162
70739
  } else (typeof o == "string" || typeof o == "boolean") && (t[n] = o);
70163
70740
  }), Object.keys(t).length > 0 && (a.messages = t);
@@ -70166,12 +70743,12 @@ function k(e) {
70166
70743
  }
70167
70744
  return s;
70168
70745
  }
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
70746
  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: {"];
70747
+ 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;");
70748
+ return `<script src="${$(i)}/install.global.js" data-config='${t}'></script>`;
70749
+ }
70750
+ function J(e, i) {
70751
+ 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
70752
  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
70753
  n.push(` ${o}: "${p}",`);
70177
70754
  }), n.push(" },")), e.sendButton && (n.push(" sendButton: {"), Object.entries(e.sendButton).forEach(([o, p]) => {
@@ -70182,16 +70759,16 @@ function D(e, i) {
70182
70759
  typeof p == "string" ? n.push(` ${o}: "${p}",`) : typeof p == "boolean" && n.push(` ${o}: ${p},`);
70183
70760
  }), n.push(" },")), e.features && (n.push(" features: {"), Object.entries(e.features).forEach(([o, p]) => {
70184
70761
  n.push(` ${o}: ${p},`);
70185
- }), n.push(" },")), e.suggestionChips && e.suggestionChips.length > 0 && (n.push(" suggestionChips: ["), e.suggestionChips.forEach((o) => {
70762
+ }), n.push(" },")), n.push(...y(e, " ")), e.suggestionChips && e.suggestionChips.length > 0 && (n.push(" suggestionChips: ["), e.suggestionChips.forEach((o) => {
70186
70763
  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(`
70764
+ }), 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
70765
  `);
70189
70766
  }
70190
70767
  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(`
70768
+ let r = i?.hooks, s = P(e), t = ["<script>", "(function() {", " 'use strict';", "", " // Configuration", ` var CONFIG = ${JSON.stringify(s, null, 2).split(`
70192
70769
  `).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(`
70770
+ `)};`, "", " // 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);", ""];
70771
+ 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
70772
  `);
70196
70773
  }
70197
70774
 
@@ -70231,14 +70808,14 @@ function buildWidgetConfig(input) {
70231
70808
  function generatePersonaInitSnippet(input, personaFormat) {
70232
70809
  const widgetConfig = buildWidgetConfig(input);
70233
70810
  const target = input.targetSelector?.trim();
70234
- return M(
70811
+ return R(
70235
70812
  widgetConfig,
70236
70813
  personaFormat,
70237
70814
  target ? { target } : void 0
70238
70815
  );
70239
70816
  }
70240
70817
  function getPersonaInstallerScriptUrl() {
70241
- const snippet = M(
70818
+ const snippet = R(
70242
70819
  {
70243
70820
  apiUrl: "https://api.runtype.com",
70244
70821
  clientToken: "ct_test_demo_00000000000000000000000000000000",
@@ -70292,7 +70869,10 @@ async function getPersonaInitApiKeyNonInteractive(apiUrl) {
70292
70869
  if (isValid) {
70293
70870
  return envApiKey;
70294
70871
  }
70295
- } catch {
70872
+ } catch (error51) {
70873
+ if (error51 instanceof ApiKeyValidationUnavailableError) {
70874
+ console.error(error51.message);
70875
+ }
70296
70876
  }
70297
70877
  }
70298
70878
  const store = new CredentialStore();
@@ -70417,7 +70997,7 @@ async function runPersonaInit(options) {
70417
70997
  // src/lib/persona-demo.ts
70418
70998
  import { createServer } from "http";
70419
70999
  import { createServer as createNetServer } from "net";
70420
- import { existsSync as existsSync13, mkdirSync as mkdirSync9, readFileSync as readFileSync17, writeFileSync as writeFileSync7 } from "fs";
71000
+ import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync17, writeFileSync as writeFileSync7 } from "fs";
70421
71001
  import path16 from "path";
70422
71002
  var PERSONA_DEMO_DEFAULT_DIR = "persona-demo";
70423
71003
  var PERSONA_DEMO_DEFAULT_PORT = 43110;
@@ -70453,7 +71033,7 @@ function ensurePersonaDemoCanWrite(directory, force) {
70453
71033
  }
70454
71034
  function writePersonaDemoPage(options) {
70455
71035
  ensurePersonaDemoCanWrite(options.directory, options.force);
70456
- mkdirSync9(options.directory, { recursive: true });
71036
+ mkdirSync10(options.directory, { recursive: true });
70457
71037
  const filePath = personaDemoIndexPath(options.directory);
70458
71038
  const readmePath = personaDemoReadmePath(options.directory);
70459
71039
  writeFileSync7(filePath, `${options.html.trim()}
@@ -74299,7 +74879,7 @@ import { Command as Command32 } from "commander";
74299
74879
  import chalk40 from "chalk";
74300
74880
 
74301
74881
  // src/lib/skills-install.ts
74302
- import { mkdirSync as mkdirSync11, readFileSync as readFileSync19, writeFileSync as writeFileSync9 } from "fs";
74882
+ import { mkdirSync as mkdirSync12, readFileSync as readFileSync19, writeFileSync as writeFileSync9 } from "fs";
74303
74883
  import path18 from "path";
74304
74884
  import readline4 from "readline";
74305
74885
  import chalk39 from "chalk";
@@ -74323,7 +74903,7 @@ function readSkillsInstallMetadata() {
74323
74903
  }
74324
74904
  function writeSkillsInstallMetadata(metadata) {
74325
74905
  try {
74326
- mkdirSync11(path18.dirname(metadataPath()), { recursive: true });
74906
+ mkdirSync12(path18.dirname(metadataPath()), { recursive: true });
74327
74907
  writeFileSync9(metadataPath(), JSON.stringify(metadata, null, 2));
74328
74908
  } catch {
74329
74909
  }
@@ -75950,7 +76530,7 @@ import { spawn as spawn2 } from "child_process";
75950
76530
  import {
75951
76531
  closeSync,
75952
76532
  existsSync as existsSync18,
75953
- mkdirSync as mkdirSync12,
76533
+ mkdirSync as mkdirSync13,
75954
76534
  openSync,
75955
76535
  readFileSync as readFileSync22,
75956
76536
  readdirSync as readdirSync8,
@@ -75961,7 +76541,7 @@ import {
75961
76541
  writeFileSync as writeFileSync10
75962
76542
  } from "fs";
75963
76543
  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";
76544
+ import { dirname as dirname11, isAbsolute as isAbsolute4, join as join16, relative as relative8, resolve as resolve12, sep as sep6 } from "path";
75965
76545
 
75966
76546
  // src/lib/update-check.ts
75967
76547
  import chalk44 from "chalk";
@@ -75988,10 +76568,10 @@ function parseVersion(version2) {
75988
76568
  }
75989
76569
  function compareVersions(left, right) {
75990
76570
  const a = parseVersion(left);
75991
- const b2 = parseVersion(right);
75992
- if (!a || !b2) return 0;
76571
+ const b = parseVersion(right);
76572
+ if (!a || !b) return 0;
75993
76573
  for (let index = 0; index < 3; index++) {
75994
- const diff = a[index] - b2[index];
76574
+ const diff = a[index] - b[index];
75995
76575
  if (diff !== 0) return diff;
75996
76576
  }
75997
76577
  return 0;
@@ -76149,7 +76729,7 @@ function getManagedCliState(homeDir = getRuntypeHomeDir()) {
76149
76729
  }
76150
76730
  }
76151
76731
  function writeManagedCliState(paths, state) {
76152
- mkdirSync12(paths.root, { recursive: true });
76732
+ mkdirSync13(paths.root, { recursive: true });
76153
76733
  const temporaryPath = `${paths.state}.${process.pid}.${Date.now()}.tmp`;
76154
76734
  try {
76155
76735
  writeFileSync10(temporaryPath, `${JSON.stringify(state, null, 2)}
@@ -76186,12 +76766,12 @@ function isPathInside(parent, child) {
76186
76766
  return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute4(relativePath);
76187
76767
  }
76188
76768
  function isSourceCheckout(entrypoint) {
76189
- let current = dirname10(entrypoint);
76769
+ let current = dirname11(entrypoint);
76190
76770
  for (let depth = 0; depth < 8; depth += 1) {
76191
76771
  if (existsSync18(join16(current, ".git")) || existsSync18(join16(current, "pnpm-workspace.yaml"))) {
76192
76772
  return true;
76193
76773
  }
76194
- const parent = dirname10(current);
76774
+ const parent = dirname11(current);
76195
76775
  if (parent === current) break;
76196
76776
  current = parent;
76197
76777
  }
@@ -76203,7 +76783,7 @@ function findProjectRoot(cwd) {
76203
76783
  if (existsSync18(join16(current, "package.json")) || existsSync18(join16(current, "pnpm-workspace.yaml"))) {
76204
76784
  return current;
76205
76785
  }
76206
- const parent = dirname10(current);
76786
+ const parent = dirname11(current);
76207
76787
  if (parent === current) return void 0;
76208
76788
  current = parent;
76209
76789
  }
@@ -76332,7 +76912,7 @@ var defaultCommandRunner = async (command, args, options = {}) => new Promise((r
76332
76912
  });
76333
76913
  });
76334
76914
  function acquireUpdateLock(paths, now) {
76335
- mkdirSync12(paths.root, { recursive: true });
76915
+ mkdirSync13(paths.root, { recursive: true });
76336
76916
  const tryAcquire = () => {
76337
76917
  try {
76338
76918
  const descriptor = openSync(paths.lock, "wx", 384);
@@ -76421,10 +77001,10 @@ async function installAndActivateCliVersion(version2, options = {}) {
76421
77001
  const temporaryRoot = join16(paths.versions, `.${version2}-${process.pid}-${now.getTime()}`);
76422
77002
  let installed = false;
76423
77003
  try {
76424
- mkdirSync12(paths.versions, { recursive: true });
77004
+ mkdirSync13(paths.versions, { recursive: true });
76425
77005
  if (!isHealthyManagedVersion(paths, version2)) {
76426
77006
  rmSync2(temporaryRoot, { force: true, recursive: true });
76427
- mkdirSync12(temporaryRoot, { recursive: true });
77007
+ mkdirSync13(temporaryRoot, { recursive: true });
76428
77008
  const npmCommand = options.npmCommand ?? (process.platform === "win32" ? "npm.cmd" : "npm");
76429
77009
  const installResult = await commandRunner(
76430
77010
  npmCommand,
@@ -76524,7 +77104,7 @@ function spawnAutoUpdateWorker(version2, context = {}) {
76524
77104
  const entrypoint = context.entrypoint ?? process.argv[1];
76525
77105
  if (!entrypoint || !existsSync18(entrypoint)) return false;
76526
77106
  const paths = getManagedCliPaths();
76527
- mkdirSync12(paths.root, { recursive: true });
77107
+ mkdirSync13(paths.root, { recursive: true });
76528
77108
  const logDescriptor = openSync(paths.log, "a", 384);
76529
77109
  try {
76530
77110
  const child = spawn2(process.execPath, [entrypoint, INTERNAL_AUTO_UPDATE_ARG, version2], {