@alphafox/cli 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +4 -3
  2. package/dist/auth/loopback-callback.js +6 -6
  3. package/dist/catalog/allowlist.d.ts +1 -1
  4. package/dist/catalog/allowlist.js +1 -1
  5. package/dist/catalog/generated/registry.json +338 -49
  6. package/dist/catalog/generated/schemas.json +1880 -779
  7. package/dist/catalog/omit.d.ts +6 -0
  8. package/dist/catalog/omit.js +11 -0
  9. package/dist/catalog/operations.d.ts +1 -1
  10. package/dist/catalog/operations.js +5 -2
  11. package/dist/commands/run.js +10 -3
  12. package/dist/engine-backtest/load-config.d.ts +4 -0
  13. package/dist/engine-backtest/load-config.js +44 -0
  14. package/dist/engine-backtest/parse-args.d.ts +3 -1
  15. package/dist/engine-backtest/parse-args.js +87 -3
  16. package/dist/engine-backtest/parse-axes.d.ts +3 -0
  17. package/dist/engine-backtest/parse-axes.js +167 -0
  18. package/dist/engine-backtest/persist.d.ts +60 -1
  19. package/dist/engine-backtest/persist.js +196 -1
  20. package/dist/engine-backtest/return-curve.d.ts +27 -0
  21. package/dist/engine-backtest/return-curve.js +80 -0
  22. package/dist/engine-backtest/run-command.d.ts +1 -4
  23. package/dist/engine-backtest/run-command.js +61 -45
  24. package/dist/engine-backtest/sweep-command.d.ts +13 -0
  25. package/dist/engine-backtest/sweep-command.js +749 -0
  26. package/dist/engine-backtest/sweep-kernel/caps.d.ts +26 -0
  27. package/dist/engine-backtest/sweep-kernel/caps.js +48 -0
  28. package/dist/engine-backtest/sweep-kernel/index.d.ts +13 -0
  29. package/dist/engine-backtest/sweep-kernel/index.js +34 -0
  30. package/dist/engine-backtest/sweep-kernel/plan.d.ts +22 -0
  31. package/dist/engine-backtest/sweep-kernel/plan.js +320 -0
  32. package/dist/engine-backtest/sweep-kernel/results.d.ts +72 -0
  33. package/dist/engine-backtest/sweep-kernel/results.js +150 -0
  34. package/dist/engine-backtest/sweep-kernel/session.d.ts +55 -0
  35. package/dist/engine-backtest/sweep-kernel/session.js +56 -0
  36. package/dist/engine-backtest/sweep-kernel/types.d.ts +36 -0
  37. package/dist/engine-backtest/sweep-kernel/types.js +2 -0
  38. package/dist/engine-backtest/types.d.ts +130 -0
  39. package/dist/install/exec.js +5 -1
  40. package/dist/install/wizard.js +26 -29
  41. package/dist/resolve-symbols/catalog.d.ts +3 -0
  42. package/dist/resolve-symbols/catalog.js +50 -0
  43. package/dist/resolve-symbols/errors.d.ts +18 -0
  44. package/dist/resolve-symbols/errors.js +26 -0
  45. package/dist/resolve-symbols/exchanges.d.ts +8 -0
  46. package/dist/resolve-symbols/exchanges.js +53 -0
  47. package/dist/resolve-symbols/match.d.ts +6 -0
  48. package/dist/resolve-symbols/match.js +250 -0
  49. package/dist/resolve-symbols/parse-args.d.ts +5 -0
  50. package/dist/resolve-symbols/parse-args.js +106 -0
  51. package/dist/resolve-symbols/run-command.d.ts +21 -0
  52. package/dist/resolve-symbols/run-command.js +149 -0
  53. package/dist/resolve-symbols/types.d.ts +37 -0
  54. package/dist/resolve-symbols/types.js +2 -0
  55. package/dist/version.d.ts +1 -1
  56. package/dist/version.js +1 -1
  57. package/docs/alphafox-cli-installation-guide.md +2 -2
  58. package/package.json +1 -1
  59. package/skills/account/SKILL.md +1 -1
  60. package/skills/admin/SKILL.md +1 -1
  61. package/skills/alphafox/SKILL.md +38 -0
  62. package/skills/alphafox-shared/SKILL.md +5 -1
  63. package/skills/auth/SKILL.md +1 -1
  64. package/skills/engine-backtest/SKILL.md +48 -6
  65. package/skills/exchange/SKILL.md +1 -1
  66. package/skills/market/SKILL.md +27 -4
  67. package/skills/notification/SKILL.md +1 -1
  68. package/skills/strategy/SKILL.md +7 -20
  69. package/skills/trading/SKILL.md +3 -1
