@vtxmacro/cli 2026.10.61 → 2026.10.63
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.
- package/bin/exo-harness.ts +2 -1
- package/bin/vtx-mcp.js +3 -2
- package/bin/vtx-service-bootstrap.js +3 -2
- package/bin/vtx-service-launcher.js +2 -1
- package/bin/vtx.js +709 -399
- package/package.json +1 -1
package/bin/vtx.js
CHANGED
|
@@ -122,7 +122,7 @@ var init_routing = __esm({
|
|
|
122
122
|
var agent_cli_release_default;
|
|
123
123
|
var init_agent_cli_release = __esm({
|
|
124
124
|
"agent-cli-release.json"() {
|
|
125
|
-
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.
|
|
125
|
+
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.63", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
|
|
126
126
|
}
|
|
127
127
|
});
|
|
128
128
|
|
|
@@ -917,7 +917,8 @@ var init_runtime_policy_generated = __esm({
|
|
|
917
917
|
request_bounds: {
|
|
918
918
|
min_agent_instruction_retry_after_ms: 25,
|
|
919
919
|
max_fallback_error_length: 500,
|
|
920
|
-
max_trade_sync_executions: 64
|
|
920
|
+
max_trade_sync_executions: 64,
|
|
921
|
+
max_user_cancel_order_ids: 64
|
|
921
922
|
},
|
|
922
923
|
pending_protection_recovery: {
|
|
923
924
|
retry_exponent_max: 30
|
|
@@ -22631,7 +22632,8 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
22631
22632
|
request_bounds: {
|
|
22632
22633
|
min_agent_instruction_retry_after_ms: 25,
|
|
22633
22634
|
max_fallback_error_length: 500,
|
|
22634
|
-
max_trade_sync_executions: 64
|
|
22635
|
+
max_trade_sync_executions: 64,
|
|
22636
|
+
max_user_cancel_order_ids: 64
|
|
22635
22637
|
},
|
|
22636
22638
|
pending_protection_recovery: {
|
|
22637
22639
|
retry_exponent_max: 30
|
|
@@ -26683,6 +26685,9 @@ async function refreshInferenceCredential(options) {
|
|
|
26683
26685
|
timeoutMs: options.requestTimeoutMs
|
|
26684
26686
|
}
|
|
26685
26687
|
);
|
|
26688
|
+
if (tokens.refreshToken === credential.refresh_token) {
|
|
26689
|
+
return { accessToken: tokens.accessToken, expiresIn: tokens.expiresIn, credential, accountKey: accountKey2 };
|
|
26690
|
+
}
|
|
26686
26691
|
const rotated = validateInferenceHostCredential({
|
|
26687
26692
|
...credential,
|
|
26688
26693
|
refresh_token: tokens.refreshToken,
|
|
@@ -59986,6 +59991,7 @@ var init_client_exchange_mutation_begin = __esm({
|
|
|
59986
59991
|
...payload.protectiveActionId ? { protective_action_id: payload.protectiveActionId } : {},
|
|
59987
59992
|
...payload.signedPayload ? { signed_payload: payload.signedPayload } : {},
|
|
59988
59993
|
...payload.safetyClose ? { safety_close: payload.safetyClose } : {},
|
|
59994
|
+
...payload.userCancel != null ? { user_cancel: payload.userCancel } : {},
|
|
59989
59995
|
attempt_evidence: payload.attemptEvidence ? {
|
|
59990
59996
|
requested_exchange_size: payload.attemptEvidence.requestedExchangeSize ?? null,
|
|
59991
59997
|
submitted_limit_price: payload.attemptEvidence.submittedLimitPrice ?? null,
|
|
@@ -61190,187 +61196,6 @@ var init_billing = __esm({
|
|
|
61190
61196
|
}
|
|
61191
61197
|
});
|
|
61192
61198
|
|
|
61193
|
-
// lib/api/market-data.ts
|
|
61194
|
-
async function getRecentCandles(limit, exchange = "kraken", symbol2 = "PI_XBTUSD", timeframe = "1m", signal) {
|
|
61195
|
-
return (await readRecentCandles(limit, exchange, symbol2, timeframe, signal, null)).candles;
|
|
61196
|
-
}
|
|
61197
|
-
async function getRecentCandlesForProfile(profileId, limit, exchange, symbol2, timeframe, signal) {
|
|
61198
|
-
return readRecentCandles(limit, exchange, symbol2, timeframe, signal, profileId);
|
|
61199
|
-
}
|
|
61200
|
-
async function getLiveTicker(symbol2 = "PI_XBTUSD", exchange = "kraken", signal) {
|
|
61201
|
-
const requestKey = `live-ticker:${symbol2}:${exchange}`;
|
|
61202
|
-
return shareClientGetRequest(requestKey, async (requestSignal) => {
|
|
61203
|
-
const requestUrl2 = `${getApiUrl()}/ticker/live?symbol=${encodeURIComponent(symbol2)}&exchange=${encodeURIComponent(exchange)}`;
|
|
61204
|
-
const trace = startRuntimeNetworkDebugTrace({
|
|
61205
|
-
kind: "runtime",
|
|
61206
|
-
label: "market_data_api:ticker_live",
|
|
61207
|
-
method: "GET",
|
|
61208
|
-
url: requestUrl2,
|
|
61209
|
-
note: `symbol=${symbol2} exchange=${exchange}`
|
|
61210
|
-
});
|
|
61211
|
-
let response = null;
|
|
61212
|
-
try {
|
|
61213
|
-
response = await apiFetch(requestUrl2, { cache: "no-store", signal: requestSignal });
|
|
61214
|
-
if (!response.ok) {
|
|
61215
|
-
const error48 = await buildMarketDataFetchError(response, "live ticker", "/ticker/live");
|
|
61216
|
-
trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
|
|
61217
|
-
trace.completeError(error48, response.status);
|
|
61218
|
-
throw error48;
|
|
61219
|
-
}
|
|
61220
|
-
trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
|
|
61221
|
-
const payload = await response.json();
|
|
61222
|
-
trace.completeSuccess(response.status);
|
|
61223
|
-
return payload;
|
|
61224
|
-
} catch (error48) {
|
|
61225
|
-
if (response && !response.ok) throw error48;
|
|
61226
|
-
if (response && !isAbortLikeError(error48)) {
|
|
61227
|
-
const failure2 = buildMarketDataResponseBodyError(error48, "live ticker", response, "/ticker/live");
|
|
61228
|
-
trace.completeError(failure2, response.status);
|
|
61229
|
-
throw failure2;
|
|
61230
|
-
}
|
|
61231
|
-
trace.completeError(error48, response?.status ?? null);
|
|
61232
|
-
if (isAbortLikeError(error48)) throw error48;
|
|
61233
|
-
throw buildMarketDataNetworkError(error48, "live ticker", "/ticker/live");
|
|
61234
|
-
}
|
|
61235
|
-
}, { signal });
|
|
61236
|
-
}
|
|
61237
|
-
async function getExecutionAssetMetadata(exchange, symbol2, options) {
|
|
61238
|
-
const params = new URLSearchParams();
|
|
61239
|
-
if (options?.forceCatalogRefresh) params.set("force_catalog_refresh", "true");
|
|
61240
|
-
if (options?.publicRequestPriority) params.set("public_request_priority", options.publicRequestPriority);
|
|
61241
|
-
const query = params.size > 0 ? `?${params.toString()}` : "";
|
|
61242
|
-
const url2 = `${getApiUrl()}/trading/execution-metadata/${encodeURIComponent(exchange)}/${encodeURIComponent(symbol2)}${query}`;
|
|
61243
|
-
const response = await apiFetch(url2, {
|
|
61244
|
-
headers: getProfileHeaders({}, options?.profileId),
|
|
61245
|
-
credentials: "include",
|
|
61246
|
-
cache: "no-store",
|
|
61247
|
-
signal: options?.signal
|
|
61248
|
-
});
|
|
61249
|
-
if (!response.ok) {
|
|
61250
|
-
const summary = `Failed to fetch execution asset metadata: ${response.status} ${response.statusText}`;
|
|
61251
|
-
const code = await response.clone().json().then((body) => typeof body?.detail?.code === "string" ? body.detail.code : null).catch(() => null);
|
|
61252
|
-
const detail = await getErrorMessageFromResponse(response, summary);
|
|
61253
|
-
throw new ExecutionAssetMetadataRequestError(
|
|
61254
|
-
detail === summary ? summary : `${summary}: ${detail}`,
|
|
61255
|
-
response.status,
|
|
61256
|
-
parseRetryAfterMs2(response.headers.get("Retry-After")),
|
|
61257
|
-
code
|
|
61258
|
-
);
|
|
61259
|
-
}
|
|
61260
|
-
return response.json();
|
|
61261
|
-
}
|
|
61262
|
-
var CANDLES_MISSING_HEADER, CandlesMissingRangeError, parseCandlesMissing, readRecentCandles, ExecutionAssetMetadataRequestError, CLIENT_EXECUTION_METADATA_DEVICE_READ, executionMetadataNeedsDeviceRead;
|
|
61263
|
-
var init_market_data = __esm({
|
|
61264
|
-
"lib/api/market-data.ts"() {
|
|
61265
|
-
"use strict";
|
|
61266
|
-
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
61267
|
-
init_define_VTX_EXO_POLICY();
|
|
61268
|
-
init_define_VTX_GROK_POLICY();
|
|
61269
|
-
init_define_VTX_PI_MODEL_POLICY();
|
|
61270
|
-
init_abort();
|
|
61271
|
-
init_runtime_redaction();
|
|
61272
|
-
init_network_debug();
|
|
61273
|
-
init_shared();
|
|
61274
|
-
init_constants();
|
|
61275
|
-
CANDLES_MISSING_HEADER = "X-VTX-Candles-Missing";
|
|
61276
|
-
CandlesMissingRangeError = class extends Error {
|
|
61277
|
-
};
|
|
61278
|
-
parseCandlesMissing = (value) => {
|
|
61279
|
-
if (value === null || value.trim() === "") return null;
|
|
61280
|
-
const [startText, endText, ...extra] = value.split(",");
|
|
61281
|
-
const startMs = Number(startText?.trim());
|
|
61282
|
-
const endMs = Number(endText?.trim());
|
|
61283
|
-
if (extra.length > 0 || !Number.isSafeInteger(startMs) || !Number.isSafeInteger(endMs) || startMs > endMs) {
|
|
61284
|
-
throw new CandlesMissingRangeError(`The candle answer named an unreadable missing range: ${sanitizeRuntimeDiagnosticValue(value)}`);
|
|
61285
|
-
}
|
|
61286
|
-
return { startMs, endMs };
|
|
61287
|
-
};
|
|
61288
|
-
readRecentCandles = async (limit, exchange, symbol2, timeframe, signal, profileId) => {
|
|
61289
|
-
const params = new URLSearchParams({ limit: limit.toString(), exchange, symbol: symbol2, timeframe });
|
|
61290
|
-
const requestUrl2 = `${getApiUrl()}/candles/recent?${params.toString()}`;
|
|
61291
|
-
const forProfile = profileId === null ? {} : { credentials: "include", headers: getProfileHeaders({}, profileId) };
|
|
61292
|
-
return shareClientGetRequest(`recent-candles:${profileId ?? "none"}:${params.toString()}`, async (requestSignal) => {
|
|
61293
|
-
const trace = startRuntimeNetworkDebugTrace({
|
|
61294
|
-
kind: "runtime",
|
|
61295
|
-
label: "market_data_api:candles_recent",
|
|
61296
|
-
method: "GET",
|
|
61297
|
-
url: requestUrl2,
|
|
61298
|
-
note: `symbol=${symbol2} exchange=${exchange} timeframe=${timeframe} limit=${limit}`
|
|
61299
|
-
});
|
|
61300
|
-
let response = null;
|
|
61301
|
-
try {
|
|
61302
|
-
response = await apiFetch(requestUrl2, {
|
|
61303
|
-
...forProfile,
|
|
61304
|
-
cache: "no-store",
|
|
61305
|
-
signal: requestSignal
|
|
61306
|
-
});
|
|
61307
|
-
if (!response.ok) {
|
|
61308
|
-
const error48 = await buildMarketDataFetchError(response, "recent candles", "/candles/recent");
|
|
61309
|
-
trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
|
|
61310
|
-
trace.completeError(error48, response.status);
|
|
61311
|
-
console.error(`[API] ${error48.message} URL: ${response.url}`);
|
|
61312
|
-
throw error48;
|
|
61313
|
-
}
|
|
61314
|
-
trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
|
|
61315
|
-
const missing2 = parseCandlesMissing(response.headers.get(CANDLES_MISSING_HEADER));
|
|
61316
|
-
const payload = await response.json();
|
|
61317
|
-
trace.completeSuccess(response.status);
|
|
61318
|
-
return { candles: payload, missing: missing2 };
|
|
61319
|
-
} catch (error48) {
|
|
61320
|
-
if (response && !response.ok) throw error48;
|
|
61321
|
-
if (response && error48 instanceof CandlesMissingRangeError) {
|
|
61322
|
-
trace.completeError(error48, response.status);
|
|
61323
|
-
throw error48;
|
|
61324
|
-
}
|
|
61325
|
-
if (response && !isAbortLikeError(error48)) {
|
|
61326
|
-
const failure2 = buildMarketDataResponseBodyError(error48, "recent candles", response, "/candles/recent");
|
|
61327
|
-
trace.completeError(failure2, response.status);
|
|
61328
|
-
throw failure2;
|
|
61329
|
-
}
|
|
61330
|
-
trace.completeError(error48, response?.status ?? null);
|
|
61331
|
-
if (isAbortLikeError(error48)) throw error48;
|
|
61332
|
-
throw buildMarketDataNetworkError(error48, "recent candles", "/candles/recent");
|
|
61333
|
-
}
|
|
61334
|
-
}, { signal, shareAbortScoped: true });
|
|
61335
|
-
};
|
|
61336
|
-
ExecutionAssetMetadataRequestError = class extends Error {
|
|
61337
|
-
constructor(message, status, retryAfterMs, code = null) {
|
|
61338
|
-
super(message);
|
|
61339
|
-
this.status = status;
|
|
61340
|
-
this.retryAfterMs = retryAfterMs;
|
|
61341
|
-
this.code = code;
|
|
61342
|
-
this.name = "ExecutionAssetMetadataRequestError";
|
|
61343
|
-
}
|
|
61344
|
-
};
|
|
61345
|
-
CLIENT_EXECUTION_METADATA_DEVICE_READ = "client_execution_metadata_device_read";
|
|
61346
|
-
executionMetadataNeedsDeviceRead = (error48) => error48 instanceof ExecutionAssetMetadataRequestError && error48.code === CLIENT_EXECUTION_METADATA_DEVICE_READ;
|
|
61347
|
-
}
|
|
61348
|
-
});
|
|
61349
|
-
|
|
61350
|
-
// lib/api/screener.ts
|
|
61351
|
-
var init_screener = __esm({
|
|
61352
|
-
"lib/api/screener.ts"() {
|
|
61353
|
-
"use strict";
|
|
61354
|
-
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
61355
|
-
init_define_VTX_EXO_POLICY();
|
|
61356
|
-
init_define_VTX_GROK_POLICY();
|
|
61357
|
-
init_define_VTX_PI_MODEL_POLICY();
|
|
61358
|
-
init_shared();
|
|
61359
|
-
}
|
|
61360
|
-
});
|
|
61361
|
-
|
|
61362
|
-
// lib/api/client-host-commands.ts
|
|
61363
|
-
var init_client_host_commands = __esm({
|
|
61364
|
-
"lib/api/client-host-commands.ts"() {
|
|
61365
|
-
"use strict";
|
|
61366
|
-
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
61367
|
-
init_define_VTX_EXO_POLICY();
|
|
61368
|
-
init_define_VTX_GROK_POLICY();
|
|
61369
|
-
init_define_VTX_PI_MODEL_POLICY();
|
|
61370
|
-
init_shared();
|
|
61371
|
-
}
|
|
61372
|
-
});
|
|
61373
|
-
|
|
61374
61199
|
// lib/runtime/server-runtime-lease.ts
|
|
61375
61200
|
var CLIENT_RUNTIME_SERVER_LEASE_STORAGE_KEY, normalizeProfileId, normalizeLeaseGeneration, parseLeaseRecord, readPersistedLeaseMap, writePersistedLeaseMap, isLeaseExpired, runtimeLeaseHeaders, persistedRuntimeLeaseHeaders, getPersistedClientRuntimeServerLease, persistExistingClientRuntimeServerLease, persistClientRuntimeServerLease, clearPersistedClientRuntimeServerLease;
|
|
61376
61201
|
var init_server_runtime_lease = __esm({
|
|
@@ -61597,6 +61422,223 @@ var init_server_runtime_lease = __esm({
|
|
|
61597
61422
|
}
|
|
61598
61423
|
});
|
|
61599
61424
|
|
|
61425
|
+
// lib/api/market-data.ts
|
|
61426
|
+
async function getRecentCandles(limit, exchange = "kraken", symbol2 = "PI_XBTUSD", timeframe = "1m", signal) {
|
|
61427
|
+
return (await readRecentCandles(limit, exchange, symbol2, timeframe, signal, null)).candles;
|
|
61428
|
+
}
|
|
61429
|
+
async function getRecentCandlesForProfile(profileId, limit, exchange, symbol2, timeframe, signal) {
|
|
61430
|
+
return readRecentCandles(limit, exchange, symbol2, timeframe, signal, profileId);
|
|
61431
|
+
}
|
|
61432
|
+
async function getLiveTicker(symbol2 = "PI_XBTUSD", exchange = "kraken", signal) {
|
|
61433
|
+
const requestKey = `live-ticker:${symbol2}:${exchange}`;
|
|
61434
|
+
return shareClientGetRequest(requestKey, async (requestSignal) => {
|
|
61435
|
+
const requestUrl2 = `${getApiUrl()}/ticker/live?symbol=${encodeURIComponent(symbol2)}&exchange=${encodeURIComponent(exchange)}`;
|
|
61436
|
+
const trace = startRuntimeNetworkDebugTrace({
|
|
61437
|
+
kind: "runtime",
|
|
61438
|
+
label: "market_data_api:ticker_live",
|
|
61439
|
+
method: "GET",
|
|
61440
|
+
url: requestUrl2,
|
|
61441
|
+
note: `symbol=${symbol2} exchange=${exchange}`
|
|
61442
|
+
});
|
|
61443
|
+
let response = null;
|
|
61444
|
+
try {
|
|
61445
|
+
response = await apiFetch(requestUrl2, { cache: "no-store", signal: requestSignal });
|
|
61446
|
+
if (!response.ok) {
|
|
61447
|
+
const error48 = await buildMarketDataFetchError(response, "live ticker", "/ticker/live");
|
|
61448
|
+
trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
|
|
61449
|
+
trace.completeError(error48, response.status);
|
|
61450
|
+
throw error48;
|
|
61451
|
+
}
|
|
61452
|
+
trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
|
|
61453
|
+
const payload = await response.json();
|
|
61454
|
+
trace.completeSuccess(response.status);
|
|
61455
|
+
return payload;
|
|
61456
|
+
} catch (error48) {
|
|
61457
|
+
if (response && !response.ok) throw error48;
|
|
61458
|
+
if (response && !isAbortLikeError(error48)) {
|
|
61459
|
+
const failure2 = buildMarketDataResponseBodyError(error48, "live ticker", response, "/ticker/live");
|
|
61460
|
+
trace.completeError(failure2, response.status);
|
|
61461
|
+
throw failure2;
|
|
61462
|
+
}
|
|
61463
|
+
trace.completeError(error48, response?.status ?? null);
|
|
61464
|
+
if (isAbortLikeError(error48)) throw error48;
|
|
61465
|
+
throw buildMarketDataNetworkError(error48, "live ticker", "/ticker/live");
|
|
61466
|
+
}
|
|
61467
|
+
}, { signal });
|
|
61468
|
+
}
|
|
61469
|
+
async function getExecutionAssetMetadata(exchange, symbol2, options) {
|
|
61470
|
+
const params = new URLSearchParams();
|
|
61471
|
+
if (options?.forceCatalogRefresh) params.set("force_catalog_refresh", "true");
|
|
61472
|
+
if (options?.publicRequestPriority) params.set("public_request_priority", options.publicRequestPriority);
|
|
61473
|
+
const query = params.size > 0 ? `?${params.toString()}` : "";
|
|
61474
|
+
const url2 = `${getApiUrl()}/trading/execution-metadata/${encodeURIComponent(exchange)}/${encodeURIComponent(symbol2)}${query}`;
|
|
61475
|
+
const response = await apiFetch(url2, {
|
|
61476
|
+
// The bot's runtime reads it on its lease once the host's session ended.
|
|
61477
|
+
headers: getProfileHeaders(options?.profileId != null ? persistedRuntimeLeaseHeaders(options.profileId) : {}, options?.profileId),
|
|
61478
|
+
credentials: "include",
|
|
61479
|
+
cache: "no-store",
|
|
61480
|
+
signal: options?.signal
|
|
61481
|
+
});
|
|
61482
|
+
if (!response.ok) {
|
|
61483
|
+
const summary = `Failed to fetch execution asset metadata: ${response.status} ${response.statusText}`;
|
|
61484
|
+
const code = await response.clone().json().then((body) => typeof body?.detail?.code === "string" ? body.detail.code : null).catch(() => null);
|
|
61485
|
+
const detail = await getErrorMessageFromResponse(response, summary);
|
|
61486
|
+
throw new ExecutionAssetMetadataRequestError(
|
|
61487
|
+
detail === summary ? summary : `${summary}: ${detail}`,
|
|
61488
|
+
response.status,
|
|
61489
|
+
parseRetryAfterMs2(response.headers.get("Retry-After")),
|
|
61490
|
+
code
|
|
61491
|
+
);
|
|
61492
|
+
}
|
|
61493
|
+
return response.json();
|
|
61494
|
+
}
|
|
61495
|
+
var CANDLES_MISSING_HEADER, CandlesMissingRangeError, parseCandlesMissing, readRecentCandles, ExecutionAssetMetadataRequestError, CLIENT_EXECUTION_METADATA_DEVICE_READ, executionMetadataNeedsDeviceRead;
|
|
61496
|
+
var init_market_data = __esm({
|
|
61497
|
+
"lib/api/market-data.ts"() {
|
|
61498
|
+
"use strict";
|
|
61499
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
61500
|
+
init_define_VTX_EXO_POLICY();
|
|
61501
|
+
init_define_VTX_GROK_POLICY();
|
|
61502
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
61503
|
+
init_abort();
|
|
61504
|
+
init_runtime_redaction();
|
|
61505
|
+
init_network_debug();
|
|
61506
|
+
init_server_runtime_lease();
|
|
61507
|
+
init_shared();
|
|
61508
|
+
init_constants();
|
|
61509
|
+
CANDLES_MISSING_HEADER = "X-VTX-Candles-Missing";
|
|
61510
|
+
CandlesMissingRangeError = class extends Error {
|
|
61511
|
+
};
|
|
61512
|
+
parseCandlesMissing = (value) => {
|
|
61513
|
+
if (value === null || value.trim() === "") return null;
|
|
61514
|
+
const [startText, endText, ...extra] = value.split(",");
|
|
61515
|
+
const startMs = Number(startText?.trim());
|
|
61516
|
+
const endMs = Number(endText?.trim());
|
|
61517
|
+
if (extra.length > 0 || !Number.isSafeInteger(startMs) || !Number.isSafeInteger(endMs) || startMs > endMs) {
|
|
61518
|
+
throw new CandlesMissingRangeError(`The candle answer named an unreadable missing range: ${sanitizeRuntimeDiagnosticValue(value)}`);
|
|
61519
|
+
}
|
|
61520
|
+
return { startMs, endMs };
|
|
61521
|
+
};
|
|
61522
|
+
readRecentCandles = async (limit, exchange, symbol2, timeframe, signal, profileId) => {
|
|
61523
|
+
const params = new URLSearchParams({ limit: limit.toString(), exchange, symbol: symbol2, timeframe });
|
|
61524
|
+
const requestUrl2 = `${getApiUrl()}/candles/recent?${params.toString()}`;
|
|
61525
|
+
const forProfile = profileId === null ? {} : { credentials: "include", headers: getProfileHeaders(persistedRuntimeLeaseHeaders(profileId), profileId) };
|
|
61526
|
+
return shareClientGetRequest(`recent-candles:${profileId ?? "none"}:${params.toString()}`, async (requestSignal) => {
|
|
61527
|
+
const trace = startRuntimeNetworkDebugTrace({
|
|
61528
|
+
kind: "runtime",
|
|
61529
|
+
label: "market_data_api:candles_recent",
|
|
61530
|
+
method: "GET",
|
|
61531
|
+
url: requestUrl2,
|
|
61532
|
+
note: `symbol=${symbol2} exchange=${exchange} timeframe=${timeframe} limit=${limit}`
|
|
61533
|
+
});
|
|
61534
|
+
let response = null;
|
|
61535
|
+
try {
|
|
61536
|
+
response = await apiFetch(requestUrl2, {
|
|
61537
|
+
...forProfile,
|
|
61538
|
+
cache: "no-store",
|
|
61539
|
+
signal: requestSignal
|
|
61540
|
+
});
|
|
61541
|
+
if (!response.ok) {
|
|
61542
|
+
const error48 = await buildMarketDataFetchError(response, "recent candles", "/candles/recent");
|
|
61543
|
+
trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
|
|
61544
|
+
trace.completeError(error48, response.status);
|
|
61545
|
+
console.error(`[API] ${error48.message} URL: ${response.url}`);
|
|
61546
|
+
throw error48;
|
|
61547
|
+
}
|
|
61548
|
+
trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
|
|
61549
|
+
const missing2 = parseCandlesMissing(response.headers.get(CANDLES_MISSING_HEADER));
|
|
61550
|
+
const payload = await response.json();
|
|
61551
|
+
trace.completeSuccess(response.status);
|
|
61552
|
+
return { candles: payload, missing: missing2 };
|
|
61553
|
+
} catch (error48) {
|
|
61554
|
+
if (response && !response.ok) throw error48;
|
|
61555
|
+
if (response && error48 instanceof CandlesMissingRangeError) {
|
|
61556
|
+
trace.completeError(error48, response.status);
|
|
61557
|
+
throw error48;
|
|
61558
|
+
}
|
|
61559
|
+
if (response && !isAbortLikeError(error48)) {
|
|
61560
|
+
const failure2 = buildMarketDataResponseBodyError(error48, "recent candles", response, "/candles/recent");
|
|
61561
|
+
trace.completeError(failure2, response.status);
|
|
61562
|
+
throw failure2;
|
|
61563
|
+
}
|
|
61564
|
+
trace.completeError(error48, response?.status ?? null);
|
|
61565
|
+
if (isAbortLikeError(error48)) throw error48;
|
|
61566
|
+
throw buildMarketDataNetworkError(error48, "recent candles", "/candles/recent");
|
|
61567
|
+
}
|
|
61568
|
+
}, { signal, shareAbortScoped: true });
|
|
61569
|
+
};
|
|
61570
|
+
ExecutionAssetMetadataRequestError = class extends Error {
|
|
61571
|
+
constructor(message, status, retryAfterMs, code = null) {
|
|
61572
|
+
super(message);
|
|
61573
|
+
this.status = status;
|
|
61574
|
+
this.retryAfterMs = retryAfterMs;
|
|
61575
|
+
this.code = code;
|
|
61576
|
+
this.name = "ExecutionAssetMetadataRequestError";
|
|
61577
|
+
}
|
|
61578
|
+
};
|
|
61579
|
+
CLIENT_EXECUTION_METADATA_DEVICE_READ = "client_execution_metadata_device_read";
|
|
61580
|
+
executionMetadataNeedsDeviceRead = (error48) => error48 instanceof ExecutionAssetMetadataRequestError && error48.code === CLIENT_EXECUTION_METADATA_DEVICE_READ;
|
|
61581
|
+
}
|
|
61582
|
+
});
|
|
61583
|
+
|
|
61584
|
+
// lib/api/screener.ts
|
|
61585
|
+
var init_screener = __esm({
|
|
61586
|
+
"lib/api/screener.ts"() {
|
|
61587
|
+
"use strict";
|
|
61588
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
61589
|
+
init_define_VTX_EXO_POLICY();
|
|
61590
|
+
init_define_VTX_GROK_POLICY();
|
|
61591
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
61592
|
+
init_shared();
|
|
61593
|
+
}
|
|
61594
|
+
});
|
|
61595
|
+
|
|
61596
|
+
// lib/api/client-host-commands.ts
|
|
61597
|
+
var init_client_host_commands = __esm({
|
|
61598
|
+
"lib/api/client-host-commands.ts"() {
|
|
61599
|
+
"use strict";
|
|
61600
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
61601
|
+
init_define_VTX_EXO_POLICY();
|
|
61602
|
+
init_define_VTX_GROK_POLICY();
|
|
61603
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
61604
|
+
init_shared();
|
|
61605
|
+
}
|
|
61606
|
+
});
|
|
61607
|
+
|
|
61608
|
+
// lib/api/client-user-cancels.ts
|
|
61609
|
+
async function readClientUserCancels(profileId, orderIds, signal) {
|
|
61610
|
+
if (orderIds.length === 0) return /* @__PURE__ */ new Set();
|
|
61611
|
+
const numericProfileId = Number(profileId);
|
|
61612
|
+
const body = { order_ids: [...orderIds] };
|
|
61613
|
+
const response = await apiFetch(`${getApiUrl()}/trading/ai/runtime/protection/user-cancels`, {
|
|
61614
|
+
method: "POST",
|
|
61615
|
+
credentials: "include",
|
|
61616
|
+
headers: getProfileHeaders(
|
|
61617
|
+
{ "Content-Type": "application/json" },
|
|
61618
|
+
Number.isSafeInteger(numericProfileId) ? numericProfileId : void 0
|
|
61619
|
+
),
|
|
61620
|
+
body: JSON.stringify(body),
|
|
61621
|
+
signal
|
|
61622
|
+
});
|
|
61623
|
+
if (!response.ok) {
|
|
61624
|
+
const detail = await response.clone().json().then((answer2) => answer2?.detail, () => null);
|
|
61625
|
+
if (isMissingApiRoute({ status: Number(response.status), detail })) return /* @__PURE__ */ new Set();
|
|
61626
|
+
throw new Error(await getErrorMessageFromResponse(response, "Failed to read the user cancels"));
|
|
61627
|
+
}
|
|
61628
|
+
const answer = await response.json();
|
|
61629
|
+
return new Set(answer.cancels.map((row) => String(row.order_id)));
|
|
61630
|
+
}
|
|
61631
|
+
var init_client_user_cancels = __esm({
|
|
61632
|
+
"lib/api/client-user-cancels.ts"() {
|
|
61633
|
+
"use strict";
|
|
61634
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
61635
|
+
init_define_VTX_EXO_POLICY();
|
|
61636
|
+
init_define_VTX_GROK_POLICY();
|
|
61637
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
61638
|
+
init_shared();
|
|
61639
|
+
}
|
|
61640
|
+
});
|
|
61641
|
+
|
|
61600
61642
|
// lib/api/logout.ts
|
|
61601
61643
|
var init_logout = __esm({
|
|
61602
61644
|
"lib/api/logout.ts"() {
|
|
@@ -61617,7 +61659,8 @@ async function getLLMConfig(cookie, profileId, signal) {
|
|
|
61617
61659
|
const key = clientGetRequestKey("llm-config", effectiveProfileId);
|
|
61618
61660
|
return shareClientGetRequest(key, async (requestSignal) => {
|
|
61619
61661
|
const headers = getProfileHeaders({
|
|
61620
|
-
"Content-Type": "application/json"
|
|
61662
|
+
"Content-Type": "application/json",
|
|
61663
|
+
...!cookie && profileId != null ? persistedRuntimeLeaseHeaders(profileId) : {}
|
|
61621
61664
|
}, profileId);
|
|
61622
61665
|
const held = cookie ? null : heldPayloads.get(key) ?? null;
|
|
61623
61666
|
if (cookie) headers.Cookie = cookie;
|
|
@@ -61659,6 +61702,7 @@ var init_llm_config = __esm({
|
|
|
61659
61702
|
init_define_VTX_PI_MODEL_POLICY();
|
|
61660
61703
|
init_constants();
|
|
61661
61704
|
init_shared();
|
|
61705
|
+
init_server_runtime_lease();
|
|
61662
61706
|
REVISION_HEADER = "X-VTX-Config-Revision";
|
|
61663
61707
|
heldPayloads = /* @__PURE__ */ new Map();
|
|
61664
61708
|
}
|
|
@@ -62006,6 +62050,48 @@ var init_client_protective_evidence = __esm({
|
|
|
62006
62050
|
}
|
|
62007
62051
|
});
|
|
62008
62052
|
|
|
62053
|
+
// lib/api/provider-relays.ts
|
|
62054
|
+
function relayNativeProviderRequest(provider, apiKey, payload, options = {}) {
|
|
62055
|
+
return apiFetch(`${getApiUrl()}/llm/native-provider-relay`, {
|
|
62056
|
+
method: "POST",
|
|
62057
|
+
credentials: "include",
|
|
62058
|
+
headers: relayHeaders(options.profileId),
|
|
62059
|
+
body: JSON.stringify({
|
|
62060
|
+
provider,
|
|
62061
|
+
api_key: apiKey,
|
|
62062
|
+
payload,
|
|
62063
|
+
...options.planId ? { plan_id: options.planId } : {},
|
|
62064
|
+
...options.traceId ? { trace_id: options.traceId } : {}
|
|
62065
|
+
}),
|
|
62066
|
+
signal: options.signal
|
|
62067
|
+
});
|
|
62068
|
+
}
|
|
62069
|
+
function relayGoogleEgressRequest(model, apiKey, payload, options) {
|
|
62070
|
+
return apiFetch(`${getApiUrl()}/llm/google-egress-relay`, {
|
|
62071
|
+
method: "POST",
|
|
62072
|
+
credentials: "include",
|
|
62073
|
+
headers: relayHeaders(options.profileId),
|
|
62074
|
+
body: JSON.stringify({ model, api_key: apiKey, payload, timeout_seconds: options.timeoutSeconds }),
|
|
62075
|
+
signal: options.signal
|
|
62076
|
+
});
|
|
62077
|
+
}
|
|
62078
|
+
var relayHeaders;
|
|
62079
|
+
var init_provider_relays = __esm({
|
|
62080
|
+
"lib/api/provider-relays.ts"() {
|
|
62081
|
+
"use strict";
|
|
62082
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
62083
|
+
init_define_VTX_EXO_POLICY();
|
|
62084
|
+
init_define_VTX_GROK_POLICY();
|
|
62085
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
62086
|
+
init_server_runtime_lease();
|
|
62087
|
+
init_shared();
|
|
62088
|
+
relayHeaders = (profileId) => getProfileHeaders({
|
|
62089
|
+
"Content-Type": "application/json",
|
|
62090
|
+
...profileId != null ? persistedRuntimeLeaseHeaders(profileId) : {}
|
|
62091
|
+
}, profileId);
|
|
62092
|
+
}
|
|
62093
|
+
});
|
|
62094
|
+
|
|
62009
62095
|
// lib/runtime/hyperliquid-account-mode-contract.ts
|
|
62010
62096
|
function resolveExactHyperliquidAccountMode(userAbstraction, ...dexEvidence) {
|
|
62011
62097
|
const mode = extractCanonicalHyperliquidAccountMode(userAbstraction);
|
|
@@ -62635,7 +62721,7 @@ var init_hyperliquid_max_leverage = __esm({
|
|
|
62635
62721
|
});
|
|
62636
62722
|
|
|
62637
62723
|
// lib/candle-timeframes.ts
|
|
62638
|
-
var candleTimeframeSeconds, compareCandleTimeframes, sortCandleTimeframes;
|
|
62724
|
+
var candleTimeframeSeconds, compareCandleTimeframes, sortCandleTimeframes, candleClosedInSeries;
|
|
62639
62725
|
var init_candle_timeframes = __esm({
|
|
62640
62726
|
"lib/candle-timeframes.ts"() {
|
|
62641
62727
|
"use strict";
|
|
@@ -62647,6 +62733,7 @@ var init_candle_timeframes = __esm({
|
|
|
62647
62733
|
candleTimeframeSeconds = (timeframe) => Object.prototype.hasOwnProperty.call(CANDLE_TIMEFRAME_SECONDS, timeframe) ? CANDLE_TIMEFRAME_SECONDS[timeframe] : void 0;
|
|
62648
62734
|
compareCandleTimeframes = (left, right) => (candleTimeframeSeconds(left) ?? Number.MAX_SAFE_INTEGER) - (candleTimeframeSeconds(right) ?? Number.MAX_SAFE_INTEGER);
|
|
62649
62735
|
sortCandleTimeframes = (timeframes) => [...timeframes].sort(compareCandleTimeframes);
|
|
62736
|
+
candleClosedInSeries = (openTimestamp, newestOpenTimestamp, timeframeSeconds, asOfTimestamp) => openTimestamp < newestOpenTimestamp || openTimestamp + timeframeSeconds <= asOfTimestamp;
|
|
62650
62737
|
}
|
|
62651
62738
|
});
|
|
62652
62739
|
|
|
@@ -65289,7 +65376,8 @@ var init_write_fence = __esm({
|
|
|
65289
65376
|
{
|
|
65290
65377
|
...pinnedAuthority ? { pinnedAuthority } : {},
|
|
65291
65378
|
mutationId: durableMutation.mutationId,
|
|
65292
|
-
...await fields(pinnedAuthority)
|
|
65379
|
+
...await fields(pinnedAuthority),
|
|
65380
|
+
...durableMutation.userCancel != null ? { userCancel: durableMutation.userCancel } : {}
|
|
65293
65381
|
},
|
|
65294
65382
|
...fencedMutationAuthorityArgs(durableMutation)
|
|
65295
65383
|
);
|
|
@@ -98594,30 +98682,6 @@ async function reportServerBackupReadiness(profileId, ready, hostId, signal, pow
|
|
|
98594
98682
|
}
|
|
98595
98683
|
return response.json();
|
|
98596
98684
|
}
|
|
98597
|
-
function relayNativeProviderRequest(provider, apiKey, payload, options = {}) {
|
|
98598
|
-
return apiFetch(`${getApiUrl()}/llm/native-provider-relay`, {
|
|
98599
|
-
method: "POST",
|
|
98600
|
-
credentials: "include",
|
|
98601
|
-
headers: getProfileHeaders({ "Content-Type": "application/json" }, options.profileId),
|
|
98602
|
-
body: JSON.stringify({
|
|
98603
|
-
provider,
|
|
98604
|
-
api_key: apiKey,
|
|
98605
|
-
payload,
|
|
98606
|
-
...options.planId ? { plan_id: options.planId } : {},
|
|
98607
|
-
...options.traceId ? { trace_id: options.traceId } : {}
|
|
98608
|
-
}),
|
|
98609
|
-
signal: options.signal
|
|
98610
|
-
});
|
|
98611
|
-
}
|
|
98612
|
-
function relayGoogleEgressRequest(model, apiKey, payload, options) {
|
|
98613
|
-
return apiFetch(`${getApiUrl()}/llm/google-egress-relay`, {
|
|
98614
|
-
method: "POST",
|
|
98615
|
-
credentials: "include",
|
|
98616
|
-
headers: getProfileHeaders({ "Content-Type": "application/json" }, options.profileId),
|
|
98617
|
-
body: JSON.stringify({ model, api_key: apiKey, payload, timeout_seconds: options.timeoutSeconds }),
|
|
98618
|
-
signal: options.signal
|
|
98619
|
-
});
|
|
98620
|
-
}
|
|
98621
98685
|
async function getClientRuntimeSecrets(profileId, options) {
|
|
98622
98686
|
const params = new URLSearchParams();
|
|
98623
98687
|
if (options?.activeProvider) {
|
|
@@ -100051,6 +100115,8 @@ var init_api2 = __esm({
|
|
|
100051
100115
|
init_market_data();
|
|
100052
100116
|
init_screener();
|
|
100053
100117
|
init_client_host_commands();
|
|
100118
|
+
init_client_exchange_mutation_begin();
|
|
100119
|
+
init_client_user_cancels();
|
|
100054
100120
|
init_logout();
|
|
100055
100121
|
init_llm_config();
|
|
100056
100122
|
init_llm_config();
|
|
@@ -100069,6 +100135,7 @@ var init_api2 = __esm({
|
|
|
100069
100135
|
init_client_exchange_reconciliation();
|
|
100070
100136
|
init_client_protective_evidence();
|
|
100071
100137
|
init_server_runtime_lease();
|
|
100138
|
+
init_provider_relays();
|
|
100072
100139
|
clientRuntimeSecretHeaders = (profileId) => {
|
|
100073
100140
|
const headers = getProfileHeaders({}, profileId);
|
|
100074
100141
|
const leaseProfileId = profileId ?? getActiveProfileId();
|
|
@@ -102199,6 +102266,7 @@ var init_browser_trading = __esm({
|
|
|
102199
102266
|
mutationId: mutation.mutationId,
|
|
102200
102267
|
operationKind: "cancel",
|
|
102201
102268
|
symbol: input.symbol,
|
|
102269
|
+
userCancel: input.userCancel === true,
|
|
102202
102270
|
onExchangeOrderDispatched: input.onExchangeOrderDispatched
|
|
102203
102271
|
}
|
|
102204
102272
|
});
|
|
@@ -104334,7 +104402,9 @@ async function getClientRuntimeExchangeMutation(profileId, mutationId, signal) {
|
|
|
104334
104402
|
method: "GET",
|
|
104335
104403
|
credentials: "include",
|
|
104336
104404
|
cache: "no-store",
|
|
104337
|
-
|
|
104405
|
+
// A host's runtime reads on its bot's lease once the host's session ended; the
|
|
104406
|
+
// Node runtime host keeps this read on its protection route (server-host/live-fetch.ts).
|
|
104407
|
+
headers: Number.isSafeInteger(numericProfileId) ? getProfileHeaders(persistedRuntimeLeaseHeaders(numericProfileId), numericProfileId) : getProfileHeaders({}),
|
|
104338
104408
|
signal
|
|
104339
104409
|
}
|
|
104340
104410
|
);
|
|
@@ -104352,6 +104422,7 @@ var init_client_exchange_mutations = __esm({
|
|
|
104352
104422
|
init_define_VTX_GROK_POLICY();
|
|
104353
104423
|
init_define_VTX_PI_MODEL_POLICY();
|
|
104354
104424
|
init_constants();
|
|
104425
|
+
init_server_runtime_lease();
|
|
104355
104426
|
init_shared();
|
|
104356
104427
|
}
|
|
104357
104428
|
});
|
|
@@ -105195,7 +105266,8 @@ var init_writes = __esm({
|
|
|
105195
105266
|
mutationId,
|
|
105196
105267
|
...context.onSettled ? { onSettled: context.onSettled } : {},
|
|
105197
105268
|
...context.signal ? { signal: context.signal } : {},
|
|
105198
|
-
...context.onExchangeOrderDispatched ? { onExchangeOrderDispatched: context.onExchangeOrderDispatched } : {}
|
|
105269
|
+
...context.onExchangeOrderDispatched ? { onExchangeOrderDispatched: context.onExchangeOrderDispatched } : {},
|
|
105270
|
+
...context.userCancel != null ? { userCancel: context.userCancel } : {}
|
|
105199
105271
|
},
|
|
105200
105272
|
captureTimeoutMs: deps.captureTimeoutMs,
|
|
105201
105273
|
begin: {
|
|
@@ -105783,7 +105855,12 @@ var init_runtime_writes = __esm({
|
|
|
105783
105855
|
},
|
|
105784
105856
|
cancelOrder: async (input) => {
|
|
105785
105857
|
const name = await listed(input.symbol, input.signal);
|
|
105786
|
-
return cancelResponse(await answering(operationsFor(input).cancelOrder({
|
|
105858
|
+
return cancelResponse(await answering(operationsFor(input).cancelOrder({
|
|
105859
|
+
...writeContext2(input),
|
|
105860
|
+
userCancel: input.userCancel === true,
|
|
105861
|
+
symbol: name,
|
|
105862
|
+
orderId: input.orderId
|
|
105863
|
+
})));
|
|
105787
105864
|
},
|
|
105788
105865
|
closePosition: async (input) => {
|
|
105789
105866
|
const name = await listed(input.symbol, input.signal);
|
|
@@ -106899,6 +106976,69 @@ var init_bounded_lock = __esm({
|
|
|
106899
106976
|
}
|
|
106900
106977
|
});
|
|
106901
106978
|
|
|
106979
|
+
// lib/runtime/protective-user-cancels.ts
|
|
106980
|
+
var MAX_USER_CANCEL_ORDER_IDS, passUserCancels, readEachUserCancel;
|
|
106981
|
+
var init_protective_user_cancels = __esm({
|
|
106982
|
+
"lib/runtime/protective-user-cancels.ts"() {
|
|
106983
|
+
"use strict";
|
|
106984
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
106985
|
+
init_define_VTX_EXO_POLICY();
|
|
106986
|
+
init_define_VTX_GROK_POLICY();
|
|
106987
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
106988
|
+
init_runtime_policy_generated2();
|
|
106989
|
+
MAX_USER_CANCEL_ORDER_IDS = runtime_policy_generated_default2.trading.engine.client_runtime.request_bounds.max_user_cancel_order_ids;
|
|
106990
|
+
passUserCancels = (read, options = {}) => {
|
|
106991
|
+
const maxPerRead = Math.max(1, Math.floor(options.maxPerRead ?? MAX_USER_CANCEL_ORDER_IDS));
|
|
106992
|
+
const answers = /* @__PURE__ */ new Map();
|
|
106993
|
+
const failures = /* @__PURE__ */ new Map();
|
|
106994
|
+
const exchangeOrderId = (orderId) => {
|
|
106995
|
+
const key = String(orderId).trim();
|
|
106996
|
+
return /^[0-9]+$/.test(key) ? key : null;
|
|
106997
|
+
};
|
|
106998
|
+
const readBatch = async (orderIds) => {
|
|
106999
|
+
try {
|
|
107000
|
+
const { cancelled, unread } = await read(orderIds);
|
|
107001
|
+
for (const orderId of orderIds) {
|
|
107002
|
+
if (unread?.has(orderId)) failures.set(orderId, unread.get(orderId));
|
|
107003
|
+
else answers.set(orderId, cancelled.has(orderId));
|
|
107004
|
+
}
|
|
107005
|
+
} catch (error48) {
|
|
107006
|
+
if (options.signal?.aborted) throw error48;
|
|
107007
|
+
for (const orderId of orderIds) failures.set(orderId, error48);
|
|
107008
|
+
}
|
|
107009
|
+
};
|
|
107010
|
+
return {
|
|
107011
|
+
prefetch: async (orderIds) => {
|
|
107012
|
+
const unknown2 = [...new Set(orderIds.map(exchangeOrderId))].filter((orderId) => orderId != null && !answers.has(orderId) && !failures.has(orderId));
|
|
107013
|
+
for (let start = 0; start < unknown2.length; start += maxPerRead) {
|
|
107014
|
+
await readBatch(unknown2.slice(start, start + maxPerRead));
|
|
107015
|
+
}
|
|
107016
|
+
},
|
|
107017
|
+
cancelled: async (orderId) => {
|
|
107018
|
+
const key = exchangeOrderId(orderId);
|
|
107019
|
+
if (key == null) return false;
|
|
107020
|
+
if (!answers.has(key) && !failures.has(key)) await readBatch([key]);
|
|
107021
|
+
if (failures.has(key)) throw failures.get(key);
|
|
107022
|
+
return answers.get(key) === true;
|
|
107023
|
+
}
|
|
107024
|
+
};
|
|
107025
|
+
};
|
|
107026
|
+
readEachUserCancel = (lookup, signal) => async (orderIds) => {
|
|
107027
|
+
const cancelled = /* @__PURE__ */ new Set();
|
|
107028
|
+
const unread = /* @__PURE__ */ new Map();
|
|
107029
|
+
for (const orderId of orderIds) {
|
|
107030
|
+
try {
|
|
107031
|
+
if (await lookup(orderId)) cancelled.add(orderId);
|
|
107032
|
+
} catch (error48) {
|
|
107033
|
+
if (signal?.aborted) throw error48;
|
|
107034
|
+
unread.set(orderId, error48);
|
|
107035
|
+
}
|
|
107036
|
+
}
|
|
107037
|
+
return { cancelled, unread };
|
|
107038
|
+
};
|
|
107039
|
+
}
|
|
107040
|
+
});
|
|
107041
|
+
|
|
106902
107042
|
// lib/runtime/prompt-number-contract.ts
|
|
106903
107043
|
var finiteNumber2, roundPromptFixed, roundPromptSignificant, roundPromptRelativeVolume, roundPromptNonnegativeUnits;
|
|
106904
107044
|
var init_prompt_number_contract = __esm({
|
|
@@ -108992,16 +109132,19 @@ var init_protective_entry_cover = __esm({
|
|
|
108992
109132
|
claims.set(entry, order);
|
|
108993
109133
|
claimed.add(order);
|
|
108994
109134
|
};
|
|
108995
|
-
const
|
|
109135
|
+
const ended = (order) => input.ended?.has(String(order.oid)) === true;
|
|
109136
|
+
const byShape = (entry, leg) => orders.find((order) => !claimed.has(order) && !ended(order) && protectiveLiveShapeMatches({
|
|
108996
109137
|
shape: liveProtectiveOrderShape(order),
|
|
108997
109138
|
symbol: symbol2,
|
|
108998
109139
|
isLong: entry.group.isLong,
|
|
108999
109140
|
leg
|
|
109000
109141
|
}));
|
|
109001
|
-
|
|
109142
|
+
const placed = (entry) => input.placed?.has(String(entry.leg.orderId)) === true || input.placed?.has(String(knownId(entry))) === true;
|
|
109143
|
+
const own = entries.filter((entry) => !placed(entry));
|
|
109144
|
+
for (const entry of own) claim(entry, pageOrderById(orders, knownId(entry)));
|
|
109002
109145
|
const named = new Set(claimed);
|
|
109003
|
-
const leaving = new Set(input.groups.filter((group) => group.cleanupRequired === true ||
|
|
109004
|
-
const waiting =
|
|
109146
|
+
const leaving = new Set(input.groups.filter((group) => group.cleanupRequired === true || own.some((entry) => entry.group === group && knownId(entry) != null && !claims.has(entry))));
|
|
109147
|
+
const waiting = own.filter(unbound);
|
|
109005
109148
|
const unread = (entry) => input.unresolved?.has(String(entry.leg.orderId)) === true;
|
|
109006
109149
|
const staying = waiting.filter((entry) => !leaving.has(entry.group));
|
|
109007
109150
|
for (const entry of [...waiting.filter((entry2) => leaving.has(entry2.group)), ...staying.filter(unread), ...staying.filter((entry2) => !unread(entry2))]) {
|
|
@@ -109046,18 +109189,18 @@ var init_protective_entry_cover = __esm({
|
|
|
109046
109189
|
},
|
|
109047
109190
|
/**
|
|
109048
109191
|
* For a lost stop: the stop losses on the page closing the position, other
|
|
109049
|
-
* than the orders a status proved ended (`
|
|
109050
|
-
*
|
|
109051
|
-
*
|
|
109192
|
+
* than the orders a status proved ended (`ended`), those this pass placed
|
|
109193
|
+
* and those its placed stops stand for (`beside.standsFor`: counted where
|
|
109194
|
+
* they were placed, protective-placed-stops.ts), an order no leg names
|
|
109195
|
+
* whole; and, unseen, what the legs this pass could not read may still cover.
|
|
109052
109196
|
*/
|
|
109053
|
-
lostStopCover: (positionSize,
|
|
109197
|
+
lostStopCover: (positionSize, beside) => {
|
|
109054
109198
|
const isLong = positionSize > 0;
|
|
109055
109199
|
const owners = new Map([...claims].map(([entry, order]) => [order, entry]));
|
|
109056
|
-
const
|
|
109057
|
-
const onPage = orders.filter((order) => !excluded.lost.has(String(order.oid)) && !excluded.placed.has(String(order.oid)) && String(order.coin).trim().toUpperCase() === symbol2.trim().toUpperCase() && order.reduce_only && order.is_trigger && order.trigger_kind === "sl" && (isLong ? ["a", "sell"] : ["b", "buy"]).includes(String(order.side).trim().toLowerCase())).reduce((total, order) => {
|
|
109200
|
+
const onPage = orders.filter((order) => !ended(order) && input.placed?.has(String(order.oid)) !== true && beside?.standsFor(order) !== true && String(order.coin).trim().toUpperCase() === symbol2.trim().toUpperCase() && order.reduce_only && order.is_trigger && order.trigger_kind === "sl" && (isLong ? ["a", "sell"] : ["b", "buy"]).includes(String(order.side).trim().toLowerCase())).reduce((total, order) => {
|
|
109058
109201
|
const owner2 = owners.get(order);
|
|
109059
109202
|
const size = Number(order.sz);
|
|
109060
|
-
return total + (owner2 != null ?
|
|
109203
|
+
return total + (owner2 != null ? coverOf(owner2) : size > 0 ? size : 0);
|
|
109061
109204
|
}, 0);
|
|
109062
109205
|
const unseen = entries.filter((entry) => entry.leg.kind === "sl" && entry.group.isLong === isLong && !placed(entry) && input.unresolved?.has(String(entry.leg.orderId)) === true).reduce((total, entry) => total + inFlightOf(entry), 0);
|
|
109063
109206
|
return { onPage, unseen };
|
|
@@ -109068,6 +109211,88 @@ var init_protective_entry_cover = __esm({
|
|
|
109068
109211
|
}
|
|
109069
109212
|
});
|
|
109070
109213
|
|
|
109214
|
+
// lib/runtime/protective-placed-stops.ts
|
|
109215
|
+
var passPlacedStops;
|
|
109216
|
+
var init_protective_placed_stops = __esm({
|
|
109217
|
+
"lib/runtime/protective-placed-stops.ts"() {
|
|
109218
|
+
"use strict";
|
|
109219
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
109220
|
+
init_define_VTX_EXO_POLICY();
|
|
109221
|
+
init_define_VTX_GROK_POLICY();
|
|
109222
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
109223
|
+
init_protective_entry_cover();
|
|
109224
|
+
init_protective_leg_evidence();
|
|
109225
|
+
init_protective_market_evidence();
|
|
109226
|
+
passPlacedStops = (symbol2) => {
|
|
109227
|
+
const stops = [];
|
|
109228
|
+
const pages = /* @__PURE__ */ new WeakMap();
|
|
109229
|
+
let pagesSeen = 0;
|
|
109230
|
+
const pageOrder = (market) => {
|
|
109231
|
+
if (!pages.has(market)) {
|
|
109232
|
+
pagesSeen += 1;
|
|
109233
|
+
pages.set(market, pagesSeen);
|
|
109234
|
+
}
|
|
109235
|
+
return pages.get(market);
|
|
109236
|
+
};
|
|
109237
|
+
const ofShape = (stop, order) => protectiveLiveShapeMatches({
|
|
109238
|
+
shape: liveProtectiveOrderShape(order),
|
|
109239
|
+
symbol: symbol2,
|
|
109240
|
+
isLong: stop.isLong,
|
|
109241
|
+
leg: stop.leg,
|
|
109242
|
+
requirePositionTpsl: false
|
|
109243
|
+
});
|
|
109244
|
+
return {
|
|
109245
|
+
/** A stop about to be sent, under its client order id: it counts at its size from now on. */
|
|
109246
|
+
add: (leg, isLong) => {
|
|
109247
|
+
const stop = {
|
|
109248
|
+
ids: [String(leg.orderId)],
|
|
109249
|
+
leg,
|
|
109250
|
+
isLong,
|
|
109251
|
+
sentMs: protectiveReadStampMs(),
|
|
109252
|
+
pagesBefore: pagesSeen,
|
|
109253
|
+
counts: true
|
|
109254
|
+
};
|
|
109255
|
+
stops.push(stop);
|
|
109256
|
+
return stop;
|
|
109257
|
+
},
|
|
109258
|
+
/** A stop never sent, or refused: it never counted. */
|
|
109259
|
+
drop: (stop) => {
|
|
109260
|
+
stops.splice(stops.indexOf(stop), 1);
|
|
109261
|
+
},
|
|
109262
|
+
/** Its answer (extractCanonicalHyperliquidOrderStateAcknowledgement): its exchange order id, and whether it filled. */
|
|
109263
|
+
answered: (stop, answer) => {
|
|
109264
|
+
stop.ids.push(answer.orderId);
|
|
109265
|
+
if (answer.state === "fulfilled") stop.counts = false;
|
|
109266
|
+
},
|
|
109267
|
+
/** Their client and exchange order ids (resolveOwnStops `placed`, which leaves them out). */
|
|
109268
|
+
ids: () => new Set(stops.flatMap((stop) => stop.ids)),
|
|
109269
|
+
/**
|
|
109270
|
+
* What they cover beside a lost stop counted on this market, and the page
|
|
109271
|
+
* orders they stand for there, which count nothing beside them
|
|
109272
|
+
* (resolveOwnStops lostStopCover).
|
|
109273
|
+
*/
|
|
109274
|
+
count: (market) => {
|
|
109275
|
+
const read = pageOrder(market);
|
|
109276
|
+
const orders = market.orders ?? [];
|
|
109277
|
+
const after = stops.filter((stop) => stop.counts && market.orders != null && read > stop.pagesBefore);
|
|
109278
|
+
const proven = (stop) => !market.viaNode || nodeAnswerProves(market.position.stateTimeMs, { hostMs: stop.sentMs });
|
|
109279
|
+
const taken = /* @__PURE__ */ new Set();
|
|
109280
|
+
for (const stop of [...after.filter((stop2) => !proven(stop2)), ...after.filter(proven)]) {
|
|
109281
|
+
const order = orders.find((candidate) => !taken.has(candidate) && ofShape(stop, candidate));
|
|
109282
|
+
if (order != null) taken.add(order);
|
|
109283
|
+
else if (proven(stop)) stop.counts = false;
|
|
109284
|
+
}
|
|
109285
|
+
const standing = after.filter((stop) => stop.counts);
|
|
109286
|
+
return {
|
|
109287
|
+
size: stops.reduce((total, stop) => total + (stop.counts ? stop.leg.size : 0), 0),
|
|
109288
|
+
standsFor: (order) => standing.some((stop) => ofShape(stop, order))
|
|
109289
|
+
};
|
|
109290
|
+
}
|
|
109291
|
+
};
|
|
109292
|
+
};
|
|
109293
|
+
}
|
|
109294
|
+
});
|
|
109295
|
+
|
|
109071
109296
|
// lib/runtime/protective-oversized-leg.ts
|
|
109072
109297
|
var OVERSIZED_LEG_GROUP_PREFIX, splitOversizedProtectiveLeg;
|
|
109073
109298
|
var init_protective_oversized_leg = __esm({
|
|
@@ -109401,7 +109626,7 @@ var init_native_position_protection = __esm({
|
|
|
109401
109626
|
});
|
|
109402
109627
|
|
|
109403
109628
|
// lib/runtime/native-protection-device.ts
|
|
109404
|
-
var NATIVE_PROTECTION_RECORD_VERSION, MAX_PLACE_ATTEMPTS, FILL_PROOF_DEADLINE_MS, owesMove, owingMove, warningKey, moveMade, pricedFrom, followsPosition, pricedOn, nativeProtectionStorage, resolveStorage, setNativeProtectionStorage, recordKey, listNativeProtectionSymbols, isPricedOrAbsent, isMember, isRetracement, isLot, isStandbyAdd, readNativeProtectionRecord, versioned, writeNativeProtectionRecord, NO_FILLS, nativeFillsPageFromUserFills, readPositionAndPage, fillsReader, flatReadOf, orderFillTimes, namedOrderId, NativeOrderNotSentError, withDispatchBoundary, locallyRefused, attempt, notSentRestores, errorText2, actionOf, positionOrderReport, isOpenInDirection2, coverRows, restingOrderIdAt, definitivelyRefused, TRAILING_LOT_FIRED, TRAILING_LOT_POSITION_ENDED, TRAILING_LOT_OTHER_SIDE, lotFillLeftPosition, uncoveredByLots, lotOfAdd, ORDER_ID_PATTERN, lotFillOrderId, TRAILING_LOT_POSITION_UNDECIDED, lotPositionSince, ownLotOrderIds, lotRetracement, lotReport, sendTrailingLot, planNativeFillLot, planNativeStandbyAdd, nameNativeStandbyAdd, dropNativeStandbyAdd, dropNativePendingLot, planNativePendingLot, planNativeOpen, recordEntryChildren, observeMembers, ridesOnOpen, namedOrderReports, UNKNOWN_ORDER_RESPONSE, resolveUnknownOrderIds, cancellingThroughVtx, moveMember, plannedPair, resolveStandbyAdds, withoutExpiredAdds, settleNativeProtectionAfterFill, reconcileNativeProtection;
|
|
109629
|
+
var NATIVE_PROTECTION_RECORD_VERSION, MAX_PLACE_ATTEMPTS, FILL_PROOF_DEADLINE_MS, owesMove, owingMove, warningKey, moveMade, pricedFrom, followsPosition, pricedOn, nativeProtectionStorage, resolveStorage, setNativeProtectionStorage, recordKey, listNativeProtectionSymbols, isPricedOrAbsent, isMember, isRetracement, isLot, isStandbyAdd, readNativeProtectionRecord, withoutStoredUserCancels, versioned, writeNativeProtectionRecord, NO_FILLS, nativeFillsPageFromUserFills, readPositionAndPage, fillsReader, flatReadOf, orderFillTimes, namedOrderId, NativeOrderNotSentError, withDispatchBoundary, locallyRefused, attempt, notSentRestores, errorText2, actionOf, positionOrderReport, isOpenInDirection2, coverRows, restingOrderIdAt, definitivelyRefused, TRAILING_LOT_FIRED, TRAILING_LOT_POSITION_ENDED, TRAILING_LOT_OTHER_SIDE, lotFillLeftPosition, uncoveredByLots, lotOfAdd, ORDER_ID_PATTERN, lotFillOrderId, TRAILING_LOT_POSITION_UNDECIDED, lotPositionSince, ownLotOrderIds, lotRetracement, lotReport, sendTrailingLot, planNativeFillLot, planNativeStandbyAdd, nameNativeStandbyAdd, dropNativeStandbyAdd, dropNativePendingLot, planNativePendingLot, planNativeOpen, recordEntryChildren, observeMembers, ridesOnOpen, namedOrderReports, UNKNOWN_ORDER_RESPONSE, resolveUnknownOrderIds, cancellingThroughVtx, endedByUserCancel, moveMember, plannedPair, resolveStandbyAdds, withoutExpiredAdds, settleNativeProtectionAfterFill, reconcileNativeProtection;
|
|
109405
109630
|
var init_native_protection_device = __esm({
|
|
109406
109631
|
"lib/runtime/native-protection-device.ts"() {
|
|
109407
109632
|
"use strict";
|
|
@@ -109445,7 +109670,7 @@ var init_native_protection_device = __esm({
|
|
|
109445
109670
|
if (position?.entryPrice == null) return members;
|
|
109446
109671
|
const priced = pricedFrom({ size: position.size, entryPrice: position.entryPrice });
|
|
109447
109672
|
const earlier = new Set(startedWith.map((member) => member.clientOrderId));
|
|
109448
|
-
return members.map((member) => member.priced != null || earlier.has(member.clientOrderId) || owesMove(member) || member.pendingModify || member.plannedAfterMs != null || member.retiredReason
|
|
109673
|
+
return members.map((member) => member.priced != null || earlier.has(member.clientOrderId) || owesMove(member) || member.pendingModify || member.plannedAfterMs != null || member.retiredReason ? member : { ...member, priced });
|
|
109449
109674
|
};
|
|
109450
109675
|
nativeProtectionStorage = null;
|
|
109451
109676
|
resolveStorage = () => nativeProtectionStorage ?? browserRuntimeStateStorage();
|
|
@@ -109495,7 +109720,14 @@ var init_native_protection_device = __esm({
|
|
|
109495
109720
|
if (parsed?.version !== NATIVE_PROTECTION_RECORD_VERSION && parsed?.version !== NATIVE_PROTECTION_RECORD_WITH_LOTS_VERSION || parsed.profileId !== profileId || parsed.symbol !== symbol2 || typeof parsed.walletAddress !== "string" || typeof parsed.isLong !== "boolean" || parsed.phase !== "entry_pending" && parsed.phase !== "active" || typeof parsed.entryMutationId !== "string" || typeof parsed.entryClientOrderId !== "string" || typeof parsed.createdAtMs !== "number" || !Array.isArray(parsed.members) || !parsed.members.every(isMember) || parsed.lots !== void 0 && (parsed.version !== NATIVE_PROTECTION_RECORD_WITH_LOTS_VERSION || !Array.isArray(parsed.lots) || !parsed.lots.every(isLot)) || parsed.standby !== void 0 && (!Array.isArray(parsed.standby) || !parsed.standby.every(isStandbyAdd)) || parsed.positionOrderId !== void 0 && typeof parsed.positionOrderId !== "string") {
|
|
109496
109721
|
throw new Error("Stored native protection record is invalid.");
|
|
109497
109722
|
}
|
|
109498
|
-
return parsed;
|
|
109723
|
+
return withoutStoredUserCancels(parsed);
|
|
109724
|
+
};
|
|
109725
|
+
withoutStoredUserCancels = (record6) => {
|
|
109726
|
+
const unmarked = (entry) => {
|
|
109727
|
+
const { userCancelledOrderId: _stored, ...rest } = entry;
|
|
109728
|
+
return rest;
|
|
109729
|
+
};
|
|
109730
|
+
return { ...record6, members: record6.members.map(unmarked), ...record6.lots ? { lots: record6.lots.map(unmarked) } : {} };
|
|
109499
109731
|
};
|
|
109500
109732
|
versioned = (record6) => {
|
|
109501
109733
|
const { lots, ...rest } = record6;
|
|
@@ -109942,13 +110174,14 @@ var init_native_protection_device = __esm({
|
|
|
109942
110174
|
}
|
|
109943
110175
|
return { ...record6, members };
|
|
109944
110176
|
};
|
|
109945
|
-
cancellingThroughVtx = async (io, orderId) =>
|
|
110177
|
+
cancellingThroughVtx = async (io, orderId) => await endedByUserCancel(io, orderId) !== false;
|
|
110178
|
+
endedByUserCancel = async (io, orderId) => {
|
|
109946
110179
|
if (!io.userCancelledOrder) return false;
|
|
109947
110180
|
try {
|
|
109948
110181
|
return await io.userCancelledOrder(orderId);
|
|
109949
110182
|
} catch (error48) {
|
|
109950
110183
|
if (io.endsPass?.(error48)) throw error48;
|
|
109951
|
-
return
|
|
110184
|
+
return null;
|
|
109952
110185
|
}
|
|
109953
110186
|
};
|
|
109954
110187
|
moveMember = async (args) => {
|
|
@@ -110155,7 +110388,7 @@ var init_native_protection_device = __esm({
|
|
|
110155
110388
|
const afterMs = boundary.addFillMs ?? 0;
|
|
110156
110389
|
record6 = {
|
|
110157
110390
|
...record6,
|
|
110158
|
-
members: record6.members.map((member) => member.retiredReason || member.
|
|
110391
|
+
members: record6.members.map((member) => member.retiredReason || member.plannedAfterMs != null ? member : owingMove(member, afterMs))
|
|
110159
110392
|
};
|
|
110160
110393
|
}
|
|
110161
110394
|
if (boundary.undecided) {
|
|
@@ -110231,7 +110464,7 @@ var init_native_protection_device = __esm({
|
|
|
110231
110464
|
if (step.action === "place_trailing") continue;
|
|
110232
110465
|
const index = members.findIndex((member) => member.kind === step.kind);
|
|
110233
110466
|
const existing = index >= 0 ? members[index] : null;
|
|
110234
|
-
if (existing?.
|
|
110467
|
+
if (existing?.retiredReason) continue;
|
|
110235
110468
|
if (existing?.pendingModify) continue;
|
|
110236
110469
|
const clientOrderId = clientOrderIdForMutation(io.newMutationId());
|
|
110237
110470
|
if (step.action === "modify") {
|
|
@@ -110403,7 +110636,7 @@ var init_native_protection_device = __esm({
|
|
|
110403
110636
|
lotIndex = lots.length - 1;
|
|
110404
110637
|
}
|
|
110405
110638
|
const journaledLot = lotIndex >= 0 ? lots[lotIndex] : null;
|
|
110406
|
-
if (journaledLot && journaledLot.mutationId == null && !journaledLot.retiredReason &&
|
|
110639
|
+
if (journaledLot && journaledLot.mutationId == null && !journaledLot.retiredReason && io.placeTrailingLot) {
|
|
110407
110640
|
const size = journaledLot.size || fillLotSize;
|
|
110408
110641
|
const retracement = lotRetracement(input.settings, size, input.sizeDecimals);
|
|
110409
110642
|
if (retracement) {
|
|
@@ -110502,6 +110735,10 @@ var init_native_protection_device = __esm({
|
|
|
110502
110735
|
...entry,
|
|
110503
110736
|
member: entry.row ? { ...entry.member, placedAtMs: entry.row.timestamp || entry.member.placedAtMs } : entry.member
|
|
110504
110737
|
}));
|
|
110738
|
+
await io.prefetchUserCancels?.([
|
|
110739
|
+
...observations.filter((entry) => entry.row == null && !entry.member.retiredReason && !entry.member.pendingModify).map((entry) => entry.member.orderId),
|
|
110740
|
+
...(record6.lots ?? []).filter((lot) => !lot.retiredReason && !page.some((order) => order.oid === lot.orderId)).map((lot) => lot.orderId)
|
|
110741
|
+
].filter((orderId) => orderId != null));
|
|
110505
110742
|
const members = [];
|
|
110506
110743
|
let anyResting = false;
|
|
110507
110744
|
const positionOpen = isOpenInDirection2(position.size, record6.isLong);
|
|
@@ -110525,7 +110762,7 @@ var init_native_protection_device = __esm({
|
|
|
110525
110762
|
const moveTargets = /* @__PURE__ */ new Map();
|
|
110526
110763
|
if (movable && position.entryPrice != null && record6.members.some((member) => owesMove(member) || follows(member))) {
|
|
110527
110764
|
const restingTrigger = (kind) => {
|
|
110528
|
-
const observed = observations.find((entry) => entry.member.kind === kind && entry.row != null && !entry.member.retiredReason
|
|
110765
|
+
const observed = observations.find((entry) => entry.member.kind === kind && entry.row != null && !entry.member.retiredReason);
|
|
110529
110766
|
return observed?.row?.trigger_px != null ? String(observed.row.trigger_px) : null;
|
|
110530
110767
|
};
|
|
110531
110768
|
for (const step of nativeAfterFillActions({
|
|
@@ -110713,7 +110950,7 @@ var init_native_protection_device = __esm({
|
|
|
110713
110950
|
members.push(moveMade(member));
|
|
110714
110951
|
continue;
|
|
110715
110952
|
}
|
|
110716
|
-
if ((owesMove(member) || follows(member)) && movable && !member.retiredReason &&
|
|
110953
|
+
if ((owesMove(member) || follows(member)) && movable && !member.retiredReason && !member.pendingModify && nativePlacementGate({
|
|
110717
110954
|
eventMs: Math.max(owesMove(member) ? member.pendingMove?.afterMs ?? 0 : 0, member.placedAtMs ?? 0),
|
|
110718
110955
|
position: position.size,
|
|
110719
110956
|
positionStateMs: stateMs,
|
|
@@ -110752,11 +110989,11 @@ var init_native_protection_device = __esm({
|
|
|
110752
110989
|
}
|
|
110753
110990
|
anyResting = true;
|
|
110754
110991
|
members.push(
|
|
110755
|
-
movable && priceNow && member.priced == null && !owesMove(member) && !member.pendingModify && !member.retiredReason
|
|
110992
|
+
movable && priceNow && member.priced == null && !owesMove(member) && !member.pendingModify && !member.retiredReason ? { ...member, priced: priceNow } : member
|
|
110756
110993
|
);
|
|
110757
110994
|
continue;
|
|
110758
110995
|
}
|
|
110759
|
-
if (member.retiredReason
|
|
110996
|
+
if (member.retiredReason) {
|
|
110760
110997
|
members.push(member);
|
|
110761
110998
|
continue;
|
|
110762
110999
|
}
|
|
@@ -110765,20 +111002,11 @@ var init_native_protection_device = __esm({
|
|
|
110765
111002
|
members.push(member);
|
|
110766
111003
|
continue;
|
|
110767
111004
|
}
|
|
110768
|
-
|
|
110769
|
-
|
|
110770
|
-
|
|
110771
|
-
|
|
110772
|
-
|
|
110773
|
-
if (io.endsPass?.(error48)) throw error48;
|
|
110774
|
-
anyResting = true;
|
|
110775
|
-
members.push(member);
|
|
110776
|
-
continue;
|
|
110777
|
-
}
|
|
110778
|
-
if (cancelledByUser) {
|
|
110779
|
-
members.push({ ...member, userCancelledOrderId: member.orderId });
|
|
110780
|
-
continue;
|
|
110781
|
-
}
|
|
111005
|
+
const memberUserCancel = member.orderId == null ? false : await endedByUserCancel(io, member.orderId);
|
|
111006
|
+
if (memberUserCancel !== false) {
|
|
111007
|
+
if (memberUserCancel == null) anyResting = true;
|
|
111008
|
+
members.push(memberUserCancel ? { ...member, retiredReason: CANCELLED_BY_USER } : member);
|
|
111009
|
+
continue;
|
|
110782
111010
|
}
|
|
110783
111011
|
if (member.plannedAfterMs != null) {
|
|
110784
111012
|
if (!kindEnabled(member)) continue;
|
|
@@ -110971,7 +111199,7 @@ var init_native_protection_device = __esm({
|
|
|
110971
111199
|
let lot = prior;
|
|
110972
111200
|
const restingRow = lot.orderId == null ? null : page.find((order) => order.oid === lot.orderId) ?? null;
|
|
110973
111201
|
const otherSideUnnamed = lot.retiredReason === TRAILING_LOT_OTHER_SIDE && lot.mutationId != null && lot.orderId == null;
|
|
110974
|
-
if (
|
|
111202
|
+
if (lot.retiredReason && !otherSideUnnamed && !(restingRow && readListedProtectiveRow({ triggerCondition: restingRow.trigger_condition }) === "resting")) {
|
|
110975
111203
|
lots.push(lot);
|
|
110976
111204
|
continue;
|
|
110977
111205
|
}
|
|
@@ -111111,7 +111339,7 @@ var init_native_protection_device = __esm({
|
|
|
111111
111339
|
lots.push(lot);
|
|
111112
111340
|
continue;
|
|
111113
111341
|
}
|
|
111114
|
-
if (lot.retiredReason
|
|
111342
|
+
if (lot.retiredReason) {
|
|
111115
111343
|
lots.push(lot);
|
|
111116
111344
|
continue;
|
|
111117
111345
|
}
|
|
@@ -111135,6 +111363,12 @@ var init_native_protection_device = __esm({
|
|
|
111135
111363
|
}
|
|
111136
111364
|
continue;
|
|
111137
111365
|
}
|
|
111366
|
+
const lotUserCancel = await endedByUserCancel(io, lotOrderId);
|
|
111367
|
+
if (lotUserCancel !== false) {
|
|
111368
|
+
if (lotUserCancel == null) anyResting = true;
|
|
111369
|
+
lots.push(lotUserCancel ? { ...lot, retiredReason: CANCELLED_BY_USER } : lot);
|
|
111370
|
+
continue;
|
|
111371
|
+
}
|
|
111138
111372
|
const evidence2 = await io.readOrderStatus(lotOrderId);
|
|
111139
111373
|
const end = classifyNativeOrderEnd({
|
|
111140
111374
|
orderStatus: evidence2.responseValid ? String(evidence2.orderStatus ?? "") : "",
|
|
@@ -111195,7 +111429,7 @@ var init_native_protection_device = __esm({
|
|
|
111195
111429
|
});
|
|
111196
111430
|
|
|
111197
111431
|
// lib/runtime/runtime-execution.ts
|
|
111198
|
-
var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, createRuntimeId, _extractFilledSize, firstMemberAcknowledgement, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, withClientProtectivePlanSetLock, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, isConfiguredProtectionRequested, protectiveAction, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, readAttachEvidence, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, nativeSettingsOf, nativePassEnded, nativeProtectionIo, nativeStorageReport, readNativeRecord, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, modifyClientTrailingLeg, trailingRatchetIo, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, runtimeProtectionAuthority, runtimeProtectionListings, runtimeProtectionListing, resolveServerNativeEntry, SERVER_NATIVE_LEGACY_REFUSAL, isServerNativeLegacyRefusal, serverUserCancelLookup, serverModeProtectionOwner, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, nextClientTrailingStopDueAtMs, ratchetClientTrailingStopsBetweenCycles, handedOverPlan, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, listStoredClientProtectionSymbols, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked;
|
|
111432
|
+
var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, createRuntimeId, _extractFilledSize, firstMemberAcknowledgement, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, withClientProtectivePlanSetLock, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, isConfiguredProtectionRequested, protectiveAction, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, readAttachEvidence, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, nativeSettingsOf, nativePassEnded, nativeProtectionIo, nativeStorageReport, readNativeRecord, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, modifyClientTrailingLeg, trailingRatchetIo, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, runtimeProtectionAuthority, runtimeProtectionListings, runtimeProtectionListing, resolveServerNativeEntry, SERVER_NATIVE_LEGACY_REFUSAL, isServerNativeLegacyRefusal, serverUserCancelLookup, passUserCancelsFor, serverModeProtectionOwner, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, nextClientTrailingStopDueAtMs, ratchetClientTrailingStopsBetweenCycles, handedOverPlan, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, listStoredClientProtectionSymbols, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked;
|
|
111199
111433
|
var init_runtime_execution = __esm({
|
|
111200
111434
|
"lib/runtime/runtime-execution.ts"() {
|
|
111201
111435
|
"use strict";
|
|
@@ -111212,6 +111446,8 @@ var init_runtime_execution = __esm({
|
|
|
111212
111446
|
init_client_runtime_ownership_errors();
|
|
111213
111447
|
init_api2();
|
|
111214
111448
|
init_client_exchange_mutations();
|
|
111449
|
+
init_client_user_cancels();
|
|
111450
|
+
init_protective_user_cancels();
|
|
111215
111451
|
init_hyperliquid_order_status();
|
|
111216
111452
|
init_execution_capacity();
|
|
111217
111453
|
init_protective_actions();
|
|
@@ -111233,6 +111469,7 @@ var init_runtime_execution = __esm({
|
|
|
111233
111469
|
init_protective_leg_evidence();
|
|
111234
111470
|
init_protective_stop_replacement();
|
|
111235
111471
|
init_protective_entry_cover();
|
|
111472
|
+
init_protective_placed_stops();
|
|
111236
111473
|
init_protective_oversized_leg();
|
|
111237
111474
|
init_protective_report_entry();
|
|
111238
111475
|
init_error_surface_contract();
|
|
@@ -111535,7 +111772,6 @@ var init_runtime_execution = __esm({
|
|
|
111535
111772
|
return [];
|
|
111536
111773
|
}
|
|
111537
111774
|
const replacedOrderId = legRecord.replacedOrderId == null ? void 0 : Number(legRecord.replacedOrderId);
|
|
111538
|
-
const userCancelledOrderId = legRecord.userCancelledOrderId == null ? void 0 : Number(legRecord.userCancelledOrderId);
|
|
111539
111775
|
const replaceJournalRecord = legRecord.replaceJournal;
|
|
111540
111776
|
let replaceJournal;
|
|
111541
111777
|
if (replaceJournalRecord != null) {
|
|
@@ -111553,7 +111789,7 @@ var init_runtime_execution = __esm({
|
|
|
111553
111789
|
...journalObservedAtMs !== void 0 ? { unknownOidObservedAtMs: journalObservedAtMs } : {}
|
|
111554
111790
|
};
|
|
111555
111791
|
}
|
|
111556
|
-
if (replacedOrderId !== void 0 && (!Number.isSafeInteger(replacedOrderId) || replacedOrderId <= 0)
|
|
111792
|
+
if (replacedOrderId !== void 0 && (!Number.isSafeInteger(replacedOrderId) || replacedOrderId <= 0)) {
|
|
111557
111793
|
protectiveGroupReadFailures.add(key);
|
|
111558
111794
|
return [];
|
|
111559
111795
|
}
|
|
@@ -111599,7 +111835,6 @@ var init_runtime_execution = __esm({
|
|
|
111599
111835
|
...evidenceWait,
|
|
111600
111836
|
...replacedOrderId !== void 0 ? { replacedOrderId } : {},
|
|
111601
111837
|
...replaceJournal ? { replaceJournal } : {},
|
|
111602
|
-
...userCancelledOrderId !== void 0 ? { userCancelledOrderId } : {},
|
|
111603
111838
|
...replacement ? { replacement } : {}
|
|
111604
111839
|
}];
|
|
111605
111840
|
});
|
|
@@ -114508,6 +114743,7 @@ var init_runtime_execution = __esm({
|
|
|
114508
114743
|
const symbol2 = request.executionContext.symbol;
|
|
114509
114744
|
const walletAddress = String(request.executionContext.walletAddress || "").trim();
|
|
114510
114745
|
const exitSide = isLong ? "sell" : "buy";
|
|
114746
|
+
const userCancels = passUserCancelsFor(request);
|
|
114511
114747
|
const common = {
|
|
114512
114748
|
profileId: request.profileId,
|
|
114513
114749
|
...clientProtectiveMutationAuthority(request),
|
|
@@ -114620,7 +114856,7 @@ var init_runtime_execution = __esm({
|
|
|
114620
114856
|
neverLandsAfterMs: (sentAtMs) => clientOrderNeverLandsAfterMs(request.config, { kind: "absent", ageStartMs: sentAtMs }),
|
|
114621
114857
|
// A Server bot's writes are VTX's own: its refused places are not bounded as a device's are.
|
|
114622
114858
|
vtxSigns: request.executionMode === "server",
|
|
114623
|
-
...
|
|
114859
|
+
...userCancels ? { userCancelledOrder: userCancels.cancelled, prefetchUserCancels: userCancels.prefetch } : {},
|
|
114624
114860
|
newMutationId: () => createRuntimeId().toLowerCase(),
|
|
114625
114861
|
nowMs: () => Date.now(),
|
|
114626
114862
|
persist: (record6) => writeNativeProtectionRecord(String(request.profileId).trim(), symbol2, record6),
|
|
@@ -115048,8 +115284,7 @@ var init_runtime_execution = __esm({
|
|
|
115048
115284
|
tp: exposure
|
|
115049
115285
|
};
|
|
115050
115286
|
const retainedGroups = expectedGroupSet.filter((group) => group.pendingEntry != null || isProtectiveReplacementJournalGroup(group));
|
|
115051
|
-
|
|
115052
|
-
const placedThisPass = /* @__PURE__ */ new Set();
|
|
115287
|
+
const placedStops = passPlacedStops(symbol2);
|
|
115053
115288
|
const unresolvedLegIds = new Set(inspectedGroups.flatMap((candidate) => candidate.legs).filter((entry) => entry.state === "unresolved").map((entry) => String(entry.leg.orderId)));
|
|
115054
115289
|
const lostOrderIds = new Set(inspectedGroups.flatMap((candidate) => candidate.legs).filter((entry) => entry.state === "terminal").flatMap(({ leg }) => [String(leg.orderId), String(lookedUp.get(String(leg.orderId)) ?? leg.orderId)]));
|
|
115055
115290
|
const statusOnlyOrders = () => inspectedGroups.flatMap((candidate) => candidate.legs).filter((entry) => entry.openOrder == null).map((entry) => ({ receivedMs: entry.statusReceivedMs ?? legsLiveSinceMs, atMs: entry.terminalStatus?.statusTimestampMs ?? entry.statusAtMs }));
|
|
@@ -115145,10 +115380,10 @@ var init_runtime_execution = __esm({
|
|
|
115145
115380
|
const resolveLostClientProtectiveLeg = async (group, waitingLeg, botCleanupInFlight, terminalStatus) => {
|
|
115146
115381
|
const { freshEvidenceSinceMs: _waitedSinceMs, ...leg } = waitingLeg;
|
|
115147
115382
|
const botCleanup = botCleanupInFlight || leg.replacement != null;
|
|
115148
|
-
let cancelledByUser =
|
|
115149
|
-
if (!
|
|
115383
|
+
let cancelledByUser = false;
|
|
115384
|
+
if (!botCleanup && userCancels) {
|
|
115150
115385
|
try {
|
|
115151
|
-
cancelledByUser = await
|
|
115386
|
+
cancelledByUser = await userCancels.cancelled(leg.orderId);
|
|
115152
115387
|
} catch (error48) {
|
|
115153
115388
|
if (request.signal?.aborted) throw error48;
|
|
115154
115389
|
return {
|
|
@@ -115178,18 +115413,23 @@ var init_runtime_execution = __esm({
|
|
|
115178
115413
|
const market2 = reachable(sizeOf(lost.position)) ? await lost.withPage() : lost;
|
|
115179
115414
|
const positionSize = sizeOf(market2.position);
|
|
115180
115415
|
const replaceReachable = reachable(positionSize) && market2.orders != null;
|
|
115181
|
-
const
|
|
115416
|
+
const own = replaceReachable ? resolveOwnStops({
|
|
115182
115417
|
symbol: symbol2,
|
|
115183
115418
|
groups: expectedGroupSet,
|
|
115184
115419
|
orders: market2.orders ?? [],
|
|
115185
115420
|
lookedUp,
|
|
115186
|
-
unresolved: unresolvedLegIds
|
|
115187
|
-
|
|
115421
|
+
unresolved: unresolvedLegIds,
|
|
115422
|
+
placed: placedStops.ids(),
|
|
115423
|
+
ended: lostOrderIds
|
|
115424
|
+
}) : null;
|
|
115425
|
+
const placed = placedStops.count(market2);
|
|
115426
|
+
const stops = own?.lostStopCover(positionSize, placed);
|
|
115188
115427
|
const markPrice = Number(market2.position.markPrice);
|
|
115189
115428
|
evidence2 = {
|
|
115190
115429
|
positionSize,
|
|
115191
115430
|
liveStopSize: stops?.onPage ?? 0,
|
|
115192
|
-
|
|
115431
|
+
// What the legs this pass could not read may still cover, and its own re-placed stops.
|
|
115432
|
+
inFlightStopSize: (stops?.unseen ?? 0) + placed.size,
|
|
115193
115433
|
markPrice: replaceReachable && Number.isFinite(markPrice) && markPrice > 0 ? markPrice : null
|
|
115194
115434
|
};
|
|
115195
115435
|
} catch (error48) {
|
|
@@ -115202,7 +115442,7 @@ var init_runtime_execution = __esm({
|
|
|
115202
115442
|
positionSize: evidence2.positionSize,
|
|
115203
115443
|
legSize: leg.size,
|
|
115204
115444
|
otherLiveStopSize: evidence2.liveStopSize,
|
|
115205
|
-
inFlightStopSize: evidence2.
|
|
115445
|
+
inFlightStopSize: evidence2.inFlightStopSize,
|
|
115206
115446
|
sizeDecimals: request.executionContext.sizeDecimals,
|
|
115207
115447
|
triggerPrice: leg.triggerPrice,
|
|
115208
115448
|
alreadyReplaced: leg.replacedOrderId != null,
|
|
@@ -115310,8 +115550,7 @@ var init_runtime_execution = __esm({
|
|
|
115310
115550
|
}]
|
|
115311
115551
|
};
|
|
115312
115552
|
}
|
|
115313
|
-
|
|
115314
|
-
placedThisPass.add(clientOrderId);
|
|
115553
|
+
const placedStop = placedStops.add(provisionalLeg, group.isLong);
|
|
115315
115554
|
let dispatchMayHaveStarted = false;
|
|
115316
115555
|
let response;
|
|
115317
115556
|
try {
|
|
@@ -115342,8 +115581,7 @@ var init_runtime_execution = __esm({
|
|
|
115342
115581
|
} catch (error48) {
|
|
115343
115582
|
if (error48 instanceof ExchangeRejectionError) {
|
|
115344
115583
|
const rejectionProjection = projectExecutionErrorContract({ error: error48, symbol: symbol2 });
|
|
115345
|
-
|
|
115346
|
-
placedThisPass.delete(clientOrderId);
|
|
115584
|
+
placedStops.drop(placedStop);
|
|
115347
115585
|
const rejectedGroup = {
|
|
115348
115586
|
...provisionalGroup,
|
|
115349
115587
|
legs: provisionalGroup.legs.filter((candidate) => candidate.orderId !== clientOrderId)
|
|
@@ -115374,8 +115612,7 @@ var init_runtime_execution = __esm({
|
|
|
115374
115612
|
};
|
|
115375
115613
|
}
|
|
115376
115614
|
if (!dispatchMayHaveStarted) {
|
|
115377
|
-
|
|
115378
|
-
placedThisPass.delete(clientOrderId);
|
|
115615
|
+
placedStops.drop(placedStop);
|
|
115379
115616
|
const restored = transitionExactGroup(provisionalGroup, group);
|
|
115380
115617
|
if (restored && isClientRuntimeWindowHandoffBeforePlanDispatch(error48)) {
|
|
115381
115618
|
throw error48;
|
|
@@ -115431,7 +115668,7 @@ var init_runtime_execution = __esm({
|
|
|
115431
115668
|
}]
|
|
115432
115669
|
};
|
|
115433
115670
|
}
|
|
115434
|
-
|
|
115671
|
+
placedStops.answered(placedStop, acknowledgement);
|
|
115435
115672
|
const { replaceJournal: _landedJournal, ...landedLeg } = provisionalLeg;
|
|
115436
115673
|
const placedLeg = { ...landedLeg, orderId: placedOrderId };
|
|
115437
115674
|
const placedGroup = {
|
|
@@ -115486,6 +115723,8 @@ var init_runtime_execution = __esm({
|
|
|
115486
115723
|
lookedUp,
|
|
115487
115724
|
unresolved: unresolvedLegIds
|
|
115488
115725
|
});
|
|
115726
|
+
const userCancels = passUserCancelsFor(request);
|
|
115727
|
+
await userCancels?.prefetch(inspectedGroups.flatMap((candidate) => candidate.group.cleanupRequired === true || exposure <= 0 || candidate.legs.some((entry) => entry.state === "fulfilled") ? [] : candidate.legs.filter((entry) => entry.state === "terminal" && entry.leg.replacement == null).map((entry) => entry.leg.orderId)));
|
|
115489
115728
|
groupLoop: for (let groupIndex = 0; groupIndex < inspectedGroups.length; groupIndex += 1) {
|
|
115490
115729
|
const inspected = inspectedGroups[groupIndex];
|
|
115491
115730
|
let durableGroup = inspected.group;
|
|
@@ -116343,6 +116582,16 @@ var init_runtime_execution = __esm({
|
|
|
116343
116582
|
SERVER_NATIVE_LEGACY_REFUSAL = "native_protection_legacy_position";
|
|
116344
116583
|
isServerNativeLegacyRefusal = (error48) => Boolean(error48 && typeof error48 === "object") && error48.code === SERVER_NATIVE_LEGACY_REFUSAL;
|
|
116345
116584
|
serverUserCancelLookup = null;
|
|
116585
|
+
passUserCancelsFor = (request) => {
|
|
116586
|
+
const profileId = String(request.profileId).trim();
|
|
116587
|
+
const lookup = serverUserCancelLookup;
|
|
116588
|
+
if (request.executionMode === "server") {
|
|
116589
|
+
return lookup ? passUserCancels(readEachUserCancel((orderId) => lookup(profileId, orderId), request.signal), { signal: request.signal }) : null;
|
|
116590
|
+
}
|
|
116591
|
+
return passUserCancels(async (orderIds) => ({ cancelled: await readClientUserCancels(profileId, orderIds, request.signal) }), {
|
|
116592
|
+
signal: request.signal
|
|
116593
|
+
});
|
|
116594
|
+
};
|
|
116346
116595
|
serverModeProtectionOwner = "server";
|
|
116347
116596
|
runtimeProtectionOwners = /* @__PURE__ */ new WeakMap();
|
|
116348
116597
|
resolveRuntimeProtectionOwner = (request) => {
|
|
@@ -116903,8 +117152,7 @@ var init_runtime_execution = __esm({
|
|
|
116903
117152
|
// A trailing stop keeps its own distance under the server (client_protective_adoption.py plan_risk).
|
|
116904
117153
|
...leg.trailingRisk ? { risk_mode: leg.trailingRisk.mode, risk_value: String(leg.trailingRisk.value) } : {},
|
|
116905
117154
|
// A stop re-placed once stays re-placed once under the server.
|
|
116906
|
-
...leg.replacedOrderId != null ? { replaced_order_id: String(leg.replacedOrderId) } : {}
|
|
116907
|
-
...leg.userCancelledOrderId != null ? { user_cancelled_order_id: String(leg.userCancelledOrderId) } : {}
|
|
117155
|
+
...leg.replacedOrderId != null ? { replaced_order_id: String(leg.replacedOrderId) } : {}
|
|
116908
117156
|
})),
|
|
116909
117157
|
...group.pendingEntry && group.legs.length === 0 ? [
|
|
116910
117158
|
...group.pendingEntry.stopLoss.enabled ? [{
|
|
@@ -119680,7 +119928,7 @@ var init_browser_observability = __esm({
|
|
|
119680
119928
|
init_define_VTX_GROK_POLICY();
|
|
119681
119929
|
init_define_VTX_PI_MODEL_POLICY();
|
|
119682
119930
|
init_runtime_policy_generated2();
|
|
119683
|
-
CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "
|
|
119931
|
+
CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "d2a1386883f9001b5d78fa222be70d5248c4700b".trim() && "d2a1386883f9001b5d78fa222be70d5248c4700b".trim() !== "unstamped" ? "d2a1386883f9001b5d78fa222be70d5248c4700b".trim() : null;
|
|
119684
119932
|
listenersInstalled = false;
|
|
119685
119933
|
state = {
|
|
119686
119934
|
loadedAtMs: Date.now(),
|
|
@@ -124652,8 +124900,8 @@ var init_candle_prompt_contract = __esm({
|
|
|
124652
124900
|
throw new Error("Candle prompt rows must be ordered by timestamp");
|
|
124653
124901
|
}
|
|
124654
124902
|
}
|
|
124655
|
-
const
|
|
124656
|
-
const openIndexes = timestamps.map((timestamp, index) => timestamp
|
|
124903
|
+
const newestOpenTimestamp = timestamps[timestamps.length - 1];
|
|
124904
|
+
const openIndexes = timestamps.map((timestamp, index) => candleClosedInSeries(timestamp, newestOpenTimestamp, intervalSeconds, asOfTimestamp) ? -1 : index).filter((index) => index >= 0);
|
|
124657
124905
|
if (openIndexes.length === 0) {
|
|
124658
124906
|
return projected;
|
|
124659
124907
|
}
|
|
@@ -124680,7 +124928,7 @@ var init_candle_prompt_contract = __esm({
|
|
|
124680
124928
|
if (intervalSeconds === void 0 || lastOpenTimestamp === void 0) {
|
|
124681
124929
|
return 0;
|
|
124682
124930
|
}
|
|
124683
|
-
const lastIsClosed = lastOpenTimestamp
|
|
124931
|
+
const lastIsClosed = candleClosedInSeries(lastOpenTimestamp, lastOpenTimestamp, intervalSeconds, input.asOfTimestamp);
|
|
124684
124932
|
return lastIsClosed ? input.openTimestamps.length : input.openTimestamps.length - 1;
|
|
124685
124933
|
};
|
|
124686
124934
|
calculateRelativeVolumeSeries = (input) => {
|
|
@@ -125934,7 +126182,8 @@ var init_market_context = __esm({
|
|
|
125934
126182
|
if (timeframeSeconds === void 0) {
|
|
125935
126183
|
throw new RuntimeReasonError(`Unsupported candle timeframe: ${timeframe}`, "internal_data_error");
|
|
125936
126184
|
}
|
|
125937
|
-
const
|
|
126185
|
+
const newestOpen = candles[candles.length - 1].timestamp;
|
|
126186
|
+
const lastIsClosed = candleClosedInSeries(newestOpen, newestOpen, timeframeSeconds, asOf);
|
|
125938
126187
|
const statsWindow = lastIsClosed ? candles : candles.slice(0, -1);
|
|
125939
126188
|
if (statsWindow.length > 0) {
|
|
125940
126189
|
const features = extractWindowFeatures(statsWindow, input.lookbacks[timeframe]);
|
|
@@ -130607,7 +130856,7 @@ var init_provider_client = __esm({
|
|
|
130607
130856
|
});
|
|
130608
130857
|
|
|
130609
130858
|
// lib/runtime/runtime-prompt-steps.ts
|
|
130610
|
-
var buildRuntimePromptParityContext, readRuntimePromptMarketData, invokeRuntimeReviewModel, resolveRuntimePromptKnobs, buildRuntimePromptCandles, requireRuntimePromptTemplates, resolveRuntimeBehaviorMemoryCutoff, buildRuntimeBehaviorStateArtifacts, buildRuntimePromptContextParts, runtimePromptArtifactInput;
|
|
130859
|
+
var buildRuntimePromptParityContext, cycleMarketTicker, readRuntimePromptMarketData, invokeRuntimeReviewModel, resolveRuntimePromptKnobs, buildRuntimePromptCandles, requireRuntimePromptTemplates, resolveRuntimeBehaviorMemoryCutoff, buildRuntimeBehaviorStateArtifacts, buildRuntimePromptContextParts, runtimePromptArtifactInput;
|
|
130611
130860
|
var init_runtime_prompt_steps = __esm({
|
|
130612
130861
|
"lib/runtime/runtime-prompt-steps.ts"() {
|
|
130613
130862
|
"use strict";
|
|
@@ -130646,6 +130895,7 @@ var init_runtime_prompt_steps = __esm({
|
|
|
130646
130895
|
}
|
|
130647
130896
|
return parityContext;
|
|
130648
130897
|
};
|
|
130898
|
+
cycleMarketTicker = (symbol2, candles, loadedTicker) => loadedTicker?.is_fresh === true && toPositiveFinite3(loadedTicker.price) !== null ? loadedTicker : candleCloseTicker(symbol2, candles) ?? loadedTicker;
|
|
130649
130899
|
readRuntimePromptMarketData = (input) => {
|
|
130650
130900
|
const marketDataStartedAtMs = Date.now();
|
|
130651
130901
|
return Promise.all(
|
|
@@ -130680,7 +130930,7 @@ var init_runtime_prompt_steps = __esm({
|
|
|
130680
130930
|
)
|
|
130681
130931
|
]);
|
|
130682
130932
|
const candles = Object.fromEntries(loadedCandles);
|
|
130683
|
-
const ticker =
|
|
130933
|
+
const ticker = cycleMarketTicker(marketSymbol, candles, loadedTicker);
|
|
130684
130934
|
if (ticker === null) throw tickerError;
|
|
130685
130935
|
if (loadedTicker === null) {
|
|
130686
130936
|
appendRuntimeDebugEvent({
|
|
@@ -132897,9 +133147,9 @@ var init_local_analysis = __esm({
|
|
|
132897
133147
|
RUNTIME_SOURCE_DEFINITION_VERSION = "runtime-source-v1";
|
|
132898
133148
|
DECISION_INPUT_DEFINITION_VERSION = "decision-input-v1";
|
|
132899
133149
|
CONTEXT_ENVELOPE_DEFINITION_VERSION = "context-envelope-v2.1";
|
|
132900
|
-
CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "
|
|
132901
|
-
"
|
|
132902
|
-
) ? "
|
|
133150
|
+
CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "d2a1386883f9001b5d78fa222be70d5248c4700b".trim() && !["unknown", "unstamped", "development"].includes(
|
|
133151
|
+
"d2a1386883f9001b5d78fa222be70d5248c4700b".trim().toLowerCase()
|
|
133152
|
+
) ? "d2a1386883f9001b5d78fa222be70d5248c4700b".trim() : null;
|
|
132903
133153
|
CLIENT_MAIN_PROMPT_RENDERER = "client_runtime.buildLocalRuntimePromptArtifacts:v1";
|
|
132904
133154
|
CLIENT_REVIEW_PROMPT_RENDERER = "client_runtime.review_prompt_assembly:v1";
|
|
132905
133155
|
resolveEffectivePromptRuntimeProvenance = (input) => ({
|
|
@@ -138129,128 +138379,76 @@ ${copyReviewPromptContext(proposedTrade, input.templates)}`;
|
|
|
138129
138379
|
}
|
|
138130
138380
|
});
|
|
138131
138381
|
|
|
138132
|
-
// lib/runtime/copy-review-
|
|
138133
|
-
var
|
|
138134
|
-
|
|
138135
|
-
|
|
138136
|
-
renderCheckInCopyReviewShadows: () => renderCheckInCopyReviewShadows,
|
|
138137
|
-
renderCopyReviewShadows: () => renderCopyReviewShadows,
|
|
138138
|
-
renderRuntimeCopyReview: () => renderRuntimeCopyReview,
|
|
138139
|
-
shadowBudget: () => shadowBudget,
|
|
138140
|
-
shadowPrompts: () => shadowPrompts
|
|
138141
|
-
});
|
|
138142
|
-
var prepareRuntimeCopyReviewPrimary, renderRuntimeCopyReview, shadowPrompts, SHADOW_RENDER_TIMEOUT_MS, SHADOW_REPORT_TIMEOUT_MS, shadowBudget, renderCopyReviewShadows, renderCheckInCopyReviewShadows;
|
|
138143
|
-
var init_copy_review_runtime = __esm({
|
|
138144
|
-
"lib/runtime/copy-review-runtime.ts"() {
|
|
138382
|
+
// lib/runtime/copy-review-render-inputs.ts
|
|
138383
|
+
var copyReviewRenderScope, copyReviewAccountSummary, requireCopyReviewAccountEquity, copyReviewWalletAddress, copyReviewParityContext, requireCopyReviewContractReady, copyReviewPrimaryFromInputs, renderCopyReviewFromPrimary, shadowPrompts;
|
|
138384
|
+
var init_copy_review_render_inputs = __esm({
|
|
138385
|
+
"lib/runtime/copy-review-render-inputs.ts"() {
|
|
138145
138386
|
"use strict";
|
|
138146
138387
|
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
138147
138388
|
init_define_VTX_EXO_POLICY();
|
|
138148
138389
|
init_define_VTX_GROK_POLICY();
|
|
138149
138390
|
init_define_VTX_PI_MODEL_POLICY();
|
|
138150
|
-
init_copy_review();
|
|
138151
|
-
init_constants();
|
|
138152
|
-
init_runtime_policy_generated2();
|
|
138153
138391
|
init_ai_settings_helpers();
|
|
138154
|
-
init_abort();
|
|
138155
138392
|
init_client_account_report();
|
|
138156
138393
|
init_copy_review_prompt();
|
|
138157
138394
|
init_render();
|
|
138158
|
-
init_hyperliquid_account_state_adapter();
|
|
138159
138395
|
init_local_analysis();
|
|
138160
|
-
init_network_debug();
|
|
138161
|
-
init_perp_dex_scope();
|
|
138162
138396
|
init_runtime_error_reason_rules();
|
|
138163
138397
|
init_runtime_prompt_steps();
|
|
138164
|
-
|
|
138165
|
-
const { config: config2, signal } = input;
|
|
138398
|
+
copyReviewRenderScope = (input) => {
|
|
138166
138399
|
const settings = sortAiSettings(input.settings || {}) || {};
|
|
138167
|
-
const
|
|
138168
|
-
|
|
138169
|
-
throw new RuntimeReasonError("The active profile wallet is unavailable. Save a wallet for this profile, then try again.", "profile_wallet_unavailable");
|
|
138170
|
-
}
|
|
138171
|
-
const { symbols: botSymbols, timeframes } = resolveRuntimeTradingScope(settings, config2);
|
|
138172
|
-
const sortedTimeframes = sortTradingTimeframes(timeframes);
|
|
138173
|
-
const symbols = input.promptSymbols(botSymbols);
|
|
138174
|
-
const activeIndicators = normalizeAiIndicatorFlags(config2.default_ai_indicators, settings.ai_indicators);
|
|
138175
|
-
const indicatorCandleCount = Number(config2.indicator_candle_count);
|
|
138400
|
+
const { symbols: botSymbols, timeframes } = resolveRuntimeTradingScope(settings, input.config);
|
|
138401
|
+
const indicatorCandleCount = Number(input.config.indicator_candle_count);
|
|
138176
138402
|
if (!Number.isSafeInteger(indicatorCandleCount) || indicatorCandleCount < 1) {
|
|
138177
138403
|
throw new RuntimeReasonError("Missing required client runtime config: indicator_candle_count", "runtime_config_missing");
|
|
138178
138404
|
}
|
|
138179
|
-
|
|
138180
|
-
|
|
138181
|
-
|
|
138182
|
-
|
|
138183
|
-
|
|
138184
|
-
lookbackSettings: settings.analysis_lookback,
|
|
138185
|
-
defaultLookbacks: config2.default_analysis_lookback_fallbacks,
|
|
138186
|
-
indicatorCandleCount,
|
|
138187
|
-
primarySymbol: symbols[0],
|
|
138188
|
-
primaryTimeframe: sortedTimeframes[0],
|
|
138189
|
-
signal,
|
|
138190
|
-
// A Client bot's candles: the stored ones, and the rest read here (the
|
|
138191
|
-
// copied market may be one nothing streams); never a VTX server read of
|
|
138192
|
-
// Hyperliquid for it.
|
|
138193
|
-
...serverBot ? {} : {
|
|
138194
|
-
candleReadContext: { profileId: input.profileId, deviceConfig: () => config2, priority: input.readPriority }
|
|
138195
|
-
}
|
|
138196
|
-
}));
|
|
138197
|
-
const fillsPromise = settleRuntimeCyclePromise(serverBot ? Promise.resolve(null) : fetchBrowserUserFills({
|
|
138198
|
-
publicRequestPriority: input.readPriority,
|
|
138199
|
-
config: config2,
|
|
138200
|
-
walletAddress,
|
|
138201
|
-
symbols,
|
|
138202
|
-
forceRefresh: false,
|
|
138203
|
-
signal
|
|
138204
|
-
}));
|
|
138205
|
-
const accountState = await fetchBrowserAccountState2({
|
|
138206
|
-
publicRequestPriority: input.readPriority,
|
|
138207
|
-
config: config2,
|
|
138208
|
-
walletAddress,
|
|
138209
|
-
symbol: symbols[0],
|
|
138210
|
-
tickerPrice: 0,
|
|
138211
|
-
leverage: resolveRuntimeLeveragePreference(settings, config2),
|
|
138212
|
-
aggregatePerpDexs: true,
|
|
138213
|
-
perpDexScope: perpDexScopeForSymbols(symbols),
|
|
138214
|
-
feeSymbols: symbols,
|
|
138215
|
-
includeEffectiveTakerRate: true,
|
|
138216
|
-
forceRefresh: serverBot,
|
|
138217
|
-
serverLoopAccountValue: serverBot,
|
|
138218
|
-
sessionId: input.payload.sessionId,
|
|
138219
|
-
signal
|
|
138220
|
-
});
|
|
138221
|
-
const fills = unwrapRuntimeCycleSettledResult(await fillsPromise);
|
|
138222
|
-
const accountSummary = {
|
|
138223
|
-
...accountState.accountSummary,
|
|
138224
|
-
total_unrealized_pnl: resolveTotalUnrealizedPnl2(
|
|
138225
|
-
accountState.accountSummary,
|
|
138226
|
-
accountState.positions
|
|
138227
|
-
) ?? accountState.accountSummary.total_unrealized_pnl
|
|
138405
|
+
return {
|
|
138406
|
+
settings,
|
|
138407
|
+
symbols: input.promptSymbols(botSymbols),
|
|
138408
|
+
sortedTimeframes: sortTradingTimeframes(timeframes),
|
|
138409
|
+
indicatorCandleCount
|
|
138228
138410
|
};
|
|
138411
|
+
};
|
|
138412
|
+
copyReviewAccountSummary = (accountState) => ({
|
|
138413
|
+
...accountState.accountSummary,
|
|
138414
|
+
total_unrealized_pnl: resolveTotalUnrealizedPnl2(
|
|
138415
|
+
accountState.accountSummary,
|
|
138416
|
+
accountState.positions
|
|
138417
|
+
) ?? accountState.accountSummary.total_unrealized_pnl
|
|
138418
|
+
});
|
|
138419
|
+
requireCopyReviewAccountEquity = (accountState, serverBot) => {
|
|
138229
138420
|
const accountEquity = Number(accountState.accountSummary?.account_value) || 0;
|
|
138230
138421
|
if (accountEquity <= 0 && !serverBot) {
|
|
138231
138422
|
throw new RuntimeReasonError("Live account equity unavailable for client runtime prompt contract.", "hyperliquid_data_unavailable");
|
|
138232
138423
|
}
|
|
138233
|
-
|
|
138424
|
+
return accountEquity;
|
|
138425
|
+
};
|
|
138426
|
+
copyReviewWalletAddress = (settings) => {
|
|
138427
|
+
const walletAddress = String(settings.hyperliquid_wallet_address || "").trim();
|
|
138428
|
+
if (!walletAddress) {
|
|
138429
|
+
throw new RuntimeReasonError("The active profile wallet is unavailable. Save a wallet for this profile, then try again.", "profile_wallet_unavailable");
|
|
138430
|
+
}
|
|
138431
|
+
return walletAddress;
|
|
138432
|
+
};
|
|
138433
|
+
copyReviewParityContext = (input) => {
|
|
138434
|
+
const { accountState, scope } = input;
|
|
138435
|
+
const accountSummary = copyReviewAccountSummary(accountState);
|
|
138436
|
+
return buildRuntimePromptParityContext({
|
|
138234
138437
|
account: {
|
|
138235
|
-
walletAddress,
|
|
138236
|
-
accountEquity,
|
|
138438
|
+
walletAddress: copyReviewWalletAddress(scope.settings),
|
|
138439
|
+
accountEquity: requireCopyReviewAccountEquity(accountState, input.serverBot),
|
|
138237
138440
|
perpDexAccounts: accountState.accountSummary?.perp_dex_accounts ?? null,
|
|
138238
138441
|
positions: accountState.positions,
|
|
138239
138442
|
totalUnrealizedPnl: accountSummary.total_unrealized_pnl ?? null
|
|
138240
138443
|
},
|
|
138241
138444
|
deviceCandleSeries: {
|
|
138242
|
-
series: symbols.flatMap((
|
|
138243
|
-
limit: indicatorCandleCount
|
|
138445
|
+
series: scope.symbols.flatMap((symbol2) => scope.sortedTimeframes.map((timeframe) => [symbol2, timeframe])),
|
|
138446
|
+
limit: scope.indicatorCandleCount
|
|
138244
138447
|
},
|
|
138245
|
-
userFills: fills ? { fills: fills.rawFills, evidence: fills.evidence } : null
|
|
138448
|
+
userFills: input.fills ? { fills: input.fills.rawFills, evidence: input.fills.evidence } : null
|
|
138246
138449
|
});
|
|
138247
|
-
|
|
138248
|
-
|
|
138249
|
-
isAnalyzing: false,
|
|
138250
|
-
isExecuting: false,
|
|
138251
|
-
promptParityContext: parityContext,
|
|
138252
|
-
copyReviewSymbol: input.copySymbol
|
|
138253
|
-
}, { schedulerInstanceId: input.payload.schedulerInstanceId ?? void 0, signal });
|
|
138450
|
+
};
|
|
138451
|
+
requireCopyReviewContractReady = (derived) => {
|
|
138254
138452
|
if (String(derived.status || "").trim() !== "derived_context_ready") {
|
|
138255
138453
|
throw new RuntimeReasonError(`Unexpected prompt derived-context status: ${String(derived.status || "unknown")}`, "internal_data_error");
|
|
138256
138454
|
}
|
|
@@ -138259,7 +138457,14 @@ var init_copy_review_runtime = __esm({
|
|
|
138259
138457
|
throw new RuntimeReasonError(`Unexpected prompt metadata status: ${String(promptMetadata?.status || "unknown")}`, "internal_data_error");
|
|
138260
138458
|
}
|
|
138261
138459
|
assertPromptContractCompatibility(promptMetadata);
|
|
138262
|
-
|
|
138460
|
+
return promptMetadata;
|
|
138461
|
+
};
|
|
138462
|
+
copyReviewPrimaryFromInputs = (input) => {
|
|
138463
|
+
const { config: config2, contract: derived, marketData, fills, accountState } = input;
|
|
138464
|
+
const { settings, symbols, sortedTimeframes, indicatorCandleCount } = input.scope;
|
|
138465
|
+
const activeIndicators = normalizeAiIndicatorFlags(config2.default_ai_indicators, settings.ai_indicators);
|
|
138466
|
+
const accountSummary = copyReviewAccountSummary(accountState);
|
|
138467
|
+
const promptMetadata = requireCopyReviewContractReady(derived);
|
|
138263
138468
|
const tickersBySymbol = Object.fromEntries(marketData.map((entry) => [entry.symbol, entry.ticker]));
|
|
138264
138469
|
const candlesBySymbol = Object.fromEntries(marketData.map((entry) => [entry.symbol, entry.candles]));
|
|
138265
138470
|
const derivedContext = asRecord(derived.derived_context);
|
|
@@ -138297,7 +138502,7 @@ var init_copy_review_runtime = __esm({
|
|
|
138297
138502
|
const { cutoffMs } = resolveRuntimeBehaviorMemoryCutoff(derivedContext, derived.derived_context_generated_at);
|
|
138298
138503
|
const accountMarginNote = requireRuntimeAccountMarginNote(asRecord(promptInstructions.account));
|
|
138299
138504
|
const behaviorState = buildRuntimeBehaviorStateArtifacts({
|
|
138300
|
-
serverOwnsBehaviorState:
|
|
138505
|
+
serverOwnsBehaviorState: input.serverOwnsBehaviorState,
|
|
138301
138506
|
derivedContext,
|
|
138302
138507
|
behaviorInstructions: asRecord(promptInstructions.behavior),
|
|
138303
138508
|
config: config2,
|
|
@@ -138362,24 +138567,10 @@ var init_copy_review_runtime = __esm({
|
|
|
138362
138567
|
}
|
|
138363
138568
|
};
|
|
138364
138569
|
};
|
|
138365
|
-
|
|
138366
|
-
const prepared = await prepareRuntimeCopyReviewPrimary({
|
|
138367
|
-
profileId: input.profileId,
|
|
138368
|
-
payload: input.payload,
|
|
138369
|
-
executionMode: input.executionMode,
|
|
138370
|
-
config: input.config,
|
|
138371
|
-
settings: input.settings,
|
|
138372
|
-
copySymbol: input.event.symbol,
|
|
138373
|
-
promptSymbols: (botSymbols) => copyReviewPromptSymbols(input.event.symbol, botSymbols),
|
|
138374
|
-
// A copy without a value of its own (no reference price) reviews at the
|
|
138375
|
-
// bot's trade size, else the configured default, as the lane serves them.
|
|
138376
|
-
promptSize: (sizes) => copyReviewPromptSize(input.event, sizes.profile || null, sizes.default),
|
|
138377
|
-
readPriority: input.readPriority,
|
|
138378
|
-
signal: input.signal
|
|
138379
|
-
});
|
|
138570
|
+
renderCopyReviewFromPrimary = (prepared, copy4) => {
|
|
138380
138571
|
const prompts = renderCopyReviewPrompts({
|
|
138381
|
-
event:
|
|
138382
|
-
source:
|
|
138572
|
+
event: copy4.event,
|
|
138573
|
+
source: copy4.source,
|
|
138383
138574
|
templates: prepared.templates,
|
|
138384
138575
|
primary: prepared.primary,
|
|
138385
138576
|
review: prepared.review
|
|
@@ -138396,6 +138587,125 @@ var init_copy_review_runtime = __esm({
|
|
|
138396
138587
|
review_system_prompt: prompts.reviewSystemPrompt,
|
|
138397
138588
|
review_user_prompt: prompts.reviewUserPrompt
|
|
138398
138589
|
});
|
|
138590
|
+
}
|
|
138591
|
+
});
|
|
138592
|
+
|
|
138593
|
+
// lib/runtime/copy-review-runtime.ts
|
|
138594
|
+
var copy_review_runtime_exports = {};
|
|
138595
|
+
__export(copy_review_runtime_exports, {
|
|
138596
|
+
prepareRuntimeCopyReviewPrimary: () => prepareRuntimeCopyReviewPrimary,
|
|
138597
|
+
renderCheckInCopyReviewShadows: () => renderCheckInCopyReviewShadows,
|
|
138598
|
+
renderCopyReviewShadows: () => renderCopyReviewShadows,
|
|
138599
|
+
renderRuntimeCopyReview: () => renderRuntimeCopyReview,
|
|
138600
|
+
shadowBudget: () => shadowBudget,
|
|
138601
|
+
shadowPrompts: () => shadowPrompts
|
|
138602
|
+
});
|
|
138603
|
+
var prepareRuntimeCopyReviewPrimary, renderRuntimeCopyReview, SHADOW_RENDER_TIMEOUT_MS, SHADOW_REPORT_TIMEOUT_MS, shadowBudget, renderCopyReviewShadows, renderCheckInCopyReviewShadows;
|
|
138604
|
+
var init_copy_review_runtime = __esm({
|
|
138605
|
+
"lib/runtime/copy-review-runtime.ts"() {
|
|
138606
|
+
"use strict";
|
|
138607
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
138608
|
+
init_define_VTX_EXO_POLICY();
|
|
138609
|
+
init_define_VTX_GROK_POLICY();
|
|
138610
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
138611
|
+
init_copy_review();
|
|
138612
|
+
init_constants();
|
|
138613
|
+
init_runtime_policy_generated2();
|
|
138614
|
+
init_abort();
|
|
138615
|
+
init_copy_review_prompt();
|
|
138616
|
+
init_hyperliquid_account_state_adapter();
|
|
138617
|
+
init_local_analysis();
|
|
138618
|
+
init_network_debug();
|
|
138619
|
+
init_perp_dex_scope();
|
|
138620
|
+
init_runtime_error_reason_rules();
|
|
138621
|
+
init_runtime_prompt_steps();
|
|
138622
|
+
init_copy_review_render_inputs();
|
|
138623
|
+
prepareRuntimeCopyReviewPrimary = async (input) => {
|
|
138624
|
+
const { config: config2, signal } = input;
|
|
138625
|
+
const scope = copyReviewRenderScope({ config: config2, settings: input.settings, promptSymbols: input.promptSymbols });
|
|
138626
|
+
const { settings, symbols, sortedTimeframes, indicatorCandleCount } = scope;
|
|
138627
|
+
const walletAddress = copyReviewWalletAddress(settings);
|
|
138628
|
+
const serverBot = input.executionMode === "server";
|
|
138629
|
+
const marketDataPromise = settleRuntimeCyclePromise(readRuntimePromptMarketData({
|
|
138630
|
+
config: config2,
|
|
138631
|
+
symbols,
|
|
138632
|
+
sortedTimeframes,
|
|
138633
|
+
lookbackSettings: settings.analysis_lookback,
|
|
138634
|
+
defaultLookbacks: config2.default_analysis_lookback_fallbacks,
|
|
138635
|
+
indicatorCandleCount,
|
|
138636
|
+
primarySymbol: symbols[0],
|
|
138637
|
+
primaryTimeframe: sortedTimeframes[0],
|
|
138638
|
+
signal,
|
|
138639
|
+
// A Client bot's candles: the stored ones, and the rest read here (the
|
|
138640
|
+
// copied market may be one nothing streams); never a VTX server read of
|
|
138641
|
+
// Hyperliquid for it.
|
|
138642
|
+
...serverBot ? {} : {
|
|
138643
|
+
candleReadContext: { profileId: input.profileId, deviceConfig: () => config2, priority: input.readPriority }
|
|
138644
|
+
}
|
|
138645
|
+
}));
|
|
138646
|
+
const fillsPromise = settleRuntimeCyclePromise(serverBot ? Promise.resolve(null) : fetchBrowserUserFills({
|
|
138647
|
+
publicRequestPriority: input.readPriority,
|
|
138648
|
+
config: config2,
|
|
138649
|
+
walletAddress,
|
|
138650
|
+
symbols,
|
|
138651
|
+
forceRefresh: false,
|
|
138652
|
+
signal
|
|
138653
|
+
}));
|
|
138654
|
+
const accountState = await fetchBrowserAccountState2({
|
|
138655
|
+
publicRequestPriority: input.readPriority,
|
|
138656
|
+
config: config2,
|
|
138657
|
+
walletAddress,
|
|
138658
|
+
symbol: symbols[0],
|
|
138659
|
+
tickerPrice: 0,
|
|
138660
|
+
leverage: resolveRuntimeLeveragePreference(settings, config2),
|
|
138661
|
+
aggregatePerpDexs: true,
|
|
138662
|
+
perpDexScope: perpDexScopeForSymbols(symbols),
|
|
138663
|
+
feeSymbols: symbols,
|
|
138664
|
+
includeEffectiveTakerRate: true,
|
|
138665
|
+
forceRefresh: serverBot,
|
|
138666
|
+
serverLoopAccountValue: serverBot,
|
|
138667
|
+
sessionId: input.payload.sessionId,
|
|
138668
|
+
signal
|
|
138669
|
+
});
|
|
138670
|
+
const fills = unwrapRuntimeCycleSettledResult(await fillsPromise);
|
|
138671
|
+
const parityContext = copyReviewParityContext({ accountState, fills, serverBot, scope });
|
|
138672
|
+
const derived = await fetchCopyReviewPromptContract(input.profileId, {
|
|
138673
|
+
...input.payload,
|
|
138674
|
+
isAnalyzing: false,
|
|
138675
|
+
isExecuting: false,
|
|
138676
|
+
promptParityContext: parityContext,
|
|
138677
|
+
copyReviewSymbol: input.copySymbol
|
|
138678
|
+
}, { schedulerInstanceId: input.payload.schedulerInstanceId ?? void 0, signal });
|
|
138679
|
+
requireCopyReviewContractReady(derived);
|
|
138680
|
+
return copyReviewPrimaryFromInputs({
|
|
138681
|
+
config: config2,
|
|
138682
|
+
settings: input.settings,
|
|
138683
|
+
serverOwnsBehaviorState: serverBot,
|
|
138684
|
+
contract: derived,
|
|
138685
|
+
marketData: unwrapRuntimeCycleSettledResult(await marketDataPromise),
|
|
138686
|
+
fills,
|
|
138687
|
+
accountState,
|
|
138688
|
+
scope,
|
|
138689
|
+
promptSize: input.promptSize
|
|
138690
|
+
});
|
|
138691
|
+
};
|
|
138692
|
+
renderRuntimeCopyReview = async (input) => {
|
|
138693
|
+
const prepared = await prepareRuntimeCopyReviewPrimary({
|
|
138694
|
+
profileId: input.profileId,
|
|
138695
|
+
payload: input.payload,
|
|
138696
|
+
executionMode: input.executionMode,
|
|
138697
|
+
config: input.config,
|
|
138698
|
+
settings: input.settings,
|
|
138699
|
+
copySymbol: input.event.symbol,
|
|
138700
|
+
promptSymbols: (botSymbols) => copyReviewPromptSymbols(input.event.symbol, botSymbols),
|
|
138701
|
+
// A copy without a value of its own (no reference price) reviews at the
|
|
138702
|
+
// bot's trade size, else the configured default, as the lane serves them.
|
|
138703
|
+
promptSize: (sizes) => copyReviewPromptSize(input.event, sizes.profile || null, sizes.default),
|
|
138704
|
+
readPriority: input.readPriority,
|
|
138705
|
+
signal: input.signal
|
|
138706
|
+
});
|
|
138707
|
+
return renderCopyReviewFromPrimary(prepared, { event: input.event, source: input.source });
|
|
138708
|
+
};
|
|
138399
138709
|
SHADOW_RENDER_TIMEOUT_MS = runtime_policy_generated_default2.copy_trading.review_shadow.render_timeout_seconds * MS_PER_SECOND;
|
|
138400
138710
|
SHADOW_REPORT_TIMEOUT_MS = runtime_policy_generated_default2.copy_trading.review_shadow.report_timeout_seconds * MS_PER_SECOND;
|
|
138401
138711
|
shadowBudget = (signal, budgetMs) => {
|