@humain/humain-code 0.8.1 → 0.8.2
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/CHANGELOG.md +25 -0
- package/dist/bundle/chunks/{chunk-3CGMVKHA.js → chunk-3E37CJCE.js} +1 -1
- package/dist/bundle/chunks/{chunk-7X6DNT45.js → chunk-3PJ7NPWN.js} +8 -6
- package/dist/bundle/chunks/{chunk-P2Y2H7SD.js → chunk-6JTCRCNF.js} +2 -2
- package/dist/bundle/chunks/{chunk-APNPBT7Y.js → chunk-BRSLXHED.js} +1 -1
- package/dist/bundle/chunks/{chunk-KONLZKPL.js → chunk-E4VUW4RI.js} +1 -1
- package/dist/bundle/chunks/{chunk-E7OBH44W.js → chunk-EFY2QPVP.js} +6 -6
- package/dist/bundle/chunks/{chunk-6YVORXTX.js → chunk-G2QMON4O.js} +253 -232
- package/dist/bundle/chunks/{chunk-QRRVZYTG.js → chunk-H2B3WLIM.js} +2 -2
- package/dist/bundle/chunks/{chunk-XZ7FTBXS.js → chunk-H7UPU2SH.js} +1187 -1196
- package/dist/bundle/chunks/{chunk-NICPFMOP.js → chunk-JKX5EGOT.js} +1 -1
- package/dist/bundle/chunks/{chunk-P42E6YY6.js → chunk-JQBZUFH7.js} +33 -32
- package/dist/bundle/chunks/{chunk-D3KYOSQY.js → chunk-JSHKS7VH.js} +1 -1
- package/dist/bundle/chunks/{chunk-SXOIQWNX.js → chunk-JX6YIPNK.js} +1 -1
- package/dist/bundle/chunks/{chunk-WBSGWISD.js → chunk-M5TVWJ5T.js} +5 -4
- package/dist/bundle/chunks/{chunk-6TTMNQXI.js → chunk-PJXBU6CR.js} +43 -40
- package/dist/bundle/chunks/{chunk-CQ2CE3RB.js → chunk-QFDZEUFU.js} +2 -2
- package/dist/bundle/chunks/{chunk-DD5UT56Y.js → chunk-R2KD2HFT.js} +67 -66
- package/dist/bundle/chunks/{chunk-IMUFBWEK.js → chunk-T2ZGMEMV.js} +42 -41
- package/dist/bundle/chunks/{chunk-ROFZVEFN.js → chunk-U4EAJPMO.js} +45 -44
- package/dist/bundle/chunks/{chunk-FQ4KS5S4.js → chunk-UZOIHLNU.js} +1 -1
- package/dist/bundle/chunks/{chunk-DJG2WUNM.js → chunk-ZSWU5KKA.js} +1 -1
- package/dist/bundle/chunks/{compat-SRCNS6OQ.js → compat-ELBUCH6U.js} +1 -1
- package/dist/bundle/chunks/{dist-4OMLHRJE.js → dist-NERIS6SW.js} +1 -1
- package/dist/bundle/chunks/{dist-TRAK7EXI.js → dist-QSYDYE3Y.js} +6 -6
- package/dist/bundle/chunks/{easter-egg-3d-VVUF3C3X.js → easter-egg-3d-VZC5WOYV.js} +1 -1
- package/dist/bundle/chunks/{execute-I3WGGPWL.js → execute-6MEJJF2T.js} +2 -2
- package/dist/bundle/chunks/{flow-implementer-4KO3Q4B5.js → flow-implementer-3P3BHQ7E.js} +4 -4
- package/dist/bundle/chunks/{inprocess-TOBRVK4C.js → inprocess-3PDJKE5F.js} +4 -4
- package/dist/bundle/chunks/{interactive-mode-BJJKPBXD.js → interactive-mode-SDUO5OLD.js} +2 -2
- package/dist/bundle/chunks/{session-picker-4JQEGLDD.js → session-picker-EYKCMFQR.js} +1 -1
- package/dist/bundle/chunks/{startup-ui-AKTA4NDP.js → startup-ui-7ODOR34R.js} +2 -2
- package/dist/bundle/chunks/{trace-command-7ORDQ3JS.js → trace-command-VM7FBWPE.js} +4 -4
- package/dist/bundle/chunks/{virtual-modules-3CT5BMBA.js → virtual-modules-IU5KWB2C.js} +8 -8
- package/dist/bundle/cli-runtime.js +3 -3
- package/dist/bundle/index.js +8 -8
- package/dist/bundle/rpc-entry.js +3 -3
- package/dist/core/model-resolver.js +2 -2
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/settings-manager.d.ts +4 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +17 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +2 -0
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +10 -0
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/extensions/usage/index.js +5 -5
- package/dist/extensions/usage/index.js.map +1 -1
- package/dist/humain/gateway/client.d.ts.map +1 -1
- package/dist/humain/gateway/client.js +36 -9
- package/dist/humain/gateway/client.js.map +1 -1
- package/dist/humain/gateway/http.d.ts.map +1 -1
- package/dist/humain/gateway/http.js +26 -6
- package/dist/humain/gateway/http.js.map +1 -1
- package/dist/humain/gateway/provider.d.ts.map +1 -1
- package/dist/humain/gateway/provider.js +9 -2
- package/dist/humain/gateway/provider.js.map +1 -1
- package/dist/humain/hcode/facade.d.ts +12 -1
- package/dist/humain/hcode/facade.d.ts.map +1 -1
- package/dist/humain/hcode/facade.js +35 -8
- package/dist/humain/hcode/facade.js.map +1 -1
- package/dist/humain/hcode/login-copy.d.ts.map +1 -1
- package/dist/humain/hcode/login-copy.js +10 -0
- package/dist/humain/hcode/login-copy.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +6 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +26 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/status-indicator.d.ts +35 -1
- package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
- package/dist/modes/interactive/components/status-indicator.js +179 -3
- package/dist/modes/interactive/components/status-indicator.js.map +1 -1
- package/dist/modes/interactive/components/working-indicator-engine.d.ts +32 -0
- package/dist/modes/interactive/components/working-indicator-engine.d.ts.map +1 -0
- package/dist/modes/interactive/components/working-indicator-engine.js +112 -0
- package/dist/modes/interactive/components/working-indicator-engine.js.map +1 -0
- package/dist/modes/interactive/fullscreen.d.ts +13 -0
- package/dist/modes/interactive/fullscreen.d.ts.map +1 -0
- package/dist/modes/interactive/fullscreen.js +25 -0
- package/dist/modes/interactive/fullscreen.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts +4 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +117 -19
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/humain-dark.json +5 -4
- package/dist/modes/interactive/theme/humain-light.json +6 -5
- package/docs/development.md +7 -0
- package/docs/providers.md +14 -4
- package/docs/settings.md +20 -0
- package/docs/usage.md +2 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/schemas/settings.schema.json +29 -0
- package/dist/bundle/chunks/chunk-YPZPCHNV.js +0 -3
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { SafeCredentialError } from "../../core/safe-credential-error.js";
|
|
2
|
+
import { sleep } from "../../utils/sleep.js";
|
|
2
3
|
import { GATEWAY_TOKEN_PATTERN, GATEWAY_USER_AGENT } from "./constants.js";
|
|
3
4
|
const LOGIN_MESSAGES = {
|
|
4
5
|
"invalid-request": "HUMAIN Gateway rejected the sign-in exchange request.",
|
|
@@ -36,7 +37,9 @@ export class GatewayMalformedResponseError extends SafeCredentialError {
|
|
|
36
37
|
export class GatewayRequestError extends SafeCredentialError {
|
|
37
38
|
status;
|
|
38
39
|
constructor(status) {
|
|
39
|
-
super(
|
|
40
|
+
super(status >= 500 && status < 600
|
|
41
|
+
? `HUMAIN Gateway is temporarily unavailable (${status}); your saved sign-in is unchanged. Wait and retry /model.`
|
|
42
|
+
: `HUMAIN Gateway request failed with status ${status}.`);
|
|
40
43
|
this.name = "GatewayRequestError";
|
|
41
44
|
this.status = status;
|
|
42
45
|
}
|
|
@@ -93,8 +96,9 @@ export async function exchangeHandoffCode(base, input, options) {
|
|
|
93
96
|
}
|
|
94
97
|
if (response.status === 405)
|
|
95
98
|
throw new GatewayLoginError("method-not-allowed");
|
|
96
|
-
if (response.status
|
|
97
|
-
throw new GatewayLoginError("unavailable");
|
|
99
|
+
if (response.status >= 500 && response.status < 600) {
|
|
100
|
+
throw new GatewayLoginError("unavailable", `HUMAIN Gateway is temporarily unavailable (${response.status}); no new session was saved. Try /login again.`);
|
|
101
|
+
}
|
|
98
102
|
if (response.status === 400) {
|
|
99
103
|
const text = (await response.text().catch(() => "")).trim();
|
|
100
104
|
throw new GatewayLoginError(text === "invalid exchange request" ? "invalid-request" : "invalid-code");
|
|
@@ -135,12 +139,21 @@ export async function revokeSession(base, token, options) {
|
|
|
135
139
|
}
|
|
136
140
|
async function authedGet(base, path, token, options) {
|
|
137
141
|
const doFetch = options.fetch ?? fetch;
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
142
|
+
let response;
|
|
143
|
+
for (let attempt = 0;; attempt++) {
|
|
144
|
+
options.signal.throwIfAborted();
|
|
145
|
+
response = await doFetch(`${base}${path}`, {
|
|
146
|
+
method: "GET",
|
|
147
|
+
redirect: "error",
|
|
148
|
+
signal: options.signal,
|
|
149
|
+
headers: baseHeaders(token),
|
|
150
|
+
});
|
|
151
|
+
const delay = discoveryRetryDelay(response, attempt);
|
|
152
|
+
if (delay === undefined)
|
|
153
|
+
break;
|
|
154
|
+
await response.body?.cancel().catch(() => undefined);
|
|
155
|
+
await sleep(delay, options.signal);
|
|
156
|
+
}
|
|
144
157
|
if (response.status === 401)
|
|
145
158
|
throw new GatewaySessionUnavailableError();
|
|
146
159
|
if (response.status === 429) {
|
|
@@ -154,6 +167,20 @@ async function authedGet(base, path, token, options) {
|
|
|
154
167
|
throw new GatewayRequestError(response.status);
|
|
155
168
|
return readJson(response);
|
|
156
169
|
}
|
|
170
|
+
/** Only discovery GETs are replayable; exchange codes and billed model requests are not. */
|
|
171
|
+
function discoveryRetryDelay(response, attempt) {
|
|
172
|
+
if (attempt >= 2 || ![500, 502, 503, 504].includes(response.status))
|
|
173
|
+
return undefined;
|
|
174
|
+
if (response.headers.get("x-should-retry") === "false")
|
|
175
|
+
return undefined;
|
|
176
|
+
const backoff = 500 * 2 ** attempt;
|
|
177
|
+
const retryAfter = response.headers.get("retry-after");
|
|
178
|
+
if (retryAfter === null)
|
|
179
|
+
return backoff;
|
|
180
|
+
const delay = /^\d+$/u.test(retryAfter.trim()) ? Number(retryAfter) * 1000 : Date.parse(retryAfter) - Date.now();
|
|
181
|
+
// As in Node discovery, fail rather than wait indefinitely or retry before the server permits it.
|
|
182
|
+
return Number.isFinite(delay) && delay <= 2000 ? Math.max(backoff, delay) : undefined;
|
|
183
|
+
}
|
|
157
184
|
export async function fetchGatewayModels(base, token, options) {
|
|
158
185
|
const body = await authedGet(base, "/v1/models", token, options);
|
|
159
186
|
if (!isObject(body) || !Array.isArray(body.data))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/humain/gateway/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAgC3E,MAAM,cAAc,GAA0C;IAC7D,iBAAiB,EAAE,uDAAuD;IAC1E,cAAc,EAAE,mEAAmE;IACnF,oBAAoB,EAAE,4DAA4D;IAClF,WAAW,EAAE,2EAA2E;IACxF,oBAAoB,EAAE,yDAAyD;CAC/E,CAAC;AAEF,MAAM,OAAO,iBAAkB,SAAQ,mBAAmB;IAChD,IAAI,CAAwB;IACrC,YAAY,IAA2B,EAAE,OAAO,GAAG,cAAc,CAAC,IAAI,CAAC;QACtE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;QAChC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;CACD;AAED,MAAM,OAAO,2BAA4B,SAAQ,KAAK;IACrD,YAAY,OAAe;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,6BAA6B,CAAC;IAC3C,CAAC;CACD;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AE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE;QACvG,UAAU;QACV,aAAa,EAAE,kBAAkB,CAAC,IAAI,CAAC,cAAc,CAAC;QACtD,QAAQ;KACR,CAAC;AACH,CAAC","sourcesContent":["import { SafeCredentialError } from \"../../core/safe-credential-error.ts\";\nimport { GATEWAY_TOKEN_PATTERN, GATEWAY_USER_AGENT } from \"./constants.ts\";\n\ninterface GatewayIdentity {\n\temail: string;\n\tuserId: string;\n}\n\nexport type GatewayModelEntry = { id: string; maxInputTokens?: number; maxOutputTokens?: number };\n\ntype GatewayAccessKind = \"unrestricted\" | \"scoped\" | \"none\" | \"unknown\";\n\nexport interface GatewayAccess {\n\taccessKind: GatewayAccessKind;\n\tmodels: string[];\n\tmodelModes: Record<string, string>;\n\t// harness -> model id -> label (wire: harness_labels.code.<model id>)\n\tharnessLabels: Record<string, Record<string, { label: string; reason: string | null }>> | null;\n\tdegraded: { reason: string } | null;\n}\n\ninterface GatewayRequestOptions {\n\tfetch?: typeof fetch;\n\tsignal: AbortSignal;\n}\n\ntype GatewayLoginErrorKind =\n\t| \"invalid-request\"\n\t| \"invalid-code\"\n\t| \"method-not-allowed\"\n\t| \"unavailable\"\n\t| \"malformed-response\";\n\nconst LOGIN_MESSAGES: Record<GatewayLoginErrorKind, string> = {\n\t\"invalid-request\": \"HUMAIN Gateway rejected the sign-in exchange request.\",\n\t\"invalid-code\": \"HUMAIN Gateway sign-in code is invalid or expired. Sign in again.\",\n\t\"method-not-allowed\": \"HUMAIN Gateway did not accept the sign-in exchange method.\",\n\tunavailable: \"HUMAIN Gateway sign-in is temporarily unavailable. Start a fresh sign-in.\",\n\t\"malformed-response\": \"HUMAIN Gateway returned an unexpected sign-in response.\",\n};\n\nexport class GatewayLoginError extends SafeCredentialError {\n\treadonly kind: GatewayLoginErrorKind;\n\tconstructor(kind: GatewayLoginErrorKind, message = LOGIN_MESSAGES[kind]) {\n\t\tsuper(message);\n\t\tthis.name = \"GatewayLoginError\";\n\t\tthis.kind = kind;\n\t}\n}\n\nexport class GatewayBudgetExhaustedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"GatewayBudgetExhaustedError\";\n\t}\n}\n\nexport class GatewaySessionUnavailableError extends SafeCredentialError {\n\tconstructor() {\n\t\tsuper(\"HUMAIN Gateway CLI session unavailable. Sign in again.\");\n\t\tthis.name = \"GatewaySessionUnavailableError\";\n\t}\n}\n\nexport class GatewayMalformedResponseError extends SafeCredentialError {\n\tconstructor() {\n\t\tsuper(\"HUMAIN Gateway returned an unexpected response.\");\n\t\tthis.name = \"GatewayMalformedResponseError\";\n\t}\n}\n\nexport class GatewayRequestError extends SafeCredentialError {\n\treadonly status: number;\n\tconstructor(status: number) {\n\t\tsuper(`HUMAIN Gateway request failed with status ${status}.`);\n\t\tthis.name = \"GatewayRequestError\";\n\t\tthis.status = status;\n\t}\n}\n\ntype UnknownRecord = Record<string, unknown>;\n\nexport function isObject(value: unknown): value is UnknownRecord {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction str(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction positiveInt(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nasync function readJson(response: Response): Promise<unknown> {\n\ttry {\n\t\treturn await response.json();\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction baseHeaders(token?: string): Record<string, string> {\n\tconst headers: Record<string, string> = { \"User-Agent\": GATEWAY_USER_AGENT };\n\tif (token !== undefined) headers.Authorization = `Bearer ${token}`;\n\treturn headers;\n}\n\nexport async function exchangeHandoffCode(\n\tbase: string,\n\tinput: { code: string; state: string; verifier: string },\n\toptions: GatewayRequestOptions,\n): Promise<{ token: string; identity: GatewayIdentity }> {\n\tconst doFetch = options.fetch ?? fetch;\n\tconst payload = JSON.stringify({\n\t\tcode: input.code,\n\t\tstate: input.state,\n\t\tclient: \"humain-code\",\n\t\tcode_verifier: input.verifier,\n\t});\n\t// Gateway caps the exchange body at 4 KB; sending more would spend the one-time code on a rejected request.\n\tif (Buffer.byteLength(payload) > 4096) {\n\t\tthrow new GatewayLoginError(\"invalid-request\", \"The pasted HUMAIN Gateway code is too long.\");\n\t}\n\tlet response: Response;\n\ttry {\n\t\tresponse = await doFetch(`${base}/handoff/exchange`, {\n\t\t\tmethod: \"POST\",\n\t\t\tredirect: \"error\",\n\t\t\tsignal: options.signal,\n\t\t\theaders: { ...baseHeaders(), \"Content-Type\": \"application/json\" },\n\t\t\tbody: payload,\n\t\t});\n\t} catch (error) {\n\t\tif (options.signal?.aborted) throw error;\n\t\tthrow new SafeCredentialError(\n\t\t\t\"Could not reach HUMAIN Gateway to finish sign-in. Check your network and sign in again.\",\n\t\t);\n\t}\n\tif (response.status === 405) throw new GatewayLoginError(\"method-not-allowed\");\n\tif (response.status === 503) throw new GatewayLoginError(\"unavailable\");\n\tif (response.status === 400) {\n\t\tconst text = (await response.text().catch(() => \"\")).trim();\n\t\tthrow new GatewayLoginError(text === \"invalid exchange request\" ? \"invalid-request\" : \"invalid-code\");\n\t}\n\tif (!response.ok) throw new GatewayRequestError(response.status);\n\tconst body = await readJson(response);\n\tif (!isObject(body)) throw new GatewayLoginError(\"malformed-response\");\n\tconst token = str(body.key);\n\tconst email = str(body.user_email) || str(body.email);\n\t// Gateway may return an empty user_id; the email then identifies the account.\n\tconst userId = str(body.user_id) || email;\n\tif (token === undefined || !GATEWAY_TOKEN_PATTERN.test(token)) throw new GatewayLoginError(\"malformed-response\");\n\tif (!userId || !email) throw new GatewayLoginError(\"malformed-response\");\n\treturn { token, identity: { email, userId } };\n}\n\nexport async function revokeSession(\n\tbase: string,\n\ttoken: string,\n\toptions: GatewayRequestOptions,\n): Promise<\"revoked\" | \"unknown\" | \"unavailable\"> {\n\tconst doFetch = options.fetch ?? fetch;\n\ttry {\n\t\tconst response = await doFetch(`${base}/api/cli/me/session`, {\n\t\t\tmethod: \"DELETE\",\n\t\t\tredirect: \"error\",\n\t\t\tsignal: options.signal,\n\t\t\theaders: baseHeaders(token),\n\t\t});\n\t\tif (response.status === 204) return \"revoked\";\n\t\tif (response.status === 401) return \"unknown\";\n\t\treturn \"unavailable\";\n\t} catch {\n\t\treturn \"unavailable\";\n\t}\n}\n\nasync function authedGet(base: string, path: string, token: string, options: GatewayRequestOptions): Promise<unknown> {\n\tconst doFetch = options.fetch ?? fetch;\n\tconst response = await doFetch(`${base}${path}`, {\n\t\tmethod: \"GET\",\n\t\tredirect: \"error\",\n\t\tsignal: options.signal,\n\t\theaders: baseHeaders(token),\n\t});\n\tif (response.status === 401) throw new GatewaySessionUnavailableError();\n\tif (response.status === 429) {\n\t\tconst body = await readJson(response);\n\t\tconst error = isObject(body) && isObject(body.error) ? body.error : undefined;\n\t\tif (error?.type === \"budget_exceeded\" || error?.code === \"gateway_budget_exhausted\") {\n\t\t\tthrow new GatewayBudgetExhaustedError(str(error?.message) ?? \"HUMAIN Gateway budget exhausted.\");\n\t\t}\n\t}\n\tif (!response.ok) throw new GatewayRequestError(response.status);\n\treturn readJson(response);\n}\n\nexport async function fetchGatewayModels(\n\tbase: string,\n\ttoken: string,\n\toptions: GatewayRequestOptions,\n): Promise<GatewayModelEntry[]> {\n\tconst body = await authedGet(base, \"/v1/models\", token, options);\n\tif (!isObject(body) || !Array.isArray(body.data)) throw new GatewayMalformedResponseError();\n\tconst models: GatewayModelEntry[] = [];\n\tfor (const entry of body.data) {\n\t\tif (!isObject(entry) || typeof entry.id !== \"string\" || entry.id === \"\") continue;\n\t\tconst model: GatewayModelEntry = { id: entry.id };\n\t\tconst maxInputTokens = positiveInt(entry.max_input_tokens);\n\t\tconst maxOutputTokens = positiveInt(entry.max_output_tokens);\n\t\tif (maxInputTokens !== undefined) model.maxInputTokens = maxInputTokens;\n\t\tif (maxOutputTokens !== undefined) model.maxOutputTokens = maxOutputTokens;\n\t\tmodels.push(model);\n\t}\n\treturn models;\n}\n\nconst ACCESS_KINDS: readonly string[] = [\"unrestricted\", \"scoped\", \"none\"];\n\nfunction parseHarnessLabels(value: unknown): GatewayAccess[\"harnessLabels\"] {\n\tif (!isObject(value)) return null;\n\tconst result: NonNullable<GatewayAccess[\"harnessLabels\"]> = {};\n\tfor (const [harness, models] of Object.entries(value)) {\n\t\tif (!isObject(models)) continue;\n\t\tconst inner: Record<string, { label: string; reason: string | null }> = {};\n\t\tfor (const [model, info] of Object.entries(models)) {\n\t\t\tif (isObject(info) && typeof info.label === \"string\") {\n\t\t\t\tinner[model] = { label: info.label, reason: str(info.reason) ?? null };\n\t\t\t}\n\t\t}\n\t\tresult[harness] = inner;\n\t}\n\treturn result;\n}\n\nexport async function fetchGatewayAccess(\n\tbase: string,\n\ttoken: string,\n\toptions: GatewayRequestOptions,\n): Promise<GatewayAccess> {\n\tconst body = await authedGet(base, \"/api/cli/me/access\", token, options);\n\tif (!isObject(body)) throw new GatewayMalformedResponseError();\n\tconst modelModes: Record<string, string> = {};\n\tif (isObject(body.model_modes)) {\n\t\tfor (const [model, mode] of Object.entries(body.model_modes)) {\n\t\t\tif (typeof mode === \"string\") modelModes[model] = mode;\n\t\t}\n\t}\n\tconst degraded =\n\t\tbody.degraded === null || body.degraded === undefined || body.degraded === false\n\t\t\t? null\n\t\t\t: { reason: isObject(body.degraded) ? (str(body.degraded.reason) ?? \"unknown\") : \"unknown\" };\n\tconst kind = str(body.access_kind);\n\treturn {\n\t\taccessKind: kind !== undefined && ACCESS_KINDS.includes(kind) ? (kind as GatewayAccessKind) : \"unknown\",\n\t\tmodels: Array.isArray(body.models) ? body.models.filter((m): m is string => typeof m === \"string\") : [],\n\t\tmodelModes,\n\t\tharnessLabels: parseHarnessLabels(body.harness_labels),\n\t\tdegraded,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/humain/gateway/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAA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AAC;AACH,CAAC","sourcesContent":["import { SafeCredentialError } from \"../../core/safe-credential-error.ts\";\nimport { sleep } from \"../../utils/sleep.ts\";\nimport { GATEWAY_TOKEN_PATTERN, GATEWAY_USER_AGENT } from \"./constants.ts\";\n\ninterface GatewayIdentity {\n\temail: string;\n\tuserId: string;\n}\n\nexport type GatewayModelEntry = { id: string; maxInputTokens?: number; maxOutputTokens?: number };\n\ntype GatewayAccessKind = \"unrestricted\" | \"scoped\" | \"none\" | \"unknown\";\n\nexport interface GatewayAccess {\n\taccessKind: GatewayAccessKind;\n\tmodels: string[];\n\tmodelModes: Record<string, string>;\n\t// harness -> model id -> label (wire: harness_labels.code.<model id>)\n\tharnessLabels: Record<string, Record<string, { label: string; reason: string | null }>> | null;\n\tdegraded: { reason: string } | null;\n}\n\ninterface GatewayRequestOptions {\n\tfetch?: typeof fetch;\n\tsignal: AbortSignal;\n}\n\ntype GatewayLoginErrorKind =\n\t| \"invalid-request\"\n\t| \"invalid-code\"\n\t| \"method-not-allowed\"\n\t| \"unavailable\"\n\t| \"malformed-response\";\n\nconst LOGIN_MESSAGES: Record<GatewayLoginErrorKind, string> = {\n\t\"invalid-request\": \"HUMAIN Gateway rejected the sign-in exchange request.\",\n\t\"invalid-code\": \"HUMAIN Gateway sign-in code is invalid or expired. Sign in again.\",\n\t\"method-not-allowed\": \"HUMAIN Gateway did not accept the sign-in exchange method.\",\n\tunavailable: \"HUMAIN Gateway sign-in is temporarily unavailable. Start a fresh sign-in.\",\n\t\"malformed-response\": \"HUMAIN Gateway returned an unexpected sign-in response.\",\n};\n\nexport class GatewayLoginError extends SafeCredentialError {\n\treadonly kind: GatewayLoginErrorKind;\n\tconstructor(kind: GatewayLoginErrorKind, message = LOGIN_MESSAGES[kind]) {\n\t\tsuper(message);\n\t\tthis.name = \"GatewayLoginError\";\n\t\tthis.kind = kind;\n\t}\n}\n\nexport class GatewayBudgetExhaustedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"GatewayBudgetExhaustedError\";\n\t}\n}\n\nexport class GatewaySessionUnavailableError extends SafeCredentialError {\n\tconstructor() {\n\t\tsuper(\"HUMAIN Gateway CLI session unavailable. Sign in again.\");\n\t\tthis.name = \"GatewaySessionUnavailableError\";\n\t}\n}\n\nexport class GatewayMalformedResponseError extends SafeCredentialError {\n\tconstructor() {\n\t\tsuper(\"HUMAIN Gateway returned an unexpected response.\");\n\t\tthis.name = \"GatewayMalformedResponseError\";\n\t}\n}\n\nexport class GatewayRequestError extends SafeCredentialError {\n\treadonly status: number;\n\tconstructor(status: number) {\n\t\tsuper(\n\t\t\tstatus >= 500 && status < 600\n\t\t\t\t? `HUMAIN Gateway is temporarily unavailable (${status}); your saved sign-in is unchanged. Wait and retry /model.`\n\t\t\t\t: `HUMAIN Gateway request failed with status ${status}.`,\n\t\t);\n\t\tthis.name = \"GatewayRequestError\";\n\t\tthis.status = status;\n\t}\n}\n\ntype UnknownRecord = Record<string, unknown>;\n\nexport function isObject(value: unknown): value is UnknownRecord {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction str(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction positiveInt(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nasync function readJson(response: Response): Promise<unknown> {\n\ttry {\n\t\treturn await response.json();\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction baseHeaders(token?: string): Record<string, string> {\n\tconst headers: Record<string, string> = { \"User-Agent\": GATEWAY_USER_AGENT };\n\tif (token !== undefined) headers.Authorization = `Bearer ${token}`;\n\treturn headers;\n}\n\nexport async function exchangeHandoffCode(\n\tbase: string,\n\tinput: { code: string; state: string; verifier: string },\n\toptions: GatewayRequestOptions,\n): Promise<{ token: string; identity: GatewayIdentity }> {\n\tconst doFetch = options.fetch ?? fetch;\n\tconst payload = JSON.stringify({\n\t\tcode: input.code,\n\t\tstate: input.state,\n\t\tclient: \"humain-code\",\n\t\tcode_verifier: input.verifier,\n\t});\n\t// Gateway caps the exchange body at 4 KB; sending more would spend the one-time code on a rejected request.\n\tif (Buffer.byteLength(payload) > 4096) {\n\t\tthrow new GatewayLoginError(\"invalid-request\", \"The pasted HUMAIN Gateway code is too long.\");\n\t}\n\tlet response: Response;\n\ttry {\n\t\tresponse = await doFetch(`${base}/handoff/exchange`, {\n\t\t\tmethod: \"POST\",\n\t\t\tredirect: \"error\",\n\t\t\tsignal: options.signal,\n\t\t\theaders: { ...baseHeaders(), \"Content-Type\": \"application/json\" },\n\t\t\tbody: payload,\n\t\t});\n\t} catch (error) {\n\t\tif (options.signal?.aborted) throw error;\n\t\tthrow new SafeCredentialError(\n\t\t\t\"Could not reach HUMAIN Gateway to finish sign-in. Check your network and sign in again.\",\n\t\t);\n\t}\n\tif (response.status === 405) throw new GatewayLoginError(\"method-not-allowed\");\n\tif (response.status >= 500 && response.status < 600) {\n\t\tthrow new GatewayLoginError(\n\t\t\t\"unavailable\",\n\t\t\t`HUMAIN Gateway is temporarily unavailable (${response.status}); no new session was saved. Try /login again.`,\n\t\t);\n\t}\n\tif (response.status === 400) {\n\t\tconst text = (await response.text().catch(() => \"\")).trim();\n\t\tthrow new GatewayLoginError(text === \"invalid exchange request\" ? \"invalid-request\" : \"invalid-code\");\n\t}\n\tif (!response.ok) throw new GatewayRequestError(response.status);\n\tconst body = await readJson(response);\n\tif (!isObject(body)) throw new GatewayLoginError(\"malformed-response\");\n\tconst token = str(body.key);\n\tconst email = str(body.user_email) || str(body.email);\n\t// Gateway may return an empty user_id; the email then identifies the account.\n\tconst userId = str(body.user_id) || email;\n\tif (token === undefined || !GATEWAY_TOKEN_PATTERN.test(token)) throw new GatewayLoginError(\"malformed-response\");\n\tif (!userId || !email) throw new GatewayLoginError(\"malformed-response\");\n\treturn { token, identity: { email, userId } };\n}\n\nexport async function revokeSession(\n\tbase: string,\n\ttoken: string,\n\toptions: GatewayRequestOptions,\n): Promise<\"revoked\" | \"unknown\" | \"unavailable\"> {\n\tconst doFetch = options.fetch ?? fetch;\n\ttry {\n\t\tconst response = await doFetch(`${base}/api/cli/me/session`, {\n\t\t\tmethod: \"DELETE\",\n\t\t\tredirect: \"error\",\n\t\t\tsignal: options.signal,\n\t\t\theaders: baseHeaders(token),\n\t\t});\n\t\tif (response.status === 204) return \"revoked\";\n\t\tif (response.status === 401) return \"unknown\";\n\t\treturn \"unavailable\";\n\t} catch {\n\t\treturn \"unavailable\";\n\t}\n}\n\nasync function authedGet(base: string, path: string, token: string, options: GatewayRequestOptions): Promise<unknown> {\n\tconst doFetch = options.fetch ?? fetch;\n\tlet response: Response;\n\tfor (let attempt = 0; ; attempt++) {\n\t\toptions.signal.throwIfAborted();\n\t\tresponse = await doFetch(`${base}${path}`, {\n\t\t\tmethod: \"GET\",\n\t\t\tredirect: \"error\",\n\t\t\tsignal: options.signal,\n\t\t\theaders: baseHeaders(token),\n\t\t});\n\t\tconst delay = discoveryRetryDelay(response, attempt);\n\t\tif (delay === undefined) break;\n\t\tawait response.body?.cancel().catch(() => undefined);\n\t\tawait sleep(delay, options.signal);\n\t}\n\tif (response.status === 401) throw new GatewaySessionUnavailableError();\n\tif (response.status === 429) {\n\t\tconst body = await readJson(response);\n\t\tconst error = isObject(body) && isObject(body.error) ? body.error : undefined;\n\t\tif (error?.type === \"budget_exceeded\" || error?.code === \"gateway_budget_exhausted\") {\n\t\t\tthrow new GatewayBudgetExhaustedError(str(error?.message) ?? \"HUMAIN Gateway budget exhausted.\");\n\t\t}\n\t}\n\tif (!response.ok) throw new GatewayRequestError(response.status);\n\treturn readJson(response);\n}\n\n/** Only discovery GETs are replayable; exchange codes and billed model requests are not. */\nfunction discoveryRetryDelay(response: Response, attempt: number): number | undefined {\n\tif (attempt >= 2 || ![500, 502, 503, 504].includes(response.status)) return undefined;\n\tif (response.headers.get(\"x-should-retry\") === \"false\") return undefined;\n\tconst backoff = 500 * 2 ** attempt;\n\tconst retryAfter = response.headers.get(\"retry-after\");\n\tif (retryAfter === null) return backoff;\n\tconst delay = /^\\d+$/u.test(retryAfter.trim()) ? Number(retryAfter) * 1000 : Date.parse(retryAfter) - Date.now();\n\t// As in Node discovery, fail rather than wait indefinitely or retry before the server permits it.\n\treturn Number.isFinite(delay) && delay <= 2000 ? Math.max(backoff, delay) : undefined;\n}\n\nexport async function fetchGatewayModels(\n\tbase: string,\n\ttoken: string,\n\toptions: GatewayRequestOptions,\n): Promise<GatewayModelEntry[]> {\n\tconst body = await authedGet(base, \"/v1/models\", token, options);\n\tif (!isObject(body) || !Array.isArray(body.data)) throw new GatewayMalformedResponseError();\n\tconst models: GatewayModelEntry[] = [];\n\tfor (const entry of body.data) {\n\t\tif (!isObject(entry) || typeof entry.id !== \"string\" || entry.id === \"\") continue;\n\t\tconst model: GatewayModelEntry = { id: entry.id };\n\t\tconst maxInputTokens = positiveInt(entry.max_input_tokens);\n\t\tconst maxOutputTokens = positiveInt(entry.max_output_tokens);\n\t\tif (maxInputTokens !== undefined) model.maxInputTokens = maxInputTokens;\n\t\tif (maxOutputTokens !== undefined) model.maxOutputTokens = maxOutputTokens;\n\t\tmodels.push(model);\n\t}\n\treturn models;\n}\n\nconst ACCESS_KINDS: readonly string[] = [\"unrestricted\", \"scoped\", \"none\"];\n\nfunction parseHarnessLabels(value: unknown): GatewayAccess[\"harnessLabels\"] {\n\tif (!isObject(value)) return null;\n\tconst result: NonNullable<GatewayAccess[\"harnessLabels\"]> = {};\n\tfor (const [harness, models] of Object.entries(value)) {\n\t\tif (!isObject(models)) continue;\n\t\tconst inner: Record<string, { label: string; reason: string | null }> = {};\n\t\tfor (const [model, info] of Object.entries(models)) {\n\t\t\tif (isObject(info) && typeof info.label === \"string\") {\n\t\t\t\tinner[model] = { label: info.label, reason: str(info.reason) ?? null };\n\t\t\t}\n\t\t}\n\t\tresult[harness] = inner;\n\t}\n\treturn result;\n}\n\nexport async function fetchGatewayAccess(\n\tbase: string,\n\ttoken: string,\n\toptions: GatewayRequestOptions,\n): Promise<GatewayAccess> {\n\tconst body = await authedGet(base, \"/api/cli/me/access\", token, options);\n\tif (!isObject(body)) throw new GatewayMalformedResponseError();\n\tconst modelModes: Record<string, string> = {};\n\tif (isObject(body.model_modes)) {\n\t\tfor (const [model, mode] of Object.entries(body.model_modes)) {\n\t\t\tif (typeof mode === \"string\") modelModes[model] = mode;\n\t\t}\n\t}\n\tconst degraded =\n\t\tbody.degraded === null || body.degraded === undefined || body.degraded === false\n\t\t\t? null\n\t\t\t: { reason: isObject(body.degraded) ? (str(body.degraded.reason) ?? \"unknown\") : \"unknown\" };\n\tconst kind = str(body.access_kind);\n\treturn {\n\t\taccessKind: kind !== undefined && ACCESS_KINDS.includes(kind) ? (kind as GatewayAccessKind) : \"unknown\",\n\t\tmodels: Array.isArray(body.models) ? body.models.filter((m): m is string => typeof m === \"string\") : [],\n\t\tmodelModes,\n\t\tharnessLabels: parseHarnessLabels(body.harness_labels),\n\t\tdegraded,\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../../src/humain/gateway/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAON,KAAK,eAAe,EAGpB,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../../src/humain/gateway/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAON,KAAK,eAAe,EAGpB,MAAM,uBAAuB,CAAC;AAgB/B,UAAU,eAAe;IACxB,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;IACtB,gEAAgE;IAChE,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AA+BD;;;GAGG;AACH,wBAAgB,oBAAoB,CACnC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,OAAO,EACb,OAAO,EAAE,OAAO,EAChB,cAAc,EAAE,MAAM,GACpB;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAgCtC;AAmBD,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,eAAe,EAAE,IAAI,GAAE,eAAoB,GAAG,eAAe,CAsLvG"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { lazyStream, } from "@earendil-works/pi-ai";
|
|
2
|
+
import { truncateErrorText } from "@earendil-works/pi-ai/utils/error-body";
|
|
2
3
|
import { sleep } from "../../utils/sleep.js";
|
|
3
4
|
import { redactAssistantMessage } from "../redact-assistant-message.js";
|
|
4
5
|
import { isObject } from "./client.js";
|
|
@@ -11,7 +12,7 @@ const MAX_ERROR_BODY_BYTES = 65_536;
|
|
|
11
12
|
const OVERSIZE_MESSAGE = "Request is larger than HUMAIN Gateway's 20 MiB limit.";
|
|
12
13
|
const REQUEST_CEILING_MS = 900_000;
|
|
13
14
|
const CEILING_MESSAGE = "HUMAIN Gateway request exceeded the 900-second limit.";
|
|
14
|
-
/**
|
|
15
|
+
/** Reads at most MAX_ERROR_BODY_BYTES as JSON or plain proxy text; larger or unreadable bodies yield `undefined`. */
|
|
15
16
|
async function readErrorBody(response) {
|
|
16
17
|
if (Number(response.headers.get("content-length")) > MAX_ERROR_BODY_BYTES)
|
|
17
18
|
return undefined;
|
|
@@ -38,11 +39,12 @@ async function readErrorBody(response) {
|
|
|
38
39
|
// Stops the clone's tee from buffering the rest of the body.
|
|
39
40
|
reader.cancel().catch(() => undefined);
|
|
40
41
|
}
|
|
42
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
41
43
|
try {
|
|
42
|
-
return JSON.parse(
|
|
44
|
+
return JSON.parse(text);
|
|
43
45
|
}
|
|
44
46
|
catch {
|
|
45
|
-
return
|
|
47
|
+
return text;
|
|
46
48
|
}
|
|
47
49
|
}
|
|
48
50
|
/**
|
|
@@ -174,6 +176,14 @@ export function withHumainGatewayHttp(api, deps = {}) {
|
|
|
174
176
|
if (!decision.retry || attempt + 1 >= MAX_ATTEMPTS) {
|
|
175
177
|
httpError.status = response.status;
|
|
176
178
|
const error = isObject(responseBody) ? responseBody.error : undefined;
|
|
179
|
+
if (response.status >= 500 && response.status <= 599) {
|
|
180
|
+
const upstream = isObject(error) ? error.message : (error ?? responseBody);
|
|
181
|
+
if (typeof upstream === "string") {
|
|
182
|
+
// Sanitize the whole upstream text before extracting/bounding a reset reason.
|
|
183
|
+
const safe = truncateErrorText(key ? upstream.replaceAll(key, "[REDACTED]") : upstream, MAX_ERROR_BODY_BYTES);
|
|
184
|
+
httpError.reason = truncateErrorText(`HTTP ${response.status}: ${safe.match(/\breset reason:[^\r\n]*/iu)?.[0] ?? safe}`, 120).replace(/\s+/gu, " ");
|
|
185
|
+
}
|
|
186
|
+
}
|
|
177
187
|
const code = isObject(error) ? (error.code ?? error.type) : undefined;
|
|
178
188
|
if (typeof code === "string")
|
|
179
189
|
httpError.code = key ? code.replaceAll(key, "[redacted]") : code;
|
|
@@ -209,11 +219,21 @@ export function withHumainGatewayHttp(api, deps = {}) {
|
|
|
209
219
|
event.reason = "error";
|
|
210
220
|
event.error.stopReason = "error";
|
|
211
221
|
}
|
|
222
|
+
const status = httpError.status;
|
|
223
|
+
const unavailable = typeof status === "number" &&
|
|
224
|
+
status >= 500 &&
|
|
225
|
+
status <= 599 &&
|
|
226
|
+
event.reason !== "aborted" &&
|
|
227
|
+
!options?.signal?.aborted;
|
|
212
228
|
const requestId = httpError.requestId;
|
|
213
229
|
event.error.errorMessage = [
|
|
214
|
-
failure ??
|
|
215
|
-
|
|
216
|
-
|
|
230
|
+
failure ??
|
|
231
|
+
(unavailable
|
|
232
|
+
? `HUMAIN Gateway is temporarily unavailable (HTTP ${status}). Try again in a moment.`
|
|
233
|
+
: event.error.errorMessage) ??
|
|
234
|
+
"HUMAIN Gateway request failed",
|
|
235
|
+
!unavailable && typeof httpError.code === "string" && `code: ${httpError.code}`,
|
|
236
|
+
!unavailable && typeof requestId === "string" && `x-litellm-call-id: ${requestId}`,
|
|
217
237
|
]
|
|
218
238
|
.filter(Boolean)
|
|
219
239
|
.join("; ");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/humain/gateway/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,UAAU,GAKV,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,MAAM,YAAY,GAAG,CAAC,CAAC;AACvB,MAAM,YAAY,GAAG,MAAM,CAAC;AAC5B,MAAM,cAAc,GAAG,UAAU,CAAC;AAClC,4EAA4E;AAC5E,MAAM,oBAAoB,GAAG,MAAM,CAAC;AACpC,MAAM,gBAAgB,GAAG,uDAAuD,CAAC;AACjF,MAAM,kBAAkB,GAAG,OAAO,CAAC;AACnC,MAAM,eAAe,GAAG,uDAAuD,CAAC;AAShF,gHAAgH;AAChH,KAAK,UAAU,aAAa,CAAC,QAAkB;IAC9C,IAAI,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC,GAAG,oBAAoB;QAAE,OAAO,SAAS,CAAC;IAC5F,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC;IAClD,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IAC9B,MAAM,MAAM,GAAiB,EAAE,CAAC;IAChC,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,CAAC;QACJ,SAAS,CAAC;YACT,MAAM,EAAE,IAAI,EAAE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EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;qBACpE;oBACD,UAAU,EAAE,OAAO;oBACnB,YAAY,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;oBACpE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;iBACrB,CAAC;gBACF,MAAM,KAAK,GAA0B,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;gBACxF,MAAM,CAAC,KAAK,CAAC,CAAC;gBACd,MAAM,KAAK,CAAC;YACb,CAAC;oBAAS,CAAC;gBACV,YAAY,CAAC,KAAK,CAAC,CAAC;YACrB,CAAC;QACF,CAAC,CAAC,EAAE,CAAC;IACN,CAAC,CAAC,CAAC;IACJ,OAAO;QACN,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC;QACxE,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;KAC7E,CAAC;AACH,CAAC","sourcesContent":["import {\n\ttype Api,\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype JsonObject,\n\tlazyStream,\n\ttype Model,\n\ttype ProviderStreams,\n\ttype SimpleStreamOptions,\n\ttype TranscriptContext,\n} from \"@earendil-works/pi-ai\";\nimport { sleep } from \"../../utils/sleep.ts\";\nimport { redactAssistantMessage } from \"../redact-assistant-message.ts\";\nimport { isObject } from \"./client.ts\";\nimport { GATEWAY_USER_AGENT } from \"./constants.ts\";\n\nconst MAX_ATTEMPTS = 3;\nconst MAX_DELAY_MS = 60_000;\nconst MAX_BODY_BYTES = 20_971_520;\n// Every retryable Gateway error body is tiny; anything larger fails closed.\nconst MAX_ERROR_BODY_BYTES = 65_536;\nconst OVERSIZE_MESSAGE = \"Request is larger than HUMAIN Gateway's 20 MiB limit.\";\nconst REQUEST_CEILING_MS = 900_000;\nconst CEILING_MESSAGE = \"HUMAIN Gateway request exceeded the 900-second limit.\";\n\ninterface GatewayHttpDeps {\n\tsleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n\trandom?: () => number;\n\t/** Test hook; production always uses the 900-second ceiling. */\n\trequestCeilingMs?: number;\n}\n\n/** Parses at most MAX_ERROR_BODY_BYTES of an error body as JSON; larger or invalid bodies yield `undefined`. */\nasync function readErrorBody(response: Response): Promise<unknown> {\n\tif (Number(response.headers.get(\"content-length\")) > MAX_ERROR_BODY_BYTES) return undefined;\n\tconst reader = response.clone().body?.getReader();\n\tif (!reader) return undefined;\n\tconst chunks: Uint8Array[] = [];\n\tlet size = 0;\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tsize += value.byteLength;\n\t\t\tif (size > MAX_ERROR_BODY_BYTES) return undefined;\n\t\t\tchunks.push(value);\n\t\t}\n\t} catch {\n\t\treturn undefined;\n\t} finally {\n\t\t// Stops the clone's tee from buffering the rest of the body.\n\t\treader.cancel().catch(() => undefined);\n\t}\n\ttry {\n\t\treturn JSON.parse(Buffer.concat(chunks).toString(\"utf8\"));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Decide whether a failed Gateway response is safe to resend. Only responses that prove the\n * request never reached a billed model call qualify; everything else fails to avoid double billing.\n */\nexport function classifyGatewayRetry(\n\tstatus: number,\n\tbody: unknown,\n\theaders: Headers,\n\trequestedModel: string,\n): { retry: boolean; delayMs?: number } {\n\tif (headers.get(\"x-should-retry\") === \"false\") return { retry: false };\n\tconst retryAfter = headers.get(\"retry-after\");\n\t// A server delay we cannot read could be later than our backoff; fail instead of resending early.\n\tif (retryAfter !== null && !/^\\d+$/u.test(retryAfter.trim())) return { retry: false };\n\tconst headerDelay = retryAfter === null ? undefined : Number(retryAfter.trim()) * 1000;\n\tconst error = isObject(body) ? body.error : undefined;\n\tlet delayMs: number | undefined;\n\tif (status === 503 && isObject(body) && Object.keys(body).length === 1 && error === \"CLI session unavailable\") {\n\t\tdelayMs = headerDelay;\n\t} else if (\n\t\tstatus === 429 &&\n\t\tisObject(error) &&\n\t\t(error.code === \"gateway_key_limit_exceeded\" || error.type === \"gateway_key_limit_exceeded\")\n\t) {\n\t\tconst fields = isObject(error.fields) ? error.fields : isObject(body) && isObject(body.fields) ? body.fields : {};\n\t\tconst seconds = fields.retry_after_seconds;\n\t\tif (seconds === undefined) delayMs = headerDelay;\n\t\telse if (typeof seconds === \"number\" && Number.isFinite(seconds) && seconds > 0) delayMs = seconds * 1000;\n\t\telse return { retry: false };\n\t} else if (\n\t\tstatus === 429 &&\n\t\theaderDelay !== undefined &&\n\t\t(isObject(error) ? error.message : error) ===\n\t\t\t`No deployments available for model '${requestedModel}'. Try again later.`\n\t) {\n\t\tdelayMs = headerDelay;\n\t} else {\n\t\treturn { retry: false };\n\t}\n\tif (delayMs !== undefined && delayMs > MAX_DELAY_MS) return { retry: false };\n\treturn delayMs === undefined ? { retry: true } : { retry: true, delayMs };\n}\n\n/** Removes `litellm_call_id`, which lets a caller pick the Gateway's billing/log id. */\nfunction stripCallId(body: string): string {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(body);\n\t} catch {\n\t\treturn body;\n\t}\n\tif (!isObject(parsed)) return body;\n\tconst metadata = parsed.metadata;\n\tconst nested = isObject(metadata) && \"litellm_call_id\" in metadata;\n\tif (!(\"litellm_call_id\" in parsed) && !nested) return body;\n\tdelete parsed.litellm_call_id;\n\tif (nested) delete metadata.litellm_call_id;\n\treturn JSON.stringify(parsed);\n}\n\nexport function withHumainGatewayHttp(api: ProviderStreams, deps: GatewayHttpDeps = {}): ProviderStreams {\n\tconst wait = deps.sleep ?? sleep;\n\tconst random = deps.random ?? Math.random;\n\tconst run = (\n\t\tmodel: Model<Api>,\n\t\tcontext: TranscriptContext,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\tsimple: boolean,\n\t) =>\n\t\tlazyStream(model, async () => {\n\t\t\tconst httpError: JsonObject = { retryable: false };\n\t\t\tlet failure: string | undefined;\n\t\t\tlet responseCost: number | undefined;\n\t\t\tlet reportedCost: number | undefined;\n\t\t\tconst key = options?.apiKey;\n\t\t\tconst fetcher = options?.fetch ?? globalThis.fetch;\n\t\t\t// The SDK timeout only bounds time to response headers; the deadline also bounds the stream.\n\t\t\t// A clearable timer (not AbortSignal.timeout) so completed requests retain nothing for 900 s.\n\t\t\tconst deadline = new AbortController();\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tif (!options?.signal?.aborted) failure ??= CEILING_MESSAGE;\n\t\t\t\tdeadline.abort();\n\t\t\t}, deps.requestCeilingMs ?? REQUEST_CEILING_MS);\n\t\t\tconst timeoutMs = options?.timeoutMs;\n\t\t\tconst requestOptions = {\n\t\t\t\t...options,\n\t\t\t\tsignal: options?.signal ? AbortSignal.any([options.signal, deadline.signal]) : deadline.signal,\n\t\t\t\ttimeoutMs:\n\t\t\t\t\ttimeoutMs !== undefined && timeoutMs > 0 && timeoutMs < REQUEST_CEILING_MS\n\t\t\t\t\t\t? timeoutMs\n\t\t\t\t\t\t: REQUEST_CEILING_MS,\n\t\t\t\t// Gateway reports request cost in `response.completed.response.usage.cost`.\n\t\t\t\tonProviderStreamEvent: async (data: unknown, streamModel: Model<Api>) => {\n\t\t\t\t\tif (isObject(data) && data.type === \"response.completed\" && isObject(data.response)) {\n\t\t\t\t\t\tconst cost = isObject(data.response.usage) ? data.response.usage.cost : undefined;\n\t\t\t\t\t\tif (typeof cost === \"number\" && Number.isFinite(cost) && cost >= 0) reportedCost = cost;\n\t\t\t\t\t}\n\t\t\t\t\tawait options?.onProviderStreamEvent?.(data, streamModel);\n\t\t\t\t},\n\t\t\t\t// Retries are owned below; SDK retries could resend a billed request.\n\t\t\t\tmaxRetries: 0,\n\t\t\t\tfetch: async (input: Parameters<typeof fetch>[0], init?: RequestInit): Promise<Response> => {\n\t\t\t\t\tconst headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n\t\t\t\t\tif (key) headers.set(\"Authorization\", `Bearer ${key}`);\n\t\t\t\t\theaders.delete(\"x-api-key\");\n\t\t\t\t\theaders.set(\"User-Agent\", GATEWAY_USER_AGENT);\n\t\t\t\t\tlet body = init?.body;\n\t\t\t\t\tif (typeof body === \"string\") {\n\t\t\t\t\t\tbody = stripCallId(body);\n\t\t\t\t\t\tif (Buffer.byteLength(body) > MAX_BODY_BYTES) {\n\t\t\t\t\t\t\tfailure = OVERSIZE_MESSAGE;\n\t\t\t\t\t\t\tthrow new Error(OVERSIZE_MESSAGE);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst signal = init?.signal ?? options?.signal;\n\t\t\t\t\tfor (let attempt = 0; ; attempt++) {\n\t\t\t\t\t\tconst response = await fetcher(input, { ...init, body, headers, redirect: \"error\" });\n\t\t\t\t\t\tconst requestId = response.headers.get(\"x-litellm-call-id\");\n\t\t\t\t\t\tif (requestId) httpError.requestId = requestId;\n\t\t\t\t\t\telse delete httpError.requestId;\n\t\t\t\t\t\tconst cost = Number(response.headers.get(\"x-litellm-response-cost\") ?? Number.NaN);\n\t\t\t\t\t\tresponseCost = Number.isFinite(cost) && cost >= 0 ? cost : undefined;\n\t\t\t\t\t\tif (response.ok) return response;\n\t\t\t\t\t\tconst responseBody = await readErrorBody(response);\n\t\t\t\t\t\tconst decision = classifyGatewayRetry(response.status, responseBody, response.headers, model.id);\n\t\t\t\t\t\tif (!decision.retry || attempt + 1 >= MAX_ATTEMPTS) {\n\t\t\t\t\t\t\thttpError.status = response.status;\n\t\t\t\t\t\t\tconst error = isObject(responseBody) ? responseBody.error : undefined;\n\t\t\t\t\t\t\tconst code = isObject(error) ? (error.code ?? error.type) : undefined;\n\t\t\t\t\t\t\tif (typeof code === \"string\") httpError.code = key ? code.replaceAll(key, \"[redacted]\") : code;\n\t\t\t\t\t\t\telse delete httpError.code;\n\t\t\t\t\t\t\tconst responseHeaders = new Headers(response.headers);\n\t\t\t\t\t\t\tresponseHeaders.set(\"x-should-retry\", \"false\");\n\t\t\t\t\t\t\treturn new Response(response.body, {\n\t\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t\t\tstatusText: response.statusText,\n\t\t\t\t\t\t\t\theaders: responseHeaders,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait response.body?.cancel().catch(() => undefined);\n\t\t\t\t\t\tconst backoff = Math.min(MAX_DELAY_MS, 1000 * 2 ** attempt) * (0.5 + random() / 2);\n\t\t\t\t\t\tawait wait(Math.max(decision.delayMs ?? 0, backoff), signal ?? undefined);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst source = simple\n\t\t\t\t? api.streamSimple(model, context, requestOptions)\n\t\t\t\t: api.stream(model, context, requestOptions);\n\t\t\tconst finish = (event: AssistantMessageEvent): void => {\n\t\t\t\tif (event.type !== \"done\" && event.type !== \"error\") return;\n\t\t\t\tconst message = event.type === \"done\" ? event.message : event.error;\n\t\t\t\tconst cost = reportedCost ?? responseCost;\n\t\t\t\tif (cost !== undefined && message.usage.cost.total === 0) message.usage.cost.total = cost;\n\t\t\t\tif (event.type === \"error\") {\n\t\t\t\t\t// A ceiling abort is a Gateway failure, not a user cancellation.\n\t\t\t\t\tif (failure === CEILING_MESSAGE && !options?.signal?.aborted) {\n\t\t\t\t\t\tevent.reason = \"error\";\n\t\t\t\t\t\tevent.error.stopReason = \"error\";\n\t\t\t\t\t}\n\t\t\t\t\tconst requestId = httpError.requestId;\n\t\t\t\t\tevent.error.errorMessage = [\n\t\t\t\t\t\tfailure ?? event.error.errorMessage ?? \"HUMAIN Gateway request failed\",\n\t\t\t\t\t\ttypeof httpError.code === \"string\" && `code: ${httpError.code}`,\n\t\t\t\t\t\ttypeof requestId === \"string\" && `x-litellm-call-id: ${requestId}`,\n\t\t\t\t\t]\n\t\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t\t.join(\"; \");\n\t\t\t\t\t// Gateway retries already happened above; agent-level retry must never resend.\n\t\t\t\t\tevent.error.diagnostics = [\n\t\t\t\t\t\t...(event.error.diagnostics ?? []),\n\t\t\t\t\t\t{ type: \"provider_http_error\", timestamp: Date.now(), details: { ...httpError } },\n\t\t\t\t\t];\n\t\t\t\t}\n\t\t\t\tredactAssistantMessage(message, key);\n\t\t\t};\n\t\t\treturn (async function* (): AsyncGenerator<AssistantMessageEvent> {\n\t\t\t\tlet ended = false;\n\t\t\t\ttry {\n\t\t\t\t\tfor await (const event of source) {\n\t\t\t\t\t\tfinish(event);\n\t\t\t\t\t\tended ||= event.type === \"done\" || event.type === \"error\";\n\t\t\t\t\t\tyield event;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (ended) throw error;\n\t\t\t\t\t// lazyStream would turn this throw into an error without the non-retryable diagnostic.\n\t\t\t\t\tconst message: AssistantMessage = {\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent: [],\n\t\t\t\t\t\tapi: model.api,\n\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\tmodel: model.id,\n\t\t\t\t\t\tusage: {\n\t\t\t\t\t\t\tusageIncomplete: true,\n\t\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstopReason: \"error\",\n\t\t\t\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t};\n\t\t\t\t\tconst event: AssistantMessageEvent = { type: \"error\", reason: \"error\", error: message };\n\t\t\t\t\tfinish(event);\n\t\t\t\t\tyield event;\n\t\t\t\t} finally {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t})();\n\t\t});\n\treturn {\n\t\tstream: (model, context, options) => run(model, context, options, false),\n\t\tstreamSimple: (model, context, options) => run(model, context, options, true),\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/humain/gateway/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,UAAU,GAKV,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wCAAwC,CAAC;AAC3E,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,MAAM,YAAY,GAAG,CAAC,CAAC;AACvB,MAAM,YAAY,GAAG,MAAM,CAAC;AAC5B,MAAM,cAAc,GAAG,UAAU,CAAC;AAClC,4EAA4E;AAC5E,MAAM,oBAAoB,GAAG,MAAM,CAAC;AACpC,MAAM,gBAAgB,GAAG,uDAAuD,CAAC;AACjF,MAAM,kBAAkB,GAAG,OAAO,CAAC;AACnC,MAAM,eAAe,GAAG,uDAAuD,CAAC;AAShF,qHAAqH;AACrH,KAAK,UAAU,aAAa,CAAC,QAAkB;IAC9C,IAAI,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC,GAAG,oBAAoB;QAAE,OAAO,SAAS,CAAC;IAC5F,MAAM,MAAM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,KAAK,EAAE,CAAC;wBACR,MAAM,EAAE,CAAC;wBACT,SAAS,EAAE,CAAC;wBACZ,UAAU,EAAE,CAAC;wBACb,WAAW,EAAE,CAAC;wBACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;qBACpE;oBACD,UAAU,EAAE,OAAO;oBACnB,YAAY,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;oBACpE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;iBACrB,CAAC;gBACF,MAAM,KAAK,GAA0B,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;gBACxF,MAAM,CAAC,KAAK,CAAC,CAAC;gBACd,MAAM,KAAK,CAAC;YACb,CAAC;oBAAS,CAAC;gBACV,YAAY,CAAC,KAAK,CAAC,CAAC;YACrB,CAAC;QACF,CAAC,CAAC,EAAE,CAAC;IACN,CAAC,CAAC,CAAC;IACJ,OAAO;QACN,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC;QACxE,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;KAC7E,CAAC;AACH,CAAC","sourcesContent":["import {\n\ttype Api,\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype JsonObject,\n\tlazyStream,\n\ttype Model,\n\ttype ProviderStreams,\n\ttype SimpleStreamOptions,\n\ttype TranscriptContext,\n} from \"@earendil-works/pi-ai\";\nimport { truncateErrorText } from \"@earendil-works/pi-ai/utils/error-body\";\nimport { sleep } from \"../../utils/sleep.ts\";\nimport { redactAssistantMessage } from \"../redact-assistant-message.ts\";\nimport { isObject } from \"./client.ts\";\nimport { GATEWAY_USER_AGENT } from \"./constants.ts\";\n\nconst MAX_ATTEMPTS = 3;\nconst MAX_DELAY_MS = 60_000;\nconst MAX_BODY_BYTES = 20_971_520;\n// Every retryable Gateway error body is tiny; anything larger fails closed.\nconst MAX_ERROR_BODY_BYTES = 65_536;\nconst OVERSIZE_MESSAGE = \"Request is larger than HUMAIN Gateway's 20 MiB limit.\";\nconst REQUEST_CEILING_MS = 900_000;\nconst CEILING_MESSAGE = \"HUMAIN Gateway request exceeded the 900-second limit.\";\n\ninterface GatewayHttpDeps {\n\tsleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n\trandom?: () => number;\n\t/** Test hook; production always uses the 900-second ceiling. */\n\trequestCeilingMs?: number;\n}\n\n/** Reads at most MAX_ERROR_BODY_BYTES as JSON or plain proxy text; larger or unreadable bodies yield `undefined`. */\nasync function readErrorBody(response: Response): Promise<unknown> {\n\tif (Number(response.headers.get(\"content-length\")) > MAX_ERROR_BODY_BYTES) return undefined;\n\tconst reader = response.clone().body?.getReader();\n\tif (!reader) return undefined;\n\tconst chunks: Uint8Array[] = [];\n\tlet size = 0;\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tsize += value.byteLength;\n\t\t\tif (size > MAX_ERROR_BODY_BYTES) return undefined;\n\t\t\tchunks.push(value);\n\t\t}\n\t} catch {\n\t\treturn undefined;\n\t} finally {\n\t\t// Stops the clone's tee from buffering the rest of the body.\n\t\treader.cancel().catch(() => undefined);\n\t}\n\tconst text = Buffer.concat(chunks).toString(\"utf8\");\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch {\n\t\treturn text;\n\t}\n}\n\n/**\n * Decide whether a failed Gateway response is safe to resend. Only responses that prove the\n * request never reached a billed model call qualify; everything else fails to avoid double billing.\n */\nexport function classifyGatewayRetry(\n\tstatus: number,\n\tbody: unknown,\n\theaders: Headers,\n\trequestedModel: string,\n): { retry: boolean; delayMs?: number } {\n\tif (headers.get(\"x-should-retry\") === \"false\") return { retry: false };\n\tconst retryAfter = headers.get(\"retry-after\");\n\t// A server delay we cannot read could be later than our backoff; fail instead of resending early.\n\tif (retryAfter !== null && !/^\\d+$/u.test(retryAfter.trim())) return { retry: false };\n\tconst headerDelay = retryAfter === null ? undefined : Number(retryAfter.trim()) * 1000;\n\tconst error = isObject(body) ? body.error : undefined;\n\tlet delayMs: number | undefined;\n\tif (status === 503 && isObject(body) && Object.keys(body).length === 1 && error === \"CLI session unavailable\") {\n\t\tdelayMs = headerDelay;\n\t} else if (\n\t\tstatus === 429 &&\n\t\tisObject(error) &&\n\t\t(error.code === \"gateway_key_limit_exceeded\" || error.type === \"gateway_key_limit_exceeded\")\n\t) {\n\t\tconst fields = isObject(error.fields) ? error.fields : isObject(body) && isObject(body.fields) ? body.fields : {};\n\t\tconst seconds = fields.retry_after_seconds;\n\t\tif (seconds === undefined) delayMs = headerDelay;\n\t\telse if (typeof seconds === \"number\" && Number.isFinite(seconds) && seconds > 0) delayMs = seconds * 1000;\n\t\telse return { retry: false };\n\t} else if (\n\t\tstatus === 429 &&\n\t\theaderDelay !== undefined &&\n\t\t(isObject(error) ? error.message : error) ===\n\t\t\t`No deployments available for model '${requestedModel}'. Try again later.`\n\t) {\n\t\tdelayMs = headerDelay;\n\t} else {\n\t\treturn { retry: false };\n\t}\n\tif (delayMs !== undefined && delayMs > MAX_DELAY_MS) return { retry: false };\n\treturn delayMs === undefined ? { retry: true } : { retry: true, delayMs };\n}\n\n/** Removes `litellm_call_id`, which lets a caller pick the Gateway's billing/log id. */\nfunction stripCallId(body: string): string {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(body);\n\t} catch {\n\t\treturn body;\n\t}\n\tif (!isObject(parsed)) return body;\n\tconst metadata = parsed.metadata;\n\tconst nested = isObject(metadata) && \"litellm_call_id\" in metadata;\n\tif (!(\"litellm_call_id\" in parsed) && !nested) return body;\n\tdelete parsed.litellm_call_id;\n\tif (nested) delete metadata.litellm_call_id;\n\treturn JSON.stringify(parsed);\n}\n\nexport function withHumainGatewayHttp(api: ProviderStreams, deps: GatewayHttpDeps = {}): ProviderStreams {\n\tconst wait = deps.sleep ?? sleep;\n\tconst random = deps.random ?? Math.random;\n\tconst run = (\n\t\tmodel: Model<Api>,\n\t\tcontext: TranscriptContext,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\tsimple: boolean,\n\t) =>\n\t\tlazyStream(model, async () => {\n\t\t\tconst httpError: JsonObject = { retryable: false };\n\t\t\tlet failure: string | undefined;\n\t\t\tlet responseCost: number | undefined;\n\t\t\tlet reportedCost: number | undefined;\n\t\t\tconst key = options?.apiKey;\n\t\t\tconst fetcher = options?.fetch ?? globalThis.fetch;\n\t\t\t// The SDK timeout only bounds time to response headers; the deadline also bounds the stream.\n\t\t\t// A clearable timer (not AbortSignal.timeout) so completed requests retain nothing for 900 s.\n\t\t\tconst deadline = new AbortController();\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tif (!options?.signal?.aborted) failure ??= CEILING_MESSAGE;\n\t\t\t\tdeadline.abort();\n\t\t\t}, deps.requestCeilingMs ?? REQUEST_CEILING_MS);\n\t\t\tconst timeoutMs = options?.timeoutMs;\n\t\t\tconst requestOptions = {\n\t\t\t\t...options,\n\t\t\t\tsignal: options?.signal ? AbortSignal.any([options.signal, deadline.signal]) : deadline.signal,\n\t\t\t\ttimeoutMs:\n\t\t\t\t\ttimeoutMs !== undefined && timeoutMs > 0 && timeoutMs < REQUEST_CEILING_MS\n\t\t\t\t\t\t? timeoutMs\n\t\t\t\t\t\t: REQUEST_CEILING_MS,\n\t\t\t\t// Gateway reports request cost in `response.completed.response.usage.cost`.\n\t\t\t\tonProviderStreamEvent: async (data: unknown, streamModel: Model<Api>) => {\n\t\t\t\t\tif (isObject(data) && data.type === \"response.completed\" && isObject(data.response)) {\n\t\t\t\t\t\tconst cost = isObject(data.response.usage) ? data.response.usage.cost : undefined;\n\t\t\t\t\t\tif (typeof cost === \"number\" && Number.isFinite(cost) && cost >= 0) reportedCost = cost;\n\t\t\t\t\t}\n\t\t\t\t\tawait options?.onProviderStreamEvent?.(data, streamModel);\n\t\t\t\t},\n\t\t\t\t// Retries are owned below; SDK retries could resend a billed request.\n\t\t\t\tmaxRetries: 0,\n\t\t\t\tfetch: async (input: Parameters<typeof fetch>[0], init?: RequestInit): Promise<Response> => {\n\t\t\t\t\tconst headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n\t\t\t\t\tif (key) headers.set(\"Authorization\", `Bearer ${key}`);\n\t\t\t\t\theaders.delete(\"x-api-key\");\n\t\t\t\t\theaders.set(\"User-Agent\", GATEWAY_USER_AGENT);\n\t\t\t\t\tlet body = init?.body;\n\t\t\t\t\tif (typeof body === \"string\") {\n\t\t\t\t\t\tbody = stripCallId(body);\n\t\t\t\t\t\tif (Buffer.byteLength(body) > MAX_BODY_BYTES) {\n\t\t\t\t\t\t\tfailure = OVERSIZE_MESSAGE;\n\t\t\t\t\t\t\tthrow new Error(OVERSIZE_MESSAGE);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst signal = init?.signal ?? options?.signal;\n\t\t\t\t\tfor (let attempt = 0; ; attempt++) {\n\t\t\t\t\t\tconst response = await fetcher(input, { ...init, body, headers, redirect: \"error\" });\n\t\t\t\t\t\tconst requestId = response.headers.get(\"x-litellm-call-id\");\n\t\t\t\t\t\tif (requestId) httpError.requestId = requestId;\n\t\t\t\t\t\telse delete httpError.requestId;\n\t\t\t\t\t\tconst cost = Number(response.headers.get(\"x-litellm-response-cost\") ?? Number.NaN);\n\t\t\t\t\t\tresponseCost = Number.isFinite(cost) && cost >= 0 ? cost : undefined;\n\t\t\t\t\t\tif (response.ok) return response;\n\t\t\t\t\t\tconst responseBody = await readErrorBody(response);\n\t\t\t\t\t\tconst decision = classifyGatewayRetry(response.status, responseBody, response.headers, model.id);\n\t\t\t\t\t\tif (!decision.retry || attempt + 1 >= MAX_ATTEMPTS) {\n\t\t\t\t\t\t\thttpError.status = response.status;\n\t\t\t\t\t\t\tconst error = isObject(responseBody) ? responseBody.error : undefined;\n\t\t\t\t\t\t\tif (response.status >= 500 && response.status <= 599) {\n\t\t\t\t\t\t\t\tconst upstream = isObject(error) ? error.message : (error ?? responseBody);\n\t\t\t\t\t\t\t\tif (typeof upstream === \"string\") {\n\t\t\t\t\t\t\t\t\t// Sanitize the whole upstream text before extracting/bounding a reset reason.\n\t\t\t\t\t\t\t\t\tconst safe = truncateErrorText(\n\t\t\t\t\t\t\t\t\t\tkey ? upstream.replaceAll(key, \"[REDACTED]\") : upstream,\n\t\t\t\t\t\t\t\t\t\tMAX_ERROR_BODY_BYTES,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\thttpError.reason = truncateErrorText(\n\t\t\t\t\t\t\t\t\t\t`HTTP ${response.status}: ${safe.match(/\\breset reason:[^\\r\\n]*/iu)?.[0] ?? safe}`,\n\t\t\t\t\t\t\t\t\t\t120,\n\t\t\t\t\t\t\t\t\t).replace(/\\s+/gu, \" \");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst code = isObject(error) ? (error.code ?? error.type) : undefined;\n\t\t\t\t\t\t\tif (typeof code === \"string\") httpError.code = key ? code.replaceAll(key, \"[redacted]\") : code;\n\t\t\t\t\t\t\telse delete httpError.code;\n\t\t\t\t\t\t\tconst responseHeaders = new Headers(response.headers);\n\t\t\t\t\t\t\tresponseHeaders.set(\"x-should-retry\", \"false\");\n\t\t\t\t\t\t\treturn new Response(response.body, {\n\t\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t\t\tstatusText: response.statusText,\n\t\t\t\t\t\t\t\theaders: responseHeaders,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait response.body?.cancel().catch(() => undefined);\n\t\t\t\t\t\tconst backoff = Math.min(MAX_DELAY_MS, 1000 * 2 ** attempt) * (0.5 + random() / 2);\n\t\t\t\t\t\tawait wait(Math.max(decision.delayMs ?? 0, backoff), signal ?? undefined);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst source = simple\n\t\t\t\t? api.streamSimple(model, context, requestOptions)\n\t\t\t\t: api.stream(model, context, requestOptions);\n\t\t\tconst finish = (event: AssistantMessageEvent): void => {\n\t\t\t\tif (event.type !== \"done\" && event.type !== \"error\") return;\n\t\t\t\tconst message = event.type === \"done\" ? event.message : event.error;\n\t\t\t\tconst cost = reportedCost ?? responseCost;\n\t\t\t\tif (cost !== undefined && message.usage.cost.total === 0) message.usage.cost.total = cost;\n\t\t\t\tif (event.type === \"error\") {\n\t\t\t\t\t// A ceiling abort is a Gateway failure, not a user cancellation.\n\t\t\t\t\tif (failure === CEILING_MESSAGE && !options?.signal?.aborted) {\n\t\t\t\t\t\tevent.reason = \"error\";\n\t\t\t\t\t\tevent.error.stopReason = \"error\";\n\t\t\t\t\t}\n\t\t\t\t\tconst status = httpError.status;\n\t\t\t\t\tconst unavailable =\n\t\t\t\t\t\ttypeof status === \"number\" &&\n\t\t\t\t\t\tstatus >= 500 &&\n\t\t\t\t\t\tstatus <= 599 &&\n\t\t\t\t\t\tevent.reason !== \"aborted\" &&\n\t\t\t\t\t\t!options?.signal?.aborted;\n\t\t\t\t\tconst requestId = httpError.requestId;\n\t\t\t\t\tevent.error.errorMessage = [\n\t\t\t\t\t\tfailure ??\n\t\t\t\t\t\t\t(unavailable\n\t\t\t\t\t\t\t\t? `HUMAIN Gateway is temporarily unavailable (HTTP ${status}). Try again in a moment.`\n\t\t\t\t\t\t\t\t: event.error.errorMessage) ??\n\t\t\t\t\t\t\t\"HUMAIN Gateway request failed\",\n\t\t\t\t\t\t!unavailable && typeof httpError.code === \"string\" && `code: ${httpError.code}`,\n\t\t\t\t\t\t!unavailable && typeof requestId === \"string\" && `x-litellm-call-id: ${requestId}`,\n\t\t\t\t\t]\n\t\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t\t.join(\"; \");\n\t\t\t\t\t// Gateway retries already happened above; agent-level retry must never resend.\n\t\t\t\t\tevent.error.diagnostics = [\n\t\t\t\t\t\t...(event.error.diagnostics ?? []),\n\t\t\t\t\t\t{ type: \"provider_http_error\", timestamp: Date.now(), details: { ...httpError } },\n\t\t\t\t\t];\n\t\t\t\t}\n\t\t\t\tredactAssistantMessage(message, key);\n\t\t\t};\n\t\t\treturn (async function* (): AsyncGenerator<AssistantMessageEvent> {\n\t\t\t\tlet ended = false;\n\t\t\t\ttry {\n\t\t\t\t\tfor await (const event of source) {\n\t\t\t\t\t\tfinish(event);\n\t\t\t\t\t\tended ||= event.type === \"done\" || event.type === \"error\";\n\t\t\t\t\t\tyield event;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (ended) throw error;\n\t\t\t\t\t// lazyStream would turn this throw into an error without the non-retryable diagnostic.\n\t\t\t\t\tconst message: AssistantMessage = {\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent: [],\n\t\t\t\t\t\tapi: model.api,\n\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\tmodel: model.id,\n\t\t\t\t\t\tusage: {\n\t\t\t\t\t\t\tusageIncomplete: true,\n\t\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstopReason: \"error\",\n\t\t\t\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t};\n\t\t\t\t\tconst event: AssistantMessageEvent = { type: \"error\", reason: \"error\", error: message };\n\t\t\t\t\tfinish(event);\n\t\t\t\t\tyield event;\n\t\t\t\t} finally {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t})();\n\t\t});\n\treturn {\n\t\tstream: (model, context, options) => run(model, context, options, false),\n\t\tstreamSimple: (model, context, options) => run(model, context, options, true),\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../src/humain/gateway/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,KAAK,UAAU,EAGf,KAAK,QAAQ,EAEb,MAAM,uBAAuB,CAAC;AAI/B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../src/humain/gateway/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,KAAK,UAAU,EAGf,KAAK,QAAQ,EAEb,MAAM,uBAAuB,CAAC;AAI/B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AAY3D,OAAO,EAKN,KAAK,kBAAkB,EAEvB,MAAM,gBAAgB,CAAC;AAIxB,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAEzD,UAAU,yBAAyB;IAClC,WAAW,CAAC,EAAE,MAAM,kBAAkB,CAAC;IACvC,QAAQ,CAAC,EAAE,mBAAmB,CAAC;IAC/B,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACrB;AAcD;;;;GAIG;AACH,wBAAgB,sBAAsB,CACrC,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,MAAM,GACd;IAAE,WAAW,EAAE,kBAAkB,CAAC;IAAC,EAAE,EAAE,OAAO,CAAA;CAAE,CAQlD;AA8DD,wBAAgB,oCAAoC,IAAI,IAAI,CAE3D;AAED;;;GAGG;AACH,wBAAgB,+BAA+B,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,UAAQ,GAAG,OAAO,CAE5G;AAkCD;;;GAGG;AACH,wBAAsB,oBAAoB,CACzC,IAAI,GAAE,yBAAyB,GAAG;IAAE,cAAc,CAAC,EAAE,MAAM,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAA;CAAO,GAC/F,OAAO,CAAC,IAAI,CAAC,CAMf;AAED,wBAAgB,2BAA2B,CAAC,IAAI,GAAE,yBAA8B,GAAG,QAAQ,CAyI1F"}
|
|
@@ -4,7 +4,7 @@ import { getAgentDir } from "../../config.js";
|
|
|
4
4
|
import { ReadOnlyAuthStorage } from "../../core/auth-storage.js";
|
|
5
5
|
import { SettingsManager } from "../../core/settings-manager.js";
|
|
6
6
|
import { DEFAULT_BLOCK_REASON, deriveGatewayCatalog, GATEWAY_SETUP_WARNING } from "./catalog.js";
|
|
7
|
-
import { fetchGatewayAccess, fetchGatewayModels, GatewayBudgetExhaustedError, GatewaySessionUnavailableError, } from "./client.js";
|
|
7
|
+
import { fetchGatewayAccess, fetchGatewayModels, GatewayBudgetExhaustedError, GatewayRequestError, GatewaySessionUnavailableError, } from "./client.js";
|
|
8
8
|
import { GATEWAY_BASE_URLS, GATEWAY_ENV_ENVIRONMENT, GATEWAY_ENV_SESSION_ID, GATEWAY_ENV_USER_ID, HUMAIN_GATEWAY_PROVIDER, } from "./constants.js";
|
|
9
9
|
import { withHumainGatewayHttp } from "./http.js";
|
|
10
10
|
import { loginToGateway, revokePendingSessions } from "./login.js";
|
|
@@ -108,6 +108,7 @@ function mapRefreshResults(listed, accessed) {
|
|
|
108
108
|
return { models: listed.value };
|
|
109
109
|
// Budget: keep the last good list for this scope; other failures never fabricate a catalog.
|
|
110
110
|
const setupPending = !(listed.reason instanceof GatewayBudgetExhaustedError) &&
|
|
111
|
+
!(listed.reason instanceof GatewayRequestError && listed.reason.status >= 500) &&
|
|
111
112
|
accessed.status === "fulfilled" &&
|
|
112
113
|
accessed.value.accessKind === "unknown";
|
|
113
114
|
return { error: setupPending ? new Error(GATEWAY_SETUP_WARNING) : listed.reason, clearCatalog: false };
|
|
@@ -237,7 +238,13 @@ export function createHumainGatewayProvider(deps = {}) {
|
|
|
237
238
|
await saveBlockedModels(sessions, env, session.userId, previouslyBlocked, catalog.blocked);
|
|
238
239
|
if (!(await publish(catalog.eligible.map((entry) => toModel(entry, env)))))
|
|
239
240
|
return;
|
|
240
|
-
const
|
|
241
|
+
const accessError = accessed.status === "rejected" ? accessed.reason : undefined;
|
|
242
|
+
const accessWarning = accessError instanceof GatewayRequestError && accessError.status >= 500
|
|
243
|
+
? accessError.message
|
|
244
|
+
: !access
|
|
245
|
+
? ACCESS_READ_WARNING
|
|
246
|
+
: undefined;
|
|
247
|
+
const warnings = accessWarning ? [...catalog.warnings, accessWarning] : catalog.warnings;
|
|
241
248
|
const listedIds = new Set(listing.models.map((entry) => entry.id));
|
|
242
249
|
const blocked = Object.entries(catalog.blocked)
|
|
243
250
|
.filter(([id]) => listedIds.has(id))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/humain/gateway/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,cAAc,GAId,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,kBAAkB,EAAE,MAAM,iDAAiD,CAAC;AACrF,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAEjE,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AACjG,OAAO,EACN,kBAAkB,EAClB,kBAAkB,EAElB,2BAA2B,EAE3B,8BAA8B,GAC9B,MAAM,aAAa,CAAC;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M,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;iBACnC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACnD,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;YAC3C,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,YAAY,EAAE,KAAK,KAAK,KAAK,IAAI,YAAY,CAAC,GAAG,KAAK,UAAU,CAAC,EAAE,CAAC;gBAC9F,QAAQ,CAAC,IAAI,CACZ,8CAA8C,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC,MAAM,KAAK,oBAAoB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,MAAM,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACtJ,CAAC;YACH,CAAC;YACD,YAAY,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,UAAU,EAAE,CAAC;YAC1C,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QAC9D,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import {\n\ttype Api,\n\ttype ApiKeyAuth,\n\ttype AuthResult,\n\ttype Credential,\n\tcreateProvider,\n\ttype Model,\n\ttype Provider,\n\ttype RefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { openAIResponsesApi } from \"@earendil-works/pi-ai/api/openai-responses.lazy\";\nimport { getAgentDir } from \"../../config.ts\";\nimport { ReadOnlyAuthStorage } from \"../../core/auth-storage.ts\";\nimport type { AppMode } from \"../../core/project-trust.ts\";\nimport { SettingsManager } from \"../../core/settings-manager.ts\";\nimport { DEFAULT_BLOCK_REASON, deriveGatewayCatalog, GATEWAY_SETUP_WARNING } from \"./catalog.ts\";\nimport {\n\tfetchGatewayAccess,\n\tfetchGatewayModels,\n\ttype GatewayAccess,\n\tGatewayBudgetExhaustedError,\n\ttype GatewayModelEntry,\n\tGatewaySessionUnavailableError,\n} from \"./client.ts\";\nimport {\n\tGATEWAY_BASE_URLS,\n\tGATEWAY_ENV_ENVIRONMENT,\n\tGATEWAY_ENV_SESSION_ID,\n\tGATEWAY_ENV_USER_ID,\n\ttype GatewayEnvironment,\n\tHUMAIN_GATEWAY_PROVIDER,\n} from \"./constants.ts\";\nimport { withHumainGatewayHttp } from \"./http.ts\";\nimport { loginToGateway, revokePendingSessions } from \"./login.ts\";\nimport { createGatewaySecretStore, type GatewaySecretStore } from \"./secret-store.ts\";\nimport { GatewaySessionStore } from \"./session-store.ts\";\n\ninterface HumainGatewayProviderDeps {\n\tenvironment?: () => GatewayEnvironment;\n\tsessions?: GatewaySessionStore;\n\tfetch?: typeof fetch;\n}\n\nconst ACCESS_RETRY_MS = 60_000;\nconst ACCESS_READ_WARNING = \"HUMAIN Gateway could not read account restrictions; showing all listed models.\";\nconst ZERO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\n/** Used when no access answer exists: `/v1/models` stays authoritative and stored blocks are kept. */\nconst NULL_LABEL_ACCESS: GatewayAccess = {\n\taccessKind: \"unrestricted\",\n\tmodels: [],\n\tmodelModes: {},\n\tharnessLabels: null,\n\tdegraded: null,\n};\n\n/**\n * Global user settings only: a repository's project settings must never redirect Gateway credentials.\n * `ok` is false when the global settings read failed (e.g. a lock held by another process), so the\n * production fallback must not be cached.\n */\nexport function readGatewayEnvironment(\n\tcwd: string,\n\tagentDir: string,\n): { environment: GatewayEnvironment; ok: boolean } {\n\tconst settings = SettingsManager.create(cwd, agentDir);\n\tconst gateway = settings.getGlobalSettings().humainGateway;\n\tconst environment = gateway?.environment === \"staging\" ? \"staging\" : \"production\";\n\treturn {\n\t\tenvironment,\n\t\tok: !settings.drainErrors().some((error) => error.scope === \"global\"),\n\t};\n}\n\nconst baseUrlFor = (environment: GatewayEnvironment) => `${GATEWAY_BASE_URLS[environment]}/v1`;\n\n/** Non-secret session reference from `auth.json`, only when it belongs to the selected environment. */\nfunction sessionOf(\n\tcredential: Credential | undefined,\n\tenvironment: GatewayEnvironment,\n): { id: string; userId: string } | undefined {\n\tconst env = credential?.type === \"api_key\" ? credential.env : undefined;\n\tconst id = env?.[GATEWAY_ENV_SESSION_ID];\n\tif (env?.[GATEWAY_ENV_ENVIRONMENT] !== environment || typeof id !== \"string\" || !id) return undefined;\n\tconst userId = env[GATEWAY_ENV_USER_ID];\n\treturn { id, userId: typeof userId === \"string\" ? userId : \"\" };\n}\n\nfunction toModel(\n\tentry: { id: string; contextWindow: number; maxTokens: number },\n\tenvironment: GatewayEnvironment,\n): Model<Api> {\n\treturn {\n\t\tid: entry.id,\n\t\tname: environment === \"staging\" ? `${entry.id} (staging)` : entry.id,\n\t\tapi: \"openai-responses\",\n\t\tprovider: HUMAIN_GATEWAY_PROVIDER,\n\t\tbaseUrl: baseUrlFor(environment),\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: ZERO_COST,\n\t\tcontextWindow: entry.contextWindow,\n\t\tmaxTokens: entry.maxTokens,\n\t\t// The Gateway pairs tool results with calls by position; Kimi K3 rejects batched parallel results.\n\t\tcompat: { requiresAdjacentToolResults: true },\n\t};\n}\n\n/** Defers platform detection to first use: a missing keychain must fail sign-in, not provider registration. */\nfunction lazySecretStore(): GatewaySecretStore {\n\tlet store: GatewaySecretStore | undefined;\n\tconst resolve = () => {\n\t\tstore ??= createGatewaySecretStore();\n\t\treturn store;\n\t};\n\treturn {\n\t\tget: async (account) => resolve().get(account),\n\t\tset: async (account, secret) => resolve().set(account, secret),\n\t\tdelete: async (account) => resolve().delete(account),\n\t};\n}\n\nlet processEnvironment: GatewayEnvironment | undefined;\n/**\n * Cached per process after a clean read: settings reads take file locks and fall back to production when\n * another process holds them, so a failed read is retried. Changing `humainGateway.environment` therefore needs a restart.\n */\nconst defaultEnvironment = () => {\n\tif (processEnvironment) return processEnvironment;\n\tconst { environment, ok } = readGatewayEnvironment(process.cwd(), getAgentDir());\n\tif (ok) processEnvironment = environment;\n\treturn environment;\n};\n\nexport function resetGatewayEnvironmentCacheForTests(): void {\n\tprocessEnvironment = undefined;\n}\n\n/**\n * Only interactive sessions reconcile at startup: print, JSON and RPC processes are short-lived, and a\n * background revocation would keep them alive.\n */\nexport function shouldReconcileGatewayOnStartup(mode: AppMode, offline: boolean, listModels = false): boolean {\n\treturn mode === \"interactive\" && !offline && !listModels;\n}\n\ntype RefreshListing = { models: GatewayModelEntry[] } | { error: unknown; clearCatalog: boolean };\n\n/** Maps the settled reads of a refresh to the listed models or the error to report. */\nfunction mapRefreshResults(\n\tlisted: PromiseSettledResult<GatewayModelEntry[]>,\n\taccessed: PromiseSettledResult<GatewayAccess>,\n): RefreshListing {\n\tfor (const result of [listed, accessed]) {\n\t\tif (result.status === \"rejected\" && result.reason instanceof GatewaySessionUnavailableError) {\n\t\t\treturn { error: result.reason, clearCatalog: true };\n\t\t}\n\t}\n\tif (listed.status === \"fulfilled\") return { models: listed.value };\n\t// Budget: keep the last good list for this scope; other failures never fabricate a catalog.\n\tconst setupPending =\n\t\t!(listed.reason instanceof GatewayBudgetExhaustedError) &&\n\t\taccessed.status === \"fulfilled\" &&\n\t\taccessed.value.accessKind === \"unknown\";\n\treturn { error: setupPending ? new Error(GATEWAY_SETUP_WARNING) : listed.reason, clearCatalog: false };\n}\n\nasync function saveBlockedModels(\n\tsessions: GatewaySessionStore,\n\tenvironment: GatewayEnvironment,\n\tuserId: string,\n\tprevious: Record<string, string>,\n\tnext: Record<string, string>,\n): Promise<void> {\n\tif (JSON.stringify(next) !== JSON.stringify(previous)) await sessions.setBlockedModels(environment, userId, next);\n}\n\n/**\n * Startup reconciliation: revokes sessions orphaned by `/logout`, which leaves no credential and so\n * never reaches the refresh network phase. Touches the keychain only when pending records exist.\n */\nexport async function revokeGatewayOrphans(\n\tdeps: HumainGatewayProviderDeps & { readCredential?: () => Promise<Credential | undefined> } = {},\n): Promise<void> {\n\tconst env = (deps.environment ?? defaultEnvironment)();\n\tconst sessions = deps.sessions ?? new GatewaySessionStore({ secrets: lazySecretStore() });\n\tconst readCredential = deps.readCredential ?? (() => new ReadOnlyAuthStorage().readRaw(HUMAIN_GATEWAY_PROVIDER));\n\tawait sessions.markOrphansPending(env, sessionOf(await readCredential(), env)?.id);\n\tawait revokePendingSessions(GATEWAY_BASE_URLS[env], env, sessions, deps.fetch);\n}\n\nexport function createHumainGatewayProvider(deps: HumainGatewayProviderDeps = {}): Provider {\n\tconst environment = deps.environment ?? defaultEnvironment;\n\tconst sessions = deps.sessions ?? new GatewaySessionStore({ secrets: lazySecretStore() });\n\tlet models: readonly Model<Api>[] = [];\n\tlet activeScope: string | undefined;\n\t// Last successful access read, for one scope only.\n\tlet lastAccess: { scope: string; access: GatewayAccess; at: number } | undefined;\n\tconst lastAccessFor = (scope: string) => (lastAccess?.scope === scope ? lastAccess.access : undefined);\n\t// Last blocked set shown for one scope, so an unchanged set is not repeated.\n\tlet shownBlocked: { scope: string; key: string } | undefined;\n\n\t/** Refetched every refresh, except within 60 s of an unknown or degraded answer. */\n\tconst loadAccess = async (\n\t\tscope: string,\n\t\tbaseUrl: string,\n\t\ttoken: string,\n\t\toptions: { fetch?: typeof fetch; signal: AbortSignal },\n\t): Promise<GatewayAccess> => {\n\t\tconst now = Date.now();\n\t\tconst last = lastAccess?.scope === scope ? lastAccess : undefined;\n\t\tif (\n\t\t\tlast &&\n\t\t\t(last.access.accessKind === \"unknown\" || last.access.degraded !== null) &&\n\t\t\tnow - last.at < ACCESS_RETRY_MS\n\t\t) {\n\t\t\treturn last.access;\n\t\t}\n\t\tconst access = await fetchGatewayAccess(baseUrl, token, options);\n\t\tif (!options.signal.aborted) lastAccess = { scope, access, at: now };\n\t\treturn access;\n\t};\n\n\tconst apiKeyAuth: ApiKeyAuth = {\n\t\tname: \"HUMAIN Gateway\",\n\t\tlogin: (interaction) => loginToGateway(interaction, { environment: environment(), sessions, fetch: deps.fetch }),\n\t\t// Metadata only: listing must not touch the keychain or the network.\n\t\tcheck: async ({ credential, signal }) => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst env = environment();\n\t\t\treturn sessionOf(credential, env)\n\t\t\t\t? { type: \"api_key\" as const, source: `HUMAIN Gateway (${env})` }\n\t\t\t\t: undefined;\n\t\t},\n\t\tresolve: async ({ credential, signal }): Promise<AuthResult | undefined> => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst env = environment();\n\t\t\tconst session = sessionOf(credential, env);\n\t\t\tconst token = session ? await sessions.getToken(session.id) : undefined;\n\t\t\tif (!token) return undefined;\n\t\t\t// `env` carries only the non-secret session reference so catalog refreshes keep their scope.\n\t\t\treturn {\n\t\t\t\tauth: { apiKey: token, baseUrl: baseUrlFor(env) },\n\t\t\t\tenv: { ...credential?.env },\n\t\t\t\tsource: `HUMAIN Gateway (${env})`,\n\t\t\t};\n\t\t},\n\t};\n\n\tconst base = createProvider({\n\t\tid: HUMAIN_GATEWAY_PROVIDER,\n\t\tname: \"HUMAIN Gateway\",\n\t\tbaseUrl: baseUrlFor(\"production\"),\n\t\tauth: { apiKey: apiKeyAuth },\n\t\tmodels: [],\n\t\tapi: { \"openai-responses\": withHumainGatewayHttp(openAIResponsesApi()) },\n\t});\n\n\treturn {\n\t\t...base,\n\t\tgetModels: () => models,\n\t\trefreshModels: async (context: RefreshModelsContext) => {\n\t\t\tconst env = environment();\n\t\t\tconst session = sessionOf(context.credential, env);\n\t\t\tconst scope = session ? `${env}\\0${session.id}` : undefined;\n\t\t\tconst publish = (next: readonly Model<Api>[]) =>\n\t\t\t\tcontext.publish({\n\t\t\t\t\tpersist: null,\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tmodels = next;\n\t\t\t\t\t\tactiveScope = scope;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\tif (scope !== activeScope && !(await publish([]))) return;\n\t\t\t// No session can mean an unreadable auth.json, a runtime key override, or another agentDir;\n\t\t\t// logout cleanup is left to revokeGatewayOrphans, which stops when the credential read fails.\n\t\t\tif (session) await sessions.markOrphansPending(env, session.id);\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\tconst baseUrl = GATEWAY_BASE_URLS[env];\n\t\t\tawait revokePendingSessions(baseUrl, env, sessions, deps.fetch);\n\t\t\t// The network phase receives the token resolved in-process as `key`.\n\t\t\tconst token = context.credential?.type === \"api_key\" ? context.credential.key : undefined;\n\t\t\tif (!session || !scope || !token) return;\n\n\t\t\tconst options = { fetch: deps.fetch, signal: context.signal };\n\t\t\tconst [listed, accessed] = await Promise.allSettled([\n\t\t\t\tfetchGatewayModels(baseUrl, token, options),\n\t\t\t\tloadAccess(scope, baseUrl, token, options),\n\t\t\t]);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst listing = mapRefreshResults(listed, accessed);\n\t\t\tif (\"error\" in listing) {\n\t\t\t\tif (listing.clearCatalog) await publish([]);\n\t\t\t\tthrow listing.error;\n\t\t\t}\n\n\t\t\t// A failed access read reuses this scope's last answer; without one, `/v1/models` alone decides.\n\t\t\tconst access = accessed.status === \"fulfilled\" ? accessed.value : lastAccessFor(scope);\n\t\t\tconst previouslyBlocked = await sessions.getBlockedModels(env, session.userId);\n\t\t\tconst catalog = deriveGatewayCatalog({\n\t\t\t\tmodels: listing.models,\n\t\t\t\taccess: access ?? NULL_LABEL_ACCESS,\n\t\t\t\tpreviouslyBlocked,\n\t\t\t});\n\t\t\tawait saveBlockedModels(sessions, env, session.userId, previouslyBlocked, catalog.blocked);\n\t\t\tif (!(await publish(catalog.eligible.map((entry) => toModel(entry, env))))) return;\n\t\t\tconst warnings = access ? catalog.warnings : [...catalog.warnings, ACCESS_READ_WARNING];\n\t\t\tconst listedIds = new Set(listing.models.map((entry) => entry.id));\n\t\t\tconst blocked = Object.entries(catalog.blocked)\n\t\t\t\t.filter(([id]) => listedIds.has(id))\n\t\t\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\t\t\tconst blockedKey = JSON.stringify(blocked);\n\t\t\tif (blocked.length > 0 && (shownBlocked?.scope !== scope || shownBlocked.key !== blockedKey)) {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Blocked for HUMAIN Code by HUMAIN Gateway: ${blocked.map(([id, reason]) => (reason === DEFAULT_BLOCK_REASON ? id : `${id} (${reason})`)).join(\"; \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tshownBlocked = { scope, key: blockedKey };\n\t\t\tif (warnings.length > 0) throw new Error(warnings.join(\" \"));\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/humain/gateway/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,cAAc,GAId,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,kBAAkB,EAAE,MAAM,iDAAiD,CAAC;AACrF,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAEjE,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AACjG,OAAO,EACN,kBAAkB,EAClB,kBAAkB,EAElB,2BAA2B,EAE3B,mBAAmB,EACnB,8BAA8B,GAC9B,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,iBAAiB,EACjB,uBAAuB,EACvB,sBAAsB,EACtB,mBAA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,GAAG,EAAE,UAAU,EAAE,CAAC;YAC1C,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QAC9D,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import {\n\ttype Api,\n\ttype ApiKeyAuth,\n\ttype AuthResult,\n\ttype Credential,\n\tcreateProvider,\n\ttype Model,\n\ttype Provider,\n\ttype RefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { openAIResponsesApi } from \"@earendil-works/pi-ai/api/openai-responses.lazy\";\nimport { getAgentDir } from \"../../config.ts\";\nimport { ReadOnlyAuthStorage } from \"../../core/auth-storage.ts\";\nimport type { AppMode } from \"../../core/project-trust.ts\";\nimport { SettingsManager } from \"../../core/settings-manager.ts\";\nimport { DEFAULT_BLOCK_REASON, deriveGatewayCatalog, GATEWAY_SETUP_WARNING } from \"./catalog.ts\";\nimport {\n\tfetchGatewayAccess,\n\tfetchGatewayModels,\n\ttype GatewayAccess,\n\tGatewayBudgetExhaustedError,\n\ttype GatewayModelEntry,\n\tGatewayRequestError,\n\tGatewaySessionUnavailableError,\n} from \"./client.ts\";\nimport {\n\tGATEWAY_BASE_URLS,\n\tGATEWAY_ENV_ENVIRONMENT,\n\tGATEWAY_ENV_SESSION_ID,\n\tGATEWAY_ENV_USER_ID,\n\ttype GatewayEnvironment,\n\tHUMAIN_GATEWAY_PROVIDER,\n} from \"./constants.ts\";\nimport { withHumainGatewayHttp } from \"./http.ts\";\nimport { loginToGateway, revokePendingSessions } from \"./login.ts\";\nimport { createGatewaySecretStore, type GatewaySecretStore } from \"./secret-store.ts\";\nimport { GatewaySessionStore } from \"./session-store.ts\";\n\ninterface HumainGatewayProviderDeps {\n\tenvironment?: () => GatewayEnvironment;\n\tsessions?: GatewaySessionStore;\n\tfetch?: typeof fetch;\n}\n\nconst ACCESS_RETRY_MS = 60_000;\nconst ACCESS_READ_WARNING = \"HUMAIN Gateway could not read account restrictions; showing all listed models.\";\nconst ZERO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\n/** Used when no access answer exists: `/v1/models` stays authoritative and stored blocks are kept. */\nconst NULL_LABEL_ACCESS: GatewayAccess = {\n\taccessKind: \"unrestricted\",\n\tmodels: [],\n\tmodelModes: {},\n\tharnessLabels: null,\n\tdegraded: null,\n};\n\n/**\n * Global user settings only: a repository's project settings must never redirect Gateway credentials.\n * `ok` is false when the global settings read failed (e.g. a lock held by another process), so the\n * production fallback must not be cached.\n */\nexport function readGatewayEnvironment(\n\tcwd: string,\n\tagentDir: string,\n): { environment: GatewayEnvironment; ok: boolean } {\n\tconst settings = SettingsManager.create(cwd, agentDir);\n\tconst gateway = settings.getGlobalSettings().humainGateway;\n\tconst environment = gateway?.environment === \"staging\" ? \"staging\" : \"production\";\n\treturn {\n\t\tenvironment,\n\t\tok: !settings.drainErrors().some((error) => error.scope === \"global\"),\n\t};\n}\n\nconst baseUrlFor = (environment: GatewayEnvironment) => `${GATEWAY_BASE_URLS[environment]}/v1`;\n\n/** Non-secret session reference from `auth.json`, only when it belongs to the selected environment. */\nfunction sessionOf(\n\tcredential: Credential | undefined,\n\tenvironment: GatewayEnvironment,\n): { id: string; userId: string } | undefined {\n\tconst env = credential?.type === \"api_key\" ? credential.env : undefined;\n\tconst id = env?.[GATEWAY_ENV_SESSION_ID];\n\tif (env?.[GATEWAY_ENV_ENVIRONMENT] !== environment || typeof id !== \"string\" || !id) return undefined;\n\tconst userId = env[GATEWAY_ENV_USER_ID];\n\treturn { id, userId: typeof userId === \"string\" ? userId : \"\" };\n}\n\nfunction toModel(\n\tentry: { id: string; contextWindow: number; maxTokens: number },\n\tenvironment: GatewayEnvironment,\n): Model<Api> {\n\treturn {\n\t\tid: entry.id,\n\t\tname: environment === \"staging\" ? `${entry.id} (staging)` : entry.id,\n\t\tapi: \"openai-responses\",\n\t\tprovider: HUMAIN_GATEWAY_PROVIDER,\n\t\tbaseUrl: baseUrlFor(environment),\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: ZERO_COST,\n\t\tcontextWindow: entry.contextWindow,\n\t\tmaxTokens: entry.maxTokens,\n\t\t// The Gateway pairs tool results with calls by position; Kimi K3 rejects batched parallel results.\n\t\tcompat: { requiresAdjacentToolResults: true },\n\t};\n}\n\n/** Defers platform detection to first use: a missing keychain must fail sign-in, not provider registration. */\nfunction lazySecretStore(): GatewaySecretStore {\n\tlet store: GatewaySecretStore | undefined;\n\tconst resolve = () => {\n\t\tstore ??= createGatewaySecretStore();\n\t\treturn store;\n\t};\n\treturn {\n\t\tget: async (account) => resolve().get(account),\n\t\tset: async (account, secret) => resolve().set(account, secret),\n\t\tdelete: async (account) => resolve().delete(account),\n\t};\n}\n\nlet processEnvironment: GatewayEnvironment | undefined;\n/**\n * Cached per process after a clean read: settings reads take file locks and fall back to production when\n * another process holds them, so a failed read is retried. Changing `humainGateway.environment` therefore needs a restart.\n */\nconst defaultEnvironment = () => {\n\tif (processEnvironment) return processEnvironment;\n\tconst { environment, ok } = readGatewayEnvironment(process.cwd(), getAgentDir());\n\tif (ok) processEnvironment = environment;\n\treturn environment;\n};\n\nexport function resetGatewayEnvironmentCacheForTests(): void {\n\tprocessEnvironment = undefined;\n}\n\n/**\n * Only interactive sessions reconcile at startup: print, JSON and RPC processes are short-lived, and a\n * background revocation would keep them alive.\n */\nexport function shouldReconcileGatewayOnStartup(mode: AppMode, offline: boolean, listModels = false): boolean {\n\treturn mode === \"interactive\" && !offline && !listModels;\n}\n\ntype RefreshListing = { models: GatewayModelEntry[] } | { error: unknown; clearCatalog: boolean };\n\n/** Maps the settled reads of a refresh to the listed models or the error to report. */\nfunction mapRefreshResults(\n\tlisted: PromiseSettledResult<GatewayModelEntry[]>,\n\taccessed: PromiseSettledResult<GatewayAccess>,\n): RefreshListing {\n\tfor (const result of [listed, accessed]) {\n\t\tif (result.status === \"rejected\" && result.reason instanceof GatewaySessionUnavailableError) {\n\t\t\treturn { error: result.reason, clearCatalog: true };\n\t\t}\n\t}\n\tif (listed.status === \"fulfilled\") return { models: listed.value };\n\t// Budget: keep the last good list for this scope; other failures never fabricate a catalog.\n\tconst setupPending =\n\t\t!(listed.reason instanceof GatewayBudgetExhaustedError) &&\n\t\t!(listed.reason instanceof GatewayRequestError && listed.reason.status >= 500) &&\n\t\taccessed.status === \"fulfilled\" &&\n\t\taccessed.value.accessKind === \"unknown\";\n\treturn { error: setupPending ? new Error(GATEWAY_SETUP_WARNING) : listed.reason, clearCatalog: false };\n}\n\nasync function saveBlockedModels(\n\tsessions: GatewaySessionStore,\n\tenvironment: GatewayEnvironment,\n\tuserId: string,\n\tprevious: Record<string, string>,\n\tnext: Record<string, string>,\n): Promise<void> {\n\tif (JSON.stringify(next) !== JSON.stringify(previous)) await sessions.setBlockedModels(environment, userId, next);\n}\n\n/**\n * Startup reconciliation: revokes sessions orphaned by `/logout`, which leaves no credential and so\n * never reaches the refresh network phase. Touches the keychain only when pending records exist.\n */\nexport async function revokeGatewayOrphans(\n\tdeps: HumainGatewayProviderDeps & { readCredential?: () => Promise<Credential | undefined> } = {},\n): Promise<void> {\n\tconst env = (deps.environment ?? defaultEnvironment)();\n\tconst sessions = deps.sessions ?? new GatewaySessionStore({ secrets: lazySecretStore() });\n\tconst readCredential = deps.readCredential ?? (() => new ReadOnlyAuthStorage().readRaw(HUMAIN_GATEWAY_PROVIDER));\n\tawait sessions.markOrphansPending(env, sessionOf(await readCredential(), env)?.id);\n\tawait revokePendingSessions(GATEWAY_BASE_URLS[env], env, sessions, deps.fetch);\n}\n\nexport function createHumainGatewayProvider(deps: HumainGatewayProviderDeps = {}): Provider {\n\tconst environment = deps.environment ?? defaultEnvironment;\n\tconst sessions = deps.sessions ?? new GatewaySessionStore({ secrets: lazySecretStore() });\n\tlet models: readonly Model<Api>[] = [];\n\tlet activeScope: string | undefined;\n\t// Last successful access read, for one scope only.\n\tlet lastAccess: { scope: string; access: GatewayAccess; at: number } | undefined;\n\tconst lastAccessFor = (scope: string) => (lastAccess?.scope === scope ? lastAccess.access : undefined);\n\t// Last blocked set shown for one scope, so an unchanged set is not repeated.\n\tlet shownBlocked: { scope: string; key: string } | undefined;\n\n\t/** Refetched every refresh, except within 60 s of an unknown or degraded answer. */\n\tconst loadAccess = async (\n\t\tscope: string,\n\t\tbaseUrl: string,\n\t\ttoken: string,\n\t\toptions: { fetch?: typeof fetch; signal: AbortSignal },\n\t): Promise<GatewayAccess> => {\n\t\tconst now = Date.now();\n\t\tconst last = lastAccess?.scope === scope ? lastAccess : undefined;\n\t\tif (\n\t\t\tlast &&\n\t\t\t(last.access.accessKind === \"unknown\" || last.access.degraded !== null) &&\n\t\t\tnow - last.at < ACCESS_RETRY_MS\n\t\t) {\n\t\t\treturn last.access;\n\t\t}\n\t\tconst access = await fetchGatewayAccess(baseUrl, token, options);\n\t\tif (!options.signal.aborted) lastAccess = { scope, access, at: now };\n\t\treturn access;\n\t};\n\n\tconst apiKeyAuth: ApiKeyAuth = {\n\t\tname: \"HUMAIN Gateway\",\n\t\tlogin: (interaction) => loginToGateway(interaction, { environment: environment(), sessions, fetch: deps.fetch }),\n\t\t// Metadata only: listing must not touch the keychain or the network.\n\t\tcheck: async ({ credential, signal }) => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst env = environment();\n\t\t\treturn sessionOf(credential, env)\n\t\t\t\t? { type: \"api_key\" as const, source: `HUMAIN Gateway (${env})` }\n\t\t\t\t: undefined;\n\t\t},\n\t\tresolve: async ({ credential, signal }): Promise<AuthResult | undefined> => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst env = environment();\n\t\t\tconst session = sessionOf(credential, env);\n\t\t\tconst token = session ? await sessions.getToken(session.id) : undefined;\n\t\t\tif (!token) return undefined;\n\t\t\t// `env` carries only the non-secret session reference so catalog refreshes keep their scope.\n\t\t\treturn {\n\t\t\t\tauth: { apiKey: token, baseUrl: baseUrlFor(env) },\n\t\t\t\tenv: { ...credential?.env },\n\t\t\t\tsource: `HUMAIN Gateway (${env})`,\n\t\t\t};\n\t\t},\n\t};\n\n\tconst base = createProvider({\n\t\tid: HUMAIN_GATEWAY_PROVIDER,\n\t\tname: \"HUMAIN Gateway\",\n\t\tbaseUrl: baseUrlFor(\"production\"),\n\t\tauth: { apiKey: apiKeyAuth },\n\t\tmodels: [],\n\t\tapi: { \"openai-responses\": withHumainGatewayHttp(openAIResponsesApi()) },\n\t});\n\n\treturn {\n\t\t...base,\n\t\tgetModels: () => models,\n\t\trefreshModels: async (context: RefreshModelsContext) => {\n\t\t\tconst env = environment();\n\t\t\tconst session = sessionOf(context.credential, env);\n\t\t\tconst scope = session ? `${env}\\0${session.id}` : undefined;\n\t\t\tconst publish = (next: readonly Model<Api>[]) =>\n\t\t\t\tcontext.publish({\n\t\t\t\t\tpersist: null,\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tmodels = next;\n\t\t\t\t\t\tactiveScope = scope;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\tif (scope !== activeScope && !(await publish([]))) return;\n\t\t\t// No session can mean an unreadable auth.json, a runtime key override, or another agentDir;\n\t\t\t// logout cleanup is left to revokeGatewayOrphans, which stops when the credential read fails.\n\t\t\tif (session) await sessions.markOrphansPending(env, session.id);\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\tconst baseUrl = GATEWAY_BASE_URLS[env];\n\t\t\tawait revokePendingSessions(baseUrl, env, sessions, deps.fetch);\n\t\t\t// The network phase receives the token resolved in-process as `key`.\n\t\t\tconst token = context.credential?.type === \"api_key\" ? context.credential.key : undefined;\n\t\t\tif (!session || !scope || !token) return;\n\n\t\t\tconst options = { fetch: deps.fetch, signal: context.signal };\n\t\t\tconst [listed, accessed] = await Promise.allSettled([\n\t\t\t\tfetchGatewayModels(baseUrl, token, options),\n\t\t\t\tloadAccess(scope, baseUrl, token, options),\n\t\t\t]);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst listing = mapRefreshResults(listed, accessed);\n\t\t\tif (\"error\" in listing) {\n\t\t\t\tif (listing.clearCatalog) await publish([]);\n\t\t\t\tthrow listing.error;\n\t\t\t}\n\n\t\t\t// A failed access read reuses this scope's last answer; without one, `/v1/models` alone decides.\n\t\t\tconst access = accessed.status === \"fulfilled\" ? accessed.value : lastAccessFor(scope);\n\t\t\tconst previouslyBlocked = await sessions.getBlockedModels(env, session.userId);\n\t\t\tconst catalog = deriveGatewayCatalog({\n\t\t\t\tmodels: listing.models,\n\t\t\t\taccess: access ?? NULL_LABEL_ACCESS,\n\t\t\t\tpreviouslyBlocked,\n\t\t\t});\n\t\t\tawait saveBlockedModels(sessions, env, session.userId, previouslyBlocked, catalog.blocked);\n\t\t\tif (!(await publish(catalog.eligible.map((entry) => toModel(entry, env))))) return;\n\t\t\tconst accessError = accessed.status === \"rejected\" ? accessed.reason : undefined;\n\t\t\tconst accessWarning =\n\t\t\t\taccessError instanceof GatewayRequestError && accessError.status >= 500\n\t\t\t\t\t? accessError.message\n\t\t\t\t\t: !access\n\t\t\t\t\t\t? ACCESS_READ_WARNING\n\t\t\t\t\t\t: undefined;\n\t\t\tconst warnings = accessWarning ? [...catalog.warnings, accessWarning] : catalog.warnings;\n\t\t\tconst listedIds = new Set(listing.models.map((entry) => entry.id));\n\t\t\tconst blocked = Object.entries(catalog.blocked)\n\t\t\t\t.filter(([id]) => listedIds.has(id))\n\t\t\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\t\t\tconst blockedKey = JSON.stringify(blocked);\n\t\t\tif (blocked.length > 0 && (shownBlocked?.scope !== scope || shownBlocked.key !== blockedKey)) {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Blocked for HUMAIN Code by HUMAIN Gateway: ${blocked.map(([id, reason]) => (reason === DEFAULT_BLOCK_REASON ? id : `${id} (${reason})`)).join(\"; \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tshownBlocked = { scope, key: blockedKey };\n\t\t\tif (warnings.length > 0) throw new Error(warnings.join(\" \"));\n\t\t},\n\t};\n}\n"]}
|
|
@@ -14,11 +14,22 @@ export interface HcodeSupportSnapshot {
|
|
|
14
14
|
export type HcodeLoginReadiness = {
|
|
15
15
|
kind: "ready";
|
|
16
16
|
}
|
|
17
|
-
/**
|
|
17
|
+
/** No HTTP response: DNS, connect, TLS or timeout. */
|
|
18
18
|
| {
|
|
19
19
|
kind: "unreachable";
|
|
20
20
|
host: string;
|
|
21
21
|
}
|
|
22
|
+
/** The selected environment answered that its HUMAIN Code profile is not configured. */
|
|
23
|
+
| {
|
|
24
|
+
kind: "not-configured";
|
|
25
|
+
environmentId: HcodeEnvironmentName;
|
|
26
|
+
}
|
|
27
|
+
/** A reachable server rejected the request; only bounded, sanitized message text is retained. */
|
|
28
|
+
| {
|
|
29
|
+
kind: "http-error";
|
|
30
|
+
status: number;
|
|
31
|
+
message?: string;
|
|
32
|
+
}
|
|
22
33
|
/** The server answered, but its sign-in settings don't match what this CLI accepts. */
|
|
23
34
|
| {
|
|
24
35
|
kind: "mismatch";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"facade.d.ts","sourceRoot":"","sources":["../../../src/humain/hcode/facade.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"facade.d.ts","sourceRoot":"","sources":["../../../src/humain/hcode/facade.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAMxD,OAAO,EAAoD,KAAK,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE/G,OAAO,EAEN,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EAGtB,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,KAAK,gBAAgB,EAAE,KAAK,oBAAoB,EAA2B,MAAM,kBAAkB,CAAC;AAG7G,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,cAAc,EAAE,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