@skrr-ai/cli 0.1.175 → 0.1.176

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 (32) hide show
  1. package/dist/commands/harnesses/leases/show.js +8 -0
  2. package/dist/commands/harnesses/show.js +3 -0
  3. package/dist/lib/dedicated-wait.js +2 -0
  4. package/dist/lib/harness-engine-update.d.ts +5 -0
  5. package/dist/lib/harness-engine-update.js +82 -0
  6. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/firstPartyHarness.d.ts +7 -8
  7. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/firstPartyHarness.js +11 -7
  8. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/firstPartyHarnessUpdater.d.ts +29 -1
  9. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/firstPartyHarnessUpdater.js +57 -6
  10. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/firstPartyHarness.d.ts +7 -8
  11. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/firstPartyHarness.js +11 -7
  12. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/firstPartyHarnessUpdater.d.ts +29 -1
  13. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/firstPartyHarnessUpdater.js +71 -4
  14. package/dist/node_modules/@skrr-ai/data-provider/index.js +8038 -8034
  15. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/contract.d.ts +5 -0
  16. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/contract.js +6 -1
  17. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/index.d.ts +1 -1
  18. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/index.js +8 -0
  19. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/loopback-server.d.ts +4 -0
  20. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/loopback-server.js +4 -2
  21. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/managed-inference-broker.d.ts +96 -0
  22. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/managed-inference-broker.js +108 -9
  23. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/contract.d.ts +5 -0
  24. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/contract.js +5 -0
  25. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/index.d.ts +1 -1
  26. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/index.js +1 -1
  27. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/loopback-server.d.ts +4 -0
  28. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/loopback-server.js +1 -1
  29. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/managed-inference-broker.d.ts +96 -0
  30. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/managed-inference-broker.js +149 -11
  31. package/oclif.manifest.json +1 -1
  32. package/package.json +2 -2
@@ -203,6 +203,11 @@ export declare const MODEL_PROXY_ERROR: {
203
203
  readonly REQUEST_TOO_LARGE: "request_too_large";
204
204
  /** Deterministic local request/policy denial; callers must not retry it. */
205
205
  readonly REQUEST_REJECTED: "request_rejected";
206
+ /**
207
+ * OSK-24521 — the host had no upstream credential to send this request with (a renewal that did
208
+ * not succeed). Answered locally; nothing was sent upstream.
209
+ */
210
+ readonly CREDENTIAL_UNAVAILABLE: "credential_unavailable";
206
211
  };
207
212
  export type ModelProxyErrorCode = (typeof MODEL_PROXY_ERROR)[keyof typeof MODEL_PROXY_ERROR];
208
213
  /** Typed error carrying a stable {@link ModelProxyErrorCode}. */
@@ -74,7 +74,12 @@ const MODEL_PROXY_ERROR = {
74
74
  CANCELLED: "cancelled",
75
75
  REQUEST_TOO_LARGE: "request_too_large",
76
76
  /** Deterministic local request/policy denial; callers must not retry it. */
77
- REQUEST_REJECTED: "request_rejected"
77
+ REQUEST_REJECTED: "request_rejected",
78
+ /**
79
+ * OSK-24521 — the host had no upstream credential to send this request with (a renewal that did
80
+ * not succeed). Answered locally; nothing was sent upstream.
81
+ */
82
+ CREDENTIAL_UNAVAILABLE: "credential_unavailable"
78
83
  };
