@wix/ditto-codegen-public 1.0.396 → 1.0.398

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.
@@ -18,10 +18,11 @@ export default tool({
18
18
  .boolean()
19
19
  .optional()
20
20
  .describe(
21
- "Default false. Set true ONLY on the final validation pass after tsc " +
22
- "succeeds to run `wix build` and verify the project builds end-to-end. " +
23
- "`wix build` is slow (~20s); omitting it on intermediate iterations keeps " +
24
- "the edit-validate loop fast.",
21
+ "Default false (tsc only). Pass true to also run `wix build`. validate " +
22
+ "runs tsc FIRST and builds only if tsc passes, so pass runBuild: true on " +
23
+ "the FIRST call to typecheck+build in one pass — it fails fast on type " +
24
+ "errors before the ~20s build, so a separate tsc-only call is redundant. " +
25
+ "Use runBuild: false only for quick intermediate tsc-only iterations.",
25
26
  ),
26
27
  },
27
28
  async execute(args, context) {
package/dist/out.js CHANGED
@@ -10737,8 +10737,9 @@ var require_environment = __commonJS({
10737
10737
  "../codegen-types/dist/types/environment.js"(exports2) {
10738
10738
  "use strict";
10739
10739
  Object.defineProperty(exports2, "__esModule", { value: true });
10740
- exports2.CODEGEN_ENVIRONMENT_HEADER = void 0;
10740
+ exports2.CODEGEN_CHARGING_MODE_HEADER = exports2.CODEGEN_ENVIRONMENT_HEADER = void 0;
10741
10741
  exports2.CODEGEN_ENVIRONMENT_HEADER = "x-codegen-environment";
10742
+ exports2.CODEGEN_CHARGING_MODE_HEADER = "x-codegen-charging-mode";
10742
10743
  }
10743
10744
  });
10744
10745
 
@@ -11501,6 +11502,254 @@ ${closeBrace}${tail}`;
11501
11502
  }
11502
11503
  });
11503
11504
 
11505
+ // dist/opencode-integration/types.js
11506
+ var require_types4 = __commonJS({
11507
+ "dist/opencode-integration/types.js"(exports2) {
11508
+ "use strict";
11509
+ Object.defineProperty(exports2, "__esModule", { value: true });
11510
+ exports2.PERMISSION_WILDCARD = void 0;
11511
+ exports2.tryParseJson = tryParseJson;
11512
+ exports2.PERMISSION_WILDCARD = "*";
11513
+ function tryParseJson(text) {
11514
+ try {
11515
+ return JSON.parse(text);
11516
+ } catch {
11517
+ return null;
11518
+ }
11519
+ }
11520
+ }
11521
+ });
11522
+
11523
+ // dist/opencode-integration/subagents.js
11524
+ var require_subagents = __commonJS({
11525
+ "dist/opencode-integration/subagents.js"(exports2) {
11526
+ "use strict";
11527
+ Object.defineProperty(exports2, "__esModule", { value: true });
11528
+ exports2.PRIMARY_AGENT_NAME = void 0;
11529
+ exports2.getAgentConfig = getAgentConfig;
11530
+ var types_1 = require_types4();
11531
+ var constants_1 = require_constants5();
11532
+ exports2.PRIMARY_AGENT_NAME = "codegen";
11533
+ var VALIDATOR_SUBAGENT_NAME = "codegen-validator";
11534
+ var WIX_DOCS_SUBAGENT_NAME = "codegen-wix-docs";
11535
+ var WDS_DOCS_SUBAGENT_NAME = "codegen-wds-docs";
11536
+ var VALIDATOR_DESCRIPTION = `Runs validate (tsc + wix build) and fixes the reported errors, consulting the
11537
+ wix-app skill / wix-mcp for SDK-shape errors; returns when the build is clean
11538
+ or reports what it couldn't fix. Validation step only \u2014 never generates features.`;
11539
+ var VALIDATOR_PROMPT = `Run 'validate({ runBuild: true })', fix the errors it reports, and re-run until
11540
+ it passes. You are fixing EXISTING code \u2014 do NOT add features or rewrite whole
11541
+ files. NEVER force a green build by suppressing types: no 'as any', no
11542
+ '@ts-ignore'/'@ts-expect-error', and do NOT switch a correct import (e.g.
11543
+ 'import { bookings } from "@wix/bookings"') to 'import * as' just to satisfy
11544
+ tsc \u2014 that ships code that compiles but breaks at runtime. A type error on a
11545
+ Wix SDK method/namespace/parameter means the call is WRONG: look up the correct
11546
+ usage via the 'wix-app' skill or wix-mcp ('SearchWixSDKDocumentation' \u2192
11547
+ 'ReadFullDocsMethodSchema') and fix it to the real exported method + its options
11548
+ object. Work in a bounded number of fix cycles \u2014 if the build isn't converging
11549
+ after a few attempts, STOP and return the remaining errors verbatim rather than
11550
+ looping; never silence them.`;
11551
+ var WIX_DOCS_DESCRIPTION = `Use ONLY to discover a Wix SDK you don't know and that the wix-app skill +
11552
+ KNOWN WIX APIS don't cover. Send ONE complete question; returns the import path
11553
+ + exported namespace/method + runtime context + full signature + any required
11554
+ scope/permission IDs + a short usage example (not a link). Don't fetch a doc you
11555
+ already identified, and don't split a lookup into separate search/signature
11556
+ calls. Read-only.`;
11557
+ var WIX_DOCS_PROMPT = `You research Wix SDK APIs via wix-mcp and report back \u2014 never write app code.
11558
+ The caller uses DIRECT imports inside an extension that already supplies
11559
+ auth/host: 'import { <namespace> } from "@wix/<pkg>"; await <namespace>.<method>(<optionsObject>)'
11560
+ \u2014 describe that form, NEVER a 'createClient'/'wixClient' client. Report the SDK,
11561
+ NOT the REST spec: REST names, namespaces, and positional params often differ,
11562
+ so verify the method EXISTS as an SDK export. Steps: (1) read the SDK
11563
+ introduction ('SearchWixSDKDocumentation' \u2192 'ReadFullDocsArticle') to confirm
11564
+ it's the RIGHT API and its runtime context \u2014 backend, the dashboard host, or the
11565
+ site/editor host (host modules like @wix/dashboard work ONLY in their own host);
11566
+ (2) read 'ReadFullDocsMethodSchema' for the exact exported name and its
11567
+ options-object parameters. Reply with: the import path + exported
11568
+ namespace/method, the runtime context, the full TypeScript signature, and a
11569
+ short usage example \u2014 never a bare link, never 'as any' or a guessed method. If
11570
+ the API is limited to one context, say so. For a required scope/permission,
11571
+ return the EXACT scope-ID string from the docs (never a guessed format); if none
11572
+ is documented, say so.`;
11573
+ var WDS_DOCS_DESCRIPTION = `Use ONLY when building dashboard UI and you need a Wix Design System
11574
+ component/prop/example you don't know and the wix-app skill doesn't cover.
11575
+ Returns the component name + props + a short usage example. Not for layouts the
11576
+ wix-app skill already covers. Read-only.`;
11577
+ var SUBAGENT_DENIED_TOOLS = {
11578
+ [
11579
+ "task"
11580
+ /* OpenCodeTool.Task */
11581
+ ]: "deny",
11582
+ [
11583
+ "todowrite"
11584
+ /* OpenCodeTool.TodoWrite */
11585
+ ]: "deny",
11586
+ [
11587
+ "todoread"
11588
+ /* OpenCodeTool.TodoRead */
11589
+ ]: "deny",
11590
+ [
11591
+ "uuid"
11592
+ /* OpenCodeTool.Uuid */
11593
+ ]: "deny",
11594
+ [
11595
+ "wix-generate"
11596
+ /* OpenCodeTool.WixGenerate */
11597
+ ]: "deny",
11598
+ [
11599
+ "required-permissions"
11600
+ /* OpenCodeTool.RequiredPermissions */
11601
+ ]: "deny",
11602
+ [
11603
+ "progress"
11604
+ /* OpenCodeTool.Progress */
11605
+ ]: "deny"
11606
+ };
11607
+ var DOCS_SUBAGENT_DENIED_TOOLS = {
11608
+ ...SUBAGENT_DENIED_TOOLS,
11609
+ [
11610
+ "edit"
11611
+ /* OpenCodeTool.Edit */
11612
+ ]: "deny",
11613
+ [
11614
+ "write"
11615
+ /* OpenCodeTool.Write */
11616
+ ]: "deny",
11617
+ [
11618
+ "batch-write"
11619
+ /* OpenCodeTool.BatchWrite */
11620
+ ]: "deny",
11621
+ [
11622
+ "multi-edit"
11623
+ /* OpenCodeTool.MultiEdit */
11624
+ ]: "deny",
11625
+ [
11626
+ "validate"
11627
+ /* OpenCodeTool.Validate */
11628
+ ]: "deny"
11629
+ };
11630
+ var READ_TOOLS = {
11631
+ [
11632
+ "read"
11633
+ /* OpenCodeTool.Read */
11634
+ ]: "allow",
11635
+ [
11636
+ "batch-read"
11637
+ /* OpenCodeTool.BatchRead */
11638
+ ]: "allow",
11639
+ [
11640
+ "grep"
11641
+ /* OpenCodeTool.Grep */
11642
+ ]: "allow",
11643
+ [
11644
+ "glob"
11645
+ /* OpenCodeTool.Glob */
11646
+ ]: "allow"
11647
+ };
11648
+ var WRITE_TOOLS = {
11649
+ [
11650
+ "edit"
11651
+ /* OpenCodeTool.Edit */
11652
+ ]: "allow",
11653
+ [
11654
+ "multi-edit"
11655
+ /* OpenCodeTool.MultiEdit */
11656
+ ]: "allow",
11657
+ [
11658
+ "write"
11659
+ /* OpenCodeTool.Write */
11660
+ ]: "allow",
11661
+ [
11662
+ "batch-write"
11663
+ /* OpenCodeTool.BatchWrite */
11664
+ ]: "allow"
11665
+ };
11666
+ function getAgentConfig(smallModel) {
11667
+ return {
11668
+ [exports2.PRIMARY_AGENT_NAME]: {
11669
+ mode: "primary",
11670
+ permission: {
11671
+ [
11672
+ "task"
11673
+ /* OpenCodeTool.Task */
11674
+ ]: {
11675
+ [types_1.PERMISSION_WILDCARD]: "deny",
11676
+ [VALIDATOR_SUBAGENT_NAME]: "allow",
11677
+ [WIX_DOCS_SUBAGENT_NAME]: "allow",
11678
+ [WDS_DOCS_SUBAGENT_NAME]: "allow"
11679
+ }
11680
+ }
11681
+ },
11682
+ [VALIDATOR_SUBAGENT_NAME]: {
11683
+ mode: "subagent",
11684
+ model: smallModel,
11685
+ steps: 40,
11686
+ description: VALIDATOR_DESCRIPTION,
11687
+ prompt: VALIDATOR_PROMPT,
11688
+ permission: {
11689
+ ...SUBAGENT_DENIED_TOOLS,
11690
+ ...READ_TOOLS,
11691
+ ...WRITE_TOOLS,
11692
+ // Runs tsc + wix build to drive the fix loop.
11693
+ [
11694
+ "validate"
11695
+ /* OpenCodeTool.Validate */
11696
+ ]: "allow",
11697
+ [
11698
+ "bash"
11699
+ /* OpenCodeTool.Bash */
11700
+ ]: "allow",
11701
+ [
11702
+ "skill"
11703
+ /* OpenCodeTool.Skill */
11704
+ ]: "allow",
11705
+ [constants_1.WIX_MCP_SERVER_NAME]: "allow"
11706
+ }
11707
+ },
11708
+ [WIX_DOCS_SUBAGENT_NAME]: {
11709
+ mode: "subagent",
11710
+ model: smallModel,
11711
+ steps: 15,
11712
+ description: WIX_DOCS_DESCRIPTION,
11713
+ prompt: WIX_DOCS_PROMPT,
11714
+ permission: {
11715
+ ...DOCS_SUBAGENT_DENIED_TOOLS,
11716
+ ...READ_TOOLS,
11717
+ [
11718
+ "bash"
11719
+ /* OpenCodeTool.Bash */
11720
+ ]: "deny",
11721
+ [
11722
+ "skill"
11723
+ /* OpenCodeTool.Skill */
11724
+ ]: "allow",
11725
+ [constants_1.WIX_MCP_SERVER_NAME]: "allow"
11726
+ }
11727
+ },
11728
+ [WDS_DOCS_SUBAGENT_NAME]: {
11729
+ mode: "subagent",
11730
+ model: smallModel,
11731
+ steps: 15,
11732
+ description: WDS_DOCS_DESCRIPTION,
11733
+ permission: {
11734
+ ...DOCS_SUBAGENT_DENIED_TOOLS,
11735
+ ...READ_TOOLS,
11736
+ // The wix-design-system skill shells out to a script, so bash is needed.
11737
+ [
11738
+ "bash"
11739
+ /* OpenCodeTool.Bash */
11740
+ ]: "allow",
11741
+ [
11742
+ "skill"
11743
+ /* OpenCodeTool.Skill */
11744
+ ]: "allow",
11745
+ [constants_1.WIX_MCP_SERVER_NAME]: "deny"
11746
+ }
11747
+ }
11748
+ };
11749
+ }
11750
+ }
11751
+ });
11752
+
11504
11753
  // dist/experiments.js
