@adaptic/utils 0.0.1014 → 0.0.1016

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/dist/index.cjs +2823 -25
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.mjs +2783 -25
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/types/__tests__/llm/client/support/rejections.d.ts +21 -0
  6. package/dist/types/__tests__/llm/client/support/rejections.d.ts.map +1 -0
  7. package/dist/types/__tests__/llm/client/support/routes.d.ts +67 -0
  8. package/dist/types/__tests__/llm/client/support/routes.d.ts.map +1 -0
  9. package/dist/types/__tests__/llm/client/support/streams.d.ts +74 -0
  10. package/dist/types/__tests__/llm/client/support/streams.d.ts.map +1 -0
  11. package/dist/types/__tests__/llm/client/support/transports.d.ts +105 -0
  12. package/dist/types/__tests__/llm/client/support/transports.d.ts.map +1 -0
  13. package/dist/types/index.d.ts +1 -0
  14. package/dist/types/index.d.ts.map +1 -1
  15. package/dist/types/llm/alias-client.d.ts +64 -0
  16. package/dist/types/llm/alias-client.d.ts.map +1 -0
  17. package/dist/types/llm/circuit-breaker.d.ts +124 -0
  18. package/dist/types/llm/circuit-breaker.d.ts.map +1 -0
  19. package/dist/types/llm/eval/comparators.d.ts +127 -0
  20. package/dist/types/llm/eval/comparators.d.ts.map +1 -0
  21. package/dist/types/llm/eval/coverage.d.ts +44 -0
  22. package/dist/types/llm/eval/coverage.d.ts.map +1 -0
  23. package/dist/types/llm/eval/golden-set.d.ts +47 -0
  24. package/dist/types/llm/eval/golden-set.d.ts.map +1 -0
  25. package/dist/types/llm/eval/index.d.ts +25 -0
  26. package/dist/types/llm/eval/index.d.ts.map +1 -0
  27. package/dist/types/llm/eval/json-shape.d.ts +74 -0
  28. package/dist/types/llm/eval/json-shape.d.ts.map +1 -0
  29. package/dist/types/llm/eval/judge.d.ts +131 -0
  30. package/dist/types/llm/eval/judge.d.ts.map +1 -0
  31. package/dist/types/llm/eval/metrics.d.ts +51 -0
  32. package/dist/types/llm/eval/metrics.d.ts.map +1 -0
  33. package/dist/types/llm/eval/run.d.ts +97 -0
  34. package/dist/types/llm/eval/run.d.ts.map +1 -0
  35. package/dist/types/llm/eval/types.d.ts +242 -0
  36. package/dist/types/llm/eval/types.d.ts.map +1 -0
  37. package/dist/types/llm/fallback-chain.d.ts +97 -0
  38. package/dist/types/llm/fallback-chain.d.ts.map +1 -0
  39. package/dist/types/llm/index.d.ts +30 -0
  40. package/dist/types/llm/index.d.ts.map +1 -0
  41. package/dist/types/llm/param-matrix.d.ts +65 -0
  42. package/dist/types/llm/param-matrix.d.ts.map +1 -0
  43. package/dist/types/llm/rate-guard.d.ts +119 -0
  44. package/dist/types/llm/rate-guard.d.ts.map +1 -0
  45. package/dist/types/llm/route-table.d.ts +155 -0
  46. package/dist/types/llm/route-table.d.ts.map +1 -0
  47. package/dist/types/llm/schema-retry.d.ts +80 -0
  48. package/dist/types/llm/schema-retry.d.ts.map +1 -0
  49. package/dist/types/llm/streaming.d.ts +93 -0
  50. package/dist/types/llm/streaming.d.ts.map +1 -0
  51. package/dist/types/llm/transports/direct.d.ts +92 -0
  52. package/dist/types/llm/transports/direct.d.ts.map +1 -0
  53. package/dist/types/llm/transports/gateway.d.ts +73 -0
  54. package/dist/types/llm/transports/gateway.d.ts.map +1 -0
  55. package/dist/types/llm/types.d.ts +292 -0
  56. package/dist/types/llm/types.d.ts.map +1 -0
  57. package/dist/types/schemas/alpaca-schemas.d.ts +6 -6
  58. package/package.json +2 -2
  59. package/dist/types/__tests__/alpaca-broker-error-preservation.test.d.ts +0 -2
  60. package/dist/types/__tests__/alpaca-broker-error-preservation.test.d.ts.map +0 -1
  61. package/dist/types/__tests__/alpaca-client-order-id.test.d.ts +0 -2
  62. package/dist/types/__tests__/alpaca-client-order-id.test.d.ts.map +0 -1
  63. package/dist/types/__tests__/alpaca-functions.test.d.ts +0 -2
  64. package/dist/types/__tests__/alpaca-functions.test.d.ts.map +0 -1
  65. package/dist/types/__tests__/alpaca-market-data-retry.test.d.ts +0 -2
  66. package/dist/types/__tests__/alpaca-market-data-retry.test.d.ts.map +0 -1
  67. package/dist/types/__tests__/alpaca-order-idempotency.test.d.ts +0 -2
  68. package/dist/types/__tests__/alpaca-order-idempotency.test.d.ts.map +0 -1
  69. package/dist/types/__tests__/alpaca-trading-api.test.d.ts +0 -2
  70. package/dist/types/__tests__/alpaca-trading-api.test.d.ts.map +0 -1
  71. package/dist/types/__tests__/api-endpoints.test.d.ts +0 -2
  72. package/dist/types/__tests__/api-endpoints.test.d.ts.map +0 -1
  73. package/dist/types/__tests__/asset-allocation.test.d.ts +0 -2
  74. package/dist/types/__tests__/asset-allocation.test.d.ts.map +0 -1
  75. package/dist/types/__tests__/atr.test.d.ts +0 -2
  76. package/dist/types/__tests__/atr.test.d.ts.map +0 -1
  77. package/dist/types/__tests__/auth-validator.test.d.ts +0 -2
  78. package/dist/types/__tests__/auth-validator.test.d.ts.map +0 -1
  79. package/dist/types/__tests__/broker-factory.test.d.ts +0 -2
  80. package/dist/types/__tests__/broker-factory.test.d.ts.map +0 -1
  81. package/dist/types/__tests__/broker-types.test.d.ts +0 -2
  82. package/dist/types/__tests__/broker-types.test.d.ts.map +0 -1
  83. package/dist/types/__tests__/cache.test.d.ts +0 -2
  84. package/dist/types/__tests__/cache.test.d.ts.map +0 -1
  85. package/dist/types/__tests__/errors.test.d.ts +0 -2
  86. package/dist/types/__tests__/errors.test.d.ts.map +0 -1
  87. package/dist/types/__tests__/financial-regression.test.d.ts +0 -2
  88. package/dist/types/__tests__/financial-regression.test.d.ts.map +0 -1
  89. package/dist/types/__tests__/format-tools.test.d.ts +0 -2
  90. package/dist/types/__tests__/format-tools.test.d.ts.map +0 -1
  91. package/dist/types/__tests__/http-keep-alive.test.d.ts +0 -2
  92. package/dist/types/__tests__/http-keep-alive.test.d.ts.map +0 -1
  93. package/dist/types/__tests__/http-timeout.test.d.ts +0 -2
  94. package/dist/types/__tests__/http-timeout.test.d.ts.map +0 -1
  95. package/dist/types/__tests__/index.test.d.ts +0 -2
  96. package/dist/types/__tests__/index.test.d.ts.map +0 -1
  97. package/dist/types/__tests__/legacy-auth.test.d.ts +0 -2
  98. package/dist/types/__tests__/legacy-auth.test.d.ts.map +0 -1
  99. package/dist/types/__tests__/logger.test.d.ts +0 -2
  100. package/dist/types/__tests__/logger.test.d.ts.map +0 -1
  101. package/dist/types/__tests__/logging.test.d.ts +0 -2
  102. package/dist/types/__tests__/logging.test.d.ts.map +0 -1
  103. package/dist/types/__tests__/market-time.test.d.ts +0 -2
  104. package/dist/types/__tests__/market-time.test.d.ts.map +0 -1
  105. package/dist/types/__tests__/massive.test.d.ts +0 -2
  106. package/dist/types/__tests__/massive.test.d.ts.map +0 -1
  107. package/dist/types/__tests__/metrics-calcs-direction.test.d.ts +0 -2
  108. package/dist/types/__tests__/metrics-calcs-direction.test.d.ts.map +0 -1
  109. package/dist/types/__tests__/misc-utils.test.d.ts +0 -2
  110. package/dist/types/__tests__/misc-utils.test.d.ts.map +0 -1
  111. package/dist/types/__tests__/paginator.test.d.ts +0 -2
  112. package/dist/types/__tests__/paginator.test.d.ts.map +0 -1
  113. package/dist/types/__tests__/performance-metrics-fees.test.d.ts +0 -2
  114. package/dist/types/__tests__/performance-metrics-fees.test.d.ts.map +0 -1
  115. package/dist/types/__tests__/performance-metrics.test.d.ts +0 -2
  116. package/dist/types/__tests__/performance-metrics.test.d.ts.map +0 -1
  117. package/dist/types/__tests__/price-utils-fees.test.d.ts +0 -2
  118. package/dist/types/__tests__/price-utils-fees.test.d.ts.map +0 -1
  119. package/dist/types/__tests__/price-utils.test.d.ts +0 -2
  120. package/dist/types/__tests__/price-utils.test.d.ts.map +0 -1
  121. package/dist/types/__tests__/property-based-financial.test.d.ts +0 -2
  122. package/dist/types/__tests__/property-based-financial.test.d.ts.map +0 -1
  123. package/dist/types/__tests__/protective-order-sides.test.d.ts +0 -2
  124. package/dist/types/__tests__/protective-order-sides.test.d.ts.map +0 -1
  125. package/dist/types/__tests__/rate-limiter.test.d.ts +0 -2
  126. package/dist/types/__tests__/rate-limiter.test.d.ts.map +0 -1
  127. package/dist/types/__tests__/retry-classification.test.d.ts +0 -2
  128. package/dist/types/__tests__/retry-classification.test.d.ts.map +0 -1
  129. package/dist/types/__tests__/retry.test.d.ts +0 -2
  130. package/dist/types/__tests__/retry.test.d.ts.map +0 -1
  131. package/dist/types/__tests__/risk-free-rate.test.d.ts +0 -2
  132. package/dist/types/__tests__/risk-free-rate.test.d.ts.map +0 -1
  133. package/dist/types/__tests__/risk-metrics.test.d.ts +0 -2
  134. package/dist/types/__tests__/risk-metrics.test.d.ts.map +0 -1
  135. package/dist/types/__tests__/schema-validation.test.d.ts +0 -2
  136. package/dist/types/__tests__/schema-validation.test.d.ts.map +0 -1
  137. package/dist/types/__tests__/stampede-load-timeout.test.d.ts +0 -2
  138. package/dist/types/__tests__/stampede-load-timeout.test.d.ts.map +0 -1
  139. package/dist/types/__tests__/strategy-metrics.test.d.ts +0 -2
  140. package/dist/types/__tests__/strategy-metrics.test.d.ts.map +0 -1
  141. package/dist/types/__tests__/technical-analysis-totality.test.d.ts +0 -2
  142. package/dist/types/__tests__/technical-analysis-totality.test.d.ts.map +0 -1
  143. package/dist/types/__tests__/technical-analysis.test.d.ts +0 -2
  144. package/dist/types/__tests__/technical-analysis.test.d.ts.map +0 -1
  145. package/dist/types/__tests__/time-utils.test.d.ts +0 -2
  146. package/dist/types/__tests__/time-utils.test.d.ts.map +0 -1
  147. package/dist/types/__tests__/trading-policy-schemas.test.d.ts +0 -2
  148. package/dist/types/__tests__/trading-policy-schemas.test.d.ts.map +0 -1
  149. package/dist/types/__tests__/trailing-stops-portfolio.test.d.ts +0 -2
  150. package/dist/types/__tests__/trailing-stops-portfolio.test.d.ts.map +0 -1
  151. package/dist/types/__tests__/volatility.test.d.ts +0 -2
  152. package/dist/types/__tests__/volatility.test.d.ts.map +0 -1
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Typed access to the canonical alias route table.
3
+ *
4
+ * The table is imported rather than fetched so an alias always resolves, even
5
+ * when the gateway is unreachable. A client that could only learn its routes
6
+ * from the gateway would have no way to fall back when the gateway itself is
7
+ * the thing that failed, which would make the mandatory fallback chain of PD-3
8
+ * conditional on the very component it exists to survive.
9
+ *
10
+ * Resolution is deliberately conservative in three ways. An unknown alias is an
11
+ * error rather than a default, because a typo silently served by whichever
12
+ * model happened to be configured is worse than a loud failure. A route whose
13
+ * vendor model id is unconfirmed is excluded, because a guessed id fails at the
14
+ * first live call rather than at review. And a shadow-only route is never
15
+ * served, because a candidate that can answer a live request has stopped being
16
+ * a candidate.
17
+ *
18
+ * @module llm/route-table
19
+ */
20
+ import type { LlmAlias, LlmAliasDefinition, LlmProvider, LlmRoute, LlmRouteTable, ResolvedRoute } from "./types";
21
+ /** Suffix naming an alias's research-isolated variant (PD-9). */
22
+ export declare const ISOLATED_SUFFIX = ".isolated";
23
+ /**
24
+ * The canonical route table.
25
+ *
26
+ * Exposed as a readonly view so a consumer can inspect routing without being
27
+ * able to mutate it. A table that could be edited at runtime would let one
28
+ * caller change every other caller's routing.
29
+ */
30
+ export declare const routeTable: LlmRouteTable;
31
+ /**
32
+ * Every alias the table defines.
33
+ *
34
+ * @returns The alias names, sorted for stable iteration.
35
+ */
36
+ export declare function listAliases(): LlmAlias[];
37
+ /**
38
+ * Look up an alias definition.
39
+ *
40
+ * @param alias The alias to resolve.
41
+ * @returns Its definition.
42
+ * @throws When the alias is not defined by the route table.
43
+ */
44
+ export declare function aliasDefinition(alias: LlmAlias): LlmAliasDefinition;
45
+ /**
46
+ * Look up a provider registry entry.
47
+ *
48
+ * @param name The provider key.
49
+ * @returns Its registry entry.
50
+ * @throws When the provider is not registered.
51
+ */
52
+ export declare function providerEntry(name: string): LlmProvider;
53
+ /** Thrown when a caller names an alias the route table does not define. */
54
+ export declare class UnknownAliasError extends Error {
55
+ /** The alias that was requested. */
56
+ readonly alias: string;
57
+ /** The aliases that do exist, so the message is actionable. */
58
+ readonly known: readonly string[];
59
+ /**
60
+ * @param alias The unrecognised alias.
61
+ * @param known The aliases the table defines.
62
+ */
63
+ constructor(alias: string, known: readonly string[]);
64
+ }
65
+ /** Thrown when an alias exists but has no leg that can currently serve a caller. */
66
+ export declare class NoServableRouteError extends Error {
67
+ /** The alias that could not be served. */
68
+ readonly alias: string;
69
+ /** Why each of its legs was excluded, in chain order. */
70
+ readonly exclusions: readonly string[];
71
+ /**
72
+ * @param alias The alias.
73
+ * @param exclusions Per-leg reasons, in chain order.
74
+ */
75
+ constructor(alias: string, exclusions: readonly string[]);
76
+ }
77
+ /**
78
+ * Order an alias's routes into the chain the client walks.
79
+ *
80
+ * @param definition The alias definition.
81
+ * @returns Routes ordered primary -> secondary -> closed incumbent.
82
+ */
83
+ export declare function orderedRoutes(definition: LlmAliasDefinition): LlmRoute[];
84
+ /**
85
+ * Stable identity for one leg, used to key its circuit breaker and its metrics.
86
+ *
87
+ * Keyed by alias, isolation and role rather than by provider and model, because
88
+ * the breaker guards a position in a chain: reverting an alias to a different
89
+ * model at the same position should inherit that position's health rather than
90
+ * start blind, and the isolated variant must never share a breaker with the
91
+ * shared one.
92
+ *
93
+ * @param alias The alias.
94
+ * @param isolated Whether this is the isolated variant.
95
+ * @param role The leg's role.
96
+ * @returns The route key.
97
+ */
98
+ export declare function routeKeyFor(alias: LlmAlias, isolated: boolean, role: string): string;
99
+ /** Why a leg was left out of a resolved chain. */
100
+ export interface RouteExclusion {
101
+ readonly role: string;
102
+ readonly provider: string;
103
+ readonly reason: string;
104
+ }
105
+ /** A resolved chain, with the reasons any leg was excluded. */
106
+ export interface ResolvedChain {
107
+ readonly alias: LlmAlias;
108
+ readonly isolated: boolean;
109
+ readonly routes: readonly ResolvedRoute[];
110
+ readonly exclusions: readonly RouteExclusion[];
111
+ }
112
+ /**
113
+ * Resolve an alias to the ordered chain of legs that can serve it today.
114
+ *
115
+ * Exclusions are returned rather than discarded so an exhausted chain can say
116
+ * why each leg was unavailable. "No route available" without that detail sends
117
+ * an operator to read config; with it, the answer is in the error.
118
+ *
119
+ * @param alias The alias to resolve.
120
+ * @param options Resolution options.
121
+ * @param options.isolated Route through the isolated variant (PD-9).
122
+ * @param options.timeoutMsOverride Per-leg budget override, never wider than the caller's own deadline.
123
+ * @returns The resolved chain.
124
+ * @throws {UnknownAliasError} When the alias is not defined.
125
+ */
126
+ export declare function resolveChain(alias: LlmAlias, options?: {
127
+ isolated?: boolean;
128
+ timeoutMsOverride?: number;
129
+ }): ResolvedChain;
130
+ /**
131
+ * The permanent closed-incumbent leg of an alias (PD-11).
132
+ *
133
+ * Found by provider tier rather than by role, because an alias whose primary is
134
+ * already a closed vendor has that primary as its revert target. Both shapes
135
+ * therefore hold the same guarantee: there is always a configured route that
136
+ * needs no new account and no code change to fall back to.
137
+ *
138
+ * @param chain A resolved chain.
139
+ * @returns The closed leg, or undefined when none is currently servable.
140
+ */
141
+ export declare function closedIncumbentLeg(chain: ResolvedChain): ResolvedRoute | undefined;
142
+ /**
143
+ * The name the gateway knows a leg by.
144
+ *
145
+ * The head of a chain is addressed by the bare alias so a caller never learns a
146
+ * leg name; every other leg carries the derived name the renderer gives it.
147
+ * Keeping this derivation beside the resolver — rather than in the transport —
148
+ * is what stops the client and the gateway config from disagreeing about a name.
149
+ *
150
+ * @param route The resolved leg.
151
+ * @param chain The chain it belongs to.
152
+ * @returns The gateway `model_name`.
153
+ */
154
+ export declare function gatewayModelNameFor(route: ResolvedRoute, chain: ResolvedChain): string;
155
+ //# sourceMappingURL=route-table.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-table.d.ts","sourceRoot":"","sources":["../../../src/llm/route-table.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,KAAK,EACV,QAAQ,EACR,kBAAkB,EAClB,WAAW,EACX,QAAQ,EACR,aAAa,EACb,aAAa,EACd,MAAM,SAAS,CAAC;AAKjB,iEAAiE;AACjE,eAAO,MAAM,eAAe,cAAc,CAAC;AAE3C;;;;;;GAMG;AACH,eAAO,MAAM,UAAU,EAAE,aAAoD,CAAC;AAE9E;;;;GAIG;AACH,wBAAgB,WAAW,IAAI,QAAQ,EAAE,CAExC;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,QAAQ,GAAG,kBAAkB,CAMnE;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,CAQvD;AAED,2EAA2E;AAC3E,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,oCAAoC;IACpC,SAAgB,KAAK,EAAE,MAAM,CAAC;IAE9B,+DAA+D;IAC/D,SAAgB,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IAEzC;;;OAGG;gBACgB,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,MAAM,EAAE;CAS3D;AAED,oFAAoF;AACpF,qBAAa,oBAAqB,SAAQ,KAAK;IAC7C,0CAA0C;IAC1C,SAAgB,KAAK,EAAE,MAAM,CAAC;IAE9B,yDAAyD;IACzD,SAAgB,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAE9C;;;OAGG;gBACgB,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,MAAM,EAAE;CAQhE;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,UAAU,EAAE,kBAAkB,GAAG,QAAQ,EAAE,CAIxE;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,QAAQ,EACf,QAAQ,EAAE,OAAO,EACjB,IAAI,EAAE,MAAM,GACX,MAAM,CAER;AAED,kDAAkD;AAClD,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED,+DAA+D;AAC/D,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,SAAS,aAAa,EAAE,CAAC;IAC1C,QAAQ,CAAC,UAAU,EAAE,SAAS,cAAc,EAAE,CAAC;CAChD;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,YAAY,CAC1B,KAAK,EAAE,QAAQ,EACf,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,OAAO,CAAC;IAAC,iBAAiB,CAAC,EAAE,MAAM,CAAA;CAAO,GAC/D,aAAa,CA8Df;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,aAAa,GAAG,aAAa,GAAG,SAAS,CAElF;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,aAAa,EACpB,KAAK,EAAE,aAAa,GACnB,MAAM,CAKR"}
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Bounded validate-and-retry for structured output.
3
+ *
4
+ * A model asked for a schema-shaped answer sometimes returns something close
5
+ * but wrong. Feeding the validator's own complaint back once fixes most of
6
+ * those, because the model can see precisely what it got wrong. A second retry
7
+ * almost never helps: if the model is still wrong after being told exactly what
8
+ * was wrong, it is persistently wrong for this prompt, and further attempts
9
+ * spend budget and latency to arrive at the same place.
10
+ *
11
+ * The retry lives ahead of the fallback chain rather than inside it. A payload
12
+ * that fails validation is evidence about the PROMPT, not about the provider's
13
+ * health, so it must not open a circuit breaker or advance to the next leg —
14
+ * the next leg would receive the same prompt and be no likelier to satisfy it.
15
+ *
16
+ * Exhaustion throws. Returning a partial or defaulted object would hand the
17
+ * caller a well-typed value that no model ever produced, and the resulting
18
+ * decision would be made on invented data with nothing to show it.
19
+ *
20
+ * @module llm/schema-retry
21
+ */
22
+ import type { LlmTransportResponse, LlmUsageRecord, LlmValidationOutcome } from "./types";
23
+ /** One validated attempt's result. */
24
+ export interface ValidatedOutcome<T> {
25
+ readonly value: T;
26
+ readonly attempts: 1 | 2;
27
+ readonly response: LlmTransportResponse<unknown>;
28
+ readonly totalUsage: LlmUsageRecord;
29
+ }
30
+ /**
31
+ * Thrown when both attempts failed validation.
32
+ *
33
+ * Carries both rejection reasons, because the pair is what distinguishes a
34
+ * flaky answer from a prompt the model cannot satisfy: two different complaints
35
+ * suggest instability, while the same complaint twice points at the prompt or
36
+ * the schema.
37
+ */
38
+ export declare class SchemaRetryExhaustedError extends Error {
39
+ /** Why the first attempt was rejected. */
40
+ readonly firstReason: string;
41
+ /** Why the retry was rejected. */
42
+ readonly secondReason: string;
43
+ /** Usage spent across both attempts, so the spend is still accounted for. */
44
+ readonly totalUsage: LlmUsageRecord;
45
+ /**
46
+ * @param firstReason Validator's complaint about attempt one.
47
+ * @param secondReason Validator's complaint about attempt two.
48
+ * @param totalUsage Usage across both attempts.
49
+ */
50
+ constructor(firstReason: string, secondReason: string, totalUsage: LlmUsageRecord);
51
+ }
52
+ /**
53
+ * Build the retry prompt.
54
+ *
55
+ * The rejected payload is echoed back alongside the complaint, because a model
56
+ * asked to "fix the error" without seeing what it produced will usually
57
+ * regenerate from scratch and reproduce the same mistake.
58
+ *
59
+ * @param originalPrompt The prompt that produced the invalid payload.
60
+ * @param rejected The payload that failed.
61
+ * @param reason The validator's complaint.
62
+ * @returns The retry prompt.
63
+ */
64
+ export declare function buildRetryPrompt(originalPrompt: string, rejected: unknown, reason: string): string;
65
+ /**
66
+ * Run a call with one validator-feedback retry.
67
+ *
68
+ * @param options Retry options.
69
+ * @param options.prompt The original prompt.
70
+ * @param options.validate Validator applied to each attempt's payload.
71
+ * @param options.call Executes one attempt with the given prompt.
72
+ * @returns The validated value with combined usage.
73
+ * @throws {SchemaRetryExhaustedError} When both attempts fail validation.
74
+ */
75
+ export declare function callWithValidation<T>(options: {
76
+ readonly prompt: string;
77
+ readonly validate: (raw: unknown) => LlmValidationOutcome<T>;
78
+ readonly call: (prompt: string) => Promise<LlmTransportResponse<unknown>>;
79
+ }): Promise<ValidatedOutcome<T>>;
80
+ //# sourceMappingURL=schema-retry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-retry.d.ts","sourceRoot":"","sources":["../../../src/llm/schema-retry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,KAAK,EACV,oBAAoB,EACpB,cAAc,EACd,oBAAoB,EACrB,MAAM,SAAS,CAAC;AAQjB,sCAAsC;AACtC,MAAM,WAAW,gBAAgB,CAAC,CAAC;IACjC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IAClB,QAAQ,CAAC,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,oBAAoB,CAAC,OAAO,CAAC,CAAC;IACjD,QAAQ,CAAC,UAAU,EAAE,cAAc,CAAC;CACrC;AAED;;;;;;;GAOG;AACH,qBAAa,yBAA0B,SAAQ,KAAK;IAClD,0CAA0C;IAC1C,SAAgB,WAAW,EAAE,MAAM,CAAC;IAEpC,kCAAkC;IAClC,SAAgB,YAAY,EAAE,MAAM,CAAC;IAErC,6EAA6E;IAC7E,SAAgB,UAAU,EAAE,cAAc,CAAC;IAE3C;;;;OAIG;gBAED,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,cAAc;CAY7B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAC9B,cAAc,EAAE,MAAM,EACtB,QAAQ,EAAE,OAAO,EACjB,MAAM,EAAE,MAAM,GACb,MAAM,CAiBR;AAED;;;;;;;;;GASG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,EAAE;IACnD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,oBAAoB,CAAC,CAAC,CAAC,CAAC;IAC7D,QAAQ,CAAC,IAAI,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC;CAC3E,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAmC/B"}
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Streaming normalisation across provider wire formats.
3
+ *
4
+ * A caller that streams wants one thing — text as it arrives — but the wire
5
+ * formats disagree about how to say it. OpenAI-compatible providers emit
6
+ * server-sent events whose payload nests the increment under
7
+ * `choices[0].delta.content` and end with a literal `[DONE]` sentinel;
8
+ * Anthropic emits typed events where the increment is `delta.text` and the end
9
+ * is an explicit `message_stop`. A consumer written against one shape breaks on
10
+ * the other, which would make a fallback across providers fail precisely when
11
+ * the fallback was needed.
12
+ *
13
+ * The one behaviour that matters more than the format is how a stream ENDS. A
14
+ * stream cut short mid-answer looks exactly like a short answer: the consumer
15
+ * has already received and probably already acted on the text. So a stream
16
+ * that stops without its terminal event raises rather than returning what it
17
+ * had — a truncated answer accepted as complete is a wrong answer that nothing
18
+ * reports.
19
+ *
20
+ * @module llm/streaming
21
+ */
22
+ /** One normalised chunk of a stream. */
23
+ export interface StreamChunk {
24
+ /** Text produced since the previous chunk. Never null; an empty increment is skipped. */
25
+ readonly delta: string;
26
+ /** Cumulative text so far, so a consumer never has to accumulate it itself. */
27
+ readonly text: string;
28
+ }
29
+ /**
30
+ * Thrown when a stream ends without its terminal event.
31
+ *
32
+ * A distinct type because the caller's correct response differs from a normal
33
+ * failure: the partial text exists and may be worth logging for diagnosis, but
34
+ * it must never be treated as the answer.
35
+ */
36
+ export declare class StreamTruncatedError extends Error {
37
+ /** Text received before the stream stopped. Present for diagnosis only. */
38
+ readonly partialText: string;
39
+ /**
40
+ * @param partialText What had arrived when the stream stopped.
41
+ * @param reason Why it stopped, when known.
42
+ */
43
+ constructor(partialText: string, reason: string);
44
+ }
45
+ /** Thrown when a provider reports an error inside an already-open stream. */
46
+ export declare class StreamProviderError extends Error {
47
+ /** Text received before the error. */
48
+ readonly partialText: string;
49
+ /**
50
+ * @param partialText What had arrived when the error appeared.
51
+ * @param detail The provider's message.
52
+ */
53
+ constructor(partialText: string, detail: string);
54
+ }
55
+ /**
56
+ * Normalise an OpenAI-compatible SSE stream.
57
+ *
58
+ * @param source The response body stream.
59
+ * @returns Normalised chunks.
60
+ * @throws {StreamTruncatedError} When the stream ends without `[DONE]`.
61
+ * @throws {StreamProviderError} When an error event appears mid-stream.
62
+ */
63
+ export declare function normaliseOpenAiStream(source: AsyncIterable<Uint8Array>): AsyncGenerator<StreamChunk>;
64
+ /**
65
+ * Normalise an Anthropic event stream.
66
+ *
67
+ * @param source The response body stream.
68
+ * @returns Normalised chunks.
69
+ * @throws {StreamTruncatedError} When the stream ends without `message_stop`.
70
+ * @throws {StreamProviderError} When an error event appears mid-stream.
71
+ */
72
+ export declare function normaliseAnthropicStream(source: AsyncIterable<Uint8Array>): AsyncGenerator<StreamChunk>;
73
+ /**
74
+ * Normalise a stream according to the wire format its provider speaks.
75
+ *
76
+ * Selecting on the route's declared API style rather than sniffing the payload
77
+ * keeps the decision with the route table, which is the thing that actually
78
+ * knows which provider is answering.
79
+ *
80
+ * @param apiStyle The provider's wire format.
81
+ * @param source The response body stream.
82
+ * @returns Normalised chunks, identical in shape across providers.
83
+ */
84
+ export declare function normaliseStream(apiStyle: "openai-compatible" | "anthropic", source: AsyncIterable<Uint8Array>): AsyncGenerator<StreamChunk>;
85
+ /**
86
+ * Drain a normalised stream into its complete text.
87
+ *
88
+ * @param stream A normalised stream.
89
+ * @returns The full text.
90
+ * @throws Whatever the stream raises; a truncated stream never resolves to text.
91
+ */
92
+ export declare function collectStream(stream: AsyncIterable<StreamChunk>): Promise<string>;
93
+ //# sourceMappingURL=streaming.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streaming.d.ts","sourceRoot":"","sources":["../../../src/llm/streaming.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAiBH,wCAAwC;AACxC,MAAM,WAAW,WAAW;IAC1B,yFAAyF;IACzF,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,+EAA+E;IAC/E,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;GAMG;AACH,qBAAa,oBAAqB,SAAQ,KAAK;IAC7C,2EAA2E;IAC3E,SAAgB,WAAW,EAAE,MAAM,CAAC;IAEpC;;;OAGG;gBACgB,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAQvD;AAED,6EAA6E;AAC7E,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,sCAAsC;IACtC,SAAgB,WAAW,EAAE,MAAM,CAAC;IAEpC;;;OAGG;gBACgB,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAKvD;AAgCD;;;;;;;GAOG;AACH,wBAAuB,qBAAqB,CAC1C,MAAM,EAAE,aAAa,CAAC,UAAU,CAAC,GAChC,cAAc,CAAC,WAAW,CAAC,CA0C7B;AAED;;;;;;;GAOG;AACH,wBAAuB,wBAAwB,CAC7C,MAAM,EAAE,aAAa,CAAC,UAAU,CAAC,GAChC,cAAc,CAAC,WAAW,CAAC,CA2C7B;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,mBAAmB,GAAG,WAAW,EAC3C,MAAM,EAAE,aAAa,CAAC,UAAU,CAAC,GAChC,cAAc,CAAC,WAAW,CAAC,CAI7B;AAED;;;;;;GAMG;AACH,wBAAsB,aAAa,CACjC,MAAM,EAAE,aAAa,CAAC,WAAW,CAAC,GACjC,OAAO,CAAC,MAAM,CAAC,CAMjB"}
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Degraded direct transport: the path used when the gateway itself is gone.
3
+ *
4
+ * Routing every call through one proxy concentrates a great deal of value — one
5
+ * place to swap a model, one place to bound spend, one place to see cost. It
6
+ * also concentrates risk: without this path, a gateway outage would take every
7
+ * LLM call in the system down at once, which is a worse failure than any of the
8
+ * provider outages the gateway exists to survive.
9
+ *
10
+ * Two constraints keep this a safety net rather than a second routing policy.
11
+ * It serves CLOSED-tier legs only, so the degraded path can never be the thing
12
+ * that silently promotes an open-weight model past its evaluation gates. And it
13
+ * resolves the model from the same route table the gateway is rendered from, so
14
+ * degraded traffic reaches the same model the gateway would have chosen.
15
+ *
16
+ * The provider SDK is reached through an injected caller, resolved lazily. A
17
+ * static import would make `@adaptic/utils` load a provider SDK for every
18
+ * consumer, including those that never make an LLM call, and would harden a
19
+ * package cycle that is currently only a declaration.
20
+ *
21
+ * @module llm/transports/direct
22
+ */
23
+ import type { LlmTransport } from "../types";
24
+ /** Usage as the incumbent client reports it; every field is optional there. */
25
+ export interface DirectCallerUsage {
26
+ readonly prompt_tokens?: number;
27
+ readonly completion_tokens?: number;
28
+ readonly reasoning_tokens?: number;
29
+ readonly cached_tokens?: number;
30
+ readonly provider?: string;
31
+ readonly model?: string;
32
+ readonly cost?: number;
33
+ }
34
+ /**
35
+ * The provider-calling function this transport delegates to.
36
+ *
37
+ * Shaped to match the incumbent `lumic.llm.call` signature so the engine can
38
+ * register its existing client with no adapter, and so the degraded path
39
+ * inherits behaviour that is already exercised in production rather than a
40
+ * second implementation that is only exercised during an outage.
41
+ */
42
+ export type DirectCaller = <T>(content: string | readonly unknown[], responseFormat: unknown, options: Record<string, unknown>) => Promise<{
43
+ response: T;
44
+ usage?: DirectCallerUsage;
45
+ tool_calls?: unknown;
46
+ }>;
47
+ /** Configuration for the direct transport. */
48
+ export interface DirectTransportConfig {
49
+ /**
50
+ * Resolves the provider-calling function.
51
+ *
52
+ * Async and called per use so a consumer that never degrades never loads a
53
+ * provider SDK, and so a consumer that cannot load one fails at the moment it
54
+ * would have degraded rather than at import.
55
+ */
56
+ readonly resolveCaller: () => Promise<DirectCaller>;
57
+ }
58
+ /**
59
+ * Thrown when the degraded path is asked to serve a leg it must not serve.
60
+ *
61
+ * Refusing loudly rather than serving the leg anyway is the point: the whole
62
+ * value of restricting this path is lost if it quietly widens under pressure,
63
+ * and pressure is exactly when it runs.
64
+ */
65
+ export declare class DirectTransportRefusedError extends Error {
66
+ /**
67
+ * @param routeKey The leg that was refused.
68
+ * @param reason Why it cannot be served directly.
69
+ */
70
+ constructor(routeKey: string, reason: string);
71
+ }
72
+ /**
73
+ * Build the degraded direct transport.
74
+ *
75
+ * @param config Transport configuration.
76
+ * @returns A transport that reaches a closed-tier provider without the gateway.
77
+ */
78
+ export declare function createDirectTransport(config: DirectTransportConfig): LlmTransport;
79
+ /**
80
+ * The default caller: the incumbent client in `@adaptic/lumic-utils`.
81
+ *
82
+ * Resolved with a dynamic import so this module has no load-time dependency on
83
+ * that package. When it cannot be loaded the failure names the degraded path
84
+ * explicitly, because "cannot find module" during an outage is otherwise a
85
+ * confusing second mystery on top of the first — and a consumer that does not
86
+ * ship that package is expected to register its own transport rather than to
87
+ * discover this at the moment the gateway fails.
88
+ *
89
+ * @returns The provider-calling function.
90
+ */
91
+ export declare function resolveDefaultDirectCaller(): Promise<DirectCaller>;
92
+ //# sourceMappingURL=direct.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"direct.d.ts","sourceRoot":"","sources":["../../../../src/llm/transports/direct.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,KAAK,EACV,YAAY,EAIb,MAAM,UAAU,CAAC;AAElB,+EAA+E;AAC/E,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,EAC3B,OAAO,EAAE,MAAM,GAAG,SAAS,OAAO,EAAE,EACpC,cAAc,EAAE,OAAO,EACvB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC7B,OAAO,CAAC;IACX,QAAQ,EAAE,CAAC,CAAC;IACZ,KAAK,CAAC,EAAE,iBAAiB,CAAC;IAC1B,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB,CAAC,CAAC;AAEH,8CAA8C;AAC9C,MAAM,WAAW,qBAAqB;IACpC;;;;;;OAMG;IACH,QAAQ,CAAC,aAAa,EAAE,MAAM,OAAO,CAAC,YAAY,CAAC,CAAC;CACrD;AAED;;;;;;GAMG;AACH,qBAAa,2BAA4B,SAAQ,KAAK;IACpD;;;OAGG;gBACgB,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAOpD;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,qBAAqB,GAC5B,YAAY,CAsCd;AA0CD;;;;;;;;;;;GAWG;AACH,wBAAsB,0BAA0B,IAAI,OAAO,CAAC,YAAY,CAAC,CAmBxE"}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Gateway transport: the normal path for every LLM call.
3
+ *
4
+ * The client sends an alias to the LiteLLM proxy and the proxy resolves it. The
5
+ * vendor model string therefore exists only in the gateway's configuration and
6
+ * never in application code (PD-5), which is what makes a model swap a config
7
+ * change rather than a deploy.
8
+ *
9
+ * The client still walks its own chain on top of the gateway's, and the
10
+ * duplication is deliberate. The gateway's fallbacks cover a provider being
11
+ * down; the client's cover the gateway being down. Only one of those two can
12
+ * cover the other, so the outer chain is the one that must exist.
13
+ *
14
+ * The gateway key is read from the environment by NAME at call time and never
15
+ * stored, logged, or included in an error (PD-2). Reading it per call rather
16
+ * than caching it at import means a rotation takes effect without a restart.
17
+ *
18
+ * @module llm/transports/gateway
19
+ */
20
+ import type { LlmTransport, LlmTransportRequest } from "../types";
21
+ /** Configuration for the gateway transport. */
22
+ export interface GatewayTransportConfig {
23
+ /** Base URL of the proxy, e.g. `https://llm-gateway.internal`. */
24
+ readonly baseUrl: string;
25
+ /** Env-var NAME holding the gateway key. Never the key itself. */
26
+ readonly apiKeyEnv: string;
27
+ /** Injected for testing; defaults to the global fetch. */
28
+ readonly fetchImpl?: typeof fetch;
29
+ /**
30
+ * Resolves the gateway model name for a leg.
31
+ *
32
+ * Injected because the naming convention belongs to the route table, and a
33
+ * transport that reinvented it would be a second place for the client and the
34
+ * gateway config to disagree about what a leg is called.
35
+ */
36
+ readonly modelNameFor: (request: LlmTransportRequest) => string;
37
+ }
38
+ /**
39
+ * Thrown when the gateway itself is unreachable, as opposed to a provider
40
+ * behind it failing.
41
+ *
42
+ * The distinction is what licenses the degraded direct path: a 502 from a
43
+ * provider means try the next leg, while a connection refused from the proxy
44
+ * means the whole gateway is gone and the chain cannot be walked through it at
45
+ * all.
46
+ */
47
+ export declare class GatewayUnreachableError extends Error {
48
+ /**
49
+ * @param baseUrl The gateway that could not be reached.
50
+ * @param cause The underlying transport error.
51
+ */
52
+ constructor(baseUrl: string, cause: unknown);
53
+ }
54
+ /** Thrown when the gateway answered, but with a failure. */
55
+ export declare class GatewayResponseError extends Error {
56
+ /** The HTTP status. */
57
+ readonly status: number;
58
+ /** Whether advancing to the next leg could plausibly help. */
59
+ readonly retryable: boolean;
60
+ /**
61
+ * @param status The HTTP status.
62
+ * @param body A bounded excerpt of the response body.
63
+ */
64
+ constructor(status: number, body: string);
65
+ }
66
+ /**
67
+ * Build the gateway transport.
68
+ *
69
+ * @param config Transport configuration.
70
+ * @returns A transport that executes one leg through the proxy.
71
+ */
72
+ export declare function createGatewayTransport(config: GatewayTransportConfig): LlmTransport;
73
+ //# sourceMappingURL=gateway.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gateway.d.ts","sourceRoot":"","sources":["../../../../src/llm/transports/gateway.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EACV,YAAY,EACZ,mBAAmB,EAGpB,MAAM,UAAU,CAAC;AAQlB,+CAA+C;AAC/C,MAAM,WAAW,sBAAsB;IACrC,kEAAkE;IAClE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,kEAAkE;IAClE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,0DAA0D;IAC1D,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;IAClC;;;;;;OAMG;IACH,QAAQ,CAAC,YAAY,EAAE,CAAC,OAAO,EAAE,mBAAmB,KAAK,MAAM,CAAC;CACjE;AAED;;;;;;;;GAQG;AACH,qBAAa,uBAAwB,SAAQ,KAAK;IAChD;;;OAGG;gBACgB,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO;CAMnD;AAED,4DAA4D;AAC5D,qBAAa,oBAAqB,SAAQ,KAAK;IAC7C,uBAAuB;IACvB,SAAgB,MAAM,EAAE,MAAM,CAAC;IAE/B,8DAA8D;IAC9D,SAAgB,SAAS,EAAE,OAAO,CAAC;IAEnC;;;OAGG;gBACgB,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM;CAMhD;AAwDD;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,sBAAsB,GAC7B,YAAY,CA0Dd"}