79
84
  class ModelProxyError extends Error {
80
85
  code;
@@ -51,7 +51,7 @@
51
51
  * ESM and CJS are both emitted because the daemon is ESM and the CLI is CJS, and
52
52
  * this package exists precisely so both can host the broker.
53
53
  */
54
- export { INFERENCE_BROKER_ORIGIN, INFERENCE_BROKER_SOCKET_ENV, MANAGED_SESSION_ENV, MANAGED_PROMPT_CACHING_ENV, MANAGED_STATUS_PATH, INFERENCE_BROKER_HOST, inferenceBrokerNoProxyEnv, LOOPBACK_BROKER_NO_PROXY_HOSTS, noProxyEnvWithHosts, type ManagedSessionStatus, buildManagedInferenceRelayCredential, startManagedInferenceBroker, isManagedInferenceModelScope, type GatewayCredential, type ManagedCapabilityRefresh, type ManagedCapabilityRefreshResult, type ManagedInferenceBrokerOptions, type ManagedInferenceBrokerSession, type ManagedInferenceBrokerTransport, type ManagedInferenceEndpoint, type ManagedInferenceLoopbackSession, type ManagedInferenceInputTokenAccounting, type ManagedInferenceModelScope, type ManagedInferenceRequestEnvelope, type ManagedReasoningPolicy, } from './managed-inference-broker.js';
54
+ export { INFERENCE_BROKER_ORIGIN, INFERENCE_BROKER_SOCKET_ENV, MANAGED_SESSION_ENV, MANAGED_PROMPT_CACHING_ENV, MANAGED_INPUT_ENVELOPE_ENV, managedInputEnvelopeValue, parseManagedInputEnvelope, MANAGED_STATUS_PATH, INFERENCE_BROKER_HOST, inferenceBrokerNoProxyEnv, LOOPBACK_BROKER_NO_PROXY_HOSTS, noProxyEnvWithHosts, type ManagedSessionStatus, buildManagedInferenceRelayCredential, startManagedInferenceBroker, isManagedInferenceModelScope, type GatewayCredential, type ManagedCapabilityRefresh, type ManagedCapabilityRefreshResult, type ManagedInferenceBrokerOptions, type ManagedInferenceBrokerSession, type ManagedInferenceBrokerTransport, type ManagedInferenceEndpoint, type ManagedInferenceLoopbackSession, type ManagedInferenceInputTokenAccounting, type ManagedInputEnvelope, type ManagedInferenceModelScope, type ManagedInferenceRequestEnvelope, type ManagedReasoningPolicy, CREDENTIAL_UNAVAILABLE_STATUS, type ManagedInferenceLocalRefusal, type ManagedInferenceUpstreamTransport, } from './managed-inference-broker.js';
55
55
  export { minimumCapabilityWindowMs, scheduleRenewalDelay, startRenewalLoop, type CapabilityRefreshOutcome, type RenewalLoop, type RenewalLoopOptions, type RenewalOutcome, type RenewalStopReason, } from './managed-inference-renewal.js';
56
56
  export { ModelProxyLoopbackServer, type ModelProxyForwarder } from './loopback-server.js';
57
57
  export * from './contract.js';
@@ -19,10 +19,12 @@ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "defau
19
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
20
  var index_exports = {};
21
21
  __export(index_exports, {
22
+ CREDENTIAL_UNAVAILABLE_STATUS: () => import_managed_inference_broker.CREDENTIAL_UNAVAILABLE_STATUS,
22
23
  INFERENCE_BROKER_HOST: () => import_managed_inference_broker.INFERENCE_BROKER_HOST,
23
24
  INFERENCE_BROKER_ORIGIN: () => import_managed_inference_broker.INFERENCE_BROKER_ORIGIN,
24
25
  INFERENCE_BROKER_SOCKET_ENV: () => import_managed_inference_broker.INFERENCE_BROKER_SOCKET_ENV,
25
26
  LOOPBACK_BROKER_NO_PROXY_HOSTS: () => import_managed_inference_broker.LOOPBACK_BROKER_NO_PROXY_HOSTS,
27
+ MANAGED_INPUT_ENVELOPE_ENV: () => import_managed_inference_broker.MANAGED_INPUT_ENVELOPE_ENV,
26
28
  MANAGED_PROMPT_CACHING_ENV: () => import_managed_inference_broker.MANAGED_PROMPT_CACHING_ENV,
27
29
  MANAGED_SESSION_ENV: () => import_managed_inference_broker.MANAGED_SESSION_ENV,
28
30
  MANAGED_STATUS_PATH: () => import_managed_inference_broker.MANAGED_STATUS_PATH,
@@ -30,8 +32,10 @@ __export(index_exports, {
30
32
  buildManagedInferenceRelayCredential: () => import_managed_inference_broker.buildManagedInferenceRelayCredential,
31
33
  inferenceBrokerNoProxyEnv: () => import_managed_inference_broker.inferenceBrokerNoProxyEnv,
32
34
  isManagedInferenceModelScope: () => import_managed_inference_broker.isManagedInferenceModelScope,
35
+ managedInputEnvelopeValue: () => import_managed_inference_broker.managedInputEnvelopeValue,
33
36
  minimumCapabilityWindowMs: () => import_managed_inference_renewal.minimumCapabilityWindowMs,
34
37
  noProxyEnvWithHosts: () => import_managed_inference_broker.noProxyEnvWithHosts,
38
+ parseManagedInputEnvelope: () => import_managed_inference_broker.parseManagedInputEnvelope,
35
39
  scheduleRenewalDelay: () => import_managed_inference_renewal.scheduleRenewalDelay,
36
40
  startManagedInferenceBroker: () => import_managed_inference_broker.startManagedInferenceBroker,
37
41
  startRenewalLoop: () => import_managed_inference_renewal.startRenewalLoop
@@ -43,10 +47,12 @@ var import_loopback_server = require("./loopback-server.js");
43
47
  __reExport(index_exports, require("./contract.js"), module.exports);
44
48
  // Annotate the CommonJS export names for ESM import in node:
45
49
  0 && (module.exports = {
50
+ CREDENTIAL_UNAVAILABLE_STATUS,
46
51
  INFERENCE_BROKER_HOST,
47
52
  INFERENCE_BROKER_ORIGIN,
48
53
  INFERENCE_BROKER_SOCKET_ENV,
49
54
  LOOPBACK_BROKER_NO_PROXY_HOSTS,
55
+ MANAGED_INPUT_ENVELOPE_ENV,
50
56
  MANAGED_PROMPT_CACHING_ENV,
51
57
  MANAGED_SESSION_ENV,
52
58
  MANAGED_STATUS_PATH,
@@ -54,8 +60,10 @@ __reExport(index_exports, require("./contract.js"), module.exports);
54
60
  buildManagedInferenceRelayCredential,
55
61
  inferenceBrokerNoProxyEnv,
56
62
  isManagedInferenceModelScope,
63
+ managedInputEnvelopeValue,
57
64
  minimumCapabilityWindowMs,
58
65
  noProxyEnvWithHosts,
66
+ parseManagedInputEnvelope,
59
67
  scheduleRenewalDelay,
60
68
  startManagedInferenceBroker,
61
69
  startRenewalLoop,
@@ -46,6 +46,10 @@ export interface LoopbackServerOptions {
46
46
  maxBodyBytes?: number;
47
47
  onError?: (err: Error) => void;
48
48
  }
49
+ export declare class RequestBodyTooLargeError extends Error {
50
+ readonly maxBodyBytes: number;
51
+ constructor(maxBodyBytes: number);
52
+ }
49
53
  export declare class ModelProxyLoopbackServer {
50
54
  private server;
51
55
  /**
@@ -18,7 +18,8 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var loopback_server_exports = {};
20
20
  __export(loopback_server_exports, {
21
- ModelProxyLoopbackServer: () => ModelProxyLoopbackServer
21
+ ModelProxyLoopbackServer: () => ModelProxyLoopbackServer,
22
+ RequestBodyTooLargeError: () => RequestBodyTooLargeError
22
23
  });
23
24
  module.exports = __toCommonJS(loopback_server_exports);
24
25
  var import_node_http = require("node:http");
@@ -224,5 +225,6 @@ function writeError(res, status, code, message) {
224
225
  }
225
226
  // Annotate the CommonJS export names for ESM import in node:
226
227
  0 && (module.exports = {
227
- ModelProxyLoopbackServer
228
+ ModelProxyLoopbackServer,
229
+ RequestBodyTooLargeError
228
230
  });
@@ -9,6 +9,7 @@
9
9
  * endpoint, and the child receives only a random secret usable against that
10
10
  * endpoint while it is alive.
11
11
  */
12
+ import { MODEL_PROXY_ERROR } from './contract.js';
12
13
  import { type CapabilityRefreshOutcome, type RenewalOutcome, type RenewalStopReason } from './managed-inference-renewal.js';
13
14
  type FetchLike = (url: string, init: RequestInit) => Promise<Response>;
14
15
  export interface GatewayCredential {
@@ -82,8 +83,51 @@ export type ManagedCapabilityRefreshResult = CapabilityRefreshOutcome & {
82
83
  token?: string;
83
84
  };
84
85
  export type ManagedCapabilityRefresh = () => Promise<ManagedCapabilityRefreshResult>;
86
+ /**
87
+ * OSK-24521 — an upstream that authenticates each request itself.
88
+ *
89
+ * The broker's other credential source is a capability it holds (`credential.authToken`) and sends
90
+ * as `Authorization: Bearer`. A host whose credential renews on its own clock (the API worker's
91
+ * process `agent.turn` key, which lives 900 s and is replaced ahead of expiry) cannot hand the
92
+ * broker one value for a session that outlives it, so it hands over the sending instead: `send`
93
+ * puts the key that is current at that moment on the request (and may send it once more on a
94
+ * replacement when the gateway refused the key, with the same buffered body). The broker then sets
95
+ * no authorization of its own and never sees a key.
96
+ *
97
+ * `send` refuses BEFORE the network when it has no key to send, by throwing a
98
+ * {@link ModelProxyError} with {@link MODEL_PROXY_ERROR.CREDENTIAL_UNAVAILABLE}. The broker answers
99
+ * that request itself (see {@link CREDENTIAL_UNAVAILABLE_STATUS}), sends nothing upstream, and keeps
100
+ * the refusal for its host ({@link ManagedInferenceBrokerSession.localRefusal}). Any other throw is
101
+ * the upstream failing, as for the capability source.
102
+ */
103
+ export interface ManagedInferenceUpstreamTransport {
104
+ send(url: string, init: RequestInit): Promise<Response>;
105
+ }
106
+ /**
107
+ * A request the broker answered itself, without reaching upstream, kept so its host can name the
108
+ * cause instead of reading it back out of whatever the harness made of the answer (OSK-24521).
109
+ */
110
+ export interface ManagedInferenceLocalRefusal {
111
+ code: typeof MODEL_PROXY_ERROR.CREDENTIAL_UNAVAILABLE | typeof MODEL_PROXY_ERROR.REQUEST_TOO_LARGE;
112
+ message: string;
113
+ }
85
114
  export interface ManagedInferenceBrokerOptions {
86
115
  credential: GatewayCredential;
116
+ /**
117
+ * OSK-24521 — send through this instead of authenticating with `credential.authToken`, which
118
+ * is then not required. `credential.baseUrl` still names the gateway every request goes to. Not
119
+ * combinable with the lease heartbeat (`leaseExpiresInMs`, `refreshCapability`), which renews a
120
+ * capability this source does not have.
121
+ */
122
+ upstream?: ManagedInferenceUpstreamTransport;
123
+ /**
124
+ * The largest request body the listener buffers, when no lease envelope sets one
125
+ * (`modelScope.requestEnvelope.maxInputBytes` wins when present). Defaults to
126
+ * {@link MODEL_PROXY_MAX_BODY_BYTES}. A larger body is answered 413
127
+ * {@link MODEL_PROXY_ERROR.REQUEST_TOO_LARGE} before it is buffered, and kept as the session's
128
+ * {@link ManagedInferenceBrokerSession.localRefusal}.
129
+ */
130
+ maxRequestBytes?: number;
87
131
  /**
88
132
  * OSK-3901 — remaining lease lifetime, in ms, at the moment the broker starts.
89
133
  *
@@ -165,6 +209,12 @@ export interface ManagedInferenceBrokerSession {
165
209
  clientModelId?: string;
166
210
  /** Non-secret, validated lease policy used during the ACP setup handshake. */
167
211
  reasoningPolicy?: ManagedReasoningPolicy;
212
+ /**
213
+ * The latest request this broker answered itself without reaching upstream, or null. Always
214
+ * present on a session this package starts; optional so a host's own double of a session (the
215
+ * daemon's tests build several) need not grow one.
216
+ */
217
+ localRefusal?(): ManagedInferenceLocalRefusal | null;
168
218
  stop(): Promise<void>;
169
219
  }
170
220
  /** A `loopback-tcp` broker: no socket, and no bearer in `env`. */
@@ -264,6 +314,52 @@ export declare function noProxyEnvWithHosts(env: Readonly<Record<string, string
264
314
  };
265
315
  export declare const MANAGED_SESSION_ENV = "OVERSKY_MANAGED_SESSION";
266
316
  export declare const MANAGED_PROMPT_CACHING_ENV = "OVERSKY_MANAGED_PROMPT_CACHING";
317
+ /**
318
+ * The lease's input envelope, in the unit the relay enforces it (OSK-24550):
319
+ * `{"version":1,"maxInputTokens":N,"algorithm":"utf8_bytes_json_v1"|"openai_o200k_json_v1"}`.
320
+ *
321
+ * `maxInputTokens` is NOT a provider token count. The relay counts it with the
322
+ * reservation's `inputTokenAccounting` algorithm, and for every reviewed Claude
323
+ * model that is the request JSON's UTF-8 bytes plus a structural allowance, so
324
+ * 131,072 is about 33-46k real Claude tokens. The cap and its unit therefore
325
+ * travel together, from the one place that holds the validated lease: this
326
+ * broker, on both hosts (the daemon's routes and `skrr code`). A harness that
327
+ * reads only the number, and compares it with provider usage, never sees the
328
+ * refusal coming. That is how three Hosted Machine conversations ended in one
329
+ * week.
330
+ *
331
+ * Advisory to the child and grants nothing: the relay still refuses over it.
332
+ */
333
+ export declare const MANAGED_INPUT_ENVELOPE_ENV = "OVERSKY_MANAGED_INPUT_ENVELOPE";
334
+ /** The value of `MANAGED_INPUT_ENVELOPE_ENV` for a validated model scope. */
335
+ export declare function managedInputEnvelopeValue(modelScope: ManagedInferenceModelScope): string;
336
+ /** A lease's input envelope as the broker advertises it: the cap and the unit it is counted in. */
337
+ export interface ManagedInputEnvelope {
338
+ /** Counted in `algorithm`'s unit, which is not a provider token for `utf8_bytes_json_v1`. */
339
+ readonly maxInputTokens: number;
340
+ readonly algorithm: ManagedInferenceInputTokenAccounting['algorithm'];
341
+ }
342
+ /**
343
+ * Read `MANAGED_INPUT_ENVELOPE_ENV` back (OSK-24550): the one reader of the
344
+ * value `managedInputEnvelopeValue` writes, for a daemon backend that hands a
345
+ * harness its limit in the harness's own unit. Anything it cannot read exactly
346
+ * (another version, a cap out of the lease's bounds, an unknown algorithm) is
347
+ * `undefined`, never a guess.
348
+ */
349
+ export declare function parseManagedInputEnvelope(value: string | undefined): ManagedInputEnvelope | undefined;
350
+ /**
351
+ * OSK-24521 — the status a request gets when the host's transport had no credential to send it
352
+ * with: 400, the one status the harnesses this answer reaches give up on at once. A credential
353
+ * the renewal could not produce is not one a retry a few seconds later will find, so a retried
354
+ * status only delays a turn that has already failed. Measured on the pinned Codex 0.169.0
355
+ * (`cloudHarness.codex.real.spec.js`): 400 ends the turn after 1 request in under 0.1 s, while
356
+ * 403, 409, 422 and 424 each take 6 requests and about 6 s, and 503 takes 30 requests and about
357
+ * 24 s. The AI SDK the first-party engine is built on retries 408, 409, 429 and every 5xx, and not
358
+ * 400. 401 is excluded because every harness reads it as a bad key. The body's
359
+ * `error.type` is `credential_unavailable`, so it is not mistaken for a malformed request, and the
360
+ * host names the cause from {@link ManagedInferenceBrokerSession.localRefusal}, not this status.
361
+ */
362
+ export declare const CREDENTIAL_UNAVAILABLE_STATUS = 400;
267
363
  export declare function managedClientModelId(scope: ManagedInferenceModelScope): string;
268
364
  /** True only for a concrete gateway descriptor; raw provider keys never enter this broker. */
269
365
  export declare function isGatewayCredential(value: unknown): value is Required<Pick<GatewayCredential, 'baseUrl' | 'authToken'>> & GatewayCredential;
@@ -18,10 +18,12 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var managed_inference_broker_exports = {};
20
20
  __export(managed_inference_broker_exports, {
21
+ CREDENTIAL_UNAVAILABLE_STATUS: () => CREDENTIAL_UNAVAILABLE_STATUS,
21
22
  INFERENCE_BROKER_HOST: () => INFERENCE_BROKER_HOST,
22
23
  INFERENCE_BROKER_ORIGIN: () => INFERENCE_BROKER_ORIGIN,
23
24
  INFERENCE_BROKER_SOCKET_ENV: () => INFERENCE_BROKER_SOCKET_ENV,
24
25
  LOOPBACK_BROKER_NO_PROXY_HOSTS: () => LOOPBACK_BROKER_NO_PROXY_HOSTS,
26
+ MANAGED_INPUT_ENVELOPE_ENV: () => MANAGED_INPUT_ENVELOPE_ENV,
25
27
  MANAGED_PROMPT_CACHING_ENV: () => MANAGED_PROMPT_CACHING_ENV,
26
28
  MANAGED_SESSION_ENV: () => MANAGED_SESSION_ENV,
27
29
  MANAGED_STATUS_PATH: () => MANAGED_STATUS_PATH,
@@ -31,7 +33,9 @@ __export(managed_inference_broker_exports, {
31
33
  isGatewayCredential: () => isGatewayCredential,
32
34
  isManagedInferenceModelScope: () => isManagedInferenceModelScope,
33
35
  managedClientModelId: () => managedClientModelId,
36
+ managedInputEnvelopeValue: () => managedInputEnvelopeValue,
34
37
  noProxyEnvWithHosts: () => noProxyEnvWithHosts,
38
+ parseManagedInputEnvelope: () => parseManagedInputEnvelope,
35
39
  startManagedInferenceBroker: () => startManagedInferenceBroker
36
40
  });
37
41
  module.exports = __toCommonJS(managed_inference_broker_exports);
@@ -74,6 +78,36 @@ function withNoProxyHosts(list, hosts) {
74
78
  }
75
79
  const MANAGED_SESSION_ENV = "OVERSKY_MANAGED_SESSION";
76
80
  const MANAGED_PROMPT_CACHING_ENV = "OVERSKY_MANAGED_PROMPT_CACHING";
81
+ const MANAGED_INPUT_ENVELOPE_ENV = "OVERSKY_MANAGED_INPUT_ENVELOPE";
82
+ function managedInputEnvelopeValue(modelScope) {
83
+ return JSON.stringify({
84
+ version: 1,
85
+ maxInputTokens: modelScope.requestEnvelope.maxInputTokens,
86
+ algorithm: modelScope.inputTokenAccounting.algorithm
87
+ });
88
+ }
89
+ function parseManagedInputEnvelope(value) {
90
+ if (!value)
91
+ return void 0;
92
+ let parsed;
93
+ try {
94
+ parsed = JSON.parse(value);
95
+ } catch {
96
+ return void 0;
97
+ }
98
+ if (!parsed || typeof parsed !== "object")
99
+ return void 0;
100
+ const { version, maxInputTokens, algorithm } = parsed;
101
+ if (version !== 1)
102
+ return void 0;
103
+ if (!Number.isSafeInteger(maxInputTokens) || Number(maxInputTokens) <= 0)
104
+ return void 0;
105
+ if (Number(maxInputTokens) > 1e6)
106
+ return void 0;
107
+ if (algorithm !== "utf8_bytes_json_v1" && algorithm !== "openai_o200k_json_v1")
108
+ return void 0;
109
+ return { maxInputTokens: Number(maxInputTokens), algorithm };
110
+ }
77
111
  const ALLOWED_PATHS = /* @__PURE__ */ new Set([
78
112
  "/v1/messages",
79
113
  "/messages",
@@ -118,6 +152,23 @@ function countTokensUnavailableResponse() {
118
152
  })()
119
153
  };
120
154
  }
155
+ const CREDENTIAL_UNAVAILABLE_STATUS = 400;
156
+ function isCredentialUnavailable(error) {
157
+ return error instanceof Error && error.code === import_contract.MODEL_PROXY_ERROR.CREDENTIAL_UNAVAILABLE;
158
+ }
159
+ function credentialUnavailableResponse(message) {
160
+ const encoded = new TextEncoder().encode(JSON.stringify({
161
+ type: "error",
162
+ error: { type: import_contract.MODEL_PROXY_ERROR.CREDENTIAL_UNAVAILABLE, message }
163
+ }));
164
+ return {
165
+ status: CREDENTIAL_UNAVAILABLE_STATUS,
166
+ headers: { "content-type": "application/json", "cache-control": "no-store" },
167
+ body: (async function* () {
168
+ yield encoded;
169
+ })()
170
+ };
171
+ }
121
172
  const FORWARDED_HEADERS = /* @__PURE__ */ new Set([
122
173
  "accept",
123
174
  "content-type",
@@ -188,9 +239,21 @@ async function startManagedInferenceBroker(options) {
188
239
  const modelScope = isManagedInferenceModelScope(options.modelScope) ? options.modelScope : null;
189
240
  const legacyModel = nonEmpty(options.model);
190
241
  const promptCacheControl = options.promptCacheControl === "strip" ? "strip" : "refuse";
191
- if (!gatewayBase || !gatewayKey || !modelScope && !legacyModel) {
242
+ const upstream = options.upstream ?? null;
243
+ if (upstream !== null && typeof upstream.send !== "function") {
244
+ throw new Error("managed inference broker upstream transport has no send");
245
+ }
246
+ if (upstream && (options.leaseExpiresInMs !== void 0 || options.refreshCapability)) {
247
+ throw new Error("managed inference broker upstream transport takes no lease heartbeat");
248
+ }
249
+ if (!gatewayBase || !upstream && !gatewayKey || !modelScope && !legacyModel) {
192
250
  throw new Error("managed inference broker requires gateway base URL, virtual key, and resolved model");
193
251
  }
252
+ const maxRequestBytes = options.maxRequestBytes ?? import_contract.MODEL_PROXY_MAX_BODY_BYTES;
253
+ if (!Number.isSafeInteger(maxRequestBytes) || maxRequestBytes <= 0) {
254
+ throw new Error("managed inference broker maxRequestBytes must be a positive integer");
255
+ }
256
+ let localRefusal = null;
194
257
  let origin;
195
258
  try {
196
259
  origin = new URL(gatewayBase).origin;
@@ -198,7 +261,7 @@ async function startManagedInferenceBroker(options) {
198
261
  throw new Error("managed inference broker received an invalid gateway base URL");
199
262
  }
200
263
  let relayToken = (0, import_node_crypto.randomBytes)(32).toString("base64url");
201
- let upstreamKey = gatewayKey;
264
+ let upstreamKey = gatewayKey ?? "";
202
265
  let renewal = null;
203
266
  const status = {
204
267
  expiresAtMs: options.leaseExpiresInMs && options.leaseExpiresInMs > 0 ? Date.now() + options.leaseExpiresInMs : null,
@@ -288,15 +351,34 @@ async function startManagedInferenceBroker(options) {
288
351
  if (FORWARDED_HEADERS.has(name.toLowerCase()))
289
352
  headers.set(name, value);
290
353
  }
291
- headers.set("authorization", `Bearer ${upstreamKey}`);
292
- const response = await fetchImpl(url.toString(), {
354
+ if (!upstream)
355
+ headers.set("authorization", `Bearer ${upstreamKey}`);
356
+ const init = {
293
357
  method: request.method,
294
358
  headers,
359
+ // Buffered whole by the listener, so a transport may send these bytes a second time.
295
360
  body: body ? body : void 0,
296
361
  signal,
297
362
  duplex: "half",
298
363
  redirect: "error"
299
- });
364
+ };
365
+ let response;
366
+ if (upstream) {
367
+ try {
368
+ response = await upstream.send(url.toString(), init);
369
+ } catch (error) {
370
+ if (!isCredentialUnavailable(error))
371
+ throw error;
372
+ localRefusal = {
373
+ code: import_contract.MODEL_PROXY_ERROR.CREDENTIAL_UNAVAILABLE,
374
+ message: error.message || "no upstream credential is available"
375
+ };
376
+ releaseSlot();
377
+ return credentialUnavailableResponse(localRefusal.message);
378
+ }
379
+ } else {
380
+ response = await fetchImpl(url.toString(), init);
381
+ }
300
382
  readBudgetHeaders(response.headers);
301
383
  return {
302
384
  status: response.status,
@@ -309,6 +391,12 @@ async function startManagedInferenceBroker(options) {
309
391
  }
310
392
  }
311
393
  };
394
+ const maxBodyBytes = envelope ? envelope.maxInputBytes : maxRequestBytes;
395
+ const onListenerError = (error) => {
396
+ if (error instanceof import_loopback_server.RequestBodyTooLargeError) {
397
+ localRefusal = { code: import_contract.MODEL_PROXY_ERROR.REQUEST_TOO_LARGE, message: error.message };
398
+ }
399
+ };
312
400
  const startListener = async () => {
313
401
  if (transport === "loopback-tcp") {
314
402
  const tcp = new import_loopback_server.ModelProxyLoopbackServer({
@@ -316,7 +404,8 @@ async function startManagedInferenceBroker(options) {
316
404
  forwarder,
317
405
  host: "127.0.0.1",
318
406
  port: 0,
319
- ...envelope ? { maxBodyBytes: envelope.maxInputBytes } : {}
407
+ maxBodyBytes,
408
+ onError: onListenerError
320
409
  });
321
410
  return { kind: "tcp", server: tcp, origin: (await tcp.start()).baseUrl };
322
411
  }
@@ -336,7 +425,8 @@ async function startManagedInferenceBroker(options) {
336
425
  socketPath: path,
337
426
  ...sharedSocketGroup ? { socketGroupId: options.socketGroupId } : {},
338
427
  advertisedBaseUrl: INFERENCE_BROKER_ORIGIN,
339
- ...envelope ? { maxBodyBytes: envelope.maxInputBytes } : {}
428
+ maxBodyBytes,
429
+ onError: onListenerError
340
430
  });
341
431
  try {
342
432
  await socket.start();
@@ -404,7 +494,12 @@ async function startManagedInferenceBroker(options) {
404
494
  });
405
495
  }
406
496
  const promptCachingEnv = modelScope?.requestEnvelope.allowPromptCaching && supportsManagedPromptCaching(modelScope) ? { [MANAGED_PROMPT_CACHING_ENV]: "1" } : {};
497
+ const leaseEnv = {
498
+ ...promptCachingEnv,
499
+ ...modelScope ? { [MANAGED_INPUT_ENVELOPE_ENV]: managedInputEnvelopeValue(modelScope) } : {}
500
+ };
407
501
  const leaseFields = {
502
+ localRefusal: () => localRefusal,
408
503
  ...modelScope ? { clientModelId: managedClientModelId(modelScope) } : {},
409
504
  ...envelope ? {
410
505
  reasoningPolicy: {
@@ -430,7 +525,7 @@ async function startManagedInferenceBroker(options) {
430
525
  return {
431
526
  // No bearer and no base URL in the environment: a TCP harness is given the
432
527
  // endpoint through its SDK, so nothing it starts inherits the token.
433
- env: { [MANAGED_SESSION_ENV]: "1", ...promptCachingEnv },
528
+ env: { [MANAGED_SESSION_ENV]: "1", ...leaseEnv },
434
529
  endpoint: {
435
530
  origin: listener.origin,
436
531
  upstreamProvider: modelScope?.upstreamProvider ?? null,
@@ -464,7 +559,7 @@ async function startManagedInferenceBroker(options) {
464
559
  ANTHROPIC_AUTH_TOKEN: relayToken,
465
560
  [INFERENCE_BROKER_SOCKET_ENV]: listener.path,
466
561
  [MANAGED_SESSION_ENV]: "1",
467
- ...promptCachingEnv
562
+ ...leaseEnv
468
563
  },
469
564
  socketPath: listener.path,
470
565
  ...leaseFields,
@@ -836,10 +931,12 @@ async function* responseBody(response, maxBytes, onComplete = () => {
836
931
  }
837
932
  // Annotate the CommonJS export names for ESM import in node:
838
933
  0 && (module.exports = {
934
+ CREDENTIAL_UNAVAILABLE_STATUS,
839
935
  INFERENCE_BROKER_HOST,
840
936
  INFERENCE_BROKER_ORIGIN,
841
937
  INFERENCE_BROKER_SOCKET_ENV,
842
938
  LOOPBACK_BROKER_NO_PROXY_HOSTS,
939
+ MANAGED_INPUT_ENVELOPE_ENV,
843
940
  MANAGED_PROMPT_CACHING_ENV,
844
941
  MANAGED_SESSION_ENV,
845
942
  MANAGED_STATUS_PATH,
@@ -849,6 +946,8 @@ async function* responseBody(response, maxBytes, onComplete = () => {
849
946
  isGatewayCredential,
850
947
  isManagedInferenceModelScope,
851
948
  managedClientModelId,
949
+ managedInputEnvelopeValue,
852
950
  noProxyEnvWithHosts,
951
+ parseManagedInputEnvelope,
853
952
  startManagedInferenceBroker
854
953
  });
@@ -203,6 +203,11 @@ export declare const MODEL_PROXY_ERROR: {
203
203
  readonly REQUEST_TOO_LARGE: "request_too_large";
204
204
  /** Deterministic local request/policy denial; callers must not retry it. */
205
205
  readonly REQUEST_REJECTED: "request_rejected";
206
+ /**
207
+ * OSK-24521 — the host had no upstream credential to send this request with (a renewal that did
208
+ * not succeed). Answered locally; nothing was sent upstream.
209
+ */
210
+ readonly CREDENTIAL_UNAVAILABLE: "credential_unavailable";
206
211
  };
207
212
  export type ModelProxyErrorCode = (typeof MODEL_PROXY_ERROR)[keyof typeof MODEL_PROXY_ERROR];
208
213
  /** Typed error carrying a stable {@link ModelProxyErrorCode}. */
@@ -134,6 +134,11 @@ export const MODEL_PROXY_ERROR = {
134
134
  REQUEST_TOO_LARGE: 'request_too_large',
135
135
  /** Deterministic local request/policy denial; callers must not retry it. */
136
136
  REQUEST_REJECTED: 'request_rejected',
137
+ /**
138
+ * OSK-24521 — the host had no upstream credential to send this request with (a renewal that did
139
+ * not succeed). Answered locally; nothing was sent upstream.
140
+ */
141
+ CREDENTIAL_UNAVAILABLE: 'credential_unavailable',
137
142
  };
138
143
  /** Typed error carrying a stable {@link ModelProxyErrorCode}. */
139
144
  export class ModelProxyError extends Error {
@@ -51,7 +51,7 @@
51
51
  * ESM and CJS are both emitted because the daemon is ESM and the CLI is CJS, and
52
52
  * this package exists precisely so both can host the broker.
53
53
  */
54
- export { INFERENCE_BROKER_ORIGIN, INFERENCE_BROKER_SOCKET_ENV, MANAGED_SESSION_ENV, MANAGED_PROMPT_CACHING_ENV, MANAGED_STATUS_PATH, INFERENCE_BROKER_HOST, inferenceBrokerNoProxyEnv, LOOPBACK_BROKER_NO_PROXY_HOSTS, noProxyEnvWithHosts, type ManagedSessionStatus, buildManagedInferenceRelayCredential, startManagedInferenceBroker, isManagedInferenceModelScope, type GatewayCredential, type ManagedCapabilityRefresh, type ManagedCapabilityRefreshResult, type ManagedInferenceBrokerOptions, type ManagedInferenceBrokerSession, type ManagedInferenceBrokerTransport, type ManagedInferenceEndpoint, type ManagedInferenceLoopbackSession, type ManagedInferenceInputTokenAccounting, type ManagedInferenceModelScope, type ManagedInferenceRequestEnvelope, type ManagedReasoningPolicy, } from './managed-inference-broker.js';
54
+ export { INFERENCE_BROKER_ORIGIN, INFERENCE_BROKER_SOCKET_ENV, MANAGED_SESSION_ENV, MANAGED_PROMPT_CACHING_ENV, MANAGED_INPUT_ENVELOPE_ENV, managedInputEnvelopeValue, parseManagedInputEnvelope, MANAGED_STATUS_PATH, INFERENCE_BROKER_HOST, inferenceBrokerNoProxyEnv, LOOPBACK_BROKER_NO_PROXY_HOSTS, noProxyEnvWithHosts, type ManagedSessionStatus, buildManagedInferenceRelayCredential, startManagedInferenceBroker, isManagedInferenceModelScope, type GatewayCredential, type ManagedCapabilityRefresh, type ManagedCapabilityRefreshResult, type ManagedInferenceBrokerOptions, type ManagedInferenceBrokerSession, type ManagedInferenceBrokerTransport, type ManagedInferenceEndpoint, type ManagedInferenceLoopbackSession, type ManagedInferenceInputTokenAccounting, type ManagedInputEnvelope, type ManagedInferenceModelScope, type ManagedInferenceRequestEnvelope, type ManagedReasoningPolicy, CREDENTIAL_UNAVAILABLE_STATUS, type ManagedInferenceLocalRefusal, type ManagedInferenceUpstreamTransport, } from './managed-inference-broker.js';
55
55
  export { minimumCapabilityWindowMs, scheduleRenewalDelay, startRenewalLoop, type CapabilityRefreshOutcome, type RenewalLoop, type RenewalLoopOptions, type RenewalOutcome, type RenewalStopReason, } from './managed-inference-renewal.js';
56
56
  export { ModelProxyLoopbackServer, type ModelProxyForwarder } from './loopback-server.js';
57
57
  export * from './contract.js';
@@ -51,7 +51,7 @@
51
51
  * ESM and CJS are both emitted because the daemon is ESM and the CLI is CJS, and
52
52
  * this package exists precisely so both can host the broker.
53
53
  */
54
- export { INFERENCE_BROKER_ORIGIN, INFERENCE_BROKER_SOCKET_ENV, MANAGED_SESSION_ENV, MANAGED_PROMPT_CACHING_ENV, MANAGED_STATUS_PATH, INFERENCE_BROKER_HOST, inferenceBrokerNoProxyEnv, LOOPBACK_BROKER_NO_PROXY_HOSTS, noProxyEnvWithHosts, buildManagedInferenceRelayCredential, startManagedInferenceBroker, isManagedInferenceModelScope, } from './managed-inference-broker.js';
54
+ export { INFERENCE_BROKER_ORIGIN, INFERENCE_BROKER_SOCKET_ENV, MANAGED_SESSION_ENV, MANAGED_PROMPT_CACHING_ENV, MANAGED_INPUT_ENVELOPE_ENV, managedInputEnvelopeValue, parseManagedInputEnvelope, MANAGED_STATUS_PATH, INFERENCE_BROKER_HOST, inferenceBrokerNoProxyEnv, LOOPBACK_BROKER_NO_PROXY_HOSTS, noProxyEnvWithHosts, buildManagedInferenceRelayCredential, startManagedInferenceBroker, isManagedInferenceModelScope, CREDENTIAL_UNAVAILABLE_STATUS, } from './managed-inference-broker.js';
55
55
  export { minimumCapabilityWindowMs, scheduleRenewalDelay, startRenewalLoop, } from './managed-inference-renewal.js';
56
56
  export { ModelProxyLoopbackServer } from './loopback-server.js';
57
57
  // Re-exported in full because `daemon/src/model-proxy/contract.ts` becomes a
@@ -46,6 +46,10 @@ export interface LoopbackServerOptions {
46
46
  maxBodyBytes?: number;
47
47
  onError?: (err: Error) => void;
48
48
  }
49
+ export declare class RequestBodyTooLargeError extends Error {
50
+ readonly maxBodyBytes: number;
51
+ constructor(maxBodyBytes: number);
52
+ }
49
53
  export declare class ModelProxyLoopbackServer {
50
54
  private server;
51
55
  /**
@@ -19,7 +19,7 @@ import { chmodSync, chownSync, unlinkSync } from 'node:fs';
19
19
  import { MODEL_PROXY_ERROR, MODEL_PROXY_MAX_BODY_BYTES, ModelProxyError, } from './contract.js';
20
20
  const AUTHORIZE_RE = /^Bearer\s+/i;
21
21
  const ORIGIN_FORM_PATH_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
22
- class RequestBodyTooLargeError extends Error {
22
+ export class RequestBodyTooLargeError extends Error {
23
23
  maxBodyBytes;
24
24
  constructor(maxBodyBytes) {
25
25
  super(`Request body exceeds ${maxBodyBytes} byte limit.`);