11505
11754
  var require_experiments = __commonJS({
11506
11755
  "dist/experiments.js"(exports2) {
@@ -11744,7 +11993,8 @@ var require_dist5 = __commonJS({
11744
11993
  askRules: [],
11745
11994
  gitConflictsRules: [],
11746
11995
  decisionCheckers: [],
11747
- plugins: []
11996
+ plugins: [],
11997
+ chargingMode: "app"
11748
11998
  };
11749
11999
  }
11750
12000
  });
@@ -14077,7 +14327,8 @@ var require_dist8 = __commonJS({
14077
14327
  askRules: [],
14078
14328
  gitConflictsRules: [],
14079
14329
  decisionCheckers: [],
14080
- plugins: [codegen_checkpoint_plugin_1.checkpointPluginFactory]
14330
+ plugins: [codegen_checkpoint_plugin_1.checkpointPluginFactory],
14331
+ chargingMode: "app"
14081
14332
  };
14082
14333
  }
14083
14334
  });
@@ -14428,7 +14679,8 @@ var require_dist10 = __commonJS({
14428
14679
  askRules: [],
14429
14680
  gitConflictsRules: [],
14430
14681
  decisionCheckers: [],
14431
- plugins: [codegen_feature_vibe_plugin_1.featureVibePluginFactory]
14682
+ plugins: [codegen_feature_vibe_plugin_1.featureVibePluginFactory],
14683
+ chargingMode: "app"
14432
14684
  };
14433
14685
  }
