@wix/ditto-codegen-public 1.0.397 → 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
@@ -11502,6 +11502,254 @@ ${closeBrace}${tail}`;
11502
11502
  }
11503
11503
  });
11504
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
+
11505
11753
  // dist/experiments.js
11506
11754
  var require_experiments = __commonJS({
11507
11755
  "dist/experiments.js"(exports2) {
@@ -14456,7 +14704,10 @@ MINIMIZE TEXT OUTPUT \u2014 CRITICAL:
14456
14704
 
14457
14705
  TOOL USAGE:
14458
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.
14459
- - \`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.
14460
14711
  - \`uuid\` to generate UUIDs (supports count param for multiple). Do NOT use bash.
14461
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.
14462
14713
  - \`required-permissions\` \u2014 declare the Wix app permissions the generated code needs (when/whether to call: workflow step 6 + PERMISSIONS).
@@ -14467,7 +14718,7 @@ TOOL USAGE:
14467
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.
14468
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.
14469
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.
14470
- - 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.
14471
14722
  - NEVER run preview, dev, release, or promote commands.
14472
14723
 
14473
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\`):
@@ -14476,10 +14727,10 @@ KNOWN WIX APIS (already documented \u2014 do NOT rediscover these from node_modu
14476
14727
 
14477
14728
  IMPLEMENTATION WORKFLOW:
14478
14729
  1. **Plan**: Determine extension types using the \`wix-app\` skill. Generate ALL UUIDs upfront. Include a \`progress\` call (e.g. "Planning extensions").
14479
- 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.
14480
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").
14481
14732
  4. **Register**: Register all extensions in \`src/extensions.ts\`. Include a \`progress\` call (e.g. "Registering extensions").
14482
- 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.
14483
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.
14484
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).
14485
14736
  8. **Stop**: STOP immediately. Do NOT refactor, clean up, or verify.
@@ -14747,6 +14998,7 @@ var require_config = __commonJS({
14747
14998
  var os_1 = require("os");
14748
14999
  var ditto_codegen_types_12 = require_dist4();
14749
15000
  var constants_1 = require_constants5();
15001
+ var subagents_1 = require_subagents();
14750
15002
  var experiments_1 = require_experiments();
14751
15003
  var rules_writer_12 = require_rules_writer();
14752
15004
  var node_modules_guard_12 = require_node_modules_guard();
@@ -14888,7 +15140,7 @@ var require_config = __commonJS({
14888
15140
  ]: "deny",
14889
15141
  external_directory: READABLE_EXTERNAL_DIRS
14890
15142
  };
14891
- function buildConfig(instructionPaths, permission, { guardNodeModules = false } = {}) {
15143
+ function buildConfig(instructionPaths, permission, { guardNodeModules = false, withAgents = false } = {}) {
14892
15144
  return {
14893
15145
  model: exports2.DEFAULT_MODEL,
14894
15146
  small_model: exports2.DEFAULT_SMALL_MODEL,
@@ -14900,7 +15152,14 @@ var require_config = __commonJS({
14900
15152
  lsp: false,
14901
15153
  mcp: WIX_MCP_CONFIG,
14902
15154
  watcher: { ignore: WATCHER_IGNORE_PATTERNS },
14903
- ...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
+ } : {}
14904
15163
  };
14905
15164
  }
14906
15165
  function ensureOpenCodeInPath() {
@@ -14934,33 +15193,19 @@ var require_config = __commonJS({
14934
15193
  return buildConfig(paths(env.askRules), ASK_PERMISSIONS);
14935
15194
  case CodeGenService_12.TaskKind.FIX_GIT_CONFLICTS:
14936
15195
  return buildConfig(paths(env.gitConflictsRules), GIT_CONFLICTS_PERMISSIONS, {
14937
- guardNodeModules: true
15196
+ guardNodeModules: true,
15197
+ withAgents: true
14938
15198
  });
14939
15199
  default:
14940
15200
  return buildConfig(paths(env.codegenRules), CODEGEN_PERMISSIONS, {
14941
- guardNodeModules: true
15201
+ guardNodeModules: true,
15202
+ withAgents: true
14942
15203
  });
14943
15204
  }
14944
15205
  }
14945
15206
  }
14946
15207
  });
14947
15208
 
14948
- // dist/opencode-integration/types.js
14949
- var require_types4 = __commonJS({
14950
- "dist/opencode-integration/types.js"(exports2) {
14951
- "use strict";
14952
- Object.defineProperty(exports2, "__esModule", { value: true });
14953
- exports2.tryParseJson = tryParseJson;
14954
- function tryParseJson(text) {
14955
- try {
14956
- return JSON.parse(text);
14957
- } catch {
14958
- return null;
14959
- }
14960
- }
14961
- }
14962
- });
14963
-
14964
15209
  // dist/opencode-integration/parser.js
14965
15210
  var require_parser = __commonJS({
14966
15211
  "dist/opencode-integration/parser.js"(exports2) {
@@ -15212,25 +15457,48 @@ var require_cost_tracker = __commonJS({
15212
15457
  "use strict";
15213
15458
  Object.defineProperty(exports2, "__esModule", { value: true });
15214
15459
  exports2.fetchOpenCodeStats = fetchOpenCodeStats;
15460
+ exports2.parseStatsTotalCost = parseStatsTotalCost;
15461
+ exports2.computeStatsDeltaCost = computeStatsDeltaCost;
15215
15462
  var child_process_1 = require("child_process");
15216
15463
  var util_1 = require("util");
15217
15464
  var logger_12 = require_logger();
15218
15465
  var execAsync = (0, util_1.promisify)(child_process_1.exec);
15219
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");
15220
15469
  async function fetchOpenCodeStats(cwd, env) {
15221
- try {
15222
- const { stdout } = await execAsync("opencode stats --models", {
15223
- cwd,
15224
- env,
15225
- timeout: CLI_TIMEOUT_MS
15226
- });
15227
- return stdout.trim() || null;
15228
- } catch (error) {
15229
- logger_12.logger.warn("[OpenCode] Could not fetch opencode stats", {
15230
- error: error instanceof Error ? error.message : String(error)
15231
- });
15232
- 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
+ }
15233
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);
15234
15502
  }
15235
15503
  }
15236
15504
  });
@@ -15444,7 +15712,7 @@ var require_process_manager = __commonJS({
15444
15712
  exports2.clearTimers = clearTimers;
15445
15713
  exports2.killProcess = killProcess;
15446
15714
  var logger_12 = require_logger();
15447
- exports2.IDLE_TIMEOUT_MS = 24e4;
15715
+ exports2.IDLE_TIMEOUT_MS = 6e5;
15448
15716
  exports2.IDLE_CHECK_INTERVAL_MS = 15e3;
15449
15717
  exports2.KILL_GRACE_PERIOD_MS = 5e3;
15450
15718
  function clearTimers(timers) {
@@ -15644,6 +15912,7 @@ var require_executor = __commonJS({
15644
15912
  "use strict";
15645
15913
  Object.defineProperty(exports2, "__esModule", { value: true });
15646
15914
  exports2.executeOpenCode = executeOpenCode;
15915
+ exports2.resolveFinalRunCost = resolveFinalRunCost;
15647
15916
  var child_process_1 = require("child_process");
15648
15917
  var ditto_codegen_types_12 = require_dist4();
15649
15918
  var config_12 = require_config();
@@ -15663,6 +15932,10 @@ var require_executor = __commonJS({
15663
15932
  const accumulatedSkills = [];
15664
15933
  let currentPrompt = options.prompt;
15665
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 });
15666
15939
  for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
15667
15940
  if (attempt > 1) {
15668
15941
  logger_12.logger.info(`[OpenCode] Retry attempt ${attempt}/${MAX_RETRIES} - starting fresh session with recovery context`);
@@ -15676,8 +15949,10 @@ var require_executor = __commonJS({
15676
15949
  const errorMsg = result.error?.message.toLowerCase() ?? "";
15677
15950
  const isIdleTimeout = !result.success && errorMsg.includes("idle timeout");
15678
15951
  const isSessionError = (0, parser_1.hasSessionError)(result.stdout);
15679
- const isRetryableFailure = isIdleTimeout || isSessionError;
15952
+ const isProcessError = result.error instanceof ditto_codegen_types_12.ProcessExecutionError;
15953
+ const isRetryableFailure = isIdleTimeout || isSessionError || isProcessError;
15680
15954
  if (!isRetryableFailure) {
15955
+ accumulatedUsage = await resolveFinalRunCost(accumulatedUsage, options, baselineCost);
15681
15956
  const finalResult2 = {
15682
15957
  ...result,
15683
15958
  agentMessage: (0, parser_1.parseAnswerText)(result.stdout),
@@ -15685,11 +15960,10 @@ var require_executor = __commonJS({
15685
15960
  skillsUsed: accumulatedSkills
15686
15961
  };
15687
15962
  logger_12.logger.info("[OpenCode] Usage summary", { usage: finalResult2.usage });
15688
- await logOpenCodeStats(options);
15689
15963
  return finalResult2;
15690
15964
  }
15691
15965
  lastResult = result;
15692
- const reason = isSessionError ? "session error" : "idle timeout";
15966
+ const reason = isSessionError ? "session error" : isProcessError ? "process execution error" : "idle timeout";
15693
15967
  logger_12.logger.warn(`[OpenCode] Attempt failed due to ${reason}, will retry`, {
15694
15968
  attempt,
15695
15969
  maxRetries: MAX_RETRIES
@@ -15698,6 +15972,7 @@ var require_executor = __commonJS({
15698
15972
  logger_12.logger.warn("[OpenCode] All retry attempts exhausted", {
15699
15973
  maxRetries: MAX_RETRIES
15700
15974
  });
15975
+ accumulatedUsage = await resolveFinalRunCost(accumulatedUsage, options, baselineCost);
15701
15976
  const finalResult = {
15702
15977
  ...lastResult,
15703
15978
  agentMessage: (0, parser_1.parseAnswerText)(lastResult.stdout),
@@ -15705,16 +15980,27 @@ var require_executor = __commonJS({
15705
15980
  skillsUsed: Array.from(accumulatedSkills)
15706
15981
  };
15707
15982
  logger_12.logger.info("[OpenCode] Usage summary", { usage: finalResult.usage });
15708
- await logOpenCodeStats(options);
15709
15983
  return finalResult;
15710
15984
  }
15711
- async function logOpenCodeStats(options) {
15985
+ async function resolveFinalRunCost(usage, options, baselineCost) {
15712
15986
  const env = (0, config_12.getOpenCodeEnv)(options.projectId, job_context_storage_12.jobContextStorage.getStore()?.kind);
15713
- const stats = await (0, cost_tracker_1.fetchOpenCodeStats)(options.outputPath, env);
15714
- if (stats) {
15715
- console.log("[OpenCode] Stats\n", stats);
15716
- logger_12.logger.debug("[OpenCode] Stats", { stats });
15717
- }
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 };
15718
16004
  }
15719
16005
  function buildArgs(prompt, continueSession) {
15720
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.397",
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": "3684f6224ad8e1cf1c5eb60a17727f8448f1f7cc0d79dcefc42157f6"
32
+ "falconPackageHash": "0c8db8ace78f75457d5473efa4a4a8a50beeb97c703c7e6367ad2082"
33
33
  }