@wix/ditto-codegen-public 1.0.397 → 1.0.399

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
@@ -113,7 +113,6 @@ var require_types_impl = __commonJS({
113
113
  TaskKind2["INIT_CODEGEN"] = "INIT_CODEGEN";
114
114
  TaskKind2["ITERATE_CODEGEN"] = "ITERATE_CODEGEN";
115
115
  TaskKind2["RUN_AGENT"] = "RUN_AGENT";
116
- TaskKind2["FIX_CODE"] = "FIX_CODE";
117
116
  TaskKind2["ASK_CODEGEN"] = "ASK_CODEGEN";
118
117
  TaskKind2["FIX_GIT_CONFLICTS"] = "FIX_GIT_CONFLICTS";
119
118
  })(TaskKind || (exports2.TaskKind = TaskKind = {}));
@@ -11502,6 +11501,254 @@ ${closeBrace}${tail}`;
11502
11501
  }
11503
11502
  });
11504
11503
 
11504
+ // dist/opencode-integration/types.js
11505
+ var require_types4 = __commonJS({
11506
+ "dist/opencode-integration/types.js"(exports2) {
11507
+ "use strict";
11508
+ Object.defineProperty(exports2, "__esModule", { value: true });
11509
+ exports2.PERMISSION_WILDCARD = void 0;
11510
+ exports2.tryParseJson = tryParseJson;
11511
+ exports2.PERMISSION_WILDCARD = "*";
11512
+ function tryParseJson(text) {
11513
+ try {
11514
+ return JSON.parse(text);
11515
+ } catch {
11516
+ return null;
11517
+ }
11518
+ }
11519
+ }
11520
+ });
11521
+
11522
+ // dist/opencode-integration/subagents.js
11523
+ var require_subagents = __commonJS({
11524
+ "dist/opencode-integration/subagents.js"(exports2) {
11525
+ "use strict";
11526
+ Object.defineProperty(exports2, "__esModule", { value: true });
11527
+ exports2.PRIMARY_AGENT_NAME = void 0;
11528
+ exports2.getAgentConfig = getAgentConfig;
11529
+ var types_1 = require_types4();
11530
+ var constants_1 = require_constants5();
11531
+ exports2.PRIMARY_AGENT_NAME = "codegen";
11532
+ var VALIDATOR_SUBAGENT_NAME = "codegen-validator";
11533
+ var WIX_DOCS_SUBAGENT_NAME = "codegen-wix-docs";
11534
+ var WDS_DOCS_SUBAGENT_NAME = "codegen-wds-docs";
11535
+ var VALIDATOR_DESCRIPTION = `Runs validate (tsc + wix build) and fixes the reported errors, consulting the
11536
+ wix-app skill / wix-mcp for SDK-shape errors; returns when the build is clean
11537
+ or reports what it couldn't fix. Validation step only \u2014 never generates features.`;
11538
+ var VALIDATOR_PROMPT = `Run 'validate({ runBuild: true })', fix the errors it reports, and re-run until
11539
+ it passes. You are fixing EXISTING code \u2014 do NOT add features or rewrite whole
11540
+ files. NEVER force a green build by suppressing types: no 'as any', no
11541
+ '@ts-ignore'/'@ts-expect-error', and do NOT switch a correct import (e.g.
11542
+ 'import { bookings } from "@wix/bookings"') to 'import * as' just to satisfy
11543
+ tsc \u2014 that ships code that compiles but breaks at runtime. A type error on a
11544
+ Wix SDK method/namespace/parameter means the call is WRONG: look up the correct
11545
+ usage via the 'wix-app' skill or wix-mcp ('SearchWixSDKDocumentation' \u2192
11546
+ 'ReadFullDocsMethodSchema') and fix it to the real exported method + its options
11547
+ object. Work in a bounded number of fix cycles \u2014 if the build isn't converging
11548
+ after a few attempts, STOP and return the remaining errors verbatim rather than
11549
+ looping; never silence them.`;
11550
+ var WIX_DOCS_DESCRIPTION = `Use ONLY to discover a Wix SDK you don't know and that the wix-app skill +
11551
+ KNOWN WIX APIS don't cover. Send ONE complete question; returns the import path
11552
+ + exported namespace/method + runtime context + full signature + any required
11553
+ scope/permission IDs + a short usage example (not a link). Don't fetch a doc you
11554
+ already identified, and don't split a lookup into separate search/signature
11555
+ calls. Read-only.`;
11556
+ var WIX_DOCS_PROMPT = `You research Wix SDK APIs via wix-mcp and report back \u2014 never write app code.
11557
+ The caller uses DIRECT imports inside an extension that already supplies
11558
+ auth/host: 'import { <namespace> } from "@wix/<pkg>"; await <namespace>.<method>(<optionsObject>)'
11559
+ \u2014 describe that form, NEVER a 'createClient'/'wixClient' client. Report the SDK,
11560
+ NOT the REST spec: REST names, namespaces, and positional params often differ,
11561
+ so verify the method EXISTS as an SDK export. Steps: (1) read the SDK
11562
+ introduction ('SearchWixSDKDocumentation' \u2192 'ReadFullDocsArticle') to confirm
11563
+ it's the RIGHT API and its runtime context \u2014 backend, the dashboard host, or the
11564
+ site/editor host (host modules like @wix/dashboard work ONLY in their own host);
11565
+ (2) read 'ReadFullDocsMethodSchema' for the exact exported name and its
11566
+ options-object parameters. Reply with: the import path + exported
11567
+ namespace/method, the runtime context, the full TypeScript signature, and a
11568
+ short usage example \u2014 never a bare link, never 'as any' or a guessed method. If
11569
+ the API is limited to one context, say so. For a required scope/permission,
11570
+ return the EXACT scope-ID string from the docs (never a guessed format); if none
11571
+ is documented, say so.`;
11572
+ var WDS_DOCS_DESCRIPTION = `Use ONLY when building dashboard UI and you need a Wix Design System
11573
+ component/prop/example you don't know and the wix-app skill doesn't cover.
11574
+ Returns the component name + props + a short usage example. Not for layouts the
11575
+ wix-app skill already covers. Read-only.`;
11576
+ var SUBAGENT_DENIED_TOOLS = {
11577
+ [
11578
+ "task"
11579
+ /* OpenCodeTool.Task */
11580
+ ]: "deny",
11581
+ [
11582
+ "todowrite"
11583
+ /* OpenCodeTool.TodoWrite */
11584
+ ]: "deny",
11585
+ [
11586
+ "todoread"
11587
+ /* OpenCodeTool.TodoRead */
11588
+ ]: "deny",
11589
+ [
11590
+ "uuid"
11591
+ /* OpenCodeTool.Uuid */
11592
+ ]: "deny",
11593
+ [
11594
+ "wix-generate"
11595
+ /* OpenCodeTool.WixGenerate */
11596
+ ]: "deny",
11597
+ [
11598
+ "required-permissions"
11599
+ /* OpenCodeTool.RequiredPermissions */
11600
+ ]: "deny",
11601
+ [
11602
+ "progress"
11603
+ /* OpenCodeTool.Progress */
11604
+ ]: "deny"
11605
+ };
11606
+ var DOCS_SUBAGENT_DENIED_TOOLS = {
11607
+ ...SUBAGENT_DENIED_TOOLS,
11608
+ [
11609
+ "edit"
11610
+ /* OpenCodeTool.Edit */
11611
+ ]: "deny",
11612
+ [
11613
+ "write"
11614
+ /* OpenCodeTool.Write */
11615
+ ]: "deny",
11616
+ [
11617
+ "batch-write"
11618
+ /* OpenCodeTool.BatchWrite */
11619
+ ]: "deny",
11620
+ [
11621
+ "multi-edit"
11622
+ /* OpenCodeTool.MultiEdit */
11623
+ ]: "deny",
11624
+ [
11625
+ "validate"
11626
+ /* OpenCodeTool.Validate */
11627
+ ]: "deny"
11628
+ };
11629
+ var READ_TOOLS = {
11630
+ [
11631
+ "read"
11632
+ /* OpenCodeTool.Read */
11633
+ ]: "allow",
11634
+ [
11635
+ "batch-read"
11636
+ /* OpenCodeTool.BatchRead */
11637
+ ]: "allow",
11638
+ [
11639
+ "grep"
11640
+ /* OpenCodeTool.Grep */
11641
+ ]: "allow",
11642
+ [
11643
+ "glob"
11644
+ /* OpenCodeTool.Glob */
11645
+ ]: "allow"
11646
+ };
11647
+ var WRITE_TOOLS = {
11648
+ [
11649
+ "edit"
11650
+ /* OpenCodeTool.Edit */
11651
+ ]: "allow",
11652
+ [
11653
+ "multi-edit"
11654
+ /* OpenCodeTool.MultiEdit */
11655
+ ]: "allow",
11656
+ [
11657
+ "write"
11658
+ /* OpenCodeTool.Write */
11659
+ ]: "allow",
11660
+ [
11661
+ "batch-write"
11662
+ /* OpenCodeTool.BatchWrite */
11663
+ ]: "allow"
11664
+ };
11665
+ function getAgentConfig(smallModel) {
11666
+ return {
11667
+ [exports2.PRIMARY_AGENT_NAME]: {
11668
+ mode: "primary",
11669
+ permission: {
11670
+ [
11671
+ "task"
11672
+ /* OpenCodeTool.Task */
11673
+ ]: {
11674
+ [types_1.PERMISSION_WILDCARD]: "deny",
11675
+ [VALIDATOR_SUBAGENT_NAME]: "allow",
11676
+ [WIX_DOCS_SUBAGENT_NAME]: "allow",
11677
+ [WDS_DOCS_SUBAGENT_NAME]: "allow"
11678
+ }
11679
+ }
11680
+ },
11681
+ [VALIDATOR_SUBAGENT_NAME]: {
11682
+ mode: "subagent",
11683
+ model: smallModel,
11684
+ steps: 40,
11685
+ description: VALIDATOR_DESCRIPTION,
11686
+ prompt: VALIDATOR_PROMPT,
11687
+ permission: {
11688
+ ...SUBAGENT_DENIED_TOOLS,
11689
+ ...READ_TOOLS,
11690
+ ...WRITE_TOOLS,
11691
+ // Runs tsc + wix build to drive the fix loop.
11692
+ [
11693
+ "validate"
11694
+ /* OpenCodeTool.Validate */
11695
+ ]: "allow",
11696
+ [
11697
+ "bash"
11698
+ /* OpenCodeTool.Bash */
11699
+ ]: "allow",
11700
+ [
11701
+ "skill"
11702
+ /* OpenCodeTool.Skill */
11703
+ ]: "allow",
11704
+ [constants_1.WIX_MCP_SERVER_NAME]: "allow"
11705
+ }
11706
+ },
11707
+ [WIX_DOCS_SUBAGENT_NAME]: {
11708
+ mode: "subagent",
11709
+ model: smallModel,
11710
+ steps: 15,
11711
+ description: WIX_DOCS_DESCRIPTION,
11712
+ prompt: WIX_DOCS_PROMPT,
11713
+ permission: {
11714
+ ...DOCS_SUBAGENT_DENIED_TOOLS,
11715
+ ...READ_TOOLS,
11716
+ [
11717
+ "bash"
11718
+ /* OpenCodeTool.Bash */
11719
+ ]: "deny",
11720
+ [
11721
+ "skill"
11722
+ /* OpenCodeTool.Skill */
11723
+ ]: "allow",
11724
+ [constants_1.WIX_MCP_SERVER_NAME]: "allow"
11725
+ }
11726
+ },
11727
+ [WDS_DOCS_SUBAGENT_NAME]: {
11728
+ mode: "subagent",
11729
+ model: smallModel,
11730
+ steps: 15,
11731
+ description: WDS_DOCS_DESCRIPTION,
11732
+ permission: {
11733
+ ...DOCS_SUBAGENT_DENIED_TOOLS,
11734
+ ...READ_TOOLS,
11735
+ // The wix-design-system skill shells out to a script, so bash is needed.
11736
+ [
11737
+ "bash"
11738
+ /* OpenCodeTool.Bash */
11739
+ ]: "allow",
11740
+ [
11741
+ "skill"
11742
+ /* OpenCodeTool.Skill */
11743
+ ]: "allow",
11744
+ [constants_1.WIX_MCP_SERVER_NAME]: "deny"
11745
+ }
11746
+ }
11747
+ };
11748
+ }
11749
+ }
11750
+ });
11751
+
11505
11752
  // dist/experiments.js
