@adaptic/utils 0.0.1032 → 0.0.1034
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/dist/index.cjs +325 -75
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +325 -76
- package/dist/index.mjs.map +1 -1
- package/dist/types/alpaca/trading/order-utils.d.ts.map +1 -1
- package/dist/types/llm/circuit-breaker.d.ts +18 -1
- package/dist/types/llm/circuit-breaker.d.ts.map +1 -1
- package/dist/types/llm/fallback-chain.d.ts.map +1 -1
- package/dist/types/llm/index.d.ts +3 -1
- package/dist/types/llm/index.d.ts.map +1 -1
- package/dist/types/llm/rate-guard.d.ts +82 -9
- package/dist/types/llm/rate-guard.d.ts.map +1 -1
- package/dist/types/llm/structured-content.d.ts +73 -0
- package/dist/types/llm/structured-content.d.ts.map +1 -0
- package/dist/types/llm/transports/gateway.d.ts.map +1 -1
- package/dist/types/schemas/alpaca-schemas.d.ts.map +1 -1
- package/dist/types/trading-policy/schemas/effective-policy.schema.d.ts +18 -18
- package/dist/types/trading-policy/schemas/model-prefs.schema.d.ts +24 -24
- package/dist/types/trading-policy/schemas/policy-mutation.schema.d.ts +36 -36
- package/dist/types/types/alpaca-types.d.ts +10 -3
- package/dist/types/types/alpaca-types.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -62486,13 +62486,18 @@ const DEFAULT_PAGINATION_DELAY_MS = 300;
|
|
|
62486
62486
|
*/
|
|
62487
62487
|
const MAX_ORDERS_PER_REQUEST = 500;
|
|
62488
62488
|
/**
|
|
62489
|
-
* Order statuses that are considered "open"
|
|
62489
|
+
* Order statuses that are considered "open".
|
|
62490
|
+
*
|
|
62491
|
+
* `held` is included because a held conditional leg (a bracket's stop-loss,
|
|
62492
|
+
* say) is a working order resting at the broker, returned by Alpaca's own
|
|
62493
|
+
* `status=open` listing and cancelable like any other open order.
|
|
62490
62494
|
*/
|
|
62491
62495
|
const OPEN_ORDER_STATUSES = [
|
|
62492
62496
|
"new",
|
|
62493
62497
|
"accepted",
|
|
62494
62498
|
"pending_new",
|
|
62495
62499
|
"accepted_for_bidding",
|
|
62500
|
+
"held",
|
|
62496
62501
|
"partially_filled",
|
|
62497
62502
|
];
|
|
62498
62503
|
/**
|
|
@@ -62500,13 +62505,15 @@ const OPEN_ORDER_STATUSES = [
|
|
|
62500
62505
|
*/
|
|
62501
62506
|
const FILLED_ORDER_STATUSES = ["filled"];
|
|
62502
62507
|
/**
|
|
62503
|
-
* Order statuses that can still potentially be filled
|
|
62508
|
+
* Order statuses that can still potentially be filled. A `held` leg fills once
|
|
62509
|
+
* its parent fills or its trigger is met.
|
|
62504
62510
|
*/
|
|
62505
62511
|
const FILLABLE_ORDER_STATUSES = [
|
|
62506
62512
|
"new",
|
|
62507
62513
|
"accepted",
|
|
62508
62514
|
"pending_new",
|
|
62509
62515
|
"accepted_for_bidding",
|
|
62516
|
+
"held",
|
|
62510
62517
|
"partially_filled",
|
|
62511
62518
|
];
|
|
62512
62519
|
/**
|
|
@@ -72314,11 +72321,35 @@ class CircuitBreakerRegistry {
|
|
|
72314
72321
|
* Register that an attempt is starting, so half-open probes stay bounded.
|
|
72315
72322
|
*
|
|
72316
72323
|
* @param routeKey The route's stable key.
|
|
72317
|
-
* @returns
|
|
72324
|
+
* @returns Whether the attempt took a half-open probe slot. A caller holding
|
|
72325
|
+
* one must end the attempt with {@link onSuccess}, {@link onFailure} or
|
|
72326
|
+
* {@link onAttemptAbandoned}, or the slot is never returned.
|
|
72318
72327
|
*/
|
|
72319
72328
|
onAttemptStart(routeKey) {
|
|
72320
72329
|
if (this.stateOf(routeKey) === "half-open") {
|
|
72321
72330
|
this.recordFor(routeKey).probesInFlight += 1;
|
|
72331
|
+
return true;
|
|
72332
|
+
}
|
|
72333
|
+
return false;
|
|
72334
|
+
}
|
|
72335
|
+
/**
|
|
72336
|
+
* Return a half-open probe slot whose attempt ended without a verdict.
|
|
72337
|
+
*
|
|
72338
|
+
* A probe that never tested the provider — refused by the client's own
|
|
72339
|
+
* pacing guard, cancelled by its caller, or found to be the wrong leg for the
|
|
72340
|
+
* request — says nothing about whether the route has recovered, so neither a
|
|
72341
|
+
* success nor a failure is recorded. The slot must still come back. Without
|
|
72342
|
+
* it the half-open route admits no further probe, no probe can ever close or
|
|
72343
|
+
* re-open the breaker, and the route stays excluded for the life of the
|
|
72344
|
+
* process while its traffic is quietly served by the next leg.
|
|
72345
|
+
*
|
|
72346
|
+
* @param routeKey The route's stable key.
|
|
72347
|
+
* @returns void
|
|
72348
|
+
*/
|
|
72349
|
+
onAttemptAbandoned(routeKey) {
|
|
72350
|
+
const record = this.records.get(routeKey);
|
|
72351
|
+
if (record !== undefined && record.probesInFlight > 0) {
|
|
72352
|
+
record.probesInFlight -= 1;
|
|
72322
72353
|
}
|
|
72323
72354
|
}
|
|
72324
72355
|
/**
|
|
@@ -72589,11 +72620,13 @@ var defaults$1 = {
|
|
|
72589
72620
|
var providers$1 = {
|
|
72590
72621
|
anthropic: {
|
|
72591
72622
|
basis: "conservative-default",
|
|
72623
|
+
scope: "model",
|
|
72624
|
+
scope_source: "https://platform.claude.com/docs/en/api/rate-limits",
|
|
72592
72625
|
requests_per_minute: 120,
|
|
72593
72626
|
max_concurrent: 12,
|
|
72594
72627
|
acquire_timeout_ms: 15000,
|
|
72595
72628
|
source: null,
|
|
72596
|
-
note: "
|
|
72629
|
+
note: "The unit is per model: the scope_source states 'Rate limits are applied separately for each model; therefore you can use different models up to their respective limits simultaneously', measured as requests, input tokens and output tokens per minute for each model class, with no concurrency ceiling. Each model therefore gets its own guard, so traffic on one model class (an Opus incumbent serving background aliases) cannot refuse calls to another (the Haiku incumbent of the hot-path alias). The NUMBERS stay conservative-default: the organisation's usage tier sets the real ceilings and is read only from the Claude Console rate-limits page, which has not been transcribed. The lowest standard tier listed at the source allows 1,000 requests per minute per model; organisations with limited history can start on an evaluation tier below that, which is why these values are held well under it. Transcribe the tier's limits (W3-07) and set basis to published."
|
|
72597
72630
|
},
|
|
72598
72631
|
openai: {
|
|
72599
72632
|
basis: "conservative-default",
|
|
@@ -72612,12 +72645,14 @@ var providers$1 = {
|
|
|
72612
72645
|
note: "Raised 2026-09-15 after the 4-concurrent ceiling was measured starving the live equity decision path: the alias chain reported 'exhausted its fallback chain' with every leg skipped by this guard (deepinfra primary+secondary and the anthropic incumbent), 173 of 473 signal-coordination calls failed (36.6%), and decisions were lost outright. Corroborating evidence at the time: ZERO 429s observed on any provider, the engine's own global fan-out gate permits 100 concurrent with 17 active, and 877 signal-analysis calls had been admitted to that gate. Concurrency and RPM are raised TOGETHER because they bind in series - lifting max_concurrent alone would only move the bottleneck to the token bucket. STILL conservative-default, NOT published: no provider console was read for these numbers, so they remain a deliberate under-estimate of an unknown ceiling. Transcribe the real tier limits (W3-07) and set basis to published."
|
|
72613
72646
|
},
|
|
72614
72647
|
deepinfra: {
|
|
72615
|
-
basis: "
|
|
72648
|
+
basis: "published",
|
|
72649
|
+
scope: "model",
|
|
72616
72650
|
requests_per_minute: 240,
|
|
72617
|
-
|
|
72651
|
+
requests_per_minute_basis: "conservative-default",
|
|
72652
|
+
max_concurrent: 200,
|
|
72618
72653
|
acquire_timeout_ms: 15000,
|
|
72619
|
-
source:
|
|
72620
|
-
note: "
|
|
72654
|
+
source: "https://docs.deepinfra.com/account/rate-limits",
|
|
72655
|
+
note: "Transcribed 2026-09-23 from the source, which states 'Every account has a default limit of 200 concurrent requests per model', that two models queried simultaneously allow 400 in total (200 per model), and that 'The rate limit is on concurrent requests, not per-minute volume.' Concurrency is therefore the bound DeepInfra enforces, and it is enforced per MODEL, so each model gets its own guard at 200. One guard shared by the whole account enforced a ceiling DeepInfra does not impose, and because an alias's primary and secondary are both served from this account, it refused the secondary exactly when the primary's queue was full. DeepInfra publishes no per-minute ceiling, so requests_per_minute is the client's own pacing backstop (requests_per_minute_basis: conservative-default), keyed per model like the bound DeepInfra does enforce. Exceeding the ceiling returns HTTP 429, and a very busy model can return 429 below it. The ceiling belongs to the account and this guard to one process, so every process calling the same model through the same account shares the 200."
|
|
72621
72656
|
},
|
|
72622
72657
|
fireworks: {
|
|
72623
72658
|
basis: "conservative-default",
|
|
@@ -72667,7 +72702,10 @@ var limitsConfig = {
|
|
|
72667
72702
|
* provider's circuit breaker, fail over to a more expensive leg, and keep doing
|
|
72668
72703
|
* so — converting a self-inflicted pacing problem into a permanent routing
|
|
72669
72704
|
* change nobody chose. Pacing at the client is what keeps the breaker measuring
|
|
72670
|
-
* the provider rather than measuring us.
|
|
72705
|
+
* the provider rather than measuring us. The same reasoning bounds the guard
|
|
72706
|
+
* from the other side: a client held far BELOW the provider's ceiling refuses
|
|
72707
|
+
* calls the provider would have served, and the chain answers those refusals by
|
|
72708
|
+
* failing over — the same unchosen routing change, arrived at by under-driving.
|
|
72671
72709
|
*
|
|
72672
72710
|
* Two distinct bounds are applied because they fail differently. The rate bound
|
|
72673
72711
|
* (requests per minute) protects the provider's published ceiling. The
|
|
@@ -72676,8 +72714,18 @@ var limitsConfig = {
|
|
|
72676
72714
|
* every one of them blows its latency budget and the fan-out produces a hundred
|
|
72677
72715
|
* timeouts instead of a queue.
|
|
72678
72716
|
*
|
|
72679
|
-
*
|
|
72680
|
-
*
|
|
72717
|
+
* Each guard is keyed by the unit its provider enforces limits in. A provider
|
|
72718
|
+
* that publishes its ceilings per model gets one independent guard per model.
|
|
72719
|
+
* Sharing one guard across its models would enforce a ceiling the provider does
|
|
72720
|
+
* not impose, and — when a chain's primary and secondary are served by the same
|
|
72721
|
+
* provider — would refuse the secondary at exactly the moment the primary's
|
|
72722
|
+
* queue is full, so the fallback that exists for that moment is never reached.
|
|
72723
|
+
*
|
|
72724
|
+
* Limits live in `provider-limits.json` rather than in code, each beside the
|
|
72725
|
+
* source it was transcribed from, so a published ceiling and a conservative
|
|
72726
|
+
* guess can never be mistaken for one another in review. The file is bundled
|
|
72727
|
+
* at build time: changing a limit is a release of this package, not a runtime
|
|
72728
|
+
* switch.
|
|
72681
72729
|
*
|
|
72682
72730
|
* @module llm/rate-guard
|
|
72683
72731
|
*/
|
|
@@ -72717,64 +72765,141 @@ class RateGuardTimeoutError extends Error {
|
|
|
72717
72765
|
provider;
|
|
72718
72766
|
/** Which of the two bounds the caller waited on. */
|
|
72719
72767
|
bound;
|
|
72768
|
+
/** The model whose guard refused the call, when the provider's limits apply per model. */
|
|
72769
|
+
modelId;
|
|
72770
|
+
/** Whether the caller stopped waiting before the guard's own wait budget ran out. */
|
|
72771
|
+
abandoned;
|
|
72720
72772
|
/**
|
|
72721
72773
|
* @param provider The provider.
|
|
72722
72774
|
* @param bound Which bound was binding.
|
|
72723
|
-
* @param waitedMs How long the caller
|
|
72775
|
+
* @param waitedMs How long the caller was prepared to wait.
|
|
72776
|
+
* @param detail The model, and whether the caller left before the budget ran out.
|
|
72724
72777
|
*/
|
|
72725
|
-
constructor(provider, bound, waitedMs) {
|
|
72726
|
-
|
|
72778
|
+
constructor(provider, bound, waitedMs, detail = {}) {
|
|
72779
|
+
const guard = detail.modelId === undefined
|
|
72780
|
+
? `client-side ${bound} guard for provider "${provider}"`
|
|
72781
|
+
: `client-side ${bound} guard for provider "${provider}", model "${detail.modelId}",`;
|
|
72782
|
+
const outcome = detail.abandoned === true
|
|
72783
|
+
? `was left by its caller before it could admit the call (wait budget ${waitedMs} ms)`
|
|
72784
|
+
: `did not admit the call within ${waitedMs} ms`;
|
|
72785
|
+
super(`${guard} ${outcome}. ` +
|
|
72727
72786
|
"The provider was never contacted, so this says nothing about its health.");
|
|
72728
72787
|
this.name = "RateGuardTimeoutError";
|
|
72729
72788
|
this.provider = provider;
|
|
72730
72789
|
this.bound = bound;
|
|
72790
|
+
this.modelId = detail.modelId;
|
|
72791
|
+
this.abandoned = detail.abandoned === true;
|
|
72731
72792
|
}
|
|
72732
72793
|
}
|
|
72794
|
+
/**
|
|
72795
|
+
* The guard a call is held by.
|
|
72796
|
+
*
|
|
72797
|
+
* A call to a per-model provider that names no model shares one provider-wide
|
|
72798
|
+
* guard held at the per-model ceiling. That is never looser than the limit of
|
|
72799
|
+
* any single model it might reach, so the fallback errs toward pacing.
|
|
72800
|
+
*
|
|
72801
|
+
* @param provider The provider key.
|
|
72802
|
+
* @param modelId The model the call is addressed to, if known.
|
|
72803
|
+
* @returns The guard's identity.
|
|
72804
|
+
*/
|
|
72805
|
+
function guardIdentity(provider, modelId) {
|
|
72806
|
+
const perModel = limitsFor(provider).scope === "model" && modelId !== undefined && modelId.length > 0;
|
|
72807
|
+
return perModel
|
|
72808
|
+
? { key: `${provider}/${modelId}`, provider, modelId }
|
|
72809
|
+
: { key: provider, provider, modelId: undefined };
|
|
72810
|
+
}
|
|
72733
72811
|
/**
|
|
72734
72812
|
* A counting semaphore bounding simultaneous in-flight calls.
|
|
72735
72813
|
*
|
|
72736
|
-
* Written here rather than pulled from a dependency because
|
|
72737
|
-
*
|
|
72738
|
-
*
|
|
72739
|
-
*
|
|
72814
|
+
* Written here rather than pulled from a dependency because the waiting
|
|
72815
|
+
* behaviour is the point. A waiter that times out must be removed from the
|
|
72816
|
+
* queue, or a burst of abandoned callers permanently consumes the permits that
|
|
72817
|
+
* later callers need. And a waiter whose caller has stopped waiting must leave
|
|
72818
|
+
* at once: left queued, it holds its caller until the wait budget expires and
|
|
72819
|
+
* is then handed a permit it can only waste.
|
|
72740
72820
|
*/
|
|
72741
72821
|
class ConcurrencyGate {
|
|
72742
72822
|
inFlight = 0;
|
|
72743
72823
|
waiters = [];
|
|
72744
72824
|
limit;
|
|
72745
|
-
|
|
72825
|
+
identity;
|
|
72746
72826
|
/**
|
|
72747
|
-
* @param
|
|
72827
|
+
* @param identity The guard this gate implements.
|
|
72748
72828
|
* @param limit Maximum simultaneous in-flight calls.
|
|
72749
72829
|
*/
|
|
72750
|
-
constructor(
|
|
72751
|
-
this.
|
|
72830
|
+
constructor(identity, limit) {
|
|
72831
|
+
this.identity = identity;
|
|
72752
72832
|
this.limit = limit;
|
|
72753
72833
|
}
|
|
72754
72834
|
/**
|
|
72755
72835
|
* Wait for a permit.
|
|
72756
72836
|
*
|
|
72757
72837
|
* @param timeoutMs How long the caller is willing to queue.
|
|
72838
|
+
* @param signal The caller's cancellation; firing it takes the caller out of the queue.
|
|
72758
72839
|
* @returns A release function the caller must invoke exactly once.
|
|
72840
|
+
* @throws {RateGuardTimeoutError} When no permit was granted in time, or the caller stopped waiting.
|
|
72759
72841
|
*/
|
|
72760
|
-
async acquire(timeoutMs) {
|
|
72842
|
+
async acquire(timeoutMs, signal) {
|
|
72843
|
+
if (signal?.aborted === true) {
|
|
72844
|
+
// Nobody is waiting for this answer. Taking a permit for it would spend
|
|
72845
|
+
// capacity a live caller needs on a call that can only be torn down.
|
|
72846
|
+
throw this.refusal(timeoutMs, true);
|
|
72847
|
+
}
|
|
72761
72848
|
if (this.inFlight < this.limit) {
|
|
72762
72849
|
this.inFlight += 1;
|
|
72763
72850
|
return () => this.release();
|
|
72764
72851
|
}
|
|
72765
72852
|
await new Promise((resolve, reject) => {
|
|
72766
|
-
|
|
72767
|
-
|
|
72768
|
-
|
|
72769
|
-
|
|
72853
|
+
/**
|
|
72854
|
+
* Take this waiter out of the queue and refuse it. A waiter that `release`
|
|
72855
|
+
* has already admitted is no longer queued; it now holds a permit, which
|
|
72856
|
+
* its call returns, so there is nothing to undo here.
|
|
72857
|
+
*
|
|
72858
|
+
* @param abandoned Whether the caller left before the wait budget ran out.
|
|
72859
|
+
* @returns void
|
|
72860
|
+
*/
|
|
72861
|
+
const leave = (abandoned) => {
|
|
72862
|
+
const index = this.waiters.indexOf(waiter);
|
|
72863
|
+
if (index === -1) {
|
|
72864
|
+
return;
|
|
72770
72865
|
}
|
|
72771
|
-
|
|
72866
|
+
this.waiters.splice(index, 1);
|
|
72867
|
+
clearTimeout(timer);
|
|
72868
|
+
signal?.removeEventListener("abort", onAbort);
|
|
72869
|
+
reject(this.refusal(timeoutMs, abandoned));
|
|
72870
|
+
};
|
|
72871
|
+
const onAbort = () => {
|
|
72872
|
+
leave(true);
|
|
72873
|
+
};
|
|
72874
|
+
const timer = setTimeout(() => {
|
|
72875
|
+
leave(false);
|
|
72772
72876
|
}, timeoutMs);
|
|
72773
|
-
|
|
72877
|
+
const waiter = {
|
|
72878
|
+
admit: () => {
|
|
72879
|
+
clearTimeout(timer);
|
|
72880
|
+
signal?.removeEventListener("abort", onAbort);
|
|
72881
|
+
resolve();
|
|
72882
|
+
},
|
|
72883
|
+
};
|
|
72884
|
+
this.waiters.push(waiter);
|
|
72885
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
72774
72886
|
});
|
|
72775
72887
|
this.inFlight += 1;
|
|
72776
72888
|
return () => this.release();
|
|
72777
72889
|
}
|
|
72890
|
+
/**
|
|
72891
|
+
* Build the refusal for a caller this gate did not admit.
|
|
72892
|
+
*
|
|
72893
|
+
* @param timeoutMs The wait budget the caller had.
|
|
72894
|
+
* @param abandoned Whether the caller left before the budget ran out.
|
|
72895
|
+
* @returns The error to raise.
|
|
72896
|
+
*/
|
|
72897
|
+
refusal(timeoutMs, abandoned) {
|
|
72898
|
+
return new RateGuardTimeoutError(this.identity.provider, "concurrency", timeoutMs, {
|
|
72899
|
+
modelId: this.identity.modelId,
|
|
72900
|
+
abandoned,
|
|
72901
|
+
});
|
|
72902
|
+
}
|
|
72778
72903
|
/**
|
|
72779
72904
|
* Return a permit and admit the next waiter.
|
|
72780
72905
|
*
|
|
@@ -72784,8 +72909,7 @@ class ConcurrencyGate {
|
|
|
72784
72909
|
this.inFlight -= 1;
|
|
72785
72910
|
const next = this.waiters.shift();
|
|
72786
72911
|
if (next !== undefined) {
|
|
72787
|
-
|
|
72788
|
-
next.resolve();
|
|
72912
|
+
next.admit();
|
|
72789
72913
|
}
|
|
72790
72914
|
}
|
|
72791
72915
|
/**
|
|
@@ -72801,44 +72925,47 @@ class ConcurrencyGate {
|
|
|
72801
72925
|
return this.waiters.length;
|
|
72802
72926
|
}
|
|
72803
72927
|
}
|
|
72804
|
-
/**
|
|
72928
|
+
/** Guards, created on first use and shared process-wide, keyed by {@link GuardIdentity.key}. */
|
|
72805
72929
|
const rateLimiters = new Map();
|
|
72806
72930
|
const concurrencyGates = new Map();
|
|
72931
|
+
const guardIdentities = new Map();
|
|
72807
72932
|
/**
|
|
72808
|
-
* The rate limiter for a
|
|
72933
|
+
* The rate limiter for a guard.
|
|
72809
72934
|
*
|
|
72810
72935
|
* Shared process-wide rather than per-call-site, because the provider's ceiling
|
|
72811
72936
|
* applies to the process as a whole. Per-call-site limiters would each stay
|
|
72812
72937
|
* under the ceiling while their sum sailed past it.
|
|
72813
72938
|
*
|
|
72814
|
-
* @param
|
|
72939
|
+
* @param identity The guard.
|
|
72815
72940
|
* @returns Its limiter.
|
|
72816
72941
|
*/
|
|
72817
|
-
function rateLimiterFor(
|
|
72818
|
-
let limiter = rateLimiters.get(
|
|
72942
|
+
function rateLimiterFor(identity) {
|
|
72943
|
+
let limiter = rateLimiters.get(identity.key);
|
|
72819
72944
|
if (limiter === undefined) {
|
|
72820
|
-
const limits = limitsFor(provider);
|
|
72945
|
+
const limits = limitsFor(identity.provider);
|
|
72821
72946
|
limiter = new TokenBucketRateLimiter({
|
|
72822
72947
|
maxTokens: limits.requests_per_minute,
|
|
72823
72948
|
refillRate: limits.requests_per_minute / SECONDS_PER_MINUTE,
|
|
72824
|
-
label: `llm:${
|
|
72949
|
+
label: `llm:${identity.key}`,
|
|
72825
72950
|
timeoutMs: limits.acquire_timeout_ms,
|
|
72826
72951
|
});
|
|
72827
|
-
rateLimiters.set(
|
|
72952
|
+
rateLimiters.set(identity.key, limiter);
|
|
72953
|
+
guardIdentities.set(identity.key, identity);
|
|
72828
72954
|
}
|
|
72829
72955
|
return limiter;
|
|
72830
72956
|
}
|
|
72831
72957
|
/**
|
|
72832
|
-
* The concurrency gate for a
|
|
72958
|
+
* The concurrency gate for a guard.
|
|
72833
72959
|
*
|
|
72834
|
-
* @param
|
|
72960
|
+
* @param identity The guard.
|
|
72835
72961
|
* @returns Its gate.
|
|
72836
72962
|
*/
|
|
72837
|
-
function concurrencyGateFor(
|
|
72838
|
-
let gate = concurrencyGates.get(
|
|
72963
|
+
function concurrencyGateFor(identity) {
|
|
72964
|
+
let gate = concurrencyGates.get(identity.key);
|
|
72839
72965
|
if (gate === undefined) {
|
|
72840
|
-
gate = new ConcurrencyGate(
|
|
72841
|
-
concurrencyGates.set(
|
|
72966
|
+
gate = new ConcurrencyGate(identity, limitsFor(identity.provider).max_concurrent);
|
|
72967
|
+
concurrencyGates.set(identity.key, gate);
|
|
72968
|
+
guardIdentities.set(identity.key, identity);
|
|
72842
72969
|
}
|
|
72843
72970
|
return gate;
|
|
72844
72971
|
}
|
|
@@ -72860,21 +72987,26 @@ function concurrencyGateFor(provider) {
|
|
|
72860
72987
|
* @param provider The provider key.
|
|
72861
72988
|
* @param call The work to run once admitted.
|
|
72862
72989
|
* @param maxWaitMs Ceiling on queue time; the configured guard timeout applies when lower.
|
|
72990
|
+
* @param scope The model the call addresses, and the caller's cancellation.
|
|
72863
72991
|
* @returns The call's result.
|
|
72864
|
-
* @throws {RateGuardTimeoutError} When neither bound admitted the call in time
|
|
72992
|
+
* @throws {RateGuardTimeoutError} When neither bound admitted the call in time,
|
|
72993
|
+
* or the caller stopped waiting first.
|
|
72865
72994
|
*/
|
|
72866
|
-
async function withProviderGuards(provider, call, maxWaitMs) {
|
|
72995
|
+
async function withProviderGuards(provider, call, maxWaitMs, scope = {}) {
|
|
72867
72996
|
const limits = limitsFor(provider);
|
|
72997
|
+
const identity = guardIdentity(provider, scope.modelId);
|
|
72868
72998
|
const waitBudgetMs = maxWaitMs === undefined
|
|
72869
72999
|
? limits.acquire_timeout_ms
|
|
72870
73000
|
: Math.min(maxWaitMs, limits.acquire_timeout_ms);
|
|
72871
73001
|
try {
|
|
72872
|
-
await rateLimiterFor(
|
|
73002
|
+
await rateLimiterFor(identity).acquire();
|
|
72873
73003
|
}
|
|
72874
73004
|
catch {
|
|
72875
|
-
throw new RateGuardTimeoutError(provider, "rate", waitBudgetMs
|
|
73005
|
+
throw new RateGuardTimeoutError(provider, "rate", waitBudgetMs, {
|
|
73006
|
+
modelId: identity.modelId,
|
|
73007
|
+
});
|
|
72876
73008
|
}
|
|
72877
|
-
const release = await concurrencyGateFor(
|
|
73009
|
+
const release = await concurrencyGateFor(identity).acquire(waitBudgetMs, scope.signal);
|
|
72878
73010
|
try {
|
|
72879
73011
|
return await call();
|
|
72880
73012
|
}
|
|
@@ -72888,16 +73020,20 @@ async function withProviderGuards(provider, call, maxWaitMs) {
|
|
|
72888
73020
|
/**
|
|
72889
73021
|
* Inspect the guards currently in use.
|
|
72890
73022
|
*
|
|
72891
|
-
* @returns A snapshot per
|
|
73023
|
+
* @returns A snapshot per guard that has been used, sorted by guard key.
|
|
72892
73024
|
*/
|
|
72893
73025
|
function guardSnapshots() {
|
|
72894
|
-
|
|
72895
|
-
|
|
72896
|
-
|
|
72897
|
-
const
|
|
72898
|
-
const
|
|
73026
|
+
return [...guardIdentities.values()]
|
|
73027
|
+
.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
|
|
73028
|
+
.map((identity) => {
|
|
73029
|
+
const limits = limitsFor(identity.provider);
|
|
73030
|
+
const limiter = rateLimiters.get(identity.key);
|
|
73031
|
+
const gate = concurrencyGates.get(identity.key);
|
|
72899
73032
|
return {
|
|
72900
|
-
|
|
73033
|
+
key: identity.key,
|
|
73034
|
+
provider: identity.provider,
|
|
73035
|
+
modelId: identity.modelId,
|
|
73036
|
+
scope: limits.scope ?? "provider",
|
|
72901
73037
|
basis: limits.basis,
|
|
72902
73038
|
requestsPerMinute: limits.requests_per_minute,
|
|
72903
73039
|
maxConcurrent: limits.max_concurrent,
|
|
@@ -72922,6 +73058,105 @@ function resetProviderGuards() {
|
|
|
72922
73058
|
}
|
|
72923
73059
|
rateLimiters.clear();
|
|
72924
73060
|
concurrencyGates.clear();
|
|
73061
|
+
guardIdentities.clear();
|
|
73062
|
+
}
|
|
73063
|
+
|
|
73064
|
+
/**
|
|
73065
|
+
* Interpretation of a model's answer to a structured (JSON) request.
|
|
73066
|
+
*
|
|
73067
|
+
* A JSON request is a promise about the answer's SHAPE, and providers keep it
|
|
73068
|
+
* in different ways. An OpenAI-compatible host given `json_object` constrains
|
|
73069
|
+
* its decoder, so its answer is bare JSON. A provider with no schema-less JSON
|
|
73070
|
+
* mode — Anthropic, reached through the gateway, supports structured output
|
|
73071
|
+
* only against a caller-supplied schema — receives nothing but the prompt's
|
|
73072
|
+
* instructions for a `json` request, and a model following them commonly
|
|
73073
|
+
* returns the object inside one markdown code fence. The fence is presentation,
|
|
73074
|
+
* not content: the object inside it is the answer the model gave.
|
|
73075
|
+
*
|
|
73076
|
+
* So exactly ONE enclosing fence is removed before parsing, and nothing else is
|
|
73077
|
+
* forgiven. Prose before or after the fence, two fenced blocks, a fence that
|
|
73078
|
+
* never closes (a truncated answer), and a fence declaring another language all
|
|
73079
|
+
* still fail. Each of those is an answer whose meaning a parser would have to
|
|
73080
|
+
* guess, and a guessed object is a decision made on data no model produced.
|
|
73081
|
+
*
|
|
73082
|
+
* Content that is not fenced is parsed exactly as it always was: JSON cannot
|
|
73083
|
+
* begin with a backtick, so every answer that parsed before this unwrapping
|
|
73084
|
+
* existed takes the same path and yields the same value.
|
|
73085
|
+
*
|
|
73086
|
+
* @module llm/structured-content
|
|
73087
|
+
*/
|
|
73088
|
+
/**
|
|
73089
|
+
* One markdown fence enclosing the whole answer: an opening line of three
|
|
73090
|
+
* backticks, optionally labelled `json`, then the body, then three closing
|
|
73091
|
+
* backticks, with nothing but whitespace outside them. The body is anchored at
|
|
73092
|
+
* both ends, so an answer holding two fenced blocks captures the text between
|
|
73093
|
+
* them and fails to parse instead of yielding either block.
|
|
73094
|
+
*/
|
|
73095
|
+
const SINGLE_ENCLOSING_JSON_FENCE = /^\s*```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n?[ \t]*```\s*$/i;
|
|
73096
|
+
/**
|
|
73097
|
+
* Thrown when a provider answered a structured request with content that does
|
|
73098
|
+
* not parse.
|
|
73099
|
+
*
|
|
73100
|
+
* Carries the usage the provider billed for that answer. The tokens were spent
|
|
73101
|
+
* whether or not the content parsed, and a chain that dropped them would report
|
|
73102
|
+
* a failed attempt as free — understating spend by exactly the calls that went
|
|
73103
|
+
* wrong.
|
|
73104
|
+
*/
|
|
73105
|
+
class LlmResponseFormatError extends Error {
|
|
73106
|
+
/** The format the caller asked for. */
|
|
73107
|
+
responseFormat;
|
|
73108
|
+
/** What the provider billed for the answer that did not parse. */
|
|
73109
|
+
usage;
|
|
73110
|
+
/** Whether the answer sat inside one enclosing fence that was removed before parsing. */
|
|
73111
|
+
fenced;
|
|
73112
|
+
/**
|
|
73113
|
+
* @param responseFormat The format the caller asked for.
|
|
73114
|
+
* @param usage What the provider billed for the answer.
|
|
73115
|
+
* @param fenced Whether one enclosing fence was removed before parsing.
|
|
73116
|
+
* @param cause The parser's own complaint.
|
|
73117
|
+
*/
|
|
73118
|
+
constructor(responseFormat, usage, fenced, cause) {
|
|
73119
|
+
super(`LLM returned content that is not valid JSON for a ${responseFormat} request` +
|
|
73120
|
+
(fenced ? " (inside one enclosing markdown fence)" : "") +
|
|
73121
|
+
`: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
73122
|
+
this.name = "LlmResponseFormatError";
|
|
73123
|
+
this.responseFormat = responseFormat;
|
|
73124
|
+
this.usage = usage;
|
|
73125
|
+
this.fenced = fenced;
|
|
73126
|
+
}
|
|
73127
|
+
}
|
|
73128
|
+
/**
|
|
73129
|
+
* The body of the one markdown fence that encloses an answer, if exactly one does.
|
|
73130
|
+
*
|
|
73131
|
+
* @param text The model's answer.
|
|
73132
|
+
* @returns The fenced body, or null when the answer is not wholly one fenced block.
|
|
73133
|
+
*/
|
|
73134
|
+
function unwrapSingleJsonFence(text) {
|
|
73135
|
+
const match = SINGLE_ENCLOSING_JSON_FENCE.exec(text);
|
|
73136
|
+
return match === null ? null : match[1];
|
|
73137
|
+
}
|
|
73138
|
+
/**
|
|
73139
|
+
* Parse a model's answer to a structured request.
|
|
73140
|
+
*
|
|
73141
|
+
* A JSON format that does not parse is an error, not an empty object. Returning
|
|
73142
|
+
* a default here would hand the caller a well-typed value that means nothing,
|
|
73143
|
+
* and the failure would surface much later as a decision made on absent data.
|
|
73144
|
+
*
|
|
73145
|
+
* @param content The raw content of the model's message.
|
|
73146
|
+
* @param responseFormat The structured format the caller asked for.
|
|
73147
|
+
* @param usage What the provider billed for this answer, carried on failure.
|
|
73148
|
+
* @returns The parsed value.
|
|
73149
|
+
* @throws {LlmResponseFormatError} When the content is not JSON, fenced or not.
|
|
73150
|
+
*/
|
|
73151
|
+
function parseStructuredContent(content, responseFormat, usage) {
|
|
73152
|
+
const text = typeof content === "string" ? content : "";
|
|
73153
|
+
const fencedBody = unwrapSingleJsonFence(text);
|
|
73154
|
+
try {
|
|
73155
|
+
return JSON.parse(fencedBody ?? text);
|
|
73156
|
+
}
|
|
73157
|
+
catch (error) {
|
|
73158
|
+
throw new LlmResponseFormatError(typeof responseFormat === "string" ? responseFormat : "json_schema", usage, fencedBody !== null, error);
|
|
73159
|
+
}
|
|
72925
73160
|
}
|
|
72926
73161
|
|
|
72927
73162
|
/**
|
|
@@ -73058,7 +73293,9 @@ async function runLeg(leg, params, execution) {
|
|
|
73058
73293
|
// The guards wrap the transport rather than the whole leg, so the per-leg
|
|
73059
73294
|
// timeout above still bounds the total wait: a caller queued behind the
|
|
73060
73295
|
// rate limiter is spending its budget just as surely as one waiting on the
|
|
73061
|
-
// provider, and only one clock should govern both.
|
|
73296
|
+
// provider, and only one clock should govern both. The leg's own signal is
|
|
73297
|
+
// handed to the guard as well, so a leg whose budget or caller is gone
|
|
73298
|
+
// leaves the queue at once instead of holding its place in it.
|
|
73062
73299
|
return await withProviderGuards(leg.route.providerName, () => leg.transport.execute({
|
|
73063
73300
|
route: leg.route,
|
|
73064
73301
|
content: execution.content,
|
|
@@ -73068,7 +73305,7 @@ async function runLeg(leg, params, execution) {
|
|
|
73068
73305
|
context: execution.context,
|
|
73069
73306
|
signal: controller.signal,
|
|
73070
73307
|
correlationId: execution.correlationId,
|
|
73071
|
-
}), budgetMs);
|
|
73308
|
+
}), budgetMs, { modelId: leg.route.modelId, signal: controller.signal });
|
|
73072
73309
|
}
|
|
73073
73310
|
finally {
|
|
73074
73311
|
clearTimeout(timer);
|
|
@@ -73180,7 +73417,7 @@ async function executeChain(alias, execution) {
|
|
|
73180
73417
|
continue;
|
|
73181
73418
|
}
|
|
73182
73419
|
const startedAt = now();
|
|
73183
|
-
execution.breakers.onAttemptStart(route.routeKey);
|
|
73420
|
+
const holdsProbe = execution.breakers.onAttemptStart(route.routeKey);
|
|
73184
73421
|
try {
|
|
73185
73422
|
const response = await runLeg(leg, leg.params, execution);
|
|
73186
73423
|
execution.breakers.onSuccess(route.routeKey);
|
|
@@ -73203,6 +73440,15 @@ async function executeChain(alias, execution) {
|
|
|
73203
73440
|
if (countsAgainstHealth) {
|
|
73204
73441
|
execution.breakers.onFailure(route.routeKey);
|
|
73205
73442
|
}
|
|
73443
|
+
else if (holdsProbe) {
|
|
73444
|
+
// No verdict on the route's health, but the probe slot this attempt
|
|
73445
|
+
// took must come back, or a half-open route admits no probe ever again.
|
|
73446
|
+
execution.breakers.onAttemptAbandoned(route.routeKey);
|
|
73447
|
+
}
|
|
73448
|
+
// A provider that answered with unparseable content still billed for the
|
|
73449
|
+
// answer; the spend belongs in the total whether or not a later leg serves.
|
|
73450
|
+
const billed = error instanceof LlmResponseFormatError ? error.usage : undefined;
|
|
73451
|
+
totalUsage = sumUsage(totalUsage, billed);
|
|
73206
73452
|
const record = {
|
|
73207
73453
|
routeKey: route.routeKey,
|
|
73208
73454
|
role: route.role,
|
|
@@ -73211,6 +73457,7 @@ async function executeChain(alias, execution) {
|
|
|
73211
73457
|
outcome,
|
|
73212
73458
|
durationMs: now() - startedAt,
|
|
73213
73459
|
reason,
|
|
73460
|
+
...(billed === undefined ? {} : { usage: billed }),
|
|
73214
73461
|
};
|
|
73215
73462
|
attempts.push(record);
|
|
73216
73463
|
execution.onAttempt?.(record);
|
|
@@ -74504,9 +74751,13 @@ function createGatewayTransport(config) {
|
|
|
74504
74751
|
const payload = (await response.json());
|
|
74505
74752
|
const choices = payload.choices;
|
|
74506
74753
|
const message = choices?.[0]?.message;
|
|
74754
|
+
// Usage is read before the content is interpreted. The provider billed for
|
|
74755
|
+
// this answer whether or not it parses, and a parse failure that dropped
|
|
74756
|
+
// the count would report the attempt as free.
|
|
74757
|
+
const usage = readUsage(payload, request);
|
|
74507
74758
|
return {
|
|
74508
|
-
response:
|
|
74509
|
-
usage
|
|
74759
|
+
response: interpretContent(message?.content, request.responseFormat, usage),
|
|
74760
|
+
usage,
|
|
74510
74761
|
tool_calls: Array.isArray(message?.tool_calls)
|
|
74511
74762
|
? message.tool_calls
|
|
74512
74763
|
: undefined,
|
|
@@ -74541,25 +74792,22 @@ function buildMessages(request) {
|
|
|
74541
74792
|
/**
|
|
74542
74793
|
* Interpret the model's content according to the requested format.
|
|
74543
74794
|
*
|
|
74544
|
-
*
|
|
74545
|
-
*
|
|
74546
|
-
*
|
|
74795
|
+
* Text is returned as sent. A structured format is parsed under the strict
|
|
74796
|
+
* single-fence rule of {@link parseStructuredContent}; a structured answer that
|
|
74797
|
+
* does not parse is an error carrying what the provider billed for it, never an
|
|
74798
|
+
* empty object.
|
|
74547
74799
|
*
|
|
74548
74800
|
* @param content The raw content.
|
|
74549
74801
|
* @param responseFormat The format the caller asked for.
|
|
74550
|
-
* @
|
|
74802
|
+
* @param usage What the provider billed for this answer.
|
|
74803
|
+
* @returns The interpreted value.
|
|
74804
|
+
* @throws {LlmResponseFormatError} When a structured answer does not parse.
|
|
74551
74805
|
*/
|
|
74552
|
-
function
|
|
74553
|
-
const text = typeof content === "string" ? content : "";
|
|
74806
|
+
function interpretContent(content, responseFormat, usage) {
|
|
74554
74807
|
if (responseFormat === "text") {
|
|
74555
|
-
return
|
|
74556
|
-
}
|
|
74557
|
-
try {
|
|
74558
|
-
return JSON.parse(text);
|
|
74559
|
-
}
|
|
74560
|
-
catch (error) {
|
|
74561
|
-
throw new Error(`LLM returned content that is not valid JSON for a ${typeof responseFormat === "string" ? responseFormat : "json_schema"} request: ${error instanceof Error ? error.message : String(error)}`);
|
|
74808
|
+
return (typeof content === "string" ? content : "");
|
|
74562
74809
|
}
|
|
74810
|
+
return parseStructuredContent(content, responseFormat, usage);
|
|
74563
74811
|
}
|
|
74564
74812
|
|
|
74565
74813
|
/**
|
|
@@ -78654,6 +78902,7 @@ const OrderStatusSchema = enumType([
|
|
|
78654
78902
|
"accepted",
|
|
78655
78903
|
"pending_new",
|
|
78656
78904
|
"accepted_for_bidding",
|
|
78905
|
+
"held",
|
|
78657
78906
|
"stopped",
|
|
78658
78907
|
"rejected",
|
|
78659
78908
|
"suspended",
|
|
@@ -80263,5 +80512,5 @@ const adaptic = {
|
|
|
80263
80512
|
};
|
|
80264
80513
|
const adptc = adaptic;
|
|
80265
80514
|
|
|
80266
|
-
export { API_RETRY_CONFIGS, AVNewsArticleSchema, AVNewsResponseSchema, AdapticUtilsError, AlpacaAccountDetailsSchema, AlpacaApiError, AlpacaBarSchema, AlpacaClient, AlpacaCryptoBarsResponseSchema, AlpacaHistoricalBarsResponseSchema, AlpacaLatestBarsResponseSchema, AlpacaLatestQuotesResponseSchema, AlpacaLatestTradesResponseSchema, AlpacaMarketDataAPI, AlpacaNewsArticleSchema, AlpacaNewsResponseSchema, AlpacaOrderSchema, AlpacaOrdersArraySchema, AlpacaPortfolioHistoryResponseSchema, AlpacaPositionSchema, AlpacaPositionsArraySchema, AlpacaQuoteSchema, AlpacaTradeSchema, AlpacaTradingAPI, AlphaVantageError, AlphaVantageQuoteResponseSchema, AssetAllocationEngine, AuthenticationError, AutonomyMode, BTC_PAIRS, BarError, ChainExhaustedError, CircuitBreakerRegistry, CircuitOpenError, CryptoDataError, CryptoOrderError, DEFAULT_CACHE_OPTIONS, DEFAULT_RISK_FREE_RATE, DEFAULT_TIMEOUTS, DEFAULT_TRADING_POLICY, DataFormatError, DecisionMemoryOutcome, DecisionOutcome, DecisionRecordStatus, DirectTransportRefusedError, DuplicateClientOrderIdError, GatewayResponseError, GatewayUnreachableError, HttpClientError, HttpServerError, KEEP_ALIVE_DEFAULTS, LlmProvider, MARKET_DATA_API, MassiveAggregatesResponseSchema, MassiveApiError, MassiveDailyOpenCloseSchema, MassiveErrorResponseSchema, MassiveGroupedDailyResponseSchema, MassiveLastTradeResponseSchema, MassiveTickerDetailsResponseSchema, MassiveTickerInfoSchema, MassiveTradeSchema as MassiveTradeZodSchema, MassiveTradesResponseSchema, NetworkError, NewsError, NoServableRouteError, OptionStrategyError, OptionsDataError, OverlaySeverity, OverlayStatus, OverlayType, QuoteError, RISK_FREE_RATE_TTL_MS, RateGuardTimeoutError, RateLimitError, RawMassivePriceDataSchema, SchemaRetryExhaustedError, StampedeProtectedCache, StreamProviderError, StreamTruncatedError, TRADING_API, TimeoutError, TokenBucketRateLimiter, TradeError, TrailingStopValidationError, USDC_PAIRS, USDT_PAIRS, USD_PAIRS, UnknownAliasError, UnsupportedBrokerError, UnsupportedCapabilityError, ValidationError, ValidationResponseError, WEBSOCKET_STREAMS, WebSocketError, account, adaptic, adptc, alpaca, analyzeBars, approximateImpliedVolatility, atrNs as atr, availableStatistic, bracketOrders, buildOCCSymbol, buildOptionSymbol, buildRetryPrompt, buyCryptoNotional, buyToClose, buyToOpen, buyWithStopLoss, buyWithTrailingStop, calculateMoneyness, calculateOrderValue, calculatePeriodPerformance, calculatePutCallRatio, calculateTotalFilledValue, callLLMByAlias, callWithValidation, cancelAllCryptoOrders, cancelOCOOrder, cancelOTOOrder, cancelTrailingStop, cancelTrailingStopsForSymbol, checkTradingEligibility, clearClientCache, clock, closeAllOptionPositions, closeOptionPosition, closedIncumbentLeg, collectStream, configureLlmClient, createAlpacaClient, createAlpacaMarketDataAPI, createAlpacaTradingAPI, createBracketOrder, createBrokerClient, createButterflySpread, createClientFromEnv, createCoveredCall, createCryptoLimitOrder, createCryptoMarketOrder, createCryptoOrder, createCryptoStopLimitOrder, createCryptoStopOrder, createDirectTransport, createExecutorFromTradingAPI, createGatewayTransport, createIronCondor$1 as createIronCondor, createIronCondor as createIronCondorAdvanced, createMultiLegOptionOrder, createOCOOrder, createOTOOrder, createOptionOrder, createPortfolioTrailingStops, createProtectiveBracket, createStampedeProtectedCache, createStraddle$1 as createStraddle, createStraddle as createStraddleAdvanced, createStrangle$1 as createStrangle, createStrangle as createStrangleAdvanced, createStreamManager, createTimeoutSignal, createTrailingStop, createVerticalSpread$1 as createVerticalSpread, createVerticalSpread as createVerticalSpreadAdvanced, enrichAlpacaError, entryWithPercentStopLoss, exerciseOption, extractAlpacaBrokerError, extractGreeks, filterByExpiration, filterByStrike, filterByType, filterOrdersByDateRange, findATMOptions, findATMStrikes, findNearestExpiration, findOptionsByDelta, formatOrderForLog, formatOrderSummary, gatewayModelNameFor, generateOptimalAllocation, getAccountConfiguration, getAccountDetails, getAccountSummary, getAgentPoolStatus, getAllOrders, getAlpacaBrokerErrorCode, getAlpacaBrokerErrorDetail, getAlpacaCalendar, getAlpacaClock, getAverageDailyVolume, getBars, getBuyingPower, getCachedRiskFreeRateSync, getCachedRiskFreeRateSyncWithProvenance, getCrypto24HourChange, getCryptoBars, getCryptoDailyPrices, getCryptoPairsByQuote, getCryptoPrice, getCryptoSnapshots, getCryptoSpread, getCryptoStreamUrl, getCryptoTrades, getCurrentPrice, getCurrentPrices, getDailyPrices, getDailyReturns, getDaysToExpiration, getDefaultRiskProfile, getEquityCurve, getExpirationDates, getFilledOrders, getGroupedOptionChain, getHistoricalOptionsBars, getHistoricalTrades, getIntradayPrices, getLatestBars, getLatestCryptoQuotes, getLatestCryptoTrades, getLatestNews, getLatestOptionsQuotes, getLatestOptionsTrades, getLatestQuote, getLatestQuotes, getLatestTrade, getLatestTrades, getLogger, getMarginInfo, getNews, getNewsForSymbols, getOCOOrderStatus, getOTOOrderStatus, getOpenCryptoOrders, getOpenOrders$1 as getOpenOrdersQuery, getOpenTrailingStops, getOptionChain, getOptionContract, getOptionContracts, getOptionSpread, getOptionsChain, getOptionsSnapshots, getOptionsStreamUrl, getOptionsTradingLevel, getOrderHistory, getOrdersBySymbol, getPDTStatus, getPopularCryptoPairs, getPortfolioHistory, getPreviousClose, getPriceRange, getRiskFreeRate, getRiskFreeRateWithProvenance, getSpread, getSpreads, getStockStreamUrl, getStrikePrices, getSupportedCryptoPairs, getSymbolSentiment, getTimeout, getTradeVolume, getTradingApiUrl, getTradingWebSocketUrl, getTrailingStopHWM, groupOrdersByStatus, groupOrdersBySymbol, guardSnapshots, hasActiveTrailingStop, hasGoodLiquidity as hasOptionLiquidity, hasGoodLiquidity$1 as hasStockLiquidity, hasSufficientVolume, httpAgent, httpsAgent, isAlpacaBrokerCredentials, isAvailable, isContractTradable, isCryptoPair, isExpiringWithin, isMarginAccount, isOptionOrderCancelable, isOptionOrderTerminal, isOrderFillable, isOrderFilled, isOrderOpen, isOrderTerminal$1 as isOrderTerminalStatus, isSupportedCryptoPair, isTransientNetworkError, index$1 as legacyApi, limitBuyWithTakeProfit, limitsFor, limitsInventory, listAliases, llmAliases, llmBreakers, normaliseAnthropicStream, normaliseOpenAiStream, normaliseParams, normaliseStream, ocoOrders, orderUtils, orderedRoutes, otoOrders, paginate, paginateAll, parseOCCSymbol, protectLongPosition, protectShortPosition, rateLimiters$1 as rateLimiters, resetLogger, resetProviderGuards, resetRiskFreeRateCache, resolveChain, resolveDefaultDirectCaller, riskNs as risk, rollOptionPosition, roundPriceForAlpaca$3 as roundPriceForAlpaca, roundPriceForAlpacaNumber, routeKeyFor, routeSupports, routeTable, safeValidateResponse, sampleCohort, searchNews, sellAllCrypto, sellCryptoNotional, sellToClose, sellToOpen, setLogger, setRiskFreeRate, shortWithStopLoss, sortOrdersByDate, strategyNs as strategy, sumUsage, index as tradingPolicy, trailingStops, unavailableStatistic, updateAccountConfiguration, updateTrailingStop, validateAlpacaCredentials, validateAlphaVantageApiKey, validateMassiveApiKey$1 as validateMassiveApiKey, validateMultiLegOrder, validateResponse, verifyFetchKeepAlive, volatilityNs as volatility, waitForOrderFill, withProviderGuards, withRetry, withTimeout };
|
|
80515
|
+
export { API_RETRY_CONFIGS, AVNewsArticleSchema, AVNewsResponseSchema, AdapticUtilsError, AlpacaAccountDetailsSchema, AlpacaApiError, AlpacaBarSchema, AlpacaClient, AlpacaCryptoBarsResponseSchema, AlpacaHistoricalBarsResponseSchema, AlpacaLatestBarsResponseSchema, AlpacaLatestQuotesResponseSchema, AlpacaLatestTradesResponseSchema, AlpacaMarketDataAPI, AlpacaNewsArticleSchema, AlpacaNewsResponseSchema, AlpacaOrderSchema, AlpacaOrdersArraySchema, AlpacaPortfolioHistoryResponseSchema, AlpacaPositionSchema, AlpacaPositionsArraySchema, AlpacaQuoteSchema, AlpacaTradeSchema, AlpacaTradingAPI, AlphaVantageError, AlphaVantageQuoteResponseSchema, AssetAllocationEngine, AuthenticationError, AutonomyMode, BTC_PAIRS, BarError, ChainExhaustedError, CircuitBreakerRegistry, CircuitOpenError, CryptoDataError, CryptoOrderError, DEFAULT_CACHE_OPTIONS, DEFAULT_RISK_FREE_RATE, DEFAULT_TIMEOUTS, DEFAULT_TRADING_POLICY, DataFormatError, DecisionMemoryOutcome, DecisionOutcome, DecisionRecordStatus, DirectTransportRefusedError, DuplicateClientOrderIdError, GatewayResponseError, GatewayUnreachableError, HttpClientError, HttpServerError, KEEP_ALIVE_DEFAULTS, LlmProvider, LlmResponseFormatError, MARKET_DATA_API, MassiveAggregatesResponseSchema, MassiveApiError, MassiveDailyOpenCloseSchema, MassiveErrorResponseSchema, MassiveGroupedDailyResponseSchema, MassiveLastTradeResponseSchema, MassiveTickerDetailsResponseSchema, MassiveTickerInfoSchema, MassiveTradeSchema as MassiveTradeZodSchema, MassiveTradesResponseSchema, NetworkError, NewsError, NoServableRouteError, OptionStrategyError, OptionsDataError, OverlaySeverity, OverlayStatus, OverlayType, QuoteError, RISK_FREE_RATE_TTL_MS, RateGuardTimeoutError, RateLimitError, RawMassivePriceDataSchema, SchemaRetryExhaustedError, StampedeProtectedCache, StreamProviderError, StreamTruncatedError, TRADING_API, TimeoutError, TokenBucketRateLimiter, TradeError, TrailingStopValidationError, USDC_PAIRS, USDT_PAIRS, USD_PAIRS, UnknownAliasError, UnsupportedBrokerError, UnsupportedCapabilityError, ValidationError, ValidationResponseError, WEBSOCKET_STREAMS, WebSocketError, account, adaptic, adptc, alpaca, analyzeBars, approximateImpliedVolatility, atrNs as atr, availableStatistic, bracketOrders, buildOCCSymbol, buildOptionSymbol, buildRetryPrompt, buyCryptoNotional, buyToClose, buyToOpen, buyWithStopLoss, buyWithTrailingStop, calculateMoneyness, calculateOrderValue, calculatePeriodPerformance, calculatePutCallRatio, calculateTotalFilledValue, callLLMByAlias, callWithValidation, cancelAllCryptoOrders, cancelOCOOrder, cancelOTOOrder, cancelTrailingStop, cancelTrailingStopsForSymbol, checkTradingEligibility, clearClientCache, clock, closeAllOptionPositions, closeOptionPosition, closedIncumbentLeg, collectStream, configureLlmClient, createAlpacaClient, createAlpacaMarketDataAPI, createAlpacaTradingAPI, createBracketOrder, createBrokerClient, createButterflySpread, createClientFromEnv, createCoveredCall, createCryptoLimitOrder, createCryptoMarketOrder, createCryptoOrder, createCryptoStopLimitOrder, createCryptoStopOrder, createDirectTransport, createExecutorFromTradingAPI, createGatewayTransport, createIronCondor$1 as createIronCondor, createIronCondor as createIronCondorAdvanced, createMultiLegOptionOrder, createOCOOrder, createOTOOrder, createOptionOrder, createPortfolioTrailingStops, createProtectiveBracket, createStampedeProtectedCache, createStraddle$1 as createStraddle, createStraddle as createStraddleAdvanced, createStrangle$1 as createStrangle, createStrangle as createStrangleAdvanced, createStreamManager, createTimeoutSignal, createTrailingStop, createVerticalSpread$1 as createVerticalSpread, createVerticalSpread as createVerticalSpreadAdvanced, enrichAlpacaError, entryWithPercentStopLoss, exerciseOption, extractAlpacaBrokerError, extractGreeks, filterByExpiration, filterByStrike, filterByType, filterOrdersByDateRange, findATMOptions, findATMStrikes, findNearestExpiration, findOptionsByDelta, formatOrderForLog, formatOrderSummary, gatewayModelNameFor, generateOptimalAllocation, getAccountConfiguration, getAccountDetails, getAccountSummary, getAgentPoolStatus, getAllOrders, getAlpacaBrokerErrorCode, getAlpacaBrokerErrorDetail, getAlpacaCalendar, getAlpacaClock, getAverageDailyVolume, getBars, getBuyingPower, getCachedRiskFreeRateSync, getCachedRiskFreeRateSyncWithProvenance, getCrypto24HourChange, getCryptoBars, getCryptoDailyPrices, getCryptoPairsByQuote, getCryptoPrice, getCryptoSnapshots, getCryptoSpread, getCryptoStreamUrl, getCryptoTrades, getCurrentPrice, getCurrentPrices, getDailyPrices, getDailyReturns, getDaysToExpiration, getDefaultRiskProfile, getEquityCurve, getExpirationDates, getFilledOrders, getGroupedOptionChain, getHistoricalOptionsBars, getHistoricalTrades, getIntradayPrices, getLatestBars, getLatestCryptoQuotes, getLatestCryptoTrades, getLatestNews, getLatestOptionsQuotes, getLatestOptionsTrades, getLatestQuote, getLatestQuotes, getLatestTrade, getLatestTrades, getLogger, getMarginInfo, getNews, getNewsForSymbols, getOCOOrderStatus, getOTOOrderStatus, getOpenCryptoOrders, getOpenOrders$1 as getOpenOrdersQuery, getOpenTrailingStops, getOptionChain, getOptionContract, getOptionContracts, getOptionSpread, getOptionsChain, getOptionsSnapshots, getOptionsStreamUrl, getOptionsTradingLevel, getOrderHistory, getOrdersBySymbol, getPDTStatus, getPopularCryptoPairs, getPortfolioHistory, getPreviousClose, getPriceRange, getRiskFreeRate, getRiskFreeRateWithProvenance, getSpread, getSpreads, getStockStreamUrl, getStrikePrices, getSupportedCryptoPairs, getSymbolSentiment, getTimeout, getTradeVolume, getTradingApiUrl, getTradingWebSocketUrl, getTrailingStopHWM, groupOrdersByStatus, groupOrdersBySymbol, guardSnapshots, hasActiveTrailingStop, hasGoodLiquidity as hasOptionLiquidity, hasGoodLiquidity$1 as hasStockLiquidity, hasSufficientVolume, httpAgent, httpsAgent, isAlpacaBrokerCredentials, isAvailable, isContractTradable, isCryptoPair, isExpiringWithin, isMarginAccount, isOptionOrderCancelable, isOptionOrderTerminal, isOrderFillable, isOrderFilled, isOrderOpen, isOrderTerminal$1 as isOrderTerminalStatus, isSupportedCryptoPair, isTransientNetworkError, index$1 as legacyApi, limitBuyWithTakeProfit, limitsFor, limitsInventory, listAliases, llmAliases, llmBreakers, normaliseAnthropicStream, normaliseOpenAiStream, normaliseParams, normaliseStream, ocoOrders, orderUtils, orderedRoutes, otoOrders, paginate, paginateAll, parseOCCSymbol, protectLongPosition, protectShortPosition, rateLimiters$1 as rateLimiters, resetLogger, resetProviderGuards, resetRiskFreeRateCache, resolveChain, resolveDefaultDirectCaller, riskNs as risk, rollOptionPosition, roundPriceForAlpaca$3 as roundPriceForAlpaca, roundPriceForAlpacaNumber, routeKeyFor, routeSupports, routeTable, safeValidateResponse, sampleCohort, searchNews, sellAllCrypto, sellCryptoNotional, sellToClose, sellToOpen, setLogger, setRiskFreeRate, shortWithStopLoss, sortOrdersByDate, strategyNs as strategy, sumUsage, index as tradingPolicy, trailingStops, unavailableStatistic, updateAccountConfiguration, updateTrailingStop, validateAlpacaCredentials, validateAlphaVantageApiKey, validateMassiveApiKey$1 as validateMassiveApiKey, validateMultiLegOrder, validateResponse, verifyFetchKeepAlive, volatilityNs as volatility, waitForOrderFill, withProviderGuards, withRetry, withTimeout };
|
|
80267
80516
|
//# sourceMappingURL=index.mjs.map
|