14434
14686
  });
@@ -14452,7 +14704,10 @@ MINIMIZE TEXT OUTPUT \u2014 CRITICAL:
14452
14704
 
14453
14705
  TOOL USAGE:
14454
14706
  - \`progress\` to mark a step done. Call it ONCE per completed step, in the SAME response as the tool calls that did the work \u2014 never dedicate a separate turn to it. Report progress at EVERY meaningful milestone (the IMPLEMENTATION WORKFLOW steps below give the exact wording to use). Keep descriptions SHORT \u2014 mention the extension type but no file names, counts, namespaces, or other specifics.
14455
- - \`validate\` for all validation (tsc + build).
14707
+ - \`validate\` (tsc + build) is run by the \`codegen-validator\` subagent \u2014 do NOT call it directly; delegate via \`task\` at step 5.
14708
+ - \`task\` delegates to haiku subagents: \`codegen-validator\` (step 5; see step 5 for the exact prompt), \`codegen-wix-docs\` (step 2; to SEARCH/discover an unknown Wix SDK method/shape/scope ID via wix-mcp), \`codegen-wds-docs\` (step 2; to discover WDS components/props you don't know). Docs subagents are for DISCOVERY only \u2014 give them a QUESTION ("which method lists X?"), never a known article URL to fetch.
14709
+ - Each \`task\` round-trip is EXPENSIVE (~90s of subagent startup, regardless of how small the question). So minimize them: ask ONE comprehensive question per API that returns everything you need at once \u2014 method name + FULL call signature + parameter shapes + required scope IDs. NEVER do a broad "find the X SDK" call and then a follow-up "what's the exact signature" call \u2014 that is two ~90s round-trips for one answer. Batch all your unknowns for a domain into a single delegation.
14710
+ - If BOTH docs subagents are needed, fire both \`task\` calls in ONE response (parallel), never serially.
14456
14711
  - \`uuid\` to generate UUIDs (supports count param for multiple). Do NOT use bash.
14457
14712
  - \`wix-generate\` to scaffold extensions non-interactively \u2014 prefer over hand-writing boilerplate; pass an array to scaffold several at once. It RETURNS every created file's contents, so trust that and do NOT \`read\`/\`batch-read\` them afterward. On a \`FAILED\` block, fix the params per the error and retry.
14458
14713
  - \`required-permissions\` \u2014 declare the Wix app permissions the generated code needs (when/whether to call: workflow step 6 + PERMISSIONS).
@@ -14463,7 +14718,7 @@ TOOL USAGE:
14463
14718
  - \`multi-edit\` to apply N find-and-replace edits across one or more files in one call. NEVER call \`edit\` more than once per turn \u2014 use multi-edit instead. \`edit\` is reserved for a single edit to one file. When fixing type errors across N files, use ONE \`multi-edit\` with all N edits.
14464
14719
  - Tool arguments are strict JSON. For multiline strings in \`write\`, \`edit\`, \`batch-write\`, and \`multi-edit\`, use JSON escape sequences (\`\\n\`, \`\\t\`, \`\\"\`) \u2014 do NOT put raw (unescaped) newlines inside JSON string values (that breaks parsing). \`batch-write\` and \`multi-edit\` also normalize literal two-character escape sequences before writing; prefer proper JSON escapes.
14465
14720
  - For tools where no batch variant exists (e.g. \`grep\`, \`glob\`), still emit MULTIPLE \`tool_use\` blocks in a SINGLE response when the calls are independent. Sequential turns waste a model round-trip per call.
14466
- - API discovery (shapes, method signatures, types) \u2014 in this order: (1) loaded skills, if they already cover the API; (2) wix-mcp docs \u2014 \`SearchWixSDKDocumentation\` and \`ReadFullDocsMethodSchema\` (ALWAYS read the schema, not just \`ReadFullDocsArticle\`: it is the source of truth for parameter shapes, since doc code examples may use incorrect call signatures); (3) grepping \`node_modules\` ONLY as a last resort if the above return nothing \u2014 SDK internals are not a documentation source, and doing it first wastes turns, inflates context, and is unreliable. ENFORCED: after 2 such lookups, further bash inspection of \`node_modules\` Wix/vite/astro internals is rejected.
14721
+ - API discovery (shapes, method signatures, types) \u2014 in this order: (1) loaded skills + KNOWN WIX APIS, if they already cover the API \u2014 if so, do NOT delegate; (2) only when you genuinely don't know which method/API to use, delegate to \`codegen-wix-docs\` (Wix SDK) or \`codegen-wds-docs\` (WDS) to SEARCH for it \u2014 pass the question, not a known article link; the subagent searches AND reads the right schema (\`ReadFullDocsMethodSchema\` is the source of truth for parameter shapes) and returns a summary. Do NOT delegate just to fetch a doc you already identified; (3) grepping \`node_modules\` ONLY as a last resort if the above return nothing \u2014 SDK internals are not a documentation source, and doing it first wastes turns, inflates context, and is unreliable. ENFORCED: after 2 such lookups, further bash inspection of \`node_modules\` Wix/vite/astro internals is rejected.
14467
14722
  - NEVER run preview, dev, release, or promote commands.
14468
14723
 
14469
14724
  KNOWN WIX APIS (already documented \u2014 do NOT rediscover these from node_modules; for full detail consult the \`wix-app\` skill's references or \`ReadFullDocsMethodSchema\`):
@@ -14472,10 +14727,10 @@ KNOWN WIX APIS (already documented \u2014 do NOT rediscover these from node_modu
14472
14727
 
14473
14728
  IMPLEMENTATION WORKFLOW:
14474
14729
  1. **Plan**: Determine extension types using the \`wix-app\` skill. Generate ALL UUIDs upfront. Include a \`progress\` call (e.g. "Planning extensions").
14475
- 2. **Research**: Load relevant SDK docs and skills for each extension type. Include a \`progress\` call (e.g. "Reading documentation").
14730
+ 2. **Research**: Load the \`wix-app\` skill per extension type. SKIP this step entirely if the skill + KNOWN WIX APIS cover everything (common for dashboard + data-collection apps). Otherwise \`progress\` ("Reading documentation"), then delegate ONLY to search for an API you genuinely can't identify \u2014 \`codegen-wix-docs\` (SDK), \`codegen-wds-docs\` (WDS), both in ONE response if both needed; pass each the question, not a known doc link \u2014 and wait for the summaries before building.
14476
14731
  3. **Build**: Write files incrementally \u2014 group by logical section, NOT all at once. For complex tasks (300+ total lines across files), split into multiple \`batch-write\` calls. NEVER hold back writing until all code is planned \u2014 write each logical piece as soon as it is ready. Build all extensions before registering. Include one \`progress\` call per extension type (e.g. "Creating dashboard page", "Creating service plugin", "Creating data collection").
14477
14732
  4. **Register**: Register all extensions in \`src/extensions.ts\`. Include a \`progress\` call (e.g. "Registering extensions").
14478
- 5. **Validate**: Run \`validate\` (typecheck only). Fix any errors and re-validate until tsc passes. Include a \`progress\` call (e.g. "Running type checks"). Then run \`validate({ runBuild: true })\` ONCE to verify the build. Pass \`installDeps: true\` ONLY when \`package.json\` changed without already running \`npm install <package-name>\` in this iteration; otherwise omit it (node_modules is pre-installed). Include a \`progress\` call (e.g. "Building project").
14733
+ 5. **Validate**: Call \`progress\` ("Running type checks"), then dispatch ONE \`task({ subagent: "codegen-validator", prompt: "Run validate({ runBuild: true }) \u2014 it typechecks AND builds in a single pass (tsc runs first and fails fast before the build). Fix any errors and re-run until it passes. Pass installDeps: true only if package.json changed and npm install was not already run in this session." })\`. Wait for the subagent to return. Do NOT call \`validate\` directly from the primary agent, and do NOT make a separate tsc-only call first \u2014 the single runBuild pass already fails fast on type errors.
14479
14734
  6. **Declare permissions**: If the generated code requires Wix app permissions, call \`required-permissions\` ONCE with their SCOPE IDs (see PERMISSIONS below). Skip this step entirely if no permissions are needed.
14480
14735
  7. **Final message**: Your last message is returned to the user as the codegen output \u2014 keep it short and plain (a sentence or two on what the app now does).
14481
14736
  8. **Stop**: STOP immediately. Do NOT refactor, clean up, or verify.
@@ -14743,6 +14998,7 @@ var require_config = __commonJS({
14743
14998
  var os_1 = require("os");
14744
14999
  var ditto_codegen_types_12 = require_dist4();
14745
15000
  var constants_1 = require_constants5();
15001
+ var subagents_1 = require_subagents();
14746
15002
  var experiments_1 = require_experiments();
14747
15003
  var rules_writer_12 = require_rules_writer();
14748
15004
  var node_modules_guard_12 = require_node_modules_guard();
@@ -14774,11 +15030,16 @@ var require_config = __commonJS({
14774
15030
  ];
14775
15031
  function getProviderConfig() {
14776
15032
  const environment = process.env.CODEGEN_ENVIRONMENT;
15033
+ const chargingMode = (0, environments_12.getCodegenEnvironmentConfig)().chargingMode ?? "app";
14777
15034
  const headers = {
14778
15035
  // Tell the proxy which environment this request belongs to so it can
14779
15036
  // select the matching upstream API key. Forwarded verbatim — the proxy
14780
15037
  // owns validation and the default.
14781
15038
  ...environment ? { [ditto_codegen_types_12.CODEGEN_ENVIRONMENT_HEADER]: environment } : {},
15039
+ // How the request is billed; the proxy resolves auth accordingly.
15040
+ [ditto_codegen_types_12.CODEGEN_CHARGING_MODE_HEADER]: chargingMode,
15041
+ // The user's Wix token — needed to resolve the account (credits mode) and
15042
+ // authorize the project.
14782
15043
  ...currentAccessToken ? { Authorization: `Bearer ${currentAccessToken}` } : {}
14783
15044
  };
14784
15045
  return {
@@ -14879,7 +15140,7 @@ var require_config = __commonJS({
14879
15140
  ]: "deny",
14880
15141
  external_directory: READABLE_EXTERNAL_DIRS
14881
15142
  };
14882
- function buildConfig(instructionPaths, permission, { guardNodeModules = false } = {}) {
15143
+ function buildConfig(instructionPaths, permission, { guardNodeModules = false, withAgents = false } = {}) {
14883
15144
  return {
14884
15145
  model: exports2.DEFAULT_MODEL,
14885
15146
  small_model: exports2.DEFAULT_SMALL_MODEL,
@@ -14891,7 +15152,14 @@ var require_config = __commonJS({
14891
15152
  lsp: false,
14892
15153
  mcp: WIX_MCP_CONFIG,
14893
15154
  watcher: { ignore: WATCHER_IGNORE_PATTERNS },
14894
- ...guardNodeModules ? { plugin: [node_modules_guard_12.GUARD_PLUGIN_PATH], autoupdate: false, share: "disabled" } : {}
15155
+ ...guardNodeModules ? { plugin: [node_modules_guard_12.GUARD_PLUGIN_PATH], autoupdate: false, share: "disabled" } : {},
15156
+ // Only code-writing flows register subagents. The read-only ask flow must
15157
+ // not: its primary agent re-opens `task`, which would let the write-capable
15158
+ // validator subagent run in a flow meant to stay read-only.
15159
+ ...withAgents ? {
15160
+ agent: (0, subagents_1.getAgentConfig)(exports2.DEFAULT_SMALL_MODEL),
15161
+ default_agent: subagents_1.PRIMARY_AGENT_NAME
15162
+ } : {}
14895
15163
  };
14896
15164
  }
14897
15165
  function ensureOpenCodeInPath() {
@@ -14925,33 +15193,19 @@ var require_config = __commonJS({
14925
15193
  return buildConfig(paths(env.askRules), ASK_PERMISSIONS);
14926
15194
  case CodeGenService_12.TaskKind.FIX_GIT_CONFLICTS:
14927
15195
  return buildConfig(paths(env.gitConflictsRules), GIT_CONFLICTS_PERMISSIONS, {
14928
- guardNodeModules: true
15196
+ guardNodeModules: true,
15197
+ withAgents: true
14929
15198
  });
14930
15199
  default:
14931
15200
  return buildConfig(paths(env.codegenRules), CODEGEN_PERMISSIONS, {
14932
- guardNodeModules: true
15201
+ guardNodeModules: true,
15202
+ withAgents: true
14933
15203
  });
14934
15204
  }
14935
15205
  }
14936
15206
  }
14937
15207
  });
14938
15208
 
14939
- // dist/opencode-integration/types.js
14940
- var require_types4 = __commonJS({
14941
- "dist/opencode-integration/types.js"(exports2) {
14942
- "use strict";
14943
- Object.defineProperty(exports2, "__esModule", { value: true });
14944
- exports2.tryParseJson = tryParseJson;
14945
- function tryParseJson(text) {
14946
- try {
14947
- return JSON.parse(text);
14948
- } catch {
14949
- return null;
14950
- }
14951
- }
14952
- }
14953
- });
14954
-
14955
15209
  // dist/opencode-integration/parser.js
14956
15210
  var require_parser = __commonJS({
14957
15211
  "dist/opencode-integration/parser.js"(exports2) {
@@ -15203,25 +15457,48 @@ var require_cost_tracker = __commonJS({
15203
15457
  "use strict";
15204
15458
  Object.defineProperty(exports2, "__esModule", { value: true });
15205
15459
  exports2.fetchOpenCodeStats = fetchOpenCodeStats;
15460
+ exports2.parseStatsTotalCost = parseStatsTotalCost;
15461
+ exports2.computeStatsDeltaCost = computeStatsDeltaCost;
15206
15462
  var child_process_1 = require("child_process");
15207
15463
  var util_1 = require("util");
15208
15464
  var logger_12 = require_logger();
15209
15465
  var execAsync = (0, util_1.promisify)(child_process_1.exec);
15210
15466
  var CLI_TIMEOUT_MS = 15e3;
15467
+ var STATS_MAX_ATTEMPTS = 3;
15468
+ var ANSI_ESCAPE = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`, "g");
15211
15469
  async function fetchOpenCodeStats(cwd, env) {
15212
- try {
15213
- const { stdout } = await execAsync("opencode stats --models", {
15214
- cwd,
15215
- env,
15216
- timeout: CLI_TIMEOUT_MS
15217
- });
15218
- return stdout.trim() || null;
15219
- } catch (error) {
15220
- logger_12.logger.warn("[OpenCode] Could not fetch opencode stats", {
15221
- error: error instanceof Error ? error.message : String(error)
15222
- });
15223
- return null;
15470
+ for (let attempt = 0; attempt < STATS_MAX_ATTEMPTS; attempt++) {
15471
+ try {
15472
+ const { stdout } = await execAsync("opencode stats --models", {
15473
+ cwd,
15474
+ env,
15475
+ timeout: CLI_TIMEOUT_MS
15476
+ });
15477
+ return stdout.trim() || null;
15478
+ } catch (error) {
15479
+ const isLastAttempt = attempt === STATS_MAX_ATTEMPTS - 1;
15480
+ logger_12.logger.warn("[OpenCode] Could not fetch opencode stats", {
15481
+ attempt: attempt + 1,
15482
+ maxAttempts: STATS_MAX_ATTEMPTS,
15483
+ willRetry: !isLastAttempt,
15484
+ error: error instanceof Error ? error.message : String(error)
15485
+ });
15486
+ if (isLastAttempt)
15487
+ return null;
15488
+ }
15224
15489
  }
15490
+ return null;
15491
+ }
15492
+ function parseStatsTotalCost(statsOutput) {
15493
+ const plain = statsOutput.replace(ANSI_ESCAPE, "");
15494
+ const match = plain.match(/Total Cost\s+\$([0-9]+(?:\.[0-9]+)?)/);
15495
+ if (!match)
15496
+ return null;
15497
+ const cost = Number.parseFloat(match[1]);
15498
+ return Number.isFinite(cost) ? cost : null;
15499
+ }
15500
+ function computeStatsDeltaCost(baselineCost, finalCost) {
15501
+ return Math.max(0, finalCost - baselineCost);
15225
15502
  }
15226
15503
  }