@@ -0,0 +1,749 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SWEEP_WASM_BATCH_VARIANTS = exports.MAX_ENGINE_BACKTEST_BATCH_VARIANTS = void 0;
4
+ exports.cloneTapeBuffers = cloneTapeBuffers;
5
+ exports.splitBatchChunk = splitBatchChunk;
6
+ exports.executeEngineBacktestSweep = executeEngineBacktestSweep;
7
+ const node_crypto_1 = require("node:crypto");
8
+ const profiles_1 = require("../config/profiles");
9
+ const client_1 = require("../http/client");
10
+ const store_1 = require("../keychain/store");
11
+ const errors_1 = require("./errors");
12
+ const load_config_1 = require("./load-config");
13
+ const parse_axes_1 = require("./parse-axes");
14
+ const persist_1 = require("./persist");
15
+ const replay_timeframe_1 = require("./replay-timeframe");
16
+ const resolve_packages_1 = require("./resolve-packages");
17
+ const sweep_kernel_1 = require("./sweep-kernel");
18
+ /** WASM `runBacktestBatch` hard limit. Keep in sync with Engine. */
19
+ exports.MAX_ENGINE_BACKTEST_BATCH_VARIANTS = 256;
20
+ /** Sweep chunk size: below the 256 cap so JSONL can refresh mid-search. */
21
+ exports.SWEEP_WASM_BATCH_VARIANTS = 32;
22
+ const CREATE_EXPERIMENT_PATH = "/api/v1/engine-backtest/experiments";
23
+ const SUBSCRIPTION_PATH = "/api/v1/subscriptions/me";
24
+ const SUBSCRIPTION_TIERS = new Set([
25
+ "free",
26
+ "pro",
27
+ "pro_max",
28
+ ]);
29
+ function cloneTapeBuffers(sourceBuffers) {
30
+ return Object.fromEntries(Object.entries(sourceBuffers).map(([key, buffer]) => [key, buffer.slice(0)]));
31
+ }
32
+ function splitBatchChunk(chunk, maxVariants = exports.MAX_ENGINE_BACKTEST_BATCH_VARIANTS) {
33
+ const limit = Math.max(1, Math.floor(maxVariants));
34
+ if (chunk.length <= limit)
35
+ return [chunk.slice()];
36
+ const parts = [];
37
+ for (let offset = 0; offset < chunk.length; offset += limit) {
38
+ parts.push(chunk.slice(offset, offset + limit));
39
+ }
40
+ return parts;
41
+ }
42
+ async function executeEngineBacktestSweep(args, flags, env = process.env, deps = {}) {
43
+ if (args.help) {
44
+ throw new errors_1.EngineBacktestError({
45
+ type: "usage",
46
+ message: "internal: help should be handled by the command wrapper",
47
+ });
48
+ }
49
+ if (!args.definitionId || !args.configRaw || !args.exchange || !args.range || !args.axesRaw) {
50
+ throw new errors_1.EngineBacktestError({
51
+ type: "usage",
52
+ subtype: "invalid_args",
53
+ message: "Missing required sweep arguments",
54
+ status: 400,
55
+ });
56
+ }
57
+ const startedAt = (deps.now ?? Date.now)();
58
+ const profile = (0, profiles_1.resolveProfile)(flags.profile, env, {
59
+ unsafeCustomEndpoint: flags.unsafeCustomEndpoint,
60
+ });
61
+ const api = deps.apiRequest ?? client_1.apiRequest;
62
+ const tokensFn = deps.loadTokens ?? store_1.loadTokens;
63
+ const persist = args.persist && !flags.dryRun;
64
+ const createExperiment = args.createExperiment && !flags.dryRun;
65
+ const mintId = deps.randomUUID ?? node_crypto_1.randomUUID;
66
+ const writeLine = deps.writeLine ??
67
+ ((value) => {
68
+ process.stdout.write(`${JSON.stringify(value)}\n`);
69
+ });
70
+ if (persist) {
71
+ requireAuth(profile, env, tokensFn);
72
+ }
73
+ const config = asConfigRecord((0, load_config_1.loadConfigValue)(args.configRaw, {
74
+ cwd: deps.cwd,
75
+ readFile: deps.readFile,
76
+ }));
77
+ const axisInputs = (0, parse_axes_1.parseSweepAxesDocument)((0, load_config_1.loadConfigValue)(args.axesRaw, {
78
+ cwd: deps.cwd,
79
+ readFile: deps.readFile,
80
+ }), config, args.mode);
81
+ const { wasm, runner } = await loadRuntime(deps, env);
82
+ const clients = [];
83
+ try {
84
+ const client = wasm.createNodeBacktestClient();
85
+ clients.push(client);
86
+ if (typeof client.init === "function") {
87
+ await client.init();
88
+ }
89
+ const configSchemaVersion = await resolveConfigSchemaVersion(client, args.definitionId, args.configSchemaVersion);
90
+ let subscriptionTier = args.tier ?? "pro";
91
+ if (persist) {
92
+ const accountTier = await loadAccountSubscriptionTier(api, profile, env);
93
+ if (args.tier !== undefined && args.tier !== accountTier) {
94
+ throw new errors_1.EngineBacktestError({
95
+ type: "usage",
96
+ subtype: "subscription_tier_mismatch",
97
+ message: `--tier ${args.tier} does not match account subscription tier ${accountTier}`,
98
+ hint: "Remove --tier for persisted sweeps, or use --no-persist to simulate another tier.",
99
+ status: 400,
100
+ details: { requestedTier: args.tier, accountTier },
101
+ });
102
+ }
103
+ subscriptionTier = accountTier;
104
+ }
105
+ const concurrency = (0, sweep_kernel_1.resolveSweepConcurrency)({
106
+ subscriptionTier,
107
+ requested: args.concurrency,
108
+ });
109
+ const coarsePlan = (0, sweep_kernel_1.planSweep)({
110
+ axes: axisInputs,
111
+ searchMode: args.searchMode,
112
+ subscriptionTier,
113
+ });
114
+ const standardPlan = args.searchMode === "fast"
115
+ ? (0, sweep_kernel_1.planSweep)({
116
+ axes: axisInputs,
117
+ searchMode: "standard",
118
+ subscriptionTier,
119
+ })
120
+ : coarsePlan;
121
+ if (coarsePlan.coordinates.length === 0) {
122
+ throw new errors_1.EngineBacktestError({
123
+ type: "usage",
124
+ subtype: "empty_sweep",
125
+ message: "Sweep plan produced no coordinates",
126
+ status: 400,
127
+ });
128
+ }
129
+ emitProgress(flags, writeLine, "planning", 0);
130
+ const plannedByKey = new Map();
131
+ const tapePlans = [];
132
+ for (const [index, coordinate] of standardPlan.coordinates.entries()) {
133
+ const planned = await planCoordinate({
134
+ client,
135
+ definitionId: args.definitionId,
136
+ configSchemaVersion,
137
+ config,
138
+ axes: coarsePlan.axes,
139
+ coordinate,
140
+ });
141
+ plannedByKey.set(coordinateKey(coordinate), planned);
142
+ if ("plan" in planned) {
143
+ tapePlans.push(planned.plan);
144
+ }
145
+ emitProgress(flags, writeLine, "planning", (index + 1) / standardPlan.coordinates.length);
146
+ }
147
+ let exchange;
148
+ try {
149
+ exchange = runner.resolveTapeExchange(args.exchange);
150
+ }
151
+ catch (err) {
152
+ throw new errors_1.EngineBacktestError({
153
+ type: "usage",
154
+ subtype: "invalid_exchange",
155
+ message: err instanceof Error ? err.message : String(err),
156
+ status: 400,
157
+ });
158
+ }
159
+ const coverage = unionTapePlans(tapePlans);
160
+ const replayPlan = (0, replay_timeframe_1.mergeReplayTimeframeWithPlan)({
161
+ replayTimeframe: args.replayTimeframe,
162
+ planTimeframes: coverage.timeframes,
163
+ seriesRequirements: coverage.seriesRequirements,
164
+ symbols: coverage.symbols,
165
+ });
166
+ emitProgress(flags, writeLine, "tape", 0);
167
+ let tapeResult = {
168
+ tape: {
169
+ from: "",
170
+ to: "",
171
+ baseTimeframe: replayPlan.baseTimeframe,
172
+ markets: {},
173
+ series: [],
174
+ },
175
+ buffers: {},
176
+ coverageWarnings: [],
177
+ };
178
+ if (tapePlans.length > 0) {
179
+ try {
180
+ tapeResult = await runner.loadTape({
181
+ exchangeId: exchange.id,
182
+ exchange,
183
+ symbols: coverage.symbols,
184
+ baseTimeframe: replayPlan.baseTimeframe,
185
+ timeframes: replayPlan.timeframes,
186
+ seriesRequirements: replayPlan.seriesRequirements,
187
+ needsFunding: coverage.needsFunding,
188
+ auxiliaryDataRequirements: coverage.auxiliaryDataRequirements,
189
+ fromMs: args.range.fromMs,
190
+ toMs: args.range.toMs,
191
+ dataQualityMode: args.dataQualityMode,
192
+ onProgress: (progress) => {
193
+ emitProgress(flags, writeLine, progress.stage || "tape", progress.fraction, progress.detail);
194
+ },
195
+ });
196
+ }
197
+ catch (err) {
198
+ if ((0, errors_1.isEngineBacktestError)(err))
199
+ throw err;
200
+ const issues = err && typeof err === "object" && "issues" in err
201
+ ? err.issues
202
+ : undefined;
203
+ throw new errors_1.EngineBacktestError({
204
+ type: "runtime",
205
+ subtype: issues ? "tape_unavailable" : "tape_load_failed",
206
+ message: err instanceof Error ? err.message : String(err),
207
+ details: issues ? { issues } : undefined,
208
+ });
209
+ }
210
+ }
211
+ emitProgress(flags, writeLine, "tape", 1);
212
+ while (clients.length < concurrency) {
213
+ const extra = wasm.createNodeBacktestClient();
214
+ clients.push(extra);
215
+ if (typeof extra.init === "function") {
216
+ await extra.init();
217
+ }
218
+ }
219
+ const executionModel = {
220
+ ...(runner.DEFAULT_EXECUTION_MODEL ?? persist_1.DEFAULT_EXECUTION_MODEL),
221
+ ...args.executionModelOverride,
222
+ };
223
+ const maxVariantsPerBatch = Math.min(exports.MAX_ENGINE_BACKTEST_BATCH_VARIANTS, Math.max(1, deps.maxVariantsPerBatch ?? exports.SWEEP_WASM_BATCH_VARIANTS));
224
+ const runPrepared = async (coordinates, onSweepProgress) => {
225
+ const failed = [];
226
+ const ready = [];
227
+ for (const coordinate of coordinates) {
228
+ const planned = plannedByKey.get(coordinateKey(coordinate)) ??
229
+ (await planCoordinate({
230
+ client,
231
+ definitionId: args.definitionId,
232
+ configSchemaVersion,
233
+ config,
234
+ axes: coarsePlan.axes,
235
+ coordinate,
236
+ }));
237
+ if ("status" in planned) {
238
+ failed.push(planned);
239
+ }
240
+ else {
241
+ ready.push(planned);
242
+ }
243
+ }
244
+ onSweepProgress(failed.length, failed);
245
+ const executed = await executeSweepBatches({
246
+ clients,
247
+ runner,
248
+ ready,
249
+ tape: tapeResult.tape,
250
+ buffers: tapeResult.buffers,
251
+ definitionId: args.definitionId,
252
+ configSchemaVersion,
253
+ subscriptionTier,
254
+ initialEquity: args.initialEquity,
255
+ executionModel,
256
+ mintId,
257
+ maxVariantsPerBatch,
258
+ onProgress: (done, points) => {
259
+ onSweepProgress(failed.length + done, [...failed, ...points]);
260
+ },
261
+ });
262
+ return [...failed, ...executed];
263
+ };
264
+ const exactTotalEstimate = args.searchMode === "fast"
265
+ ? standardPlan.coordinates.length
266
+ : coarsePlan.coordinates.length;
267
+ let sweepPoints = [];
268
+ emitProgress(flags, writeLine, "sweep", 0);
269
+ const coarsePoints = await runPrepared(coarsePlan.coordinates, (done, points) => {
270
+ sweepPoints = points;
271
+ emitProgress(flags, writeLine, "sweep", done / Math.max(exactTotalEstimate, 1));
272
+ });
273
+ sweepPoints = coarsePoints;
274
+ let refinement = [];
275
+ if (args.searchMode === "fast") {
276
+ const center = (0, sweep_kernel_1.selectBestNonLiquidatedPoint)(coarsePoints);
277
+ refinement = center
278
+ ? (0, sweep_kernel_1.planSweepFastRefinement)({
279
+ coarsePlan,
280
+ standardPlan,
281
+ center: center.coordinate,
282
+ })
283
+ : [];
284
+ }
285
+ if (refinement.length > 0) {
286
+ const refinementPoints = await runPrepared(refinement, (done, points) => {
287
+ sweepPoints = [...coarsePoints, ...points];
288
+ emitProgress(flags, writeLine, "sweep", (coarsePlan.coordinates.length + done) /
289
+ (coarsePlan.coordinates.length + refinement.length));
290
+ });
291
+ sweepPoints = [...coarsePoints, ...refinementPoints];
292
+ }
293
+ emitProgress(flags, writeLine, "sweep", 1);
294
+ const engineVersion = (typeof client.version === "function"
295
+ ? (await client.version()).trim()
296
+ : "") || "node-wasm";
297
+ const best = (0, sweep_kernel_1.selectBestNonLiquidatedPoint)(sweepPoints);
298
+ const successful = sweepPoints.filter((point) => point.status === "ok");
299
+ const elapsedMs = Math.max(0, (deps.now ?? Date.now)() - startedAt);
300
+ const sampled = standardPlan.requestedCombinationCount >
301
+ coarsePlan.coordinates.length + refinement.length;
302
+ const completed = (0, persist_1.shouldPersistSweepCompletion)({
303
+ completed: true,
304
+ cancelled: false,
305
+ });
306
+ let experimentId = args.experimentId;
307
+ let sweepId;
308
+ let clientSweepId;
309
+ let persisted = false;
310
+ if (persist && completed) {
311
+ emitProgress(flags, writeLine, "persist", 0);
312
+ if (createExperiment) {
313
+ const created = await postJson(api, profile, env, CREATE_EXPERIMENT_PATH, {
314
+ name: args.name,
315
+ strategyDefinitionId: args.definitionId,
316
+ strategyDefinitionDisplay: {
317
+ zh: args.definitionLabelZh?.trim() || args.definitionId,
318
+ en: args.definitionLabelEn?.trim() || args.definitionId,
319
+ },
320
+ }, mintId);
321
+ experimentId = extractEntityId(created.json);
322
+ if (!experimentId) {
323
+ throw new errors_1.EngineBacktestError({
324
+ type: "runtime",
325
+ subtype: "create_experiment_no_id",
326
+ message: "experiments.create response did not include an id",
327
+ details: created.json,
328
+ });
329
+ }
330
+ }
331
+ if (!experimentId) {
332
+ throw new errors_1.EngineBacktestError({
333
+ type: "usage",
334
+ subtype: "missing_experiment",
335
+ message: "Provide --experiment <uuid> or --create-experiment --name <name>",
336
+ status: 400,
337
+ });
338
+ }
339
+ const tapeSymbols = (0, persist_1.uniqueSeriesField)(tapeResult.tape.series, "symbol");
340
+ const snapshot = (0, persist_1.buildSweepBaseSnapshot)({
341
+ definitionId: args.definitionId,
342
+ configSchemaVersion,
343
+ config,
344
+ exchangeId: exchange.id,
345
+ rangeStart: tapeResult.tape.from
346
+ ? tapeResult.tape.from.slice(0, 10)
347
+ : args.range.rangeStart,
348
+ rangeEnd: tapeResult.tape.to
349
+ ? (0, persist_1.exclusiveTapeEndToRangeEnd)(tapeResult.tape.to)
350
+ : args.range.rangeEnd,
351
+ initialEquity: args.initialEquity,
352
+ subscriptionTier,
353
+ dataQualityMode: args.dataQualityMode,
354
+ symbols: tapeSymbols.length > 0 ? tapeSymbols : coverage.symbols,
355
+ timeframes: (0, persist_1.uniqueSeriesField)(tapeResult.tape.series, "timeframe"),
356
+ baseTimeframe: tapeResult.tape.baseTimeframe || args.replayTimeframe,
357
+ executionModel,
358
+ positionSideDual: true,
359
+ engineVersion,
360
+ });
361
+ clientSweepId = (0, persist_1.mintClientSweepId)(mintId);
362
+ const body = (0, persist_1.buildCreateSweepRequest)({
363
+ clientSweepId,
364
+ snapshot,
365
+ axes: coarsePlan.axes,
366
+ mode: args.mode,
367
+ searchMode: args.searchMode,
368
+ concurrency,
369
+ requestedCombinationCount: standardPlan.requestedCombinationCount,
370
+ sampled,
371
+ points: sweepPoints,
372
+ successfulCount: successful.length,
373
+ failedCount: sweepPoints.length - successful.length,
374
+ liquidatedCount: successful.filter((point) => (point.metrics?.liquidationCount ?? 0) > 0).length,
375
+ elapsedMs,
376
+ best,
377
+ engineVersion,
378
+ });
379
+ const saved = await postJson(api, profile, env, (0, persist_1.sweepsPath)(experimentId), body, mintId);
380
+ sweepId = extractEntityId(saved.json);
381
+ if (!sweepId) {
382
+ throw new errors_1.EngineBacktestError({
383
+ type: "runtime",
384
+ subtype: "create_sweep_no_id",
385
+ message: "sweeps.create response did not include an id",
386
+ details: saved.json,
387
+ });
388
+ }
389
+ persisted = true;
390
+ emitProgress(flags, writeLine, "persist", 1);
391
+ }
392
+ return {
393
+ persisted,
394
+ sweepId,
395
+ clientSweepId,
396
+ mode: args.mode,
397
+ searchMode: args.searchMode,
398
+ requestedCombinationCount: standardPlan.requestedCombinationCount,
399
+ sampled,
400
+ combinationCount: sweepPoints.length,
401
+ successfulCount: successful.length,
402
+ failedCount: sweepPoints.length - successful.length,
403
+ liquidatedCount: successful.filter((point) => (point.metrics?.liquidationCount ?? 0) > 0).length,
404
+ elapsedMs,
405
+ best: best
406
+ ? {
407
+ coordinate: best.coordinate,
408
+ returnPct: best.returnPct,
409
+ config: (0, sweep_kernel_1.applySweepCoordinate)(config, coarsePlan.axes, best.coordinate),
410
+ }
411
+ : null,
412
+ points: sweepPoints,
413
+ engineVersion,
414
+ experimentId,
415
+ experimentUrl: experimentId
416
+ ? (0, persist_1.experimentSweepPageUrl)(profile.name, experimentId)
417
+ : undefined,
418
+ coverageWarnings: tapeResult.coverageWarnings ?? [],
419
+ axes: coarsePlan.axes,
420
+ };
421
+ }
422
+ finally {
423
+ for (const client of clients) {
424
+ client.terminate();
425
+ }
426
+ }
427
+ }
428
+ function requireAuth(profile, env, loadTokensFn) {
429
+ const tokens = loadTokensFn(profile.name, env);
430
+ if (tokens?.accessToken?.trim())
431
+ return;
432
+ throw new errors_1.EngineBacktestError({
433
+ type: "http",
434
+ status: 401,
435
+ message: "Not authenticated. Run alphafox auth login.",
436
+ hint: "Tokens live in the OS keychain. Do not pass --token.",
437
+ subtype: "unauthenticated",
438
+ });
439
+ }
440
+ function extractErrorMessage(json, fallback) {
441
+ if (json && typeof json === "object") {
442
+ const o = json;
443
+ if (typeof o.message === "string")
444
+ return o.message;
445
+ if (typeof o.detail === "string")
446
+ return o.detail;
447
+ if (typeof o.error === "string")
448
+ return o.error;
449
+ if (o.error && typeof o.error === "object") {
450
+ const e = o.error;
451
+ if (typeof e.message === "string")
452
+ return e.message;
453
+ }
454
+ }
455
+ return fallback || "Request failed";
456
+ }
457
+ function extractErrorCode(json) {
458
+ if (json && typeof json === "object") {
459
+ const o = json;
460
+ if (typeof o.code === "string" || typeof o.code === "number")
461
+ return o.code;
462
+ }
463
+ return undefined;
464
+ }
465
+ function extractEntityId(json) {
466
+ if (!json || typeof json !== "object")
467
+ return undefined;
468
+ const o = json;
469
+ if (typeof o.id === "string" && o.id.trim())
470
+ return o.id.trim();
471
+ if (o.data && typeof o.data === "object") {
472
+ const d = o.data;
473
+ if (typeof d.id === "string" && d.id.trim())
474
+ return d.id.trim();
475
+ }
476
+ return undefined;
477
+ }
478
+ function extractSubscriptionTier(json) {
479
+ if (!json || typeof json !== "object")
480
+ return undefined;
481
+ const root = json;
482
+ const nested = root.data && typeof root.data === "object"
483
+ ? root.data
484
+ : undefined;
485
+ const value = root.subscriptionTier ?? nested?.subscriptionTier;
486
+ return typeof value === "string" &&
487
+ SUBSCRIPTION_TIERS.has(value)
488
+ ? value
489
+ : undefined;
490
+ }
491
+ async function postJson(api, profile, env, path, body, mintId) {
492
+ const res = await api({
493
+ method: "POST",
494
+ path,
495
+ body,
496
+ profile,
497
+ idempotencyKey: mintId(),
498
+ }, env);
499
+ if (res.status >= 400) {
500
+ throw new errors_1.EngineBacktestError({
501
+ type: "http",
502
+ status: res.status,
503
+ message: extractErrorMessage(res.json, res.bodyText),
504
+ code: extractErrorCode(res.json),
505
+ details: res.json,
506
+ });
507
+ }
508
+ return res;
509
+ }
510
+ async function loadAccountSubscriptionTier(api, profile, env) {
511
+ const res = await api({
512
+ method: "GET",
513
+ path: SUBSCRIPTION_PATH,
514
+ profile,
515
+ }, env);
516
+ if (res.status >= 400) {
517
+ throw new errors_1.EngineBacktestError({
518
+ type: "http",
519
+ status: res.status,
520
+ message: extractErrorMessage(res.json, res.bodyText),
521
+ code: extractErrorCode(res.json),
522
+ details: res.json,
523
+ });
524
+ }
525
+ const tier = extractSubscriptionTier(res.json);
526
+ if (!tier) {
527
+ throw new errors_1.EngineBacktestError({
528
+ type: "runtime",
529
+ subtype: "subscription_tier_unresolved",
530
+ message: "subscriptions.me response did not include a valid subscriptionTier",
531
+ details: res.json,
532
+ });
533
+ }
534
+ return tier;
535
+ }
536
+ async function loadRuntime(deps, env) {
537
+ if (deps.createNodeBacktestClient &&
538
+ deps.loadTape &&
539
+ deps.assembleScenario &&
540
+ deps.resolveTapeExchange) {
541
+ return {
542
+ wasm: { createNodeBacktestClient: deps.createNodeBacktestClient },
543
+ runner: {
544
+ loadTape: deps.loadTape,
545
+ assembleScenario: deps.assembleScenario,
546
+ resolveTapeExchange: deps.resolveTapeExchange,
547
+ DEFAULT_EXECUTION_MODEL: deps.defaultExecutionModel ?? persist_1.DEFAULT_EXECUTION_MODEL,
548
+ },
549
+ };
550
+ }
551
+ const [wasmLoaded, runnerLoaded] = await Promise.all([
552
+ (0, resolve_packages_1.loadBacktestWasm)(env, deps.resolveHooks),
553
+ (0, resolve_packages_1.loadBacktestRunner)(env, deps.resolveHooks),
554
+ ]);
555
+ return { wasm: wasmLoaded.module, runner: runnerLoaded.module };
556
+ }
557
+ async function resolveConfigSchemaVersion(client, definitionId, explicit) {
558
+ if (explicit !== undefined) {
559
+ return explicit;
560
+ }
561
+ const listed = await client.strategyDefinitions();
562
+ const found = listed.definitions.find((d) => d.id === definitionId);
563
+ const version = found?.configSchemaVersion;
564
+ if (typeof version !== "number" || !Number.isInteger(version) || version <= 0) {
565
+ throw new errors_1.EngineBacktestError({
566
+ type: "runtime",
567
+ subtype: "config_schema_version_unresolved",
568
+ message: `strategyDefinitions() has no configSchemaVersion for "${definitionId}"`,
569
+ hint: "Pass --config-schema-version explicitly.",
570
+ details: { definitionId },
571
+ });
572
+ }
573
+ return version;
574
+ }
575
+ async function planCoordinate(input) {
576
+ const nextConfig = (0, sweep_kernel_1.applySweepCoordinate)(input.config, input.axes, input.coordinate);
577
+ try {
578
+ const plan = await input.client.planBacktest({
579
+ definitionId: input.definitionId,
580
+ configSchemaVersion: input.configSchemaVersion,
581
+ config: nextConfig,
582
+ });
583
+ if (!isSupportedPlan(plan)) {
584
+ const reason = plan && typeof plan === "object" && "support" in plan
585
+ ? plan.support
586
+ ?.reason
587
+ : undefined;
588
+ return {
589
+ coordinate: input.coordinate,
590
+ status: "failed",
591
+ error: reason?.message ??
592
+ `planBacktest does not support definition "${input.definitionId}"`,
593
+ };
594
+ }
595
+ return {
596
+ coordinate: input.coordinate,
597
+ config: nextConfig,
598
+ plan,
599
+ };
600
+ }
601
+ catch (err) {
602
+ if ((0, errors_1.isEngineBacktestError)(err))
603
+ throw err;
604
+ return {
605
+ coordinate: input.coordinate,
606
+ status: "failed",
607
+ error: err instanceof Error ? err.message : String(err),
608
+ };
609
+ }
610
+ }
611
+ async function executeSweepBatches(input) {
612
+ if (input.ready.length === 0) {
613
+ return [];
614
+ }
615
+ const workers = input.clients.slice(0, Math.min(input.clients.length, input.ready.length));
616
+ const chunks = partitionRoundRobin(input.ready, workers.length);
617
+ const completed = Array.from({
618
+ length: input.ready.length,
619
+ });
620
+ await Promise.all(chunks.map(async (chunk, workerIndex) => {
621
+ const client = workers[workerIndex];
622
+ for (const subChunk of splitBatchChunk(chunk, input.maxVariantsPerBatch)) {
623
+ const scenarios = subChunk.map((item) => input.runner.assembleScenario({
624
+ runId: input.mintId(),
625
+ definitionId: input.definitionId,
626
+ configSchemaVersion: input.configSchemaVersion,
627
+ config: item.item.config,
628
+ subscriptionTier: input.subscriptionTier,
629
+ initialEquity: input.initialEquity,
630
+ tape: input.tape,
631
+ executionModel: input.executionModel,
632
+ }));
633
+ const first = scenarios[0];
634
+ if (!first)
635
+ continue;
636
+ const { tape: _tape, ...baseScenario } = first;
637
+ const batch = {
638
+ version: 1,
639
+ batchId: input.mintId(),
640
+ baseScenario,
641
+ variants: scenarios.map((scenario) => ({
642
+ runId: scenario.runId,
643
+ config: scenario.trader.config,
644
+ })),
645
+ tape: input.tape,
646
+ };
647
+ const result = await client.runBacktestBatch(batch, cloneTapeBuffers(input.buffers));
648
+ if (result.results.length !== subChunk.length) {
649
+ throw new errors_1.EngineBacktestError({
650
+ type: "runtime",
651
+ subtype: "batch_result_count",
652
+ message: "runBacktestBatch returned an unexpected result count",
653
+ details: {
654
+ expected: subChunk.length,
655
+ actual: result.results.length,
656
+ },
657
+ });
658
+ }
659
+ subChunk.forEach((entry, index) => {
660
+ const point = result.results[index];
661
+ completed[entry.index] = readBatchPoint(entry.item.coordinate, point);
662
+ });
663
+ const finished = completed.filter((point) => point !== undefined);
664
+ input.onProgress(finished.length, finished);
665
+ }
666
+ }));
667
+ return completed.filter((point) => point !== undefined);
668
+ }
669
+ function readBatchPoint(coordinate, point) {
670
+ if (point.status === "completed") {
671
+ return {
672
+ coordinate,
673
+ status: "ok",
674
+ metrics: (0, sweep_kernel_1.extractSweepMetrics)(point.metrics),
675
+ };
676
+ }
677
+ return {
678
+ coordinate,
679
+ status: "failed",
680
+ error: point.errors?.[0]?.message ?? "runBacktestBatch variant failed",
681
+ };
682
+ }
683
+ function partitionRoundRobin(items, workerCount) {
684
+ const count = Math.min(Math.max(1, workerCount), items.length);
685
+ const chunks = Array.from({ length: count }, () => []);
686
+ items.forEach((item, index) => {
687
+ chunks[index % count].push({ index, item });
688
+ });
689
+ return chunks;
690
+ }
691
+ function unionTapePlans(plans) {
692
+ const symbols = [...new Set(plans.flatMap((plan) => plan.symbols))];
693
+ const timeframes = [...new Set(plans.flatMap((plan) => plan.timeframes))];
694
+ const warmup = new Map();
695
+ for (const plan of plans) {
696
+ for (const requirement of plan.seriesRequirements) {
697
+ const key = `${requirement.symbol}\u0000${requirement.timeframe}`;
698
+ const previous = warmup.get(key);
699
+ if (!previous ||
700
+ requirement.minWarmupCandles > previous.minWarmupCandles) {
701
+ warmup.set(key, requirement);
702
+ }
703
+ }
704
+ }
705
+ const auxiliary = new Map();
706
+ for (const plan of plans) {
707
+ for (const item of plan.auxiliaryDataRequirements) {
708
+ auxiliary.set(JSON.stringify(item), item);
709
+ }
710
+ }
711
+ return {
712
+ symbols,
713
+ timeframes,
714
+ seriesRequirements: [...warmup.values()],
715
+ needsFunding: plans.some((plan) => plan.needsFunding),
716
+ auxiliaryDataRequirements: [...auxiliary.values()],
717
+ };
718
+ }
719
+ function isSupportedPlan(plan) {
720
+ return (!!plan &&
721
+ typeof plan === "object" &&
722
+ !("status" in plan && plan.status === "failed") &&
723
+ "support" in plan &&
724
+ plan.support?.status === "supported");
725
+ }
726
+ function asConfigRecord(value) {
727
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
728
+ throw new errors_1.EngineBacktestError({
729
+ type: "usage",
730
+ subtype: "invalid_config",
731
+ message: "--config must be a JSON object",
732
+ status: 400,
733
+ });
734
+ }
735
+ return value;
736
+ }
737
+ function coordinateKey(coordinate) {
738
+ return coordinate.values.join("\u0000");
739
+ }
740
+ function emitProgress(flags, writeLine, stage, fraction, detail) {
741
+ if (flags.format !== "jsonl")
742
+ return;
743
+ writeLine({
744
+ event: "progress",
745
+ stage,
746
+ fraction,
747
+ ...(detail ? { detail } : {}),
748
+ });
749
+ }