@vtxmacro/cli 2026.10.51 → 2026.10.53

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/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.51", 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" } } };
125
+ agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.53", 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
 
@@ -59016,7 +59016,7 @@ function getProfileHeaders(baseHeaders = {}, explicitProfileId) {
59016
59016
  if (profileId) headers["x-profile-id"] = profileId.toString();
59017
59017
  return headers;
59018
59018
  }
59019
- var configuredApiTransport, getApiUrl, browserCacheMode, sendApiRequest, apiFetch, sleep, DEVICE_CLOCK_HEADER, deviceClockHeader, API_NO_ROUTE_DETAIL, isMissingApiRoute, sendExchangeMutationReport, inFlightClientGetRequests, recentClientGetResponses, clientGetRequestGenerations, initializedClientGetRequestKeys, CLIENT_GET_DEDUPE_TTL_MS, CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS, CLIENT_LLM_CONFIG_PRIME_TTL_MS, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, singleUserHostCache, canUseClientGetRequestCache, clientGetRequestCacheActive, invalidateClientGetRequestCache, raceWithAbortSignal, shareClientGetRequest, clientGetRequestKey, clientPreferencesRequestKey, invalidateClientPreferencesCache, parseRetryAfterMs2, resolveAuthBootstrapRetryDelayMs, fetchAuthBootstrapGetWithRetry, annotateMarketDataRequestError, buildMarketDataFetchError, buildMarketDataNetworkError, buildMarketDataResponseBodyError, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, throwUnauthorizedIfNeeded, activeProfileId, PROFILE_STORAGE_KEY;
59019
+ var configuredApiTransport, getApiUrl, withoutContentType, browserRequestInit, sendApiRequest, apiFetch, sleep, DEVICE_CLOCK_HEADER, deviceClockHeader, API_NO_ROUTE_DETAIL, isMissingApiRoute, sendExchangeMutationReport, inFlightClientGetRequests, recentClientGetResponses, clientGetRequestGenerations, initializedClientGetRequestKeys, CLIENT_GET_DEDUPE_TTL_MS, CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS, CLIENT_LLM_CONFIG_PRIME_TTL_MS, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, singleUserHostCache, canUseClientGetRequestCache, clientGetRequestCacheActive, invalidateClientGetRequestCache, raceWithAbortSignal, shareClientGetRequest, clientGetRequestKey, clientPreferencesRequestKey, invalidateClientPreferencesCache, parseRetryAfterMs2, resolveAuthBootstrapRetryDelayMs, fetchAuthBootstrapGetWithRetry, annotateMarketDataRequestError, buildMarketDataFetchError, buildMarketDataNetworkError, buildMarketDataResponseBodyError, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, throwUnauthorizedIfNeeded, activeProfileId, PROFILE_STORAGE_KEY;
59020
59020
  var init_shared = __esm({
59021
59021
  "lib/api/shared.ts"() {
59022
59022
  "use strict";
@@ -59045,9 +59045,26 @@ var init_shared = __esm({
59045
59045
  RFC1918_172_BLOCK_SECOND_OCTET
59046
59046
  );
59047
59047
  };
59048
- browserCacheMode = (init2) => typeof window !== "undefined" && init2?.cache === "no-store" ? { ...init2, cache: "default" } : init2;
59048
+ withoutContentType = (headers) => {
59049
+ if (headers instanceof Headers) {
59050
+ const kept2 = new Headers(headers);
59051
+ kept2.delete("Content-Type");
59052
+ return kept2;
59053
+ }
59054
+ const entries = Array.isArray(headers) ? headers : Object.entries(headers);
59055
+ const kept = entries.filter(([name]) => name.toLowerCase() !== "content-type");
59056
+ return Array.isArray(headers) ? kept : Object.fromEntries(kept);
59057
+ };
59058
+ browserRequestInit = (init2) => {
59059
+ if (typeof window === "undefined" || !init2) return init2;
59060
+ const shaped = init2.cache === "no-store" ? { ...init2, cache: "default" } : init2;
59061
+ const method = (init2.method ?? "GET").toUpperCase();
59062
+ const bodyless = init2.body == null && (method === "GET" || method === "HEAD");
59063
+ if (!bodyless || !init2.headers || !new Headers(init2.headers).has("Content-Type")) return shaped;
59064
+ return { ...shaped, headers: withoutContentType(init2.headers) };
59065
+ };
59049
59066
  sendApiRequest = (input, requested) => {
59050
- const init2 = browserCacheMode(requested);
59067
+ const init2 = browserRequestInit(requested);
59051
59068
  const transport = configuredApiTransport;
59052
59069
  if (!transport) return fetch(input, init2);
59053
59070
  const headers = new Headers(init2?.headers ?? (input instanceof Request ? input.headers : void 0));
@@ -98696,9 +98713,8 @@ async function reportClientRuntimeDecision(profileId, payload, options) {
98696
98713
  if (payload.externalInferenceBindings !== void 0) {
98697
98714
  extras.external_inference_bindings = payload.externalInferenceBindings;
98698
98715
  }
98699
- if (payload.externalAgentInstruction !== void 0) {
98700
- extras.external_agent_instruction = payload.externalAgentInstruction ?? null;
98701
- }
98716
+ if (payload.externalAgentInstruction !== void 0) extras.external_agent_instruction = payload.externalAgentInstruction ?? null;
98717
+ if (payload.unsentOrder) extras.unsent_order = { decision: payload.unsentOrder.decision, units: payload.unsentOrder.units, constraint_reason_code: payload.unsentOrder.constraintReasonCode };
98702
98718
  const body = buildClientRuntimeBody(payload, extras);
98703
98719
  const digestPromise = globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(body)).then((digest2) => Array.from(new Uint8Array(digest2), (byte) => byte.toString(HEX_RADIX).padStart(BYTE_HEX_DIGITS, "0")).join(""));
98704
98720
  const idempotencyKey = options?.idempotencyKey || createIdempotencyKey("runtime-decision");
@@ -98890,7 +98906,8 @@ async function reportClientRuntimeError(profileId, payload, options) {
98890
98906
  execution_reason_code: payload.executionReasonCode ?? null,
98891
98907
  execution_stage: payload.executionStage ?? null,
98892
98908
  dispatch_outcome: payload.dispatchOutcome ?? null,
98893
- provider_failure: payload.providerFailure ?? null
98909
+ provider_failure: payload.providerFailure ?? null,
98910
+ ...payload.externalAgentInstruction ? { external_agent_instruction: payload.externalAgentInstruction } : {}
98894
98911
  }),
98895
98912
  options
98896
98913
  );
@@ -98933,9 +98950,7 @@ async function reportClientRuntimeTradeSync(profileId, payload, options) {
98933
98950
  if (typeof payload.isExecuting === "boolean") {
98934
98951
  extras.is_executing = payload.isExecuting;
98935
98952
  }
98936
- if (payload.externalAgentInstruction !== void 0) {
98937
- extras.external_agent_instruction = payload.externalAgentInstruction ?? null;
98938
- }
98953
+ if (payload.externalAgentInstruction !== void 0) extras.external_agent_instruction = payload.externalAgentInstruction ?? null;
98939
98954
  return postClientRuntime(
98940
98955
  "/runtime/trade-sync",
98941
98956
  profileId,
@@ -104809,10 +104824,10 @@ var init_prompt_number_contract = __esm({
104809
104824
  }
104810
104825
  });
104811
104826
 
104812
- // lib/runtime/server-execution-capacity.ts
104813
- var capacityUnitsUsedForPosition, allocatePlanCapacity;
104814
- var init_server_execution_capacity = __esm({
104815
- "lib/runtime/server-execution-capacity.ts"() {
104827
+ // lib/runtime/execution-capacity.ts
104828
+ var capacityUnitsUsedForPosition, openCapacityRoom, allocatePlanCapacity, withCapacityTrim;
104829
+ var init_execution_capacity = __esm({
104830
+ "lib/runtime/execution-capacity.ts"() {
104816
104831
  "use strict";
104817
104832
  init_define_VTX_CLAUDE_CODE_POLICY();
104818
104833
  init_define_VTX_EXO_POLICY();
@@ -104839,7 +104854,7 @@ var init_server_execution_capacity = __esm({
104839
104854
  }
104840
104855
  return Math.max(0, unitsUsed);
104841
104856
  };
104842
- allocatePlanCapacity = (positions, plans, limits) => {
104857
+ openCapacityRoom = (positions, limits) => {
104843
104858
  let globalUnits = 0;
104844
104859
  const exchangeUsage = /* @__PURE__ */ new Map();
104845
104860
  for (const position of positions) {
@@ -104856,14 +104871,33 @@ var init_server_execution_capacity = __esm({
104856
104871
  const remainingExchangeByDex = new Map(
104857
104872
  [...exchangeUsage].map(([dex, used]) => [dex, exchangeLimit - used])
104858
104873
  );
104874
+ const signedUnits = (symbol2) => {
104875
+ const normalized = normalizeHyperliquidMarketSymbol(symbol2);
104876
+ const position = positions.find((candidate) => normalizeHyperliquidMarketSymbol(candidate.symbol) === normalized);
104877
+ return position ? signedUnitsFromEntryPosition(position.size, position.entry_price, limits.unit_size) : 0;
104878
+ };
104879
+ const remainingExchange = (symbol2) => remainingExchangeByDex.get(getHyperliquidMarketDex(symbol2)) ?? exchangeLimit;
104880
+ return {
104881
+ signedUnits,
104882
+ caps: (symbol2) => ({
104883
+ remaining_global_units: remainingGlobal,
104884
+ remaining_exchange_units: remainingExchange(symbol2),
104885
+ remaining_asset_units: Math.trunc(limits.max_trades_per_asset || 0) - Math.abs(signedUnits(symbol2))
104886
+ }),
104887
+ take: (symbol2, decision, acceptedUnits) => {
104888
+ const currentAbsUnits = Math.abs(signedUnits(symbol2));
104889
+ const target = classifyExecutionIntent(decision, acceptedUnits, signedUnits(symbol2));
104890
+ const added = Math.max(0, Math.abs(target.targetSignedUnits) - currentAbsUnits);
104891
+ remainingGlobal = Math.max(0, remainingGlobal - added);
104892
+ remainingExchangeByDex.set(getHyperliquidMarketDex(symbol2), Math.max(0, remainingExchange(symbol2) - added));
104893
+ }
104894
+ };
104895
+ };
104896
+ allocatePlanCapacity = (positions, plans, limits) => {
104897
+ const room = openCapacityRoom(positions, limits);
104859
104898
  return plans.map((rawPlan) => {
104860
104899
  const symbol2 = normalizeHyperliquidMarketSymbol(rawPlan.symbol);
104861
104900
  const units = Math.trunc(rawPlan.units);
104862
- const dex = getHyperliquidMarketDex(symbol2);
104863
- const remainingExchange = remainingExchangeByDex.get(dex) ?? exchangeLimit;
104864
- const position = positions.find((candidate) => normalizeHyperliquidMarketSymbol(candidate.symbol) === symbol2);
104865
- const signedUnits = position ? signedUnitsFromEntryPosition(position.size, position.entry_price, limits.unit_size) : 0;
104866
- const currentAbsUnits = Math.abs(signedUnits);
104867
104901
  const acceptance = evaluateRuntimeDecisionAcceptance({
104868
104902
  decision: rawPlan.decision,
104869
104903
  units,
@@ -104872,24 +104906,26 @@ var init_server_execution_capacity = __esm({
104872
104906
  kill_switch_active: false,
104873
104907
  // The cycle's prompt allowance was applied with the decision.
104874
104908
  max_trades_per_prompt: units,
104875
- remaining_global_units: remainingGlobal,
104876
- remaining_exchange_units: remainingExchange,
104877
- remaining_asset_units: Math.trunc(limits.max_trades_per_asset || 0) - currentAbsUnits,
104878
- current_symbol_signed_units: signedUnits,
104909
+ ...room.caps(symbol2),
104910
+ current_symbol_signed_units: room.signedUnits(symbol2),
104879
104911
  model_allowed: true,
104880
104912
  provider_allowed: true
104881
104913
  }
104882
104914
  });
104883
104915
  const acceptedUnits = acceptance.accepted ? acceptance.normalized_units : 0;
104884
- if (acceptance.accepted) {
104885
- const target = classifyExecutionIntent(rawPlan.decision, acceptedUnits, signedUnits);
104886
- const globalDelta = Math.max(0, Math.abs(target.targetSignedUnits) - currentAbsUnits);
104887
- remainingGlobal = Math.max(0, remainingGlobal - globalDelta);
104888
- remainingExchangeByDex.set(dex, Math.max(0, remainingExchange - globalDelta));
104889
- }
104916
+ if (acceptance.accepted) room.take(symbol2, rawPlan.decision, acceptedUnits);
104890
104917
  return { symbol: symbol2, accepted: acceptance.accepted, units: acceptedUnits, reason_code: acceptance.reason_code };
104891
104918
  });
104892
104919
  };
104920
+ withCapacityTrim = (result, trim) => {
104921
+ const decisionOrders = result.executionReports.filter((report) => report.status === "executed" && (report.action === "BUY" || report.action === "SELL") && (result.intent !== "flip" || report.execution_metadata?.decision_leg === "entry"));
104922
+ const trimmed = decisionOrders[decisionOrders.length - 1];
104923
+ if (!trimmed) return result;
104924
+ return {
104925
+ ...result,
104926
+ executionReports: result.executionReports.map((report) => report === trimmed ? { ...report, execution_metadata: { ...report.execution_metadata, ...trim } } : report)
104927
+ };
104928
+ };
104893
104929
  }
104894
104930
  });
104895
104931
 
@@ -105480,7 +105516,7 @@ var init_native_position_protection = __esm({
105480
105516
  });
105481
105517
 
105482
105518
  // lib/runtime/native-protection-device.ts
105483
- var NATIVE_PROTECTION_RECORD_VERSION, nativeProtectionStorage, resolveStorage, setNativeProtectionStorage, recordKey, isMember, isRetracement, isLot, isStandbyAdd, readNativeProtectionRecord, versioned, writeNativeProtectionRecord, NO_FILLS, nativeFillsPageFromUserFills, fillsReader, flatReadOf, orderFillTimes, namedOrderId, NativeOrderNotSentError, withDispatchBoundary, attempt, notSentRestores, errorText, actionOf, isOpenInDirection2, coverRows, restingOrderIdAt, definitivelyRefused, TRAILING_LOT_FIRED, TRAILING_LOT_POSITION_ENDED, TRAILING_LOT_OTHER_SIDE, lotFillLeftPosition, lotOfAdd, ORDER_ID_PATTERN, lotFillOrderId, lotPositionSince, ownLotOrderIds, lotRetracement, lotReport, sendTrailingLot, planNativeFillLot, planNativeStandbyAdd, nameNativeStandbyAdd, dropNativeStandbyAdd, dropNativePendingLot, planNativePendingLot, planNativeOpen, recordEntryChildren, observeMembers, UNKNOWN_ORDER_RESPONSE, resolveUnknownOrderIds, plannedPair, resolveStandbyAdds, settleNativeProtectionAfterFill, reconcileNativeProtection;
105519
+ var NATIVE_PROTECTION_RECORD_VERSION, owesMove, owingMove, moveMade, nativeProtectionStorage, resolveStorage, setNativeProtectionStorage, recordKey, isMember, isRetracement, isLot, isStandbyAdd, readNativeProtectionRecord, versioned, writeNativeProtectionRecord, NO_FILLS, nativeFillsPageFromUserFills, fillsReader, flatReadOf, orderFillTimes, namedOrderId, NativeOrderNotSentError, withDispatchBoundary, attempt, notSentRestores, errorText, actionOf, isOpenInDirection2, coverRows, restingOrderIdAt, definitivelyRefused, TRAILING_LOT_FIRED, TRAILING_LOT_POSITION_ENDED, TRAILING_LOT_OTHER_SIDE, lotFillLeftPosition, lotOfAdd, ORDER_ID_PATTERN, lotFillOrderId, lotPositionSince, ownLotOrderIds, lotRetracement, lotReport, sendTrailingLot, planNativeFillLot, planNativeStandbyAdd, nameNativeStandbyAdd, dropNativeStandbyAdd, dropNativePendingLot, planNativePendingLot, planNativeOpen, recordEntryChildren, observeMembers, UNKNOWN_ORDER_RESPONSE, resolveUnknownOrderIds, cancellingThroughVtx, moveMember, plannedPair, resolveStandbyAdds, settleNativeProtectionAfterFill, reconcileNativeProtection;
105484
105520
  var init_native_protection_device = __esm({
105485
105521
  "lib/runtime/native-protection-device.ts"() {
105486
105522
  "use strict";
@@ -105494,6 +105530,20 @@ var init_native_protection_device = __esm({
105494
105530
  init_order_identity();
105495
105531
  init_native_position_protection();
105496
105532
  NATIVE_PROTECTION_RECORD_VERSION = 1;
105533
+ owesMove = (member) => member.pendingMove != null && (member.pendingMove.clientOrderId === member.clientOrderId || member.pendingMove.pendingClientOrderId != null && member.pendingMove.pendingClientOrderId === member.clientOrderId);
105534
+ owingMove = (member, afterMs) => ({
105535
+ ...member,
105536
+ pendingMove: {
105537
+ afterMs: Math.max(owesMove(member) ? member.pendingMove?.afterMs ?? 0 : 0, afterMs),
105538
+ clientOrderId: member.clientOrderId,
105539
+ // A modify journaled before this fill still owes this move once it is named.
105540
+ ...member.pendingModify ? { pendingClientOrderId: member.pendingModify.clientOrderId } : {}
105541
+ }
105542
+ });
105543
+ moveMade = (member) => {
105544
+ const { pendingMove: _made, ...rest } = member;
105545
+ return rest;
105546
+ };
105497
105547
  nativeProtectionStorage = null;
105498
105548
  resolveStorage = () => {
105499
105549
  if (nativeProtectionStorage) return nativeProtectionStorage;
@@ -105511,7 +105561,7 @@ var init_native_protection_device = __esm({
105511
105561
  isMember = (value) => {
105512
105562
  if (!value || typeof value !== "object") return false;
105513
105563
  const member = value;
105514
- return (member.kind === "sl" || member.kind === "tp") && typeof member.clientOrderId === "string" && (member.orderId === null || typeof member.orderId === "number" && Number.isSafeInteger(member.orderId)) && typeof member.trigger === "string" && (member.placedAtMs === null || typeof member.placedAtMs === "number") && typeof member.sentAtMs === "number" && typeof member.replacedOnce === "boolean" && (member.plannedAfterMs === void 0 || typeof member.plannedAfterMs === "number") && (member.pendingModify === void 0 || typeof member.pendingModify === "object" && member.pendingModify !== null && typeof member.pendingModify.clientOrderId === "string" && typeof member.pendingModify.trigger === "string" && typeof member.pendingModify.sentAtMs === "number");
105564
+ return (member.kind === "sl" || member.kind === "tp") && typeof member.clientOrderId === "string" && (member.orderId === null || typeof member.orderId === "number" && Number.isSafeInteger(member.orderId)) && typeof member.trigger === "string" && (member.placedAtMs === null || typeof member.placedAtMs === "number") && typeof member.sentAtMs === "number" && typeof member.replacedOnce === "boolean" && (member.plannedAfterMs === void 0 || typeof member.plannedAfterMs === "number") && (member.pendingMove === void 0 || typeof member.pendingMove === "object" && member.pendingMove !== null && Number.isFinite(member.pendingMove.afterMs) && typeof member.pendingMove.clientOrderId === "string" && (member.pendingMove.pendingClientOrderId === void 0 || typeof member.pendingMove.pendingClientOrderId === "string")) && (member.pendingModify === void 0 || typeof member.pendingModify === "object" && member.pendingModify !== null && typeof member.pendingModify.clientOrderId === "string" && typeof member.pendingModify.trigger === "string" && typeof member.pendingModify.sentAtMs === "number");
105515
105565
  };
105516
105566
  isRetracement = (value) => {
105517
105567
  if (!value || typeof value !== "object") return false;
@@ -105868,11 +105918,11 @@ var init_native_protection_device = __esm({
105868
105918
  recordEntryChildren = (record6, entryResponse) => ({
105869
105919
  ...record6,
105870
105920
  phase: "active",
105871
- members: record6.members.map((member, index) => ({
105921
+ members: record6.members.map((member, index) => owingMove({
105872
105922
  ...member,
105873
105923
  // The entry is member 0 of the action; its children follow in order.
105874
105924
  orderId: member.orderId ?? restingOrderIdAt(entryResponse, index + 1)
105875
- }))
105925
+ }, 0))
105876
105926
  });
105877
105927
  observeMembers = (record6, page) => record6.members.map((member) => ({
105878
105928
  member,
@@ -105917,6 +105967,82 @@ var init_native_protection_device = __esm({
105917
105967
  }
105918
105968
  return { ...record6, members };
105919
105969
  };
105970
+ cancellingThroughVtx = async (io, orderId) => {
105971
+ if (!io.userCancelledOrder) return false;
105972
+ try {
105973
+ return await io.userCancelledOrder(orderId);
105974
+ } catch (error48) {
105975
+ if (io.endsPass?.(error48)) throw error48;
105976
+ return true;
105977
+ }
105978
+ };
105979
+ moveMember = async (args) => {
105980
+ const { io, symbol: symbol2, member, orderId, trigger, clientOrderId } = args;
105981
+ const action = actionOf(member.kind);
105982
+ const sentAtMs = io.nowMs();
105983
+ const journaled = { ...member, orderId, pendingModify: { clientOrderId, trigger, sentAtMs } };
105984
+ if (!args.journal(journaled)) {
105985
+ return {
105986
+ member,
105987
+ landed: false,
105988
+ report: {
105989
+ order_id: String(orderId),
105990
+ symbol: symbol2,
105991
+ action,
105992
+ status: "failed",
105993
+ execution_metadata: { reason_code: "protective_lifecycle_persistence_failed", trigger_price: trigger }
105994
+ }
105995
+ };
105996
+ }
105997
+ const outcome = await notSentRestores(
105998
+ () => attempt(io, () => io.modifyPositionOrder({
105999
+ orderId,
106000
+ kind: member.kind,
106001
+ triggerPrice: Number(trigger),
106002
+ clientOrderId
106003
+ })),
106004
+ () => args.journal(member)
106005
+ );
106006
+ if (!outcome.ok && outcome.refused) {
106007
+ if (outcome.error instanceof NativeOrderNotSentError) args.journal(member);
106008
+ return {
106009
+ member: { ...member, orderId },
106010
+ landed: false,
106011
+ report: {
106012
+ order_id: String(orderId),
106013
+ symbol: symbol2,
106014
+ action,
106015
+ status: "failed",
106016
+ execution_metadata: {
106017
+ reason_code: outcome.error instanceof NativeOrderNotSentError ? "protective_modify_not_sent" : "protective_modify_rejected",
106018
+ trigger_price: trigger,
106019
+ error: errorText(outcome.error)
106020
+ }
106021
+ }
106022
+ };
106023
+ }
106024
+ const newOrderId = outcome.ok ? restingOrderIdAt(outcome.response, 0) : null;
106025
+ const { pendingModify: _applied, pendingMove: _moved, ...rest } = journaled;
106026
+ return {
106027
+ // Otherwise the journal stays: reconciliation names the new order or
106028
+ // proves it never landed.
106029
+ member: newOrderId != null ? { ...rest, clientOrderId, orderId: newOrderId, trigger, placedAtMs: null, sentAtMs } : journaled,
106030
+ landed: newOrderId != null,
106031
+ report: {
106032
+ order_id: String(newOrderId ?? orderId),
106033
+ symbol: symbol2,
106034
+ action,
106035
+ status: newOrderId != null ? "executed" : "failed",
106036
+ execution_metadata: {
106037
+ reason_code: newOrderId != null ? "protective_native_moved_to_position_entry" : "protective_modify_outcome_unknown",
106038
+ trigger_price: trigger,
106039
+ position_tpsl: true,
106040
+ protected_size: args.protectedSize,
106041
+ ...newOrderId != null ? { replaced_order_id: String(orderId) } : {}
106042
+ }
106043
+ }
106044
+ };
106045
+ };
105920
106046
  plannedPair = (settings, afterMs, io) => ["sl", "tp"].filter((kind) => (kind === "sl" ? settings.stopLoss : settings.takeProfit) != null).map((kind) => ({
105921
106047
  kind,
105922
106048
  clientOrderId: clientOrderIdForMutation(io.newMutationId()),
@@ -106032,6 +106158,13 @@ var init_native_protection_device = __esm({
106032
106158
  const settlingAdds = (record6.standby ?? []).length > 0;
106033
106159
  const boundary = await resolveStandbyAdds({ record: record6, settings: input.settings, io, fills, position, page });
106034
106160
  record6 = boundary.record;
106161
+ if (record6.phase === "entry_pending" || boundary.addFillMs != null) {
106162
+ const afterMs = boundary.addFillMs ?? 0;
106163
+ record6 = {
106164
+ ...record6,
106165
+ members: record6.members.map((member) => member.retiredReason || member.userCancelledOrderId != null || member.plannedAfterMs != null ? member : owingMove(member, afterMs))
106166
+ };
106167
+ }
106035
106168
  if (boundary.undecided) {
106036
106169
  return { record: record6, reports };
106037
106170
  }
@@ -106039,6 +106172,29 @@ var init_native_protection_device = __esm({
106039
106172
  if (record6.positionOrderId == null && boundary.addFillMs == null && !settlingAdds && ORDER_ID_PATTERN.test(entryOrderId)) {
106040
106173
  record6 = { ...record6, positionOrderId: entryOrderId };
106041
106174
  }
106175
+ const observations = observeMembers(record6, page);
106176
+ const restingTrigger = (kind) => {
106177
+ const observed = observations.find((entry) => entry.member.kind === kind);
106178
+ return observed?.row?.trigger_px != null ? String(observed.row.trigger_px) : null;
106179
+ };
106180
+ let eventMs = Math.max(
106181
+ 0,
106182
+ ...observations.map((entry) => entry.row?.timestamp ?? entry.member.placedAtMs ?? 0),
106183
+ // An add's own fill, the fill each member's move answers, and the fill a
106184
+ // planned pair answers: Hyperliquid's times.
106185
+ boundary.addFillMs ?? 0,
106186
+ ...record6.members.map((member) => Math.max(owesMove(member) ? member.pendingMove?.afterMs ?? 0 : 0, member.plannedAfterMs ?? 0))
106187
+ );
106188
+ if (eventMs <= 0 && input.entryOrderId) {
106189
+ const entryStatus = await io.readOrderStatus(input.entryOrderId);
106190
+ eventMs = entryStatus.statusTimestampMs ?? 0;
106191
+ }
106192
+ const gate = nativePlacementGate({
106193
+ eventMs,
106194
+ position: position.size,
106195
+ positionStateMs: position.stateTimeMs ?? Number.NEGATIVE_INFINITY,
106196
+ isLong: record6.isLong
106197
+ });
106042
106198
  if (!isOpenInDirection2(position.size, record6.isLong)) {
106043
106199
  reports.push({
106044
106200
  order_id: input.entryOrderId,
@@ -106050,13 +106206,15 @@ var init_native_protection_device = __esm({
106050
106206
  live_position_size: position.size
106051
106207
  }
106052
106208
  });
106053
- return { record: { ...record6, phase: "active" }, reports };
106209
+ return {
106210
+ record: {
106211
+ ...record6,
106212
+ phase: "active",
106213
+ ...gate === "not_required" ? { members: record6.members.map(moveMade) } : {}
106214
+ },
106215
+ reports
106216
+ };
106054
106217
  }
106055
- const observations = observeMembers(record6, page);
106056
- const restingTrigger = (kind) => {
106057
- const observed = observations.find((entry) => entry.member.kind === kind);
106058
- return observed?.row?.trigger_px != null ? String(observed.row.trigger_px) : null;
106059
- };
106060
106218
  if (position.entryPrice == null) {
106061
106219
  reports.push({
106062
106220
  order_id: input.entryOrderId,
@@ -106075,89 +106233,33 @@ var init_native_protection_device = __esm({
106075
106233
  fillSize: input.fillSize,
106076
106234
  resting: { sl: restingTrigger("sl"), tp: restingTrigger("tp") }
106077
106235
  });
106078
- let eventMs = Math.max(
106079
- 0,
106080
- ...observations.map((entry) => entry.row?.timestamp ?? entry.member.placedAtMs ?? 0),
106081
- // An add's own fill, and the fill a planned pair answers: Hyperliquid's times.
106082
- boundary.addFillMs ?? 0,
106083
- ...record6.members.map((member) => member.plannedAfterMs ?? 0)
106084
- );
106085
- if (eventMs <= 0 && input.entryOrderId) {
106086
- const entryStatus = await io.readOrderStatus(input.entryOrderId);
106087
- eventMs = entryStatus.statusTimestampMs ?? 0;
106088
- }
106089
- const gate = nativePlacementGate({
106090
- eventMs,
106091
- position: position.size,
106092
- positionStateMs: position.stateTimeMs ?? Number.NEGATIVE_INFINITY,
106093
- isLong: record6.isLong
106094
- });
106095
106236
  const members = [...record6.members];
106096
106237
  for (const step of actions) {
106097
106238
  if (step.action === "place_trailing") continue;
106098
106239
  const index = members.findIndex((member) => member.kind === step.kind);
106099
106240
  const existing = index >= 0 ? members[index] : null;
106100
106241
  if (existing?.userCancelledOrderId != null || existing?.retiredReason) continue;
106242
+ if (existing?.pendingModify) continue;
106101
106243
  const clientOrderId = clientOrderIdForMutation(io.newMutationId());
106102
106244
  if (step.action === "modify") {
106103
106245
  const row = observations.find((entry) => entry.member.kind === step.kind)?.row;
106104
106246
  if (!row) continue;
106105
- const sentAtMs2 = io.nowMs();
106106
- members[index] = {
106107
- ...members[index],
106108
- orderId: row.oid,
106109
- pendingModify: { clientOrderId, trigger: step.trigger, sentAtMs: sentAtMs2 }
106110
- };
106111
- if (!io.persist({ ...record6, phase: "active", members })) {
106112
- members[index] = existing;
106113
- reports.push({
106114
- order_id: String(row.oid),
106115
- symbol: symbol2,
106116
- action: actionOf(step.kind),
106117
- status: "failed",
106118
- execution_metadata: { reason_code: "protective_lifecycle_persistence_failed", trigger_price: step.trigger }
106119
- });
106120
- continue;
106121
- }
106122
- const outcome2 = await attempt(io, () => io.modifyPositionOrder({
106123
- orderId: row.oid,
106124
- kind: step.kind,
106125
- triggerPrice: Number(step.trigger),
106126
- clientOrderId
106127
- }));
106128
- if (!outcome2.ok && outcome2.refused) {
106129
- members[index] = { ...existing, orderId: row.oid };
106130
- reports.push({
106131
- order_id: String(row.oid),
106132
- symbol: symbol2,
106133
- action: actionOf(step.kind),
106134
- status: "failed",
106135
- execution_metadata: {
106136
- reason_code: outcome2.error instanceof NativeOrderNotSentError ? "protective_modify_not_sent" : "protective_modify_rejected",
106137
- trigger_price: step.trigger,
106138
- error: errorText(outcome2.error)
106139
- }
106140
- });
106141
- continue;
106142
- }
106143
- const newOrderId = outcome2.ok ? restingOrderIdAt(outcome2.response, 0) : null;
106144
- if (newOrderId != null) {
106145
- const { pendingModify: _applied, ...rest } = members[index];
106146
- members[index] = { ...rest, clientOrderId, orderId: newOrderId, trigger: step.trigger, placedAtMs: null, sentAtMs: sentAtMs2 };
106147
- }
106148
- reports.push({
106149
- order_id: String(newOrderId ?? row.oid),
106247
+ if (await cancellingThroughVtx(io, row.oid)) continue;
106248
+ const moved = await moveMember({
106249
+ io,
106150
106250
  symbol: symbol2,
106151
- action: actionOf(step.kind),
106152
- status: newOrderId != null ? "executed" : "failed",
106153
- execution_metadata: {
106154
- reason_code: newOrderId != null ? "protective_native_moved_to_position_entry" : "protective_modify_outcome_unknown",
106155
- trigger_price: step.trigger,
106156
- position_tpsl: true,
106157
- protected_size: Math.abs(position.size),
106158
- ...newOrderId != null ? { replaced_order_id: String(row.oid) } : {}
106251
+ member: members[index],
106252
+ orderId: row.oid,
106253
+ trigger: step.trigger,
106254
+ clientOrderId,
106255
+ protectedSize: Math.abs(position.size),
106256
+ journal: (member) => {
106257
+ members[index] = member;
106258
+ return io.persist({ ...record6, phase: "active", members });
106159
106259
  }
106160
106260
  });
106261
+ members[index] = moved.member;
106262
+ reports.push(moved.report);
106161
106263
  continue;
106162
106264
  }
106163
106265
  if (existing != null && existing.orderId == null && existing.plannedAfterMs == null && !unknownClientOrderIds.has(existing.clientOrderId)) {
@@ -106220,7 +106322,10 @@ var init_native_protection_device = __esm({
106220
106322
  () => io.persist({ ...record6, phase: "active", members: before })
106221
106323
  );
106222
106324
  if (!outcome.ok && outcome.refused) {
106223
- if (outcome.error instanceof NativeOrderNotSentError) members.splice(0, members.length, ...before);
106325
+ if (outcome.error instanceof NativeOrderNotSentError) {
106326
+ members.splice(0, members.length, ...before);
106327
+ io.persist({ ...record6, phase: "active", members: before });
106328
+ }
106224
106329
  reports.push({
106225
106330
  order_id: null,
106226
106331
  symbol: symbol2,
@@ -106321,7 +106426,12 @@ var init_native_protection_device = __esm({
106321
106426
  }
106322
106427
  });
106323
106428
  }
106324
- record6 = { ...record6, phase: "active", members, ...lots.length > 0 ? { lots } : {} };
106429
+ const movingKinds = new Set(actions.flatMap((step) => step.action === "modify" ? [step.kind] : []));
106430
+ const settledMembers = members.map((member) => {
106431
+ if (member.pendingMove && !owesMove(member)) return moveMade(member);
106432
+ return gate === "place" && member.pendingMove && !member.pendingModify && !movingKinds.has(member.kind) && observations.some((entry) => entry.row != null && entry.member.orderId === member.orderId) ? moveMade(member) : member;
106433
+ });
106434
+ record6 = { ...record6, phase: "active", members: settledMembers, ...lots.length > 0 ? { lots } : {} };
106325
106435
  return { record: record6, reports };
106326
106436
  };
106327
106437
  reconcileNativeProtection = async (input) => {
@@ -106375,6 +106485,24 @@ var init_native_protection_device = __esm({
106375
106485
  }) : null;
106376
106486
  };
106377
106487
  const kindEnabled = (member) => (member.kind === "sl" ? input.settings.stopLoss : input.settings.takeProfit) != null;
106488
+ const movable = positionOpen && !undecidedAdds && position.entryPrice != null;
106489
+ const moveTargets = /* @__PURE__ */ new Map();
106490
+ if (movable && position.entryPrice != null && record6.members.some(owesMove)) {
106491
+ const restingTrigger = (kind) => {
106492
+ const observed = observations.find((entry) => entry.member.kind === kind && entry.row != null && !entry.member.retiredReason && entry.member.userCancelledOrderId == null);
106493
+ return observed?.row?.trigger_px != null ? String(observed.row.trigger_px) : null;
106494
+ };
106495
+ for (const step of nativeAfterFillActions({
106496
+ settings: { ...input.settings, stopLoss: input.settings.stopLoss && { ...input.settings.stopLoss, trailing: false } },
106497
+ isLong: record6.isLong,
106498
+ sizeDecimals: input.sizeDecimals,
106499
+ position: { size: position.size, entryPrice: position.entryPrice },
106500
+ fillSize: "0",
106501
+ resting: { sl: restingTrigger("sl"), tp: restingTrigger("tp") }
106502
+ })) {
106503
+ if (step.action === "modify") moveTargets.set(step.kind, step.trigger);
106504
+ }
106505
+ }
106378
106506
  const placeMember = async (args) => {
106379
106507
  const gate = nativePlacementGate({
106380
106508
  eventMs: args.eventMs,
@@ -106513,6 +106641,47 @@ var init_native_protection_device = __esm({
106513
106641
  }
106514
106642
  continue;
106515
106643
  }
106644
+ if (member.pendingMove && !owesMove(member)) {
106645
+ anyResting = true;
106646
+ members.push(moveMade(member));
106647
+ continue;
106648
+ }
106649
+ if (member.pendingMove && movable && !member.retiredReason && member.userCancelledOrderId == null && !member.pendingModify && nativePlacementGate({
106650
+ eventMs: Math.max(member.pendingMove.afterMs, member.placedAtMs ?? 0),
106651
+ position: position.size,
106652
+ positionStateMs: stateMs,
106653
+ isLong: record6.isLong
106654
+ }) === "place") {
106655
+ const target = moveTargets.get(member.kind);
106656
+ if (target === void 0) {
106657
+ anyResting = true;
106658
+ members.push(moveMade(member));
106659
+ continue;
106660
+ }
106661
+ if (!await cancellingThroughVtx(io, row.oid)) {
106662
+ const moved = await moveMember({
106663
+ io,
106664
+ symbol: symbol2,
106665
+ member,
106666
+ orderId: row.oid,
106667
+ trigger: target,
106668
+ clientOrderId: clientOrderIdForMutation(io.newMutationId()),
106669
+ protectedSize: Math.abs(position.size),
106670
+ journal: (next) => io.persist({
106671
+ ...record6,
106672
+ members: [
106673
+ ...members,
106674
+ next,
106675
+ ...observations.slice(observationIndex + 1).map((entry) => entry.member)
106676
+ ]
106677
+ })
106678
+ });
106679
+ reports.push(moved.report);
106680
+ anyResting = true;
106681
+ members.push(moved.member);
106682
+ continue;
106683
+ }
106684
+ }
106516
106685
  anyResting = true;
106517
106686
  members.push(member);
106518
106687
  continue;
@@ -106526,9 +106695,20 @@ var init_native_protection_device = __esm({
106526
106695
  members.push(member);
106527
106696
  continue;
106528
106697
  }
106529
- if (member.orderId != null && io.userCancelledOrder && await io.userCancelledOrder(member.orderId)) {
106530
- members.push({ ...member, userCancelledOrderId: member.orderId });
106531
- continue;
106698
+ if (member.orderId != null && io.userCancelledOrder) {
106699
+ let cancelledByUser;
106700
+ try {
106701
+ cancelledByUser = await io.userCancelledOrder(member.orderId);
106702
+ } catch (error48) {
106703
+ if (io.endsPass?.(error48)) throw error48;
106704
+ anyResting = true;
106705
+ members.push(member);
106706
+ continue;
106707
+ }
106708
+ if (cancelledByUser) {
106709
+ members.push({ ...member, userCancelledOrderId: member.orderId });
106710
+ continue;
106711
+ }
106532
106712
  }
106533
106713
  if (member.plannedAfterMs != null) {
106534
106714
  if (!kindEnabled(member)) continue;
@@ -106932,7 +107112,7 @@ var init_native_protection_device = __esm({
106932
107112
  });
106933
107113
 
106934
107114
  // lib/runtime/runtime-execution.ts
106935
- var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, 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, replaceProtectiveLeg, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, pendingProtectiveReplacementReport, isConfiguredProtectionRequested, protectiveAction, executedProtectiveReport, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, observedProtectiveGroupingMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, attachmentMemberNeverLanded, storedClientProtectiveCover, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, liveProtectiveOrderShape, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, nativeSettingsOf, nativePassEnded, nativeProtectionIo, nativeStorageReport, readNativeRecord, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep2, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, 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, withCapacityTrim, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, maintainClientRuntimeTrailingStops, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked;
107115
+ var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, 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, replaceProtectiveLeg, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, pendingProtectiveReplacementReport, isConfiguredProtectionRequested, protectiveAction, executedProtectiveReport, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, observedProtectiveGroupingMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, attachmentMemberNeverLanded, storedClientProtectiveCover, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, liveProtectiveOrderShape, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, nativeSettingsOf, nativePassEnded, nativeProtectionIo, nativeStorageReport, readNativeRecord, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep2, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, 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, maintainClientRuntimeTrailingStops, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked;
106936
107116
  var init_runtime_execution = __esm({
106937
107117
  "lib/runtime/runtime-execution.ts"() {
106938
107118
  "use strict";
@@ -106948,7 +107128,7 @@ var init_runtime_execution = __esm({
106948
107128
  init_api2();
106949
107129
  init_client_exchange_mutations();
106950
107130
  init_hyperliquid_order_status();
106951
- init_server_execution_capacity();
107131
+ init_execution_capacity();
106952
107132
  init_protective_actions();
106953
107133
  init_browser_trading();
106954
107134
  init_execution_guard_contract();
@@ -112690,15 +112870,6 @@ var init_runtime_execution = __esm({
112690
112870
  ...input.executionContext.decisionSnapshotId ? { decision_snapshot_id: input.executionContext.decisionSnapshotId } : {}
112691
112871
  }
112692
112872
  });
112693
- withCapacityTrim = (result, trim) => {
112694
- const decisionOrders = result.executionReports.filter((report) => report.status === "executed" && (report.action === "BUY" || report.action === "SELL") && (result.intent !== "flip" || report.execution_metadata?.decision_leg === "entry"));
112695
- const trimmed = decisionOrders[decisionOrders.length - 1];
112696
- if (!trimmed) return result;
112697
- return {
112698
- ...result,
112699
- executionReports: result.executionReports.map((report) => report === trimmed ? { ...report, execution_metadata: { ...report.execution_metadata, ...trim } } : report)
112700
- };
112701
- };
112702
112873
  SERVER_AUDIT_RECORDED_ELSEWHERE = /* @__PURE__ */ new Set([
112703
112874
  "suppressed_duplicate_decision",
112704
112875
  "same_intent_cooldown",
@@ -115342,6 +115513,7 @@ async function invokeProfileModelCascade(input) {
115342
115513
  if (Array.isArray(observed)) attempts = observed;
115343
115514
  if (error48 instanceof Error) error48.runtimeInvocationAttempts = attempts;
115344
115515
  const ownAttempts = attempts.filter((attempt2) => !priorIds.has(attempt2.client_invocation_id));
115516
+ if (error48 instanceof Error) Object.assign(error48, { runtimeOwnInvocationAttempts: ownAttempts });
115345
115517
  if (error48 instanceof Error) failedModels.push(fallbackAttemptFor(entry, error48, ownAttempts));
115346
115518
  if (index === entries.length - 1 || !canAdvanceProfileModel(error48, entry.kind === "external_agent" || entry.source === "external_agent", input.signal, ownAttempts)) surface(error48);
115347
115519
  lastFailure = error48;
@@ -115386,7 +115558,8 @@ var init_profile_model_cascade = __esm({
115386
115558
  // lib/runtime/model-call-failure.ts
115387
115559
  function describeModelCallFailure(error48, options = {}) {
115388
115560
  const attempts = failureAttempts(error48);
115389
- const last = attempts.at(-1);
115561
+ const ownAttempts = ownFailureAttempts(error48, options.ownAttempts);
115562
+ const last = (ownAttempts ?? attempts).at(-1);
115390
115563
  const message = getSanitizedRuntimeErrorMessage(error48) || (error48 instanceof Error ? error48.message : String(error48 ?? "")) || "The model call failed.";
115391
115564
  const status = typeof last?.provider_status_code === "number" ? last.provider_status_code : error48?.runtimeProviderStatusCode;
115392
115565
  const statusCode = typeof status === "number" && Number.isInteger(status) ? status : null;
@@ -115405,16 +115578,17 @@ function describeModelCallFailure(error48, options = {}) {
115405
115578
  detail: typeof diagnostic === "string" && diagnostic ? diagnostic : message,
115406
115579
  class: failureClass,
115407
115580
  // The provider client marks each failed attempt it would retry (a rate
115408
- // limit, a server error, a 408, a timeout, a dropped connection).
115409
- transient: !cancelled && last?.status === "failed" && last.retryable === true,
115410
- model_fallback_safe: !cancelled && canAdvanceProfileModel(error48, Boolean(options.external), options.signal),
115581
+ // limit, a server error, a 408, a timeout, a dropped connection). An empty
115582
+ // reply it has already asked again for, up to its own limit.
115583
+ transient: !cancelled && !emptyReply && last?.status === "failed" && last.retryable === true,
115584
+ model_fallback_safe: !cancelled && canAdvanceProfileModel(error48, Boolean(options.external), options.signal, ownAttempts),
115411
115585
  outcome_unknown: attempts.some((attempt2) => attempt2.status !== "succeeded" && attempt2.provider_status_code == null && !isNeverSentInvocation(attempt2)) || /outcome.?unknown|dispatch.?unknown/i.test(message),
115412
115586
  partial_output: partialOutput,
115413
115587
  retry_after_seconds: retryHintSeconds(last, error48),
115414
115588
  status_code: statusCode
115415
115589
  };
115416
115590
  }
115417
- var FAILURE_CODE_CLASSES, failureAttempts, retryHintSeconds;
115591
+ var FAILURE_CODE_CLASSES, failureAttempts, ownFailureAttempts, failingModelAttempts, retryHintSeconds;
115418
115592
  var init_model_call_failure = __esm({
115419
115593
  "lib/runtime/model-call-failure.ts"() {
115420
115594
  "use strict";
@@ -115444,6 +115618,12 @@ var init_model_call_failure = __esm({
115444
115618
  const attempts = error48?.runtimeInvocationAttempts;
115445
115619
  return Array.isArray(attempts) ? attempts : [];
115446
115620
  };
115621
+ ownFailureAttempts = (error48, ownAttempts) => {
115622
+ if (ownAttempts) return ownAttempts;
115623
+ const attached = error48?.runtimeOwnInvocationAttempts;
115624
+ return Array.isArray(attached) ? attached : void 0;
115625
+ };
115626
+ failingModelAttempts = (error48) => ownFailureAttempts(error48) ?? failureAttempts(error48);
115447
115627
  retryHintSeconds = (attempt2, error48) => {
115448
115628
  const diagnostics = attempt2?.provider_diagnostics ?? {};
115449
115629
  const hints = [
@@ -115474,7 +115654,8 @@ function serverModelCallFailure(reason, evidence) {
115474
115654
  }
115475
115655
  if (!terminal || terminal.status !== "failed") return null;
115476
115656
  const failure2 = describeModelCallFailure(reason);
115477
- const transient = failure2.class !== "out_of_credit" && (failure2.class === "rate_limit" || failure2.class === "provider_unavailable" || terminal.provider_status_code === HTTP_STATUS.TOO_MANY_REQUESTS || googleEgressUnreachable(terminal));
115657
+ const ownTerminal = failingModelAttempts(reason).at(-1);
115658
+ const transient = failure2.class !== "out_of_credit" && (failure2.class === "rate_limit" || failure2.class === "provider_unavailable" || failure2.status_code === HTTP_STATUS.TOO_MANY_REQUESTS || ownTerminal !== void 0 && googleEgressUnreachable(ownTerminal));
115478
115659
  return {
115479
115660
  report: { class: failure2.class, transient },
115480
115661
  overloaded: false,
@@ -115549,7 +115730,7 @@ var init_browser_observability = __esm({
115549
115730
  init_define_VTX_GROK_POLICY();
115550
115731
  init_define_VTX_PI_MODEL_POLICY();
115551
115732
  init_runtime_policy_generated2();
115552
- CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "6284a7b4880c39e52d48be2d18084f99f2d8b46f".trim() && "6284a7b4880c39e52d48be2d18084f99f2d8b46f".trim() !== "unstamped" ? "6284a7b4880c39e52d48be2d18084f99f2d8b46f".trim() : null;
115733
+ CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "bca614db2bfe3a23799f3a565b8b0f5338f01287".trim() && "bca614db2bfe3a23799f3a565b8b0f5338f01287".trim() !== "unstamped" ? "bca614db2bfe3a23799f3a565b8b0f5338f01287".trim() : null;
115553
115734
  listenersInstalled = false;
115554
115735
  state = {
115555
115736
  loadedAtMs: Date.now(),
@@ -117850,6 +118031,10 @@ var init_copy_trading_evidence = __esm({
117850
118031
  });
117851
118032
 
117852
118033
  // lib/runtime/copy-trading-execution.ts
118034
+ function copyOrderReduceOnly(input) {
118035
+ const { desiredPosition, actualPosition, size } = input;
118036
+ return Math.abs(desiredPosition) <= COPY_TRADING_SIZE_EPSILON || actualPosition * (desiredPosition - actualPosition) < 0 && Math.abs(size) <= Math.abs(actualPosition) + COPY_TRADING_SIZE_EPSILON;
118037
+ }
117853
118038
  function capCopiedToActual(copied, actual) {
117854
118039
  if (Math.abs(copied) <= COPY_TRADING_SIZE_EPSILON) return 0;
117855
118040
  if (copied * actual <= 0) return 0;
@@ -117884,7 +118069,7 @@ function copiedTargetNow(reconciliation, recordedTarget, actualPosition) {
117884
118069
  );
117885
118070
  return { copiedNow, targetNow, kept: copiedTargetBesideOwnPosition(targetNow, copiedNow, actualPosition) };
117886
118071
  }
117887
- var _extractOrderResponseStates, executeClientCopyTradingIntent, _copyCancelOrderId, executeClientCopyTradingOrderAction;
118072
+ var _extractOrderResponseStates, CLIENT_COPY_TRADING_EXECUTION, executeClientCopyTradingIntent, executeCopyTradingIntent, _copyCancelOrderId, executeClientCopyTradingOrderAction, executeCopyTradingOrderAction;
117888
118073
  var init_copy_trading_execution = __esm({
117889
118074
  "lib/runtime/copy-trading-execution.ts"() {
117890
118075
  "use strict";
@@ -117928,21 +118113,34 @@ var init_copy_trading_execution = __esm({
117928
118113
  });
117929
118114
  return parsed.every((item) => item != null) ? parsed : null;
117930
118115
  };
117931
- executeClientCopyTradingIntent = async (input) => {
118116
+ CLIENT_COPY_TRADING_EXECUTION = {
118117
+ runtimeMode: "client",
118118
+ pendingStatus: "pending_client",
118119
+ marketOrder: (input) => executeClientMarketOrder(input),
118120
+ limitOrder: (input) => executeClientLimitOrder(input),
118121
+ triggerOrder: (input) => executeClientTriggerOrder(input),
118122
+ orderBatch: (input) => executeClientOrderBatch(input),
118123
+ modifyOrder: (input) => executeClientModifyOrder(input),
118124
+ cancelOrder: (input) => executeClientCancelOrder(input),
118125
+ sizePrecision: (input) => quantizeHyperliquidOrderSize(input),
118126
+ orderStatusEvidence: (context, orderId) => readCopyOrderStatusEvidence(context, orderId)
118127
+ };
118128
+ executeClientCopyTradingIntent = (input) => executeCopyTradingIntent(input, CLIENT_COPY_TRADING_EXECUTION);
118129
+ executeCopyTradingIntent = async (input, execution) => {
117932
118130
  throwIfAborted2(input.signal);
117933
118131
  const intent = input.intent;
117934
- if (intent.status !== "pending_client") {
118132
+ if (intent.status !== execution.pendingStatus) {
117935
118133
  return {
117936
118134
  status: "skipped",
117937
118135
  orderId: null,
117938
- message: `Copy Trading intent is not pending_client: ${intent.status}`
118136
+ message: `Copy Trading intent is not ${execution.pendingStatus}: ${intent.status}`
117939
118137
  };
117940
118138
  }
117941
- if (intent.runtime_mode !== "client") {
118139
+ if (intent.runtime_mode !== execution.runtimeMode) {
117942
118140
  return {
117943
118141
  status: "skipped",
117944
118142
  orderId: null,
117945
- message: `Copy Trading intent runtime mode is not client: ${intent.runtime_mode}`
118143
+ message: `Copy Trading intent runtime mode is not ${execution.runtimeMode}: ${intent.runtime_mode}`
117946
118144
  };
117947
118145
  }
117948
118146
  let destinationSide = intent.destination_side;
@@ -117986,7 +118184,7 @@ var init_copy_trading_execution = __esm({
117986
118184
  };
117987
118185
  }
117988
118186
  try {
117989
- let sizePrecision = await quantizeHyperliquidOrderSize({
118187
+ let sizePrecision = await execution.sizePrecision({
117990
118188
  publicRequestPriority: reduceOnly ? "trading_reduce" : "trading_execute",
117991
118189
  symbol: intent.symbol,
117992
118190
  size: destinationSize,
@@ -118055,7 +118253,7 @@ var init_copy_trading_execution = __esm({
118055
118253
  destinationSide = liveDelta > 0 ? "buy" : "sell";
118056
118254
  destinationSize = Math.abs(liveDelta);
118057
118255
  exactFullCloseBeforeQuantization = Math.abs(desiredPosition) <= tolerance && Math.abs(actualPosition) > tolerance;
118058
- reduceOnly = Math.abs(desiredPosition) <= tolerance || (actualPosition > 0 && liveDelta < 0 && desiredPosition >= 0 || actualPosition < 0 && liveDelta > 0 && desiredPosition <= 0);
118256
+ reduceOnly = copyOrderReduceOnly({ desiredPosition, actualPosition, size: destinationSize });
118059
118257
  maxOrderNotional = copyOrderNotionalCap(
118060
118258
  followerOrderNotionalCap,
118061
118259
  platformOrderNotionalCap,
@@ -118160,8 +118358,8 @@ var init_copy_trading_execution = __esm({
118160
118358
  }
118161
118359
  };
118162
118360
  }
118163
- if (desiredPosition != null && Math.abs(desiredPosition) <= COPY_TRADING_SIZE_EPSILON) {
118164
- reduceOnly = true;
118361
+ if (desiredPosition != null && Number.isFinite(desiredPosition) && actualPosition != null && Number.isFinite(actualPosition)) {
118362
+ reduceOnly = copyOrderReduceOnly({ desiredPosition, actualPosition, size: destinationSize });
118165
118363
  }
118166
118364
  const stableIdentity = _stableMutationIdentity(
118167
118365
  intent.sanitized_metadata?.client_mutation_id,
@@ -118175,7 +118373,7 @@ var init_copy_trading_execution = __esm({
118175
118373
  actual_destination_position: actualPosition
118176
118374
  } : {}
118177
118375
  };
118178
- const response = await executeClientMarketOrder({
118376
+ const response = await execution.marketOrder({
118179
118377
  profileId: String(input.profileId),
118180
118378
  runtimeSessionId: input.runtimeSessionId,
118181
118379
  runtimeLeaseToken: input.runtimeLeaseToken,
@@ -118250,16 +118448,17 @@ var init_copy_trading_execution = __esm({
118250
118448
  const cloid = String(destinationOrderId || "").trim().toLowerCase();
118251
118449
  return /^0x[0-9a-f]{32}$/.test(cloid) ? cloid : null;
118252
118450
  };
118253
- executeClientCopyTradingOrderAction = async (input) => {
118451
+ executeClientCopyTradingOrderAction = (input) => executeCopyTradingOrderAction(input, CLIENT_COPY_TRADING_EXECUTION);
118452
+ executeCopyTradingOrderAction = async (input, execution) => {
118254
118453
  throwIfAborted2(input.signal);
118255
118454
  const action = input.action;
118256
- if (action.status !== "pending_client") {
118455
+ if (action.status !== execution.pendingStatus) {
118257
118456
  return {
118258
118457
  status: "skipped",
118259
118458
  destinationOrderId: null,
118260
118459
  destinationOrderState: null,
118261
118460
  orderMemberResults: null,
118262
- message: `Copy Trading order action is not pending_client: ${action.status}`
118461
+ message: `Copy Trading order action is not ${execution.pendingStatus}: ${action.status}`
118263
118462
  };
118264
118463
  }
118265
118464
  const stableIdentity = _stableMutationIdentity(
@@ -118282,7 +118481,7 @@ var init_copy_trading_execution = __esm({
118282
118481
  };
118283
118482
  const cancelledOrderStatusEvidence = async (orderId) => {
118284
118483
  if (orderId == null) return {};
118285
- const evidence = await readCopyOrderStatusEvidence(
118484
+ const evidence = await execution.orderStatusEvidence(
118286
118485
  { config: input.config ?? null, signal: input.signal, walletAddress: input.walletAddress },
118287
118486
  orderId
118288
118487
  );
@@ -118294,7 +118493,7 @@ var init_copy_trading_execution = __esm({
118294
118493
  if (orderId == null) {
118295
118494
  throw new RuntimeReasonError("Copy Trading cancel action is missing a valid destination order id.", "internal_data_error");
118296
118495
  }
118297
- await executeClientCancelOrder({
118496
+ await execution.cancelOrder({
118298
118497
  ...common,
118299
118498
  orderId
118300
118499
  });
@@ -118314,7 +118513,7 @@ var init_copy_trading_execution = __esm({
118314
118513
  }
118315
118514
  let response;
118316
118515
  if (action.action_type === "create" && Array.isArray(action.order_members) && action.order_members.length > 1) {
118317
- response = await executeClientOrderBatch({
118516
+ response = await execution.orderBatch({
118318
118517
  ...common,
118319
118518
  members: action.order_members.map((member) => ({
118320
118519
  side: member.side,
@@ -118336,7 +118535,7 @@ var init_copy_trading_execution = __esm({
118336
118535
  if (typeof previousOrderId === "number" && previousOrderId <= 0 || typeof previousOrderId === "string" && !/^0x[0-9a-f]{32}$/.test(previousOrderId)) {
118337
118536
  throw new RuntimeReasonError("Copy Trading modify action is missing a valid previous destination order id.", "internal_data_error");
118338
118537
  }
118339
- response = await executeClientModifyOrder({
118538
+ response = await execution.modifyOrder({
118340
118539
  ...common,
118341
118540
  orderId: previousOrderId,
118342
118541
  side: action.side,
@@ -118350,7 +118549,7 @@ var init_copy_trading_execution = __esm({
118350
118549
  triggerIsMarket: action.trigger_is_market ?? void 0
118351
118550
  });
118352
118551
  } else if (action.order_kind === "trigger") {
118353
- response = await executeClientTriggerOrder({
118552
+ response = await execution.triggerOrder({
118354
118553
  ...common,
118355
118554
  side: action.side,
118356
118555
  size,
@@ -118361,7 +118560,7 @@ var init_copy_trading_execution = __esm({
118361
118560
  triggerIsMarket: action.trigger_is_market ?? void 0
118362
118561
  });
118363
118562
  } else {
118364
- response = await executeClientLimitOrder({
118563
+ response = await execution.limitOrder({
118365
118564
  ...common,
118366
118565
  side: action.side,
118367
118566
  size,
@@ -118414,6 +118613,28 @@ var init_copy_trading_execution = __esm({
118414
118613
  }
118415
118614
  });
118416
118615
 
118616
+ // lib/runtime/agent-instruction-carry.ts
118617
+ var carryAgentInstruction, carriedAgentInstruction;
118618
+ var init_agent_instruction_carry = __esm({
118619
+ "lib/runtime/agent-instruction-carry.ts"() {
118620
+ "use strict";
118621
+ init_define_VTX_CLAUDE_CODE_POLICY();
118622
+ init_define_VTX_EXO_POLICY();
118623
+ init_define_VTX_GROK_POLICY();
118624
+ init_define_VTX_PI_MODEL_POLICY();
118625
+ carryAgentInstruction = (error48, binding) => {
118626
+ if (!binding || !error48 || typeof error48 !== "object" && typeof error48 !== "function") return error48;
118627
+ error48.runtimeExternalAgentInstruction = binding;
118628
+ return error48;
118629
+ };
118630
+ carriedAgentInstruction = (error48) => {
118631
+ if (!error48 || typeof error48 !== "object" && typeof error48 !== "function") return null;
118632
+ const binding = error48.runtimeExternalAgentInstruction;
118633
+ return binding && typeof binding === "object" ? binding : null;
118634
+ };
118635
+ }
118636
+ });
118637
+
118417
118638
  // lib/trade-history-order-id.ts
118418
118639
  var INTEGER_ID_PATTERN, toSafeIntegerAlias, addOrderIdLookupKey, collectOrderIdLookupKeys;
118419
118640
  var init_trade_history_order_id = __esm({
@@ -119033,7 +119254,7 @@ var init_portfolio_evidence = __esm({
119033
119254
  });
119034
119255
 
119035
119256
  // lib/runtime/host-wake-schedule.ts
119036
- var marker, markBatchableTimer, markDeferrableTimer;
119257
+ var marker, markBatchableTimer, markDeferrableTimer, longRequests, startLongRequest;
119037
119258
  var init_host_wake_schedule = __esm({
119038
119259
  "lib/runtime/host-wake-schedule.ts"() {
119039
119260
  "use strict";
@@ -119050,6 +119271,15 @@ var init_host_wake_schedule = __esm({
119050
119271
  marker?.(handle, "deferrable", options);
119051
119272
  return handle;
119052
119273
  };
119274
+ longRequests = 0;
119275
+ startLongRequest = (run) => {
119276
+ longRequests += 1;
119277
+ try {
119278
+ return run();
119279
+ } finally {
119280
+ longRequests -= 1;
119281
+ }
119282
+ };
119053
119283
  }
119054
119284
  });
119055
119285
 
@@ -122308,6 +122538,7 @@ var init_provider_client = __esm({
122308
122538
  init_provider_observability();
122309
122539
  init_api2();
122310
122540
  init_network_debug();
122541
+ init_host_wake_schedule();
122311
122542
  init_abort();
122312
122543
  init_runtime_redaction();
122313
122544
  init_error_surface_contract();
@@ -122939,7 +123170,7 @@ var init_provider_client = __esm({
122939
123170
  providerResponseSignals = /* @__PURE__ */ new WeakMap();
122940
123171
  fetchProvider = async (url2, init2) => {
122941
123172
  if (init2.signal?.aborted) throw init2.signal.reason ?? new DOMException("Cancelled", "AbortError");
122942
- const response = await awaitProviderOperation(fetch(url2, init2), init2.signal);
123173
+ const response = await awaitProviderOperation(startLongRequest(() => fetch(url2, init2)), init2.signal);
122943
123174
  if (init2.signal) providerResponseSignals.set(response, init2.signal);
122944
123175
  return response;
122945
123176
  };
@@ -123572,12 +123803,12 @@ var init_provider_client = __esm({
123572
123803
  response = null;
123573
123804
  const marker2 = beginProviderDispatch(body);
123574
123805
  dispatchMarker = marker2;
123575
- const dispatched = useRelay ? await relayNativeProviderRequest(provider, String(apiKey || "").trim(), body, {
123806
+ const dispatched = useRelay ? await startLongRequest(() => relayNativeProviderRequest(provider, String(apiKey || "").trim(), body, {
123576
123807
  profileId: profileId == null ? void 0 : Number(profileId),
123577
123808
  signal,
123578
123809
  planId: relayPlan?.id,
123579
123810
  traceId: trace.id
123580
- }) : await fetchProvider(dispatchUrl, {
123811
+ })) : await fetchProvider(dispatchUrl, {
123581
123812
  method: "POST",
123582
123813
  headers: requestHeaders,
123583
123814
  body: JSON.stringify(body),
@@ -124360,11 +124591,11 @@ var init_provider_client = __esm({
124360
124591
  if (new TextEncoder().encode(JSON.stringify(payload)).byteLength > egress.budget.policy.max_request_bytes) throw new Error("Google egress request exceeds configured limit.");
124361
124592
  egress.budget.attempts += 1;
124362
124593
  if (egress.route === "node") {
124363
- const relayed = await awaitProviderOperation(relayGoogleEgressRequest(model, apiKey, payload, {
124594
+ const relayed = await awaitProviderOperation(startLongRequest(() => relayGoogleEgressRequest(model, apiKey, payload, {
124364
124595
  profileId: egress.profileId,
124365
124596
  signal,
124366
124597
  timeoutSeconds: egress.timeoutSeconds
124367
- }), signal);
124598
+ })), signal);
124368
124599
  if (signal) providerResponseSignals.set(relayed, signal);
124369
124600
  return relayed;
124370
124601
  }
@@ -124547,6 +124778,7 @@ var init_provider_client = __esm({
124547
124778
  const normalized = detail.toLowerCase();
124548
124779
  if (isProviderOutOfCreditText(detail) || isProviderOutOfCreditReply(statusCode, "")) return PROVIDER_OUT_OF_CREDIT_FAILURE_CODE;
124549
124780
  if (statusCode === HTTP_STATUS.TOO_MANY_REQUESTS) return "rate_limit";
124781
+ if (isProviderServerErrorStatus(statusCode)) return "provider_error";
124550
124782
  if (statusCode === HTTP_STATUS.UNAUTHORIZED || statusCode === HTTP_STATUS.FORBIDDEN || normalized.includes("unauthorized") || normalized.includes("forbidden")) {
124551
124783
  return "authorization";
124552
124784
  }
@@ -126811,7 +127043,7 @@ __export(local_analysis_exports, {
126811
127043
  runLocalRuntimeCycle: () => runLocalRuntimeCycle,
126812
127044
  summarizeReviewFailureExplanation: () => summarizeReviewFailureExplanation
126813
127045
  });
126814
- var cycleCandles, CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, EXTERNAL_INFERENCE_RESULT_WAIT_MS, TRUNCATION_ELLIPSIS2, assertPromptModelController, resolveRuntimeReasoningControlsForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, buildServerBehaviorStateArtifacts, serverBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, acceptancePositionCaps, accountSnapshotCapturedAt, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, BEHAVIOR_MEMORY_UNAVAILABLE_ERROR, BehaviorMemoryUnavailableError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite3, compactSnippet, hashRuntimeDebugText, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, MANIFEST_COMPONENT_NAME, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, currentModelOutputJsonText, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, SERVER_UNREADABLE_REPLY_HOLD_REASONING, buildMissingDecisionHold, buildDecisionPlansFromResponse, buildReviewCandidatePlansFromResponse, forceUnavailableSymbolsToHold, extractTemplatePlaceholders, requireReviewPrimaryUserPromptTemplate, containsCompetingBehaviorStateMarkup, containsCompetingMainBehaviorStateMarkup, requireStrategyReviewTemplates, preflightStrategyReviewPromptContract, extractRuntimeReasoningSelection, isAbortError, isRuntimeTimeoutAbortReason, summarizeReviewFailureExplanation, buildReviewFailureHoldReason, createAbortError2, settleRuntimeCyclePromise, unwrapRuntimeCycleSettledResult, normalizeDecisionLabel, normalizeRuntimeSymbol, PromptContractFetchError, isLivePromptContextUnavailableError, buildFailClosedHoldResult, buildPromptConstructionFailureResult, buildLivePromptContextUnavailableFailureResult, pickFirstString, normalizeRuntimeStringList, requirePositiveRuntimeLimit, resolveRuntimeTradingScope, normalizeRuntimeProviderAlias, resolveCatalogModelEntry, createClientRuntimeProviderSetupError, createProviderSetupRejectionError, evaluateModelEligibility, extractReviewRuntimeReasoningSelection, isUsableRuntimeSettingsFallback, resolveRuntimeSettings, formatRuntimeDurationMs, normalizeRuntimeTimingNote, appendRuntimeTimingEvent, reportPromptParityTelemetry, resolveLocalRuntimeSecretRequirements, resolveLocalRuntimeSecretProvider, AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, resolvePromptRelativeVolumeContext, promptRelativeVolumeBaseline, CANDLE_CLOSE_TICKER_TIMEFRAME, candleCloseTicker, promptMarketAsOfTimestamp, deviceMarketReads, buildPromptCandlesPayload, formatUtcTimestampWithWeekday, formatUtcNowWithWeekday, formatPromptPrice, capacityUnitSize, buildPromptAccountStatusValue, buildPromptPositionsValue, sanitizePromptSymbol, fillTimeMs, fillSize, normalizeFillSide, normalizeFillOrderId, normalizeFillRiskOrderIdentity, fillStartPosition, fillSortValue, sortFillsAscending, sortFillsDescending, inferEntryFromStartPositionChain, inferEntryFromCurrentPositionSize, calculateCurrentPositionState, calculatePositionEntryTimes, countPositionAdds, latestPositionRiskIncreaseTimeMs, latestPositionRiskIncreaseEvidence, compactPromptRiskIncrease, roundPositiveDecimalHalfUp, compactPromptLastTrade, ENTRY_TRADE_FIELDS, PREVIOUS_DECISION_FIELDS, PREVIOUS_CAMPAIGN_FIELDS, hasExactKeys2, isNonnegativeInteger, isFiniteNumber, isExactEnumString, isNonemptyPromptText, isCampaignReasoningText, projectBackendDecisionMemoryItem, requireRenderedStrategyBehaviorState, canonicalFillSideForRiskEvidence, isValidRiskEvidenceFill, isValidCampaignBoundaryFill, normalizeFillHistoryCoverage, resolveFillHistoryCoverageForSymbol, buildPromptBehaviorStateArtifacts, buildReviewSystemPrompt, formatReviewUserPrompt, assemblePromptContextVars, buildPromptBehaviorStateValue, buildLocalRuntimePromptArtifacts, createRuntimeId2, asRecord, buildRuntimeConstraintRejectionMessage, hasDeviceProviderSecret, requireNonEmptyStringField, requirePositiveIntegerField, compareContractVersion, parsePromptContractTimestamp, assertPromptContractCompatibility, assertPromptContractTemporalBounds, sleepWithAbort, requireAgentPollRetryAfterMs, materializeClaimedClientRuntimeAgentInstruction, attachClientRuntimeErrorProvenance, isExternalRuntimeProviderResult, invokeClientExternalInference, assertPromptContractBindingTupleEqual, assertPromptContractScopeMatch, fetchBoundPromptContracts, carryReturnedModelCalls, runLocalRuntimeCycle;
127046
+ var cycleCandles, CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, EXTERNAL_INFERENCE_RESULT_WAIT_MS, TRUNCATION_ELLIPSIS2, assertPromptModelController, resolveRuntimeReasoningControlsForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, buildServerBehaviorStateArtifacts, serverBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, judgesPositionCaps, NO_POSITION_CAPS, POSITION_CAP_REFUSALS, judgeCyclePlans, capacityTrimOf, tradabilityExecutionBlock, accountSnapshotCapturedAt, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, BEHAVIOR_MEMORY_UNAVAILABLE_ERROR, BehaviorMemoryUnavailableError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite3, compactSnippet, hashRuntimeDebugText, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, MANIFEST_COMPONENT_NAME, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, currentModelOutputJsonText, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, SERVER_UNREADABLE_REPLY_HOLD_REASONING, buildMissingDecisionHold, buildDecisionPlansFromResponse, buildReviewCandidatePlansFromResponse, forceUnavailableSymbolsToHold, extractTemplatePlaceholders, requireReviewPrimaryUserPromptTemplate, containsCompetingBehaviorStateMarkup, containsCompetingMainBehaviorStateMarkup, requireStrategyReviewTemplates, preflightStrategyReviewPromptContract, extractRuntimeReasoningSelection, isAbortError, isRuntimeTimeoutAbortReason, summarizeReviewFailureExplanation, buildReviewFailureHoldReason, createAbortError2, settleRuntimeCyclePromise, unwrapRuntimeCycleSettledResult, normalizeDecisionLabel, normalizeRuntimeSymbol, PromptContractFetchError, isLivePromptContextUnavailableError, buildFailClosedHoldResult, buildPromptConstructionFailureResult, buildLivePromptContextUnavailableFailureResult, pickFirstString, normalizeRuntimeStringList, requirePositiveRuntimeLimit, resolveRuntimeTradingScope, normalizeRuntimeProviderAlias, resolveCatalogModelEntry, createClientRuntimeProviderSetupError, createProviderSetupRejectionError, evaluateModelEligibility, extractReviewRuntimeReasoningSelection, isUsableRuntimeSettingsFallback, resolveRuntimeSettings, formatRuntimeDurationMs, normalizeRuntimeTimingNote, appendRuntimeTimingEvent, reportPromptParityTelemetry, resolveLocalRuntimeSecretRequirements, resolveLocalRuntimeSecretProvider, AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, resolvePromptRelativeVolumeContext, promptRelativeVolumeBaseline, CANDLE_CLOSE_TICKER_TIMEFRAME, candleCloseTicker, promptMarketAsOfTimestamp, deviceMarketReads, buildPromptCandlesPayload, formatUtcTimestampWithWeekday, formatUtcNowWithWeekday, formatPromptPrice, capacityUnitSize, buildPromptAccountStatusValue, buildPromptPositionsValue, sanitizePromptSymbol, fillTimeMs, fillSize, normalizeFillSide, normalizeFillOrderId, normalizeFillRiskOrderIdentity, fillStartPosition, fillSortValue, sortFillsAscending, sortFillsDescending, inferEntryFromStartPositionChain, inferEntryFromCurrentPositionSize, calculateCurrentPositionState, calculatePositionEntryTimes, countPositionAdds, latestPositionRiskIncreaseTimeMs, latestPositionRiskIncreaseEvidence, compactPromptRiskIncrease, roundPositiveDecimalHalfUp, compactPromptLastTrade, ENTRY_TRADE_FIELDS, PREVIOUS_DECISION_FIELDS, PREVIOUS_CAMPAIGN_FIELDS, hasExactKeys2, isNonnegativeInteger, isFiniteNumber, isExactEnumString, isNonemptyPromptText, isCampaignReasoningText, projectBackendDecisionMemoryItem, requireRenderedStrategyBehaviorState, canonicalFillSideForRiskEvidence, isValidRiskEvidenceFill, isValidCampaignBoundaryFill, normalizeFillHistoryCoverage, resolveFillHistoryCoverageForSymbol, buildPromptBehaviorStateArtifacts, buildReviewSystemPrompt, formatReviewUserPrompt, assemblePromptContextVars, buildPromptBehaviorStateValue, buildLocalRuntimePromptArtifacts, createRuntimeId2, asRecord, buildRuntimeConstraintRejectionMessage, hasDeviceProviderSecret, requireNonEmptyStringField, requirePositiveIntegerField, compareContractVersion, parsePromptContractTimestamp, assertPromptContractCompatibility, assertPromptContractTemporalBounds, sleepWithAbort, requireAgentPollRetryAfterMs, materializeClaimedClientRuntimeAgentInstruction, attachClientRuntimeErrorProvenance, isExternalRuntimeProviderResult, invokeClientExternalInference, assertPromptContractBindingTupleEqual, assertPromptContractScopeMatch, fetchBoundPromptContracts, carryReturnedModelCalls, runLocalRuntimeCycle;
126815
127047
  var init_local_analysis = __esm({
126816
127048
  "lib/runtime/local-analysis.ts"() {
126817
127049
  "use strict";
@@ -126822,7 +127054,8 @@ var init_local_analysis = __esm({
126822
127054
  init_provider_status();
126823
127055
  init_provider_credit();
126824
127056
  init_sl_tp_execution_settings();
126825
- init_server_execution_capacity();
127057
+ init_execution_capacity();
127058
+ init_agent_instruction_carry();
126826
127059
  init_runtime_error_reason_rules();
126827
127060
  init_retired_model_source();
126828
127061
  init_byokProviderRegistry();
@@ -126994,7 +127227,77 @@ var init_local_analysis = __esm({
126994
127227
  };
126995
127228
  isServerDispatchAccountStateStale = (value) => value instanceof Error && value.name === "ServerDispatchAccountStateStale";
126996
127229
  isClientRuntimeAiSchedulePaused = (value) => value instanceof ClientRuntimeAiSchedulePaused;
126997
- acceptancePositionCaps = (executionMode, caps) => executionMode === "server" ? { remaining_global_units: null, remaining_exchange_units: null, remaining_asset_units: null } : caps;
127230
+ judgesPositionCaps = (executionMode, mode) => executionMode !== "server" && mode !== "assistant";
127231
+ NO_POSITION_CAPS = { remaining_global_units: null, remaining_exchange_units: null, remaining_asset_units: null };
127232
+ POSITION_CAP_REFUSALS = /* @__PURE__ */ new Set(["global_capacity_reached", "exchange_capacity_reached", "asset_capacity_reached", "capacity_reached"]);
127233
+ judgeCyclePlans = (input) => {
127234
+ let remainingAllowance = input.allowance;
127235
+ const orderCount = input.plans.filter((plan) => (plan.decision === "BUY" || plan.decision === "SELL") && Math.trunc(Number(plan.units)) > 0).length;
127236
+ const judgements = new Array(input.plans.length);
127237
+ const judgingOrder = input.reductionsFirst ? reductionFirstOrder(input.plans.map((plan) => ({
127238
+ decision: plan.decision,
127239
+ units: plan.units,
127240
+ signedUnits: input.room.signedUnits(plan.symbol)
127241
+ }))) : input.plans.map((_, slot) => slot);
127242
+ for (const slot of judgingOrder) {
127243
+ const plan = input.plans[slot];
127244
+ const signedUnits = input.room.signedUnits(plan.symbol);
127245
+ const allowanceUnits = Math.min(Math.max(0, Math.trunc(Number(plan.units) || 0)), remainingAllowance);
127246
+ const acceptance = evaluateRuntimeDecisionAcceptance({
127247
+ decision: plan.decision,
127248
+ units: plan.units,
127249
+ constraints: {
127250
+ ...input.constraints,
127251
+ max_trades_per_prompt: remainingAllowance,
127252
+ ...input.positionCaps ? input.room.caps(plan.symbol) : NO_POSITION_CAPS,
127253
+ current_symbol_signed_units: signedUnits
127254
+ }
127255
+ });
127256
+ if (!acceptance.accepted) {
127257
+ const capRefused = POSITION_CAP_REFUSALS.has(String(acceptance.reason_code)) && orderCount > 1;
127258
+ const allowanceRefused = acceptance.reason_code === "max_per_prompt_zero" && input.plans.length > 1 && remainingAllowance < input.allowance;
127259
+ if (!capRefused && !allowanceRefused) return { judgements, refused: { reasonCode: acceptance.reason_code } };
127260
+ judgements[slot] = { kind: "unsent", reasonCode: acceptance.reason_code || "capacity_reached" };
127261
+ input.onJudged?.(slot, judgements[slot], remainingAllowance);
127262
+ continue;
127263
+ }
127264
+ const classified = classifyExecutionIntent(acceptance.decision, acceptance.normalized_units, signedUnits);
127265
+ const minimum = classified.intent === "open" && input.tradability.openEnabled ? input.tradability.openMinimum : classified.intent === "add" && input.tradability.increaseEnabled ? input.tradability.increaseMinimum : null;
127266
+ if (input.tradability.enabled && minimum !== null && (plan.tradability == null || plan.tradability < minimum)) {
127267
+ judgements[slot] = {
127268
+ kind: "blocked",
127269
+ decision: acceptance.decision,
127270
+ units: acceptance.normalized_units,
127271
+ intent: classified.intent === "open" ? "open" : "add",
127272
+ minimum
127273
+ };
127274
+ input.onJudged?.(slot, judgements[slot], remainingAllowance);
127275
+ continue;
127276
+ }
127277
+ if (classified.side !== null) {
127278
+ remainingAllowance = Math.max(0, remainingAllowance - acceptance.normalized_units);
127279
+ input.room.take(plan.symbol, acceptance.decision, acceptance.normalized_units);
127280
+ }
127281
+ judgements[slot] = {
127282
+ kind: "accepted",
127283
+ decision: acceptance.decision,
127284
+ units: acceptance.normalized_units,
127285
+ signedUnits,
127286
+ ...input.positionCaps && classified.side !== null && acceptance.normalized_units < allowanceUnits ? { trimmedFrom: allowanceUnits } : {}
127287
+ };
127288
+ input.onJudged?.(slot, judgements[slot], remainingAllowance);
127289
+ }
127290
+ return { judgements, refused: null };
127291
+ };
127292
+ capacityTrimOf = (judgement) => judgement.kind === "accepted" && judgement.trimmedFrom !== void 0 ? { capacityTrim: { requestedUnits: judgement.trimmedFrom, constraintReasonCode: "units_capped" } } : {};
127293
+ tradabilityExecutionBlock = (tradability, intent, minimum) => ({
127294
+ reasonCode: "tradability_below_minimum",
127295
+ control: "tradability",
127296
+ intent,
127297
+ tradability: tradability ?? null,
127298
+ minimum,
127299
+ message: `Tradability ${tradability == null ? "missing" : String(tradability)} is below the ${intent === "open" ? "Open" : "Add"} minimum of ${minimum}. No order was placed.`
127300
+ });
126998
127301
  accountSnapshotCapturedAt = (executionMode, accountStateFetchedAtMs) => new Date(
126999
127302
  (executionMode === "server" ? accountStateFetchedAtMs : null) ?? Date.now()
127000
127303
  ).toISOString();
@@ -127087,10 +127390,7 @@ var init_local_analysis = __esm({
127087
127390
  if (!position) return 0;
127088
127391
  return signedUnitsFromEntryPosition(position.size, position.entry_price, tradeSize);
127089
127392
  };
127090
- const globalUnitsUsed = Array.from(positionBySymbol.keys()).reduce(
127091
- (total, positionSymbol) => total + Math.abs(signedUnitsForSymbol(positionSymbol)),
127092
- 0
127093
- );
127393
+ for (const positionSymbol of positionBySymbol.keys()) signedUnitsForSymbol(positionSymbol);
127094
127394
  const maxTradesPerPrompt = Math.max(0, Math.trunc(clampNumber(
127095
127395
  settings.max_trades_per_prompt,
127096
127396
  config2.default_max_trades_per_prompt
@@ -127107,13 +127407,13 @@ var init_local_analysis = __esm({
127107
127407
  settings.max_trades_per_exchange,
127108
127408
  maxTradesGlobal
127109
127409
  )));
127110
- const exchangeUnitsUsed = /* @__PURE__ */ new Map();
127111
- for (const positionSymbol of positionBySymbol.keys()) {
127112
- const venue = getHyperliquidMarketDex(positionSymbol);
127113
- exchangeUnitsUsed.set(venue, (exchangeUnitsUsed.get(venue) ?? 0) + Math.abs(signedUnitsForSymbol(positionSymbol)));
127114
- }
127115
- let remainingPromptUnits = maxTradesPerPrompt;
127116
- let remainingGlobalUnits = Math.max(0, maxTradesGlobal - globalUnitsUsed);
127410
+ const capacityRoom = openCapacityRoom(accountState.positions, {
127411
+ unit_size: tradeSize,
127412
+ capacity_unit_size: tradeSize,
127413
+ max_trades_global: maxTradesGlobal,
127414
+ max_trades_per_exchange: maxTradesPerExchange,
127415
+ max_trades_per_asset: maxTradesPerAsset
127416
+ });
127117
127417
  const marginMode = resolveRuntimeMarginModePreference(settings, config2);
127118
127418
  const buildExecutionContext = (planSymbol) => {
127119
127419
  const price = priceForSymbol(planSymbol);
@@ -127168,81 +127468,63 @@ var init_local_analysis = __esm({
127168
127468
  Math.round(clampNumber(settings.tradability_increase_minimum, config2.default_tradability_increase_minimum))
127169
127469
  )
127170
127470
  );
127171
- const executionPlans = decisionPlans.map((entry) => {
127172
- const currentSignedUnits = signedUnitsForSymbol(entry.symbol);
127173
- const intent = classifyExecutionIntent(entry.decision, entry.units, currentSignedUnits).intent;
127174
- const applicableTradabilityMinimum = intent === "open" && tradabilityOpenEnabled ? tradabilityOpenMinimum : intent === "add" && tradabilityIncreaseEnabled ? tradabilityIncreaseMinimum : null;
127471
+ const { judgements, refused } = judgeCyclePlans({
127472
+ plans: decisionPlans,
127473
+ room: capacityRoom,
127474
+ positionCaps: judgesPositionCaps(runtimeInput.executionMode, runtimeInput.mode),
127475
+ // The Agent's own order, its instruction's market first: the Agent
127476
+ // ranked its plans, and its market's order is the one the decision
127477
+ // records (the user's choice over judging reductions first here).
127478
+ reductionsFirst: false,
127479
+ allowance: maxTradesPerPrompt,
127480
+ constraints: {
127481
+ runtime_disabled: settings.main_model_enabled === false,
127482
+ kill_switch_active: false,
127483
+ max_trades_per_prompt: maxTradesPerPrompt,
127484
+ remaining_global_units: null,
127485
+ remaining_asset_units: null,
127486
+ model_allowed: true,
127487
+ provider_allowed: true
127488
+ },
127489
+ tradability: {
127490
+ enabled: tradabilityEnabled,
127491
+ openEnabled: tradabilityOpenEnabled,
127492
+ increaseEnabled: tradabilityIncreaseEnabled,
127493
+ openMinimum: tradabilityOpenMinimum,
127494
+ increaseMinimum: tradabilityIncreaseMinimum
127495
+ }
127496
+ });
127497
+ if (refused) {
127498
+ throw new Error(buildRuntimeConstraintRejectionMessage({
127499
+ reasonCode: refused.reasonCode,
127500
+ constraintsRecord: {},
127501
+ model: instruction.model,
127502
+ provider: "external_agent"
127503
+ }));
127504
+ }
127505
+ const executionPlans = decisionPlans.map((entry, slot) => {
127175
127506
  const executionContext = buildExecutionContext(entry.symbol);
127176
- if (tradabilityEnabled && applicableTradabilityMinimum !== null && (entry.tradability === null || entry.tradability < applicableTradabilityMinimum)) {
127177
- const blockIntent = intent === "open" ? "open" : "add";
127507
+ const judgement = judgements[slot];
127508
+ if (judgement.kind === "blocked") {
127178
127509
  return {
127179
127510
  ...entry,
127511
+ decision: judgement.decision,
127512
+ units: judgement.units,
127180
127513
  executionContext,
127181
- executionBlock: {
127182
- reasonCode: "tradability_below_minimum",
127183
- control: "tradability",
127184
- intent: blockIntent,
127185
- tradability: entry.tradability,
127186
- minimum: applicableTradabilityMinimum,
127187
- message: `Tradability ${entry.tradability ?? "missing"} is below the ${blockIntent === "open" ? "Open" : "Add"} minimum of ${applicableTradabilityMinimum}. No order was placed.`
127188
- }
127514
+ executionBlock: tradabilityExecutionBlock(entry.tradability, judgement.intent, judgement.minimum)
127189
127515
  };
127190
127516
  }
127191
- const remainingAssetUnits = Math.max(0, maxTradesPerAsset - Math.abs(currentSignedUnits));
127192
- const accepted = evaluateRuntimeDecisionAcceptance({
127193
- decision: entry.decision,
127194
- units: entry.units,
127195
- constraints: {
127196
- runtime_disabled: settings.main_model_enabled === false,
127197
- kill_switch_active: false,
127198
- max_trades_per_prompt: remainingPromptUnits,
127199
- ...acceptancePositionCaps(runtimeInput.executionMode, {
127200
- remaining_exchange_units: Math.max(0, maxTradesPerExchange - (exchangeUnitsUsed.get(getHyperliquidMarketDex(entry.symbol)) ?? 0)),
127201
- remaining_global_units: remainingGlobalUnits,
127202
- remaining_asset_units: remainingAssetUnits
127203
- }),
127204
- current_symbol_signed_units: currentSignedUnits,
127205
- model_allowed: true,
127206
- provider_allowed: true
127207
- }
127208
- });
127209
- if (!accepted.accepted) {
127210
- if (decisionPlans.length > 1 && remainingPromptUnits < maxTradesPerPrompt && (accepted.reason_code === "exchange_capacity_reached" || accepted.reason_code === "global_capacity_reached" || accepted.reason_code === "asset_capacity_reached" || accepted.reason_code === "capacity_reached" || accepted.reason_code === "max_per_prompt_zero")) {
127211
- return {
127212
- ...entry,
127213
- decision: "HOLD",
127214
- units: 0,
127215
- reasoning: `Skipped by client runtime constraints: ${accepted.reason_code}`,
127216
- executionContext,
127217
- ...entry.decision === "BUY" || entry.decision === "SELL" ? { unsentOrder: { decision: entry.decision, units: entry.units, constraintReasonCode: accepted.reason_code } } : {}
127218
- };
127219
- }
127220
- throw new Error(buildRuntimeConstraintRejectionMessage({
127221
- reasonCode: accepted.reason_code,
127222
- constraintsRecord: {},
127223
- model: instruction.model,
127224
- provider: "external_agent"
127225
- }));
127517
+ if (judgement.kind === "unsent") {
127518
+ return {
127519
+ ...entry,
127520
+ decision: "HOLD",
127521
+ units: 0,
127522
+ reasoning: `Skipped by client runtime constraints: ${judgement.reasonCode}`,
127523
+ executionContext,
127524
+ ...entry.decision === "BUY" || entry.decision === "SELL" ? { unsentOrder: { decision: entry.decision, units: entry.units, constraintReasonCode: judgement.reasonCode } } : {}
127525
+ };
127226
127526
  }
127227
- const classified = classifyExecutionIntent(
127228
- accepted.decision,
127229
- accepted.normalized_units,
127230
- currentSignedUnits
127231
- );
127232
- const exposureIncrease = Math.max(
127233
- 0,
127234
- Math.abs(classified.targetSignedUnits) - Math.abs(currentSignedUnits)
127235
- );
127236
- remainingPromptUnits = Math.max(0, remainingPromptUnits - accepted.normalized_units);
127237
- remainingGlobalUnits = Math.max(0, remainingGlobalUnits - exposureIncrease);
127238
- const venue = getHyperliquidMarketDex(entry.symbol);
127239
- exchangeUnitsUsed.set(venue, (exchangeUnitsUsed.get(venue) ?? 0) + exposureIncrease);
127240
- return {
127241
- ...entry,
127242
- decision: accepted.decision,
127243
- units: accepted.normalized_units,
127244
- executionContext
127245
- };
127527
+ return { ...entry, decision: judgement.decision, units: judgement.units, executionContext, ...capacityTrimOf(judgement) };
127246
127528
  });
127247
127529
  const selected = executionPlans.find(
127248
127530
  (entry) => normalizeRuntimeSymbol(entry.symbol) === normalizeRuntimeSymbol(symbol2)
@@ -127428,9 +127710,9 @@ var init_local_analysis = __esm({
127428
127710
  RUNTIME_SOURCE_DEFINITION_VERSION = "runtime-source-v1";
127429
127711
  DECISION_INPUT_DEFINITION_VERSION = "decision-input-v1";
127430
127712
  CONTEXT_ENVELOPE_DEFINITION_VERSION = "context-envelope-v2.1";
127431
- CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "6284a7b4880c39e52d48be2d18084f99f2d8b46f".trim() && !["unknown", "unstamped", "development"].includes(
127432
- "6284a7b4880c39e52d48be2d18084f99f2d8b46f".trim().toLowerCase()
127433
- ) ? "6284a7b4880c39e52d48be2d18084f99f2d8b46f".trim() : null;
127713
+ CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "bca614db2bfe3a23799f3a565b8b0f5338f01287".trim() && !["unknown", "unstamped", "development"].includes(
127714
+ "bca614db2bfe3a23799f3a565b8b0f5338f01287".trim().toLowerCase()
127715
+ ) ? "bca614db2bfe3a23799f3a565b8b0f5338f01287".trim() : null;
127434
127716
  CLIENT_MAIN_PROMPT_RENDERER = "client_runtime.buildLocalRuntimePromptArtifacts:v1";
127435
127717
  CLIENT_REVIEW_PROMPT_RENDERER = "client_runtime.review_prompt_assembly:v1";
127436
127718
  resolveEffectivePromptRuntimeProvenance = (input) => ({
@@ -130579,18 +130861,22 @@ ${stringifyPromptJson(parts.candlesPayload)}
130579
130861
  }
130580
130862
  input.onCycleWorkStarted?.();
130581
130863
  if (claimedAgentInstruction) {
130582
- return attachDecisionSettlementDeadline(await buildClaimedAgentRuntimeCycleResult({
130583
- runtimeInput: input,
130584
- config: config2,
130585
- settings,
130586
- settingsFallbackUsed,
130587
- instruction: claimedAgentInstruction,
130588
- cycleId,
130589
- decisionSnapshotId,
130590
- decisionSnapshotCapturedAt,
130591
- signal: timeoutController.signal,
130592
- cycleStartedAtMs
130593
- }));
130864
+ try {
130865
+ return attachDecisionSettlementDeadline(await buildClaimedAgentRuntimeCycleResult({
130866
+ runtimeInput: input,
130867
+ config: config2,
130868
+ settings,
130869
+ settingsFallbackUsed,
130870
+ instruction: claimedAgentInstruction,
130871
+ cycleId,
130872
+ decisionSnapshotId,
130873
+ decisionSnapshotCapturedAt,
130874
+ signal: timeoutController.signal,
130875
+ cycleStartedAtMs
130876
+ }));
130877
+ } catch (error48) {
130878
+ throw carryAgentInstruction(error48, claimedAgentInstruction.binding);
130879
+ }
130594
130880
  }
130595
130881
  const preferredModel = String(settings.preferred_model || "").trim();
130596
130882
  if (!preferredModel) {
@@ -132339,19 +132625,15 @@ ${stringifyPromptJson(parts.candlesPayload)}
132339
132625
  });
132340
132626
  }
132341
132627
  }
132342
- let remainingPromptUnits = Math.max(0, Math.trunc(Number(runtimeConstraints.max_trades_per_prompt) || 0));
132343
- let remainingGlobalUnits = runtimeConstraints.remaining_global_units;
132344
- const exchangeUnitsUsed = /* @__PURE__ */ new Map();
132345
- for (const positionSymbol of positionBySymbol.keys()) {
132346
- const venue = getHyperliquidMarketDex(positionSymbol);
132347
- exchangeUnitsUsed.set(venue, (exchangeUnitsUsed.get(venue) ?? 0) + Math.abs(computePlanSignedUnits(positionSymbol)));
132348
- }
132349
- if (runtimeConstraints.remaining_exchange_units != null) {
132350
- const venue = getHyperliquidMarketDex(symbol2);
132351
- exchangeUnitsUsed.set(venue, Math.max(exchangeUnitsUsed.get(venue) ?? 0, maxTradesPerExchange - runtimeConstraints.remaining_exchange_units));
132352
- }
132353
- const initialPromptUnits = remainingPromptUnits;
132354
- const initialGlobalUnits = remainingGlobalUnits;
132628
+ const cycleAllowance = Math.max(0, Math.trunc(Number(runtimeConstraints.max_trades_per_prompt) || 0));
132629
+ for (const positionSymbol of positionBySymbol.keys()) computePlanSignedUnits(positionSymbol);
132630
+ const capacityRoom = openCapacityRoom(positions, {
132631
+ unit_size: metadataTradeSize,
132632
+ capacity_unit_size: capacityUnitSize(metadataTradeSize, config2.default_ai_trade_amount),
132633
+ max_trades_global: maxTradesGlobal,
132634
+ max_trades_per_exchange: maxTradesPerExchange,
132635
+ max_trades_per_asset: maxTradesPerAsset
132636
+ });
132355
132637
  const tradabilityEnabled = resolveBooleanSetting(
132356
132638
  settings,
132357
132639
  "tradability_enabled",
@@ -132381,141 +132663,96 @@ ${stringifyPromptJson(parts.candlesPayload)}
132381
132663
  Math.round(Number(settings.tradability_increase_minimum ?? config2.default_tradability_increase_minimum))
132382
132664
  )
132383
132665
  );
132384
- const acceptExecutionPlan = (entry) => {
132385
- const planSymbol = normalizeRuntimeSymbol(entry.symbol);
132386
- const isPrimaryPlanSymbol = planSymbol === normalizeRuntimeSymbol(symbol2);
132387
- const planSignedUnits = computePlanSignedUnits(entry.symbol);
132388
- const initialClassifiedPlan = classifyExecutionIntent(entry.decision, entry.units, planSignedUnits);
132389
- const applicableMinimum = initialClassifiedPlan.intent === "open" && tradabilityOpenEnabled ? tradabilityOpenMinimum : initialClassifiedPlan.intent === "add" && tradabilityIncreaseEnabled ? tradabilityIncreaseMinimum : null;
132390
- if (tradabilityEnabled && applicableMinimum !== null && (entry.tradability == null || entry.tradability < applicableMinimum)) {
132391
- appendRuntimeDebugEvent({
132392
- label: "execution_plan_tradability_rejected",
132393
- note: [
132394
- `symbol=${planSymbol || entry.symbol}`,
132395
- `intent=${initialClassifiedPlan.intent}`,
132396
- `tradability=${entry.tradability ?? "missing"}`,
132397
- `minimum=${applicableMinimum}`
132398
- ].join(" "),
132399
- outcome: "ok"
132400
- });
132401
- const scoreLabel = entry.tradability == null ? "missing" : String(entry.tradability);
132402
- const blockIntent = initialClassifiedPlan.intent === "open" ? "open" : "add";
132403
- const intentLabel = blockIntent === "open" ? "Open" : "Add";
132404
- return {
132405
- symbol: entry.symbol,
132406
- decision: entry.decision,
132407
- units: entry.units,
132408
- tradability: entry.tradability,
132409
- reasoning: entry.reasoning,
132410
- executionContext: buildExecutionContextForSymbol(entry.symbol),
132411
- executionBlock: {
132412
- reasonCode: "tradability_below_minimum",
132413
- control: "tradability",
132414
- intent: blockIntent,
132415
- tradability: entry.tradability ?? null,
132416
- minimum: applicableMinimum,
132417
- message: `Tradability ${scoreLabel} is below the ${intentLabel} minimum of ${applicableMinimum}. No order was placed.`
132418
- }
132419
- };
132420
- }
132421
- const remainingAssetUnits = runtimeConstraints.remaining_asset_units == null ? null : isPrimaryPlanSymbol ? runtimeConstraints.remaining_asset_units : Math.max(0, maxTradesPerAsset - Math.abs(planSignedUnits));
132422
- const planConstraints = {
132423
- ...localAcceptanceConstraints,
132424
- max_trades_per_prompt: remainingPromptUnits,
132425
- ...acceptancePositionCaps(input.executionMode, {
132426
- remaining_global_units: remainingGlobalUnits,
132427
- remaining_exchange_units: Math.max(0, maxTradesPerExchange - (exchangeUnitsUsed.get(getHyperliquidMarketDex(entry.symbol)) ?? 0)),
132428
- remaining_asset_units: remainingAssetUnits
132429
- }),
132430
- current_symbol_signed_units: planSignedUnits
132431
- };
132432
- const planAcceptance = evaluateRuntimeDecisionAcceptance({
132433
- decision: entry.decision,
132434
- units: entry.units,
132435
- constraints: planConstraints
132436
- });
132437
- if (!planAcceptance.accepted) {
132438
- const aggregateCapacityConsumed = remainingPromptUnits < initialPromptUnits || remainingGlobalUnits !== initialGlobalUnits;
132439
- const capacityReason = planAcceptance.reason_code === "global_capacity_reached" || planAcceptance.reason_code === "exchange_capacity_reached" || planAcceptance.reason_code === "asset_capacity_reached" || planAcceptance.reason_code === "capacity_reached" || planAcceptance.reason_code === "max_per_prompt_zero";
132440
- if (finalDecisionPlans.length > 1 && aggregateCapacityConsumed && capacityReason) {
132666
+ const { judgements, refused } = judgeCyclePlans({
132667
+ plans: finalDecisionPlans,
132668
+ room: capacityRoom,
132669
+ positionCaps: judgesPositionCaps(input.executionMode, input.mode),
132670
+ reductionsFirst: true,
132671
+ allowance: cycleAllowance,
132672
+ constraints: localAcceptanceConstraints,
132673
+ tradability: {
132674
+ enabled: tradabilityEnabled,
132675
+ openEnabled: tradabilityOpenEnabled,
132676
+ increaseEnabled: tradabilityIncreaseEnabled,
132677
+ openMinimum: tradabilityOpenMinimum,
132678
+ increaseMinimum: tradabilityIncreaseMinimum
132679
+ },
132680
+ onJudged: (slot, judgement, remainingAllowance) => {
132681
+ const entry = finalDecisionPlans[slot];
132682
+ const planSymbol = normalizeRuntimeSymbol(entry.symbol) || entry.symbol;
132683
+ const roomCaps = capacityRoom.caps(entry.symbol);
132684
+ if (judgement.kind === "blocked") {
132685
+ appendRuntimeDebugEvent({
132686
+ label: "execution_plan_tradability_rejected",
132687
+ note: [
132688
+ `symbol=${planSymbol}`,
132689
+ `intent=${judgement.intent}`,
132690
+ `tradability=${entry.tradability ?? "missing"}`,
132691
+ `minimum=${judgement.minimum}`
132692
+ ].join(" "),
132693
+ outcome: "ok"
132694
+ });
132695
+ } else if (judgement.kind === "unsent") {
132441
132696
  appendRuntimeDebugEvent({
132442
132697
  label: "execution_plan_capacity_skipped",
132443
132698
  note: [
132444
- `symbol=${planSymbol || entry.symbol}`,
132445
- `reason=${planAcceptance.reason_code || "capacity_reached"}`,
132446
- `remaining_prompt=${remainingPromptUnits}`,
132447
- `remaining_global=${remainingGlobalUnits ?? "unbounded"}`
132699
+ `symbol=${planSymbol}`,
132700
+ `reason=${judgement.reasonCode}`,
132701
+ `remaining_prompt=${remainingAllowance}`,
132702
+ `remaining_global=${roomCaps.remaining_global_units}`
132703
+ ].join(" ")
132704
+ });
132705
+ } else {
132706
+ appendRuntimeDebugEvent({
132707
+ label: "execution_plan_capacity",
132708
+ note: [
132709
+ `symbol=${planSymbol}`,
132710
+ `signed_units=${judgement.signedUnits}`,
132711
+ `accepted_units=${judgement.units}`,
132712
+ `remaining_prompt=${remainingAllowance}`,
132713
+ `remaining_global=${roomCaps.remaining_global_units}`,
132714
+ `remaining_asset=${roomCaps.remaining_asset_units}`
132448
132715
  ].join(" ")
132449
132716
  });
132450
- return {
132451
- symbol: entry.symbol,
132452
- decision: "HOLD",
132453
- units: 0,
132454
- tradability: entry.tradability,
132455
- reasoning: `Skipped by client runtime constraints: ${planAcceptance.reason_code || "capacity_reached"}`,
132456
- executionContext: buildExecutionContextForSymbol(entry.symbol),
132457
- ...entry.decision === "BUY" || entry.decision === "SELL" ? {
132458
- unsentOrder: {
132459
- decision: entry.decision,
132460
- units: entry.units,
132461
- constraintReasonCode: planAcceptance.reason_code || "capacity_reached"
132462
- }
132463
- } : {}
132464
- };
132465
- }
132466
- throw new Error(buildRuntimeConstraintRejectionMessage({
132467
- reasonCode: planAcceptance.reason_code,
132468
- constraintsRecord: runtimeConstraintsRecord,
132469
- model: finalModel,
132470
- provider: finalProvider,
132471
- modelEligibilityReason: modelEligibility.reason
132472
- }));
132473
- }
132474
- const classifiedPlan = classifyExecutionIntent(
132475
- planAcceptance.decision,
132476
- planAcceptance.normalized_units,
132477
- planSignedUnits
132478
- );
132479
- if (classifiedPlan.side !== null) {
132480
- remainingPromptUnits = Math.max(0, remainingPromptUnits - planAcceptance.normalized_units);
132481
- const currentAbsUnits = Math.abs(planSignedUnits);
132482
- const targetAbsUnits = Math.abs(classifiedPlan.targetSignedUnits);
132483
- const globalDelta = Math.max(0, targetAbsUnits - currentAbsUnits);
132484
- const venue = getHyperliquidMarketDex(entry.symbol);
132485
- exchangeUnitsUsed.set(venue, (exchangeUnitsUsed.get(venue) ?? 0) + globalDelta);
132486
- if (remainingGlobalUnits !== null && globalDelta > 0) {
132487
- remainingGlobalUnits = Math.max(0, remainingGlobalUnits - globalDelta);
132488
132717
  }
132489
132718
  }
132490
- appendRuntimeDebugEvent({
132491
- label: "execution_plan_capacity",
132492
- note: [
132493
- `symbol=${planSymbol || entry.symbol}`,
132494
- `signed_units=${planSignedUnits}`,
132495
- `accepted_units=${planAcceptance.normalized_units}`,
132496
- `remaining_prompt=${remainingPromptUnits}`,
132497
- `remaining_global=${remainingGlobalUnits ?? "unbounded"}`,
132498
- `remaining_asset=${remainingAssetUnits ?? "unbounded"}`
132499
- ].join(" ")
132500
- });
132501
- return {
132719
+ });
132720
+ if (refused) {
132721
+ throw new Error(buildRuntimeConstraintRejectionMessage({
132722
+ reasonCode: refused.reasonCode,
132723
+ constraintsRecord: runtimeConstraintsRecord,
132724
+ model: finalModel,
132725
+ provider: finalProvider,
132726
+ modelEligibilityReason: modelEligibility.reason
132727
+ }));
132728
+ }
132729
+ const acceptedExecutionPlans = finalDecisionPlans.map((entry, slot) => {
132730
+ const judgement = judgements[slot];
132731
+ const base = {
132502
132732
  symbol: entry.symbol,
132503
- decision: planAcceptance.decision,
132504
- units: planAcceptance.normalized_units,
132505
132733
  tradability: entry.tradability,
132506
132734
  reasoning: entry.reasoning,
132507
132735
  executionContext: buildExecutionContextForSymbol(entry.symbol)
132508
132736
  };
132509
- };
132510
- const acceptedBySlot = /* @__PURE__ */ new Map();
132511
- for (const slot of reductionFirstOrder(finalDecisionPlans.map((entry) => ({
132512
- decision: entry.decision,
132513
- units: entry.units,
132514
- signedUnits: computePlanSignedUnits(entry.symbol)
132515
- })))) {
132516
- acceptedBySlot.set(slot, acceptExecutionPlan(finalDecisionPlans[slot]));
132517
- }
132518
- const acceptedExecutionPlans = finalDecisionPlans.map((_, slot) => acceptedBySlot.get(slot));
132737
+ if (judgement.kind === "blocked") {
132738
+ return {
132739
+ ...base,
132740
+ decision: judgement.decision,
132741
+ units: judgement.units,
132742
+ executionBlock: tradabilityExecutionBlock(entry.tradability, judgement.intent, judgement.minimum)
132743
+ };
132744
+ }
132745
+ if (judgement.kind === "unsent") {
132746
+ return {
132747
+ ...base,
132748
+ decision: "HOLD",
132749
+ units: 0,
132750
+ reasoning: `Skipped by client runtime constraints: ${judgement.reasonCode}`,
132751
+ ...entry.decision === "BUY" || entry.decision === "SELL" ? { unsentOrder: { decision: entry.decision, units: entry.units, constraintReasonCode: judgement.reasonCode } } : {}
132752
+ };
132753
+ }
132754
+ return { ...base, decision: judgement.decision, units: judgement.units, ...capacityTrimOf(judgement) };
132755
+ });
132519
132756
  const selectedAcceptedPlan = acceptedExecutionPlans.find((entry) => normalizeRuntimeSymbol(entry.symbol) === normalizeRuntimeSymbol(symbol2)) ?? acceptedExecutionPlans[0];
132520
132757
  const acceptance = {
132521
132758
  accepted: true,
@@ -132781,6 +133018,8 @@ var init_engine = __esm({
132781
133018
  init_exchange_mutation_fence();
132782
133019
  init_hyperliquid_account_state_adapter();
132783
133020
  init_hyperliquid_market_symbol();
133021
+ init_agent_instruction_carry();
133022
+ init_execution_capacity();
132784
133023
  init_client_killswitch();
132785
133024
  init_perp_dex_scope();
132786
133025
  init_api2();
@@ -136504,6 +136743,10 @@ var init_engine = __esm({
136504
136743
  ),
136505
136744
  externalInferenceBindings: result.externalInferenceBindings ?? [],
136506
136745
  externalAgentInstruction: result.externalAgentInstruction ?? null,
136746
+ // The cycle's market's order its own limits refused: the decision
136747
+ // reports HOLD for it, and an Agent or external model's authority
136748
+ // (which names the order) accepts that HOLD as not sent.
136749
+ unsentOrder: result.executionPlans?.find((plan) => normalizeHyperliquidMarketSymbol(plan.symbol) === normalizeHyperliquidMarketSymbol(result.executionContext.symbol))?.unsentOrder ?? null,
136507
136750
  mode: runtimeMode
136508
136751
  }, {
136509
136752
  signal: analysisAbortController.signal,
@@ -136526,13 +136769,44 @@ var init_engine = __esm({
136526
136769
  }))
136527
136770
  });
136528
136771
  }
136529
- throw decisionError;
136772
+ throw carryAgentInstruction(decisionError, result.externalAgentInstruction);
136530
136773
  }
136531
136774
  if (!decisionResponse) {
136532
136775
  await this._recoverFromNoDecisionCycle(requestId, "decision_submit", "empty_decision_response");
136533
136776
  return;
136534
136777
  }
136778
+ const settleUnsentAgentDecision = async (why) => {
136779
+ if (runtimeMode !== "trader" || !result.externalAgentInstruction || this._executionFinalizationRequired) return;
136780
+ await reportClientRuntimeTradeSync(profileId, {
136781
+ sessionId,
136782
+ deviceId,
136783
+ schedulerInstanceId: this._instanceId,
136784
+ mode: runtimeMode,
136785
+ lastRunAt: runStartedAt,
136786
+ syncedAt: result.completedAt,
136787
+ analysisRunId: requestId,
136788
+ analysisMode: runtimeMode,
136789
+ cycleId: result.cycleId,
136790
+ decisionSnapshotId: result.decisionSnapshotId,
136791
+ executionSnapshotId: null,
136792
+ contractVersion: result.contractVersion,
136793
+ contractHash: result.contractHash,
136794
+ policyGenerationId: result.policyGenerationId,
136795
+ executions: [],
136796
+ isAnalyzing: false,
136797
+ isExecuting: false,
136798
+ externalAgentInstruction: result.externalAgentInstruction
136799
+ }, {
136800
+ requestTimeoutMs: this._settlementRequestTimeoutMs ?? void 0,
136801
+ idempotencyKey: `runtime-trade-sync-${createRuntimeUuid2()}`
136802
+ }).catch((settleError) => appendRuntimeDebugEvent({
136803
+ label: "agent_instruction_unsent_settle_failed",
136804
+ note: `stage=${why} error=${getSanitizedRuntimeErrorMessage(settleError) || "unknown"}`,
136805
+ outcome: "error"
136806
+ }));
136807
+ };
136535
136808
  if (analysisAbortController.signal.aborted || this._isStopping || this._analysisRequestId !== requestId) {
136809
+ await settleUnsentAgentDecision("cycle_ended_after_decision");
136536
136810
  return;
136537
136811
  }
136538
136812
  this._setRuntimeStatus(decisionResponse.runtime, "decision");
@@ -136549,6 +136823,7 @@ var init_engine = __esm({
136549
136823
  note: `cycle_id=${result.cycleId} reconciled=${String(decisionResponse.decision_reconciled === true)}`,
136550
136824
  outcome: "ok"
136551
136825
  });
136826
+ await settleUnsentAgentDecision("decision_saved_after_execution_deadline");
136552
136827
  this._notifyListeners();
136553
136828
  return;
136554
136829
  }
@@ -136557,6 +136832,7 @@ var init_engine = __esm({
136557
136832
  if (runtimeMode === "trader") {
136558
136833
  observeCycle({ stage: "execution" });
136559
136834
  if (shouldAbortForContractInvalidation("pre_trade_execution")) {
136835
+ await settleUnsentAgentDecision("pre_trade_execution");
136560
136836
  return;
136561
136837
  }
136562
136838
  if (hasActionableDecision) {
@@ -136581,6 +136857,7 @@ var init_engine = __esm({
136581
136857
  });
136582
136858
  const config2 = await this.refreshExecutionConfig(profileId);
136583
136859
  if (shouldAbortForContractInvalidation("post_execution_config_refresh")) {
136860
+ await settleUnsentAgentDecision("post_execution_config_refresh");
136584
136861
  return;
136585
136862
  }
136586
136863
  const executionResults = [];
@@ -136608,6 +136885,22 @@ var init_engine = __esm({
136608
136885
  capacityPlans.forEach(({ planIndex }, index) => serverCapacityByPlan.set(planIndex, allocations[index]));
136609
136886
  }
136610
136887
  const runPlan = async (plan, planIndex) => {
136888
+ const withPlanCapacityTrim = (planResult) => {
136889
+ if (plan.capacityTrim) {
136890
+ return withCapacityTrim(planResult, {
136891
+ requested_units: plan.capacityTrim.requestedUnits,
136892
+ accepted_units: plan.units,
136893
+ constraint_reason_code: plan.capacityTrim.constraintReasonCode
136894
+ });
136895
+ }
136896
+ const allocation = serverCapacityByPlan.get(planIndex);
136897
+ const decidedUnits = Math.trunc(Number(plan.units) || 0);
136898
+ return allocation && !("unavailable" in allocation) && allocation.accepted && allocation.units < decidedUnits ? withCapacityTrim(planResult, {
136899
+ requested_units: decidedUnits,
136900
+ accepted_units: allocation.units,
136901
+ constraint_reason_code: allocation.reason_code ?? "units_capped"
136902
+ }) : planResult;
136903
+ };
136611
136904
  let planEntryOrderDispatched = false;
136612
136905
  let planExitOrderDispatched = false;
136613
136906
  const decisionWallet = String(
@@ -136709,6 +137002,7 @@ var init_engine = __esm({
136709
137002
  },
136710
137003
  shouldCancelBeforeExchangeOrderDispatch: () => this._windowHandoffRequested
136711
137004
  });
137005
+ if (plan.capacityTrim) executionResult = withPlanCapacityTrim(executionResult);
136712
137006
  } catch (executionError) {
136713
137007
  const committedReports = getCommittedExecutionReports(executionError);
136714
137008
  const committedOrder = getCommittedDecisionOrder(executionError);
@@ -136717,7 +137011,7 @@ var init_engine = __esm({
136717
137011
  const handoffCleanup = getClientRuntimeWindowHandoffCleanup(executionError);
136718
137012
  if (handoffCleanup || committedReports.length > 0) {
136719
137013
  this._executionFinalizationRequired = true;
136720
- return { control: "break", result: {
137014
+ return { control: "break", result: withPlanCapacityTrim({
136721
137015
  status: committedReports.length > 0 ? "executed" : "skipped",
136722
137016
  intent: "hold",
136723
137017
  side: null,
@@ -136731,7 +137025,7 @@ var init_engine = __esm({
136731
137025
  ...handoffCleanup ? { handoffCleanup } : {},
136732
137026
  executionSnapshotId: `handoff-cleanup-${planIndex + 1}-${Date.now()}`,
136733
137027
  executionSnapshotCapturedAt: (/* @__PURE__ */ new Date()).toISOString()
136734
- } };
137028
+ }) };
136735
137029
  }
136736
137030
  return { control: "break" };
136737
137031
  }
@@ -136779,6 +137073,7 @@ var init_engine = __esm({
136779
137073
  }
136780
137074
  }]
136781
137075
  };
137076
+ executionResult = withPlanCapacityTrim(executionResult);
136782
137077
  if (abortedAfterCommittedOrder) {
136783
137078
  this._executionFinalizationRequired = true;
136784
137079
  return { control: "break", result: executionResult };
@@ -136903,6 +137198,7 @@ var init_engine = __esm({
136903
137198
  }
136904
137199
  const outcome = await runPlan(executionPlans[planIndex], planIndex);
136905
137200
  if (outcome.control === "return") {
137201
+ await settleUnsentAgentDecision("plan_ended_cycle");
136906
137202
  return;
136907
137203
  }
136908
137204
  if (outcome.result) {
@@ -136981,9 +137277,11 @@ var init_engine = __esm({
136981
137277
  outcome: "ok"
136982
137278
  });
136983
137279
  if (!this._executionFinalizationRequired && (analysisAbortController.signal.aborted || this._isStopping || this._analysisRequestId !== requestId)) {
137280
+ await settleUnsentAgentDecision("cycle_ended_before_trade_sync");
136984
137281
  return;
136985
137282
  }
136986
137283
  if (!this._executionFinalizationRequired && shouldAbortForContractInvalidation("pre_trade_sync_submit")) {
137284
+ await settleUnsentAgentDecision("pre_trade_sync_submit");
136987
137285
  return;
136988
137286
  }
136989
137287
  const tradeSyncPayload = {
@@ -137647,7 +137945,8 @@ var init_engine = __esm({
137647
137945
  executionReasonCode: executionProjection?.reason_code ?? null,
137648
137946
  executionStage: executionProjection?.execution_stage ?? null,
137649
137947
  dispatchOutcome: executionProjection?.dispatch_outcome ?? null,
137650
- providerFailure: serverModelFailure?.report ?? null
137948
+ providerFailure: serverModelFailure?.report ?? null,
137949
+ externalAgentInstruction: carriedAgentInstruction(reason)
137651
137950
  },
137652
137951
  {
137653
137952
  requestTimeoutMs: this._settlementRequestTimeoutMs ?? void 0