11506
11753
  var require_experiments = __commonJS({
11507
11754
  "dist/experiments.js"(exports2) {
@@ -14456,7 +14703,10 @@ MINIMIZE TEXT OUTPUT \u2014 CRITICAL:
14456
14703
 
14457
14704
  TOOL USAGE:
14458
14705
  - \`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).
14706
+ - \`validate\` (tsc + build) is run by the \`codegen-validator\` subagent \u2014 do NOT call it directly; delegate via \`task\` at step 5.
14707
+ - \`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.
14708
+ - 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.
14709
+ - If BOTH docs subagents are needed, fire both \`task\` calls in ONE response (parallel), never serially.
14460
14710
  - \`uuid\` to generate UUIDs (supports count param for multiple). Do NOT use bash.
14461
14711
  - \`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
14712
  - \`required-permissions\` \u2014 declare the Wix app permissions the generated code needs (when/whether to call: workflow step 6 + PERMISSIONS).
@@ -14467,7 +14717,7 @@ TOOL USAGE:
14467
14717
  - \`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
14718
  - 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
14719
  - 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.
14720
+ - 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
14721
  - NEVER run preview, dev, release, or promote commands.
14472
14722
 
14473
14723
  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 +14726,10 @@ KNOWN WIX APIS (already documented \u2014 do NOT rediscover these from node_modu
14476
14726
 
14477
14727
  IMPLEMENTATION WORKFLOW:
14478
14728
  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").
14729
+ 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
14730
  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
14731
  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").
14732
+ 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
14733
  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
14734
  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
14735
  8. **Stop**: STOP immediately. Do NOT refactor, clean up, or verify.
@@ -14747,6 +14997,7 @@ var require_config = __commonJS({
14747
14997
  var os_1 = require("os");
14748
14998
  var ditto_codegen_types_12 = require_dist4();
14749
14999
  var constants_1 = require_constants5();
15000
+ var subagents_1 = require_subagents();
14750
15001
  var experiments_1 = require_experiments();
14751
15002
  var rules_writer_12 = require_rules_writer();
14752
15003
  var node_modules_guard_12 = require_node_modules_guard();
@@ -14888,7 +15139,7 @@ var require_config = __commonJS({
14888
15139
  ]: "deny",
14889
15140
  external_directory: READABLE_EXTERNAL_DIRS
14890
15141
  };
14891
- function buildConfig(instructionPaths, permission, { guardNodeModules = false } = {}) {
15142
+ function buildConfig(instructionPaths, permission, { guardNodeModules = false, withAgents = false } = {}) {
14892
15143
  return {
14893
15144
  model: exports2.DEFAULT_MODEL,
14894
15145
  small_model: exports2.DEFAULT_SMALL_MODEL,
@@ -14900,7 +15151,14 @@ var require_config = __commonJS({
14900
15151
  lsp: false,
14901
15152
  mcp: WIX_MCP_CONFIG,
14902
15153
  watcher: { ignore: WATCHER_IGNORE_PATTERNS },
14903
- ...guardNodeModules ? { plugin: [node_modules_guard_12.GUARD_PLUGIN_PATH], autoupdate: false, share: "disabled" } : {}
15154
+ ...guardNodeModules ? { plugin: [node_modules_guard_12.GUARD_PLUGIN_PATH], autoupdate: false, share: "disabled" } : {},
15155
+ // Only code-writing flows register subagents. The read-only ask flow must
15156
+ // not: its primary agent re-opens `task`, which would let the write-capable
15157
+ // validator subagent run in a flow meant to stay read-only.
15158
+ ...withAgents ? {
15159
+ agent: (0, subagents_1.getAgentConfig)(exports2.DEFAULT_SMALL_MODEL),
15160
+ default_agent: subagents_1.PRIMARY_AGENT_NAME
15161
+ } : {}
14904
15162
  };
14905
15163
  }
14906
15164
  function ensureOpenCodeInPath() {
@@ -14934,33 +15192,19 @@ var require_config = __commonJS({
14934
15192
  return buildConfig(paths(env.askRules), ASK_PERMISSIONS);
14935
15193
  case CodeGenService_12.TaskKind.FIX_GIT_CONFLICTS:
14936
15194
  return buildConfig(paths(env.gitConflictsRules), GIT_CONFLICTS_PERMISSIONS, {
14937
- guardNodeModules: true
15195
+ guardNodeModules: true,
15196
+ withAgents: true
14938
15197
  });
14939
15198
  default:
14940
15199
  return buildConfig(paths(env.codegenRules), CODEGEN_PERMISSIONS, {
14941
- guardNodeModules: true
15200
+ guardNodeModules: true,
15201
+ withAgents: true
14942
15202
  });
14943
15203
  }
14944
15204
  }
14945
15205
  }
14946
15206
  });
14947
15207
 
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
15208
  // dist/opencode-integration/parser.js
14965
15209
  var require_parser = __commonJS({
14966
15210
  "dist/opencode-integration/parser.js"(exports2) {
@@ -15212,25 +15456,48 @@ var require_cost_tracker = __commonJS({
15212
15456
  "use strict";
15213
15457
  Object.defineProperty(exports2, "__esModule", { value: true });
15214
15458
  exports2.fetchOpenCodeStats = fetchOpenCodeStats;
15459
+ exports2.parseStatsTotalCost = parseStatsTotalCost;
15460
+ exports2.computeStatsDeltaCost = computeStatsDeltaCost;
15215
15461
  var child_process_1 = require("child_process");
15216
15462
  var util_1 = require("util");
15217
15463
  var logger_12 = require_logger();
15218
15464
  var execAsync = (0, util_1.promisify)(child_process_1.exec);
15219
15465
  var CLI_TIMEOUT_MS = 15e3;
15466
+ var STATS_MAX_ATTEMPTS = 3;
15467
+ var ANSI_ESCAPE = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`, "g");
15220
15468
  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;
15469
+ for (let attempt = 0; attempt < STATS_MAX_ATTEMPTS; attempt++) {
15470
+ try {
15471
+ const { stdout } = await execAsync("opencode stats --models", {
15472
+ cwd,
15473
+ env,
15474
+ timeout: CLI_TIMEOUT_MS
15475
+ });
15476
+ return stdout.trim() || null;
15477
+ } catch (error) {
15478
+ const isLastAttempt = attempt === STATS_MAX_ATTEMPTS - 1;
15479
+ logger_12.logger.warn("[OpenCode] Could not fetch opencode stats", {
15480
+ attempt: attempt + 1,
15481
+ maxAttempts: STATS_MAX_ATTEMPTS,
15482
+ willRetry: !isLastAttempt,
15483
+ error: error instanceof Error ? error.message : String(error)
15484
+ });
15485
+ if (isLastAttempt)
15486
+ return null;
15487
+ }
15233
15488
  }
15489
+ return null;
15490
+ }
15491
+ function parseStatsTotalCost(statsOutput) {
15492
+ const plain = statsOutput.replace(ANSI_ESCAPE, "");
15493
+ const match = plain.match(/Total Cost\s+\$([0-9]+(?:\.[0-9]+)?)/);
15494
+ if (!match)
15495
+ return null;
15496
+ const cost = Number.parseFloat(match[1]);
15497
+ return Number.isFinite(cost) ? cost : null;
15498
+ }
15499
+ function computeStatsDeltaCost(baselineCost, finalCost) {
15500
+ return Math.max(0, finalCost - baselineCost);
15234
15501
  }
15235
15502
  }