15227
15504
  });
@@ -15435,7 +15712,7 @@ var require_process_manager = __commonJS({
15435
15712
  exports2.clearTimers = clearTimers;
15436
15713
  exports2.killProcess = killProcess;
15437
15714
  var logger_12 = require_logger();
15438
- exports2.IDLE_TIMEOUT_MS = 24e4;
15715
+ exports2.IDLE_TIMEOUT_MS = 6e5;
15439
15716
  exports2.IDLE_CHECK_INTERVAL_MS = 15e3;
15440
15717
  exports2.KILL_GRACE_PERIOD_MS = 5e3;
15441
15718
  function clearTimers(timers) {
@@ -15635,6 +15912,7 @@ var require_executor = __commonJS({
15635
15912
  "use strict";
15636
15913
  Object.defineProperty(exports2, "__esModule", { value: true });
15637
15914
  exports2.executeOpenCode = executeOpenCode;
15915
+ exports2.resolveFinalRunCost = resolveFinalRunCost;
15638
15916
  var child_process_1 = require("child_process");
15639
15917
  var ditto_codegen_types_12 = require_dist4();
15640
15918
  var config_12 = require_config();
@@ -15654,6 +15932,10 @@ var require_executor = __commonJS({
15654
15932
  const accumulatedSkills = [];
15655
15933
  let currentPrompt = options.prompt;
15656
15934
  let continueSession = options.continueSession ?? false;
15935
+ const env = (0, config_12.getOpenCodeEnv)(options.projectId, job_context_storage_12.jobContextStorage.getStore()?.kind);
15936
+ const statsBaseline = await (0, cost_tracker_1.fetchOpenCodeStats)(options.outputPath, env);
15937
+ const baselineCost = statsBaseline ? (0, cost_tracker_1.parseStatsTotalCost)(statsBaseline) : null;
15938
+ logger_12.logger.debug("[OpenCode] Stats baseline before run", { baselineCost });
15657
15939
  for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
15658
15940
  if (attempt > 1) {
15659
15941
  logger_12.logger.info(`[OpenCode] Retry attempt ${attempt}/${MAX_RETRIES} - starting fresh session with recovery context`);
@@ -15667,8 +15949,10 @@ var require_executor = __commonJS({
15667
15949
  const errorMsg = result.error?.message.toLowerCase() ?? "";
15668
15950
  const isIdleTimeout = !result.success && errorMsg.includes("idle timeout");
15669
15951
  const isSessionError = (0, parser_1.hasSessionError)(result.stdout);
15670
- const isRetryableFailure = isIdleTimeout || isSessionError;
15952
+ const isProcessError = result.error instanceof ditto_codegen_types_12.ProcessExecutionError;
15953
+ const isRetryableFailure = isIdleTimeout || isSessionError || isProcessError;
15671
15954
  if (!isRetryableFailure) {
15955
+ accumulatedUsage = await resolveFinalRunCost(accumulatedUsage, options, baselineCost);
15672
15956
  const finalResult2 = {
15673
15957
  ...result,
15674
15958
  agentMessage: (0, parser_1.parseAnswerText)(result.stdout),
@@ -15676,11 +15960,10 @@ var require_executor = __commonJS({
15676
15960
  skillsUsed: accumulatedSkills
15677
15961
  };
15678
15962
  logger_12.logger.info("[OpenCode] Usage summary", { usage: finalResult2.usage });
15679
- await logOpenCodeStats(options);
15680
15963
  return finalResult2;
15681
15964
  }
15682
15965
  lastResult = result;
15683
- const reason = isSessionError ? "session error" : "idle timeout";
15966
+ const reason = isSessionError ? "session error" : isProcessError ? "process execution error" : "idle timeout";
15684
15967
  logger_12.logger.warn(`[OpenCode] Attempt failed due to ${reason}, will retry`, {
15685
15968
  attempt,
15686
15969
  maxRetries: MAX_RETRIES
@@ -15689,6 +15972,7 @@ var require_executor = __commonJS({
15689
15972
  logger_12.logger.warn("[OpenCode] All retry attempts exhausted", {
15690
15973
  maxRetries: MAX_RETRIES
15691
15974
  });
15975
+ accumulatedUsage = await resolveFinalRunCost(accumulatedUsage, options, baselineCost);
15692
15976
  const finalResult = {
15693
15977
  ...lastResult,
15694
15978
  agentMessage: (0, parser_1.parseAnswerText)(lastResult.stdout),
@@ -15696,16 +15980,27 @@ var require_executor = __commonJS({
15696
15980
  skillsUsed: Array.from(accumulatedSkills)
15697
15981
  };
15698
15982
  logger_12.logger.info("[OpenCode] Usage summary", { usage: finalResult.usage });
15699
- await logOpenCodeStats(options);
15700
15983
  return finalResult;
15701
15984
  }
15702
- async function logOpenCodeStats(options) {
15985
+ async function resolveFinalRunCost(usage, options, baselineCost) {
15703
15986
  const env = (0, config_12.getOpenCodeEnv)(options.projectId, job_context_storage_12.jobContextStorage.getStore()?.kind);
15704
- const stats = await (0, cost_tracker_1.fetchOpenCodeStats)(options.outputPath, env);
15705
- if (stats) {
15706
- console.log("[OpenCode] Stats\n", stats);
15707
- logger_12.logger.debug("[OpenCode] Stats", { stats });
15708
- }
15987
+ const statsFinal = await (0, cost_tracker_1.fetchOpenCodeStats)(options.outputPath, env);
15988
+ if (statsFinal) {
15989
+ console.log("[OpenCode] Stats\n", statsFinal);
15990
+ logger_12.logger.debug("[OpenCode] Stats", { stats: statsFinal });
15991
+ }
15992
+ const finalCost = statsFinal ? (0, cost_tracker_1.parseStatsTotalCost)(statsFinal) : null;
15993
+ if (baselineCost === null || finalCost === null)
15994
+ return usage;
15995
+ const runCost = (0, cost_tracker_1.computeStatsDeltaCost)(baselineCost, finalCost);
15996
+ if (runCost <= 0)
15997
+ return usage;
15998
+ logger_12.logger.info("[OpenCode] Run cost reconciled from stats delta", {
15999
+ baselineCost,
16000
+ finalCost,
16001
+ runCost
16002
+ });
16003
+ return { ...usage, cost: runCost };
15709
16004
  }
15710
16005
  function buildArgs(prompt, continueSession) {
15711
16006
  const sessionArgs = continueSession ? ["--continue"] : [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wix/ditto-codegen-public",
3
- "version": "1.0.396",
3
+ "version": "1.0.398",
4
4
  "description": "AI-powered Wix CLI app generator - standalone executable",
5
5
  "scripts": {
6
6
  "build": "node build.mjs",
@@ -29,5 +29,5 @@
29
29
  "esbuild": "^0.27.2",
30
30
  "vitest": "^4.0.16"
31
31
  },
32
- "falconPackageHash": "2f0586c4d53630355c7e9241bff1ad2835812ac4cdcbd3367c622614"
32
+ "falconPackageHash": "0c8db8ace78f75457d5473efa4a4a8a50beeb97c703c7e6367ad2082"
33
33
  }