15236
15503
  });
@@ -15444,7 +15711,7 @@ var require_process_manager = __commonJS({
15444
15711
  exports2.clearTimers = clearTimers;
15445
15712
  exports2.killProcess = killProcess;
15446
15713
  var logger_12 = require_logger();
15447
- exports2.IDLE_TIMEOUT_MS = 24e4;
15714
+ exports2.IDLE_TIMEOUT_MS = 6e5;
15448
15715
  exports2.IDLE_CHECK_INTERVAL_MS = 15e3;
15449
15716
  exports2.KILL_GRACE_PERIOD_MS = 5e3;
15450
15717
  function clearTimers(timers) {
@@ -15644,6 +15911,7 @@ var require_executor = __commonJS({
15644
15911
  "use strict";
15645
15912
  Object.defineProperty(exports2, "__esModule", { value: true });
15646
15913
  exports2.executeOpenCode = executeOpenCode;
15914
+ exports2.resolveFinalRunCost = resolveFinalRunCost;
15647
15915
  var child_process_1 = require("child_process");
15648
15916
  var ditto_codegen_types_12 = require_dist4();
15649
15917
  var config_12 = require_config();
@@ -15663,6 +15931,10 @@ var require_executor = __commonJS({
15663
15931
  const accumulatedSkills = [];
15664
15932
  let currentPrompt = options.prompt;
15665
15933
  let continueSession = options.continueSession ?? false;
15934
+ const env = (0, config_12.getOpenCodeEnv)(options.projectId, job_context_storage_12.jobContextStorage.getStore()?.kind);
15935
+ const statsBaseline = await (0, cost_tracker_1.fetchOpenCodeStats)(options.outputPath, env);
15936
+ const baselineCost = statsBaseline ? (0, cost_tracker_1.parseStatsTotalCost)(statsBaseline) : null;
15937
+ logger_12.logger.debug("[OpenCode] Stats baseline before run", { baselineCost });
15666
15938
  for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
15667
15939
  if (attempt > 1) {
15668
15940
  logger_12.logger.info(`[OpenCode] Retry attempt ${attempt}/${MAX_RETRIES} - starting fresh session with recovery context`);
@@ -15676,8 +15948,10 @@ var require_executor = __commonJS({
15676
15948
  const errorMsg = result.error?.message.toLowerCase() ?? "";
15677
15949
  const isIdleTimeout = !result.success && errorMsg.includes("idle timeout");
15678
15950
  const isSessionError = (0, parser_1.hasSessionError)(result.stdout);
15679
- const isRetryableFailure = isIdleTimeout || isSessionError;
15951
+ const isProcessError = result.error instanceof ditto_codegen_types_12.ProcessExecutionError;
15952
+ const isRetryableFailure = isIdleTimeout || isSessionError || isProcessError;
15680
15953
  if (!isRetryableFailure) {
15954
+ accumulatedUsage = await resolveFinalRunCost(accumulatedUsage, options, baselineCost);
15681
15955
  const finalResult2 = {
15682
15956
  ...result,
15683
15957
  agentMessage: (0, parser_1.parseAnswerText)(result.stdout),
@@ -15685,11 +15959,10 @@ var require_executor = __commonJS({
15685
15959
  skillsUsed: accumulatedSkills
15686
15960
  };
15687
15961
  logger_12.logger.info("[OpenCode] Usage summary", { usage: finalResult2.usage });
15688
- await logOpenCodeStats(options);
15689
15962
  return finalResult2;
15690
15963
  }
15691
15964
  lastResult = result;
15692
- const reason = isSessionError ? "session error" : "idle timeout";
15965
+ const reason = isSessionError ? "session error" : isProcessError ? "process execution error" : "idle timeout";
15693
15966
  logger_12.logger.warn(`[OpenCode] Attempt failed due to ${reason}, will retry`, {
15694
15967
  attempt,
15695
15968
  maxRetries: MAX_RETRIES
@@ -15698,6 +15971,7 @@ var require_executor = __commonJS({
15698
15971
  logger_12.logger.warn("[OpenCode] All retry attempts exhausted", {
15699
15972
  maxRetries: MAX_RETRIES
15700
15973
  });
15974
+ accumulatedUsage = await resolveFinalRunCost(accumulatedUsage, options, baselineCost);
15701
15975
  const finalResult = {
15702
15976
  ...lastResult,
15703
15977
  agentMessage: (0, parser_1.parseAnswerText)(lastResult.stdout),
@@ -15705,16 +15979,27 @@ var require_executor = __commonJS({
15705
15979
  skillsUsed: Array.from(accumulatedSkills)
15706
15980
  };
15707
15981
  logger_12.logger.info("[OpenCode] Usage summary", { usage: finalResult.usage });
15708
- await logOpenCodeStats(options);
15709
15982
  return finalResult;
15710
15983
  }
15711
- async function logOpenCodeStats(options) {
15984
+ async function resolveFinalRunCost(usage, options, baselineCost) {
15712
15985
  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
- }
15986
+ const statsFinal = await (0, cost_tracker_1.fetchOpenCodeStats)(options.outputPath, env);
15987
+ if (statsFinal) {
15988
+ console.log("[OpenCode] Stats\n", statsFinal);
15989
+ logger_12.logger.debug("[OpenCode] Stats", { stats: statsFinal });
15990
+ }
15991
+ const finalCost = statsFinal ? (0, cost_tracker_1.parseStatsTotalCost)(statsFinal) : null;
15992
+ if (baselineCost === null || finalCost === null)
15993
+ return usage;
15994
+ const runCost = (0, cost_tracker_1.computeStatsDeltaCost)(baselineCost, finalCost);
15995
+ if (runCost <= 0)
15996
+ return usage;
15997
+ logger_12.logger.info("[OpenCode] Run cost reconciled from stats delta", {
15998
+ baselineCost,
15999
+ finalCost,
16000
+ runCost
16001
+ });
16002
+ return { ...usage, cost: runCost };
15718
16003
  }
15719
16004
  function buildArgs(prompt, continueSession) {
15720
16005
  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.399",
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": "639b09f42d56304b11f1af865c04965d768f5449b8883a0b7e85b572"
33
33
  }