@humain/humain-code 0.5.0 → 0.5.3
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 +37 -1
- package/README.md +3 -1
- package/dist/agent-monitor/client.d.ts +2 -2
- package/dist/agent-monitor/client.d.ts.map +1 -1
- package/dist/agent-monitor/client.js +3 -2
- package/dist/agent-monitor/client.js.map +1 -1
- package/dist/bundle/chunks/anthropic.js +10 -9
- package/dist/bundle/chunks/{chunk-DR37WKFZ.js → chunk-AO6FF5JL.js} +1 -1
- package/dist/bundle/chunks/{chunk-Q3SFYT2X.js → chunk-EY3LZOUP.js} +1356 -1358
- package/dist/bundle/chunks/{chunk-T3HXWZG4.js → chunk-L2VKM23Q.js} +76 -2
- package/dist/bundle/chunks/{chunk-5C4VL2AR.js → chunk-ODJUBJK2.js} +2 -2
- package/dist/bundle/chunks/{chunk-A6YBWW4T.js → chunk-UJLCKIMZ.js} +646 -495
- package/dist/bundle/chunks/{chunk-476XBL3W.js → chunk-Y3OPKKDR.js} +3 -77
- package/dist/bundle/chunks/{cli-VXU7OWFU.js → cli-ENEFJH2B.js} +1 -1
- package/dist/bundle/chunks/{compat-S2IBVV6V.js → compat-CJBWWYHE.js} +1 -1
- package/dist/bundle/chunks/{dist-645GFIWH.js → dist-RKNCFFGM.js} +2 -2
- package/dist/bundle/chunks/github-copilot.js +28 -26
- package/dist/bundle/chunks/openai-chatgpt.js +2 -2
- package/dist/bundle/chunks/openai-codex.js +10 -9
- package/dist/bundle/chunks/openrouter.js +10 -9
- package/dist/bundle/chunks/radius.js +9 -8
- package/dist/bundle/chunks/{runtime-5VFZTMWL.js → runtime-K3F2QDQP.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-GU6AW5ZK.js → virtual-modules-5D6QIJPN.js} +2 -2
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +4 -4
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +19 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +24 -2
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/safe-credential-error.d.ts +11 -0
- package/dist/core/safe-credential-error.d.ts.map +1 -0
- package/dist/core/safe-credential-error.js +14 -0
- package/dist/core/safe-credential-error.js.map +1 -0
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +4 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-schema.d.ts +3 -0
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +6 -0
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/humain/gateway/catalog.d.ts +36 -0
- package/dist/humain/gateway/catalog.d.ts.map +1 -0
- package/dist/humain/gateway/catalog.js +74 -0
- package/dist/humain/gateway/catalog.js.map +1 -0
- package/dist/humain/gateway/client.d.ts +58 -0
- package/dist/humain/gateway/client.d.ts.map +1 -0
- package/dist/humain/gateway/client.js +212 -0
- package/dist/humain/gateway/client.js.map +1 -0
- package/dist/humain/gateway/constants.d.ts +23 -0
- package/dist/humain/gateway/constants.d.ts.map +1 -0
- package/dist/humain/gateway/constants.js +32 -0
- package/dist/humain/gateway/constants.js.map +1 -0
- package/dist/humain/gateway/http.d.ts +18 -0
- package/dist/humain/gateway/http.d.ts.map +1 -0
- package/dist/humain/gateway/http.js +274 -0
- package/dist/humain/gateway/http.js.map +1 -0
- package/dist/humain/gateway/login.d.ts +13 -0
- package/dist/humain/gateway/login.d.ts.map +1 -0
- package/dist/humain/gateway/login.js +121 -0
- package/dist/humain/gateway/login.js.map +1 -0
- package/dist/humain/gateway/provider.d.ts +34 -0
- package/dist/humain/gateway/provider.d.ts.map +1 -0
- package/dist/humain/gateway/provider.js +253 -0
- package/dist/humain/gateway/provider.js.map +1 -0
- package/dist/humain/gateway/secret-store.d.ts +19 -0
- package/dist/humain/gateway/secret-store.d.ts.map +1 -0
- package/dist/humain/gateway/secret-store.js +252 -0
- package/dist/humain/gateway/secret-store.js.map +1 -0
- package/dist/humain/gateway/session-store.d.ts +42 -0
- package/dist/humain/gateway/session-store.d.ts.map +1 -0
- package/dist/humain/gateway/session-store.js +175 -0
- package/dist/humain/gateway/session-store.js.map +1 -0
- package/dist/humain/index.d.ts.map +1 -1
- package/dist/humain/index.js +2 -0
- package/dist/humain/index.js.map +1 -1
- package/dist/humain/login-menu.d.ts +14 -0
- package/dist/humain/login-menu.d.ts.map +1 -0
- package/dist/humain/login-menu.js +21 -0
- package/dist/humain/login-menu.js.map +1 -0
- package/dist/humain/node-http.d.ts.map +1 -1
- package/dist/humain/node-http.js +6 -31
- package/dist/humain/node-http.js.map +1 -1
- package/dist/humain/redact-assistant-message.d.ts +4 -0
- package/dist/humain/redact-assistant-message.d.ts.map +1 -0
- package/dist/humain/redact-assistant-message.js +34 -0
- package/dist/humain/redact-assistant-message.js.map +1 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +17 -4
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +3 -2
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +11 -0
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +16 -3
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/radius-login-selector.d.ts +5 -4
- package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/radius-login-selector.js +11 -9
- package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +2 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +53 -36
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/sleep.d.ts +1 -1
- package/dist/utils/sleep.d.ts.map +1 -1
- package/dist/utils/sleep.js +10 -6
- package/dist/utils/sleep.js.map +1 -1
- package/docs/humain-code.md +13 -1
- package/docs/index.md +1 -1
- package/docs/models.md +3 -1
- package/docs/providers.md +58 -2
- package/docs/quickstart.md +8 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/schemas/settings.schema.json +19 -0
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import { lazyStream, } from "@earendil-works/pi-ai";
|
|
2
|
+
import { sleep } from "../../utils/sleep.js";
|
|
3
|
+
import { redactAssistantMessage } from "../redact-assistant-message.js";
|
|
4
|
+
import { isObject } from "./client.js";
|
|
5
|
+
import { GATEWAY_USER_AGENT } from "./constants.js";
|
|
6
|
+
const MAX_ATTEMPTS = 3;
|
|
7
|
+
const MAX_DELAY_MS = 60_000;
|
|
8
|
+
const MAX_BODY_BYTES = 20_971_520;
|
|
9
|
+
// Every retryable Gateway error body is tiny; anything larger fails closed.
|
|
10
|
+
const MAX_ERROR_BODY_BYTES = 65_536;
|
|
11
|
+
const OVERSIZE_MESSAGE = "Request is larger than HUMAIN Gateway's 20 MiB limit.";
|
|
12
|
+
const REQUEST_CEILING_MS = 900_000;
|
|
13
|
+
const CEILING_MESSAGE = "HUMAIN Gateway request exceeded the 900-second limit.";
|
|
14
|
+
/** Parses at most MAX_ERROR_BODY_BYTES of an error body as JSON; larger or invalid bodies yield `undefined`. */
|
|
15
|
+
async function readErrorBody(response) {
|
|
16
|
+
if (Number(response.headers.get("content-length")) > MAX_ERROR_BODY_BYTES)
|
|
17
|
+
return undefined;
|
|
18
|
+
const reader = response.clone().body?.getReader();
|
|
19
|
+
if (!reader)
|
|
20
|
+
return undefined;
|
|
21
|
+
const chunks = [];
|
|
22
|
+
let size = 0;
|
|
23
|
+
try {
|
|
24
|
+
for (;;) {
|
|
25
|
+
const { done, value } = await reader.read();
|
|
26
|
+
if (done)
|
|
27
|
+
break;
|
|
28
|
+
size += value.byteLength;
|
|
29
|
+
if (size > MAX_ERROR_BODY_BYTES)
|
|
30
|
+
return undefined;
|
|
31
|
+
chunks.push(value);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
// Stops the clone's tee from buffering the rest of the body.
|
|
39
|
+
reader.cancel().catch(() => undefined);
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Decide whether a failed Gateway response is safe to resend. Only responses that prove the
|
|
50
|
+
* request never reached a billed model call qualify; everything else fails to avoid double billing.
|
|
51
|
+
*/
|
|
52
|
+
export function classifyGatewayRetry(status, body, headers, requestedModel) {
|
|
53
|
+
if (headers.get("x-should-retry") === "false")
|
|
54
|
+
return { retry: false };
|
|
55
|
+
const retryAfter = headers.get("retry-after");
|
|
56
|
+
// A server delay we cannot read could be later than our backoff; fail instead of resending early.
|
|
57
|
+
if (retryAfter !== null && !/^\d+$/u.test(retryAfter.trim()))
|
|
58
|
+
return { retry: false };
|
|
59
|
+
const headerDelay = retryAfter === null ? undefined : Number(retryAfter.trim()) * 1000;
|
|
60
|
+
const error = isObject(body) ? body.error : undefined;
|
|
61
|
+
let delayMs;
|
|
62
|
+
if (status === 503 && isObject(body) && Object.keys(body).length === 1 && error === "CLI session unavailable") {
|
|
63
|
+
delayMs = headerDelay;
|
|
64
|
+
}
|
|
65
|
+
else if (status === 429 &&
|
|
66
|
+
isObject(error) &&
|
|
67
|
+
(error.code === "gateway_key_limit_exceeded" || error.type === "gateway_key_limit_exceeded")) {
|
|
68
|
+
const fields = isObject(error.fields) ? error.fields : isObject(body) && isObject(body.fields) ? body.fields : {};
|
|
69
|
+
const seconds = fields.retry_after_seconds;
|
|
70
|
+
if (seconds === undefined)
|
|
71
|
+
delayMs = headerDelay;
|
|
72
|
+
else if (typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0)
|
|
73
|
+
delayMs = seconds * 1000;
|
|
74
|
+
else
|
|
75
|
+
return { retry: false };
|
|
76
|
+
}
|
|
77
|
+
else if (status === 429 &&
|
|
78
|
+
headerDelay !== undefined &&
|
|
79
|
+
(isObject(error) ? error.message : error) ===
|
|
80
|
+
`No deployments available for model '${requestedModel}'. Try again later.`) {
|
|
81
|
+
delayMs = headerDelay;
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
return { retry: false };
|
|
85
|
+
}
|
|
86
|
+
if (delayMs !== undefined && delayMs > MAX_DELAY_MS)
|
|
87
|
+
return { retry: false };
|
|
88
|
+
return delayMs === undefined ? { retry: true } : { retry: true, delayMs };
|
|
89
|
+
}
|
|
90
|
+
/** Removes `litellm_call_id`, which lets a caller pick the Gateway's billing/log id. */
|
|
91
|
+
function stripCallId(body) {
|
|
92
|
+
let parsed;
|
|
93
|
+
try {
|
|
94
|
+
parsed = JSON.parse(body);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return body;
|
|
98
|
+
}
|
|
99
|
+
if (!isObject(parsed))
|
|
100
|
+
return body;
|
|
101
|
+
const metadata = parsed.metadata;
|
|
102
|
+
const nested = isObject(metadata) && "litellm_call_id" in metadata;
|
|
103
|
+
if (!("litellm_call_id" in parsed) && !nested)
|
|
104
|
+
return body;
|
|
105
|
+
delete parsed.litellm_call_id;
|
|
106
|
+
if (nested)
|
|
107
|
+
delete metadata.litellm_call_id;
|
|
108
|
+
return JSON.stringify(parsed);
|
|
109
|
+
}
|
|
110
|
+
export function withHumainGatewayHttp(api, deps = {}) {
|
|
111
|
+
const wait = deps.sleep ?? sleep;
|
|
112
|
+
const random = deps.random ?? Math.random;
|
|
113
|
+
const run = (model, context, options, simple) => lazyStream(model, async () => {
|
|
114
|
+
const httpError = { retryable: false };
|
|
115
|
+
let failure;
|
|
116
|
+
let responseCost;
|
|
117
|
+
let reportedCost;
|
|
118
|
+
const key = options?.apiKey;
|
|
119
|
+
const fetcher = options?.fetch ?? globalThis.fetch;
|
|
120
|
+
// The SDK timeout only bounds time to response headers; the deadline also bounds the stream.
|
|
121
|
+
// A clearable timer (not AbortSignal.timeout) so completed requests retain nothing for 900 s.
|
|
122
|
+
const deadline = new AbortController();
|
|
123
|
+
const timer = setTimeout(() => {
|
|
124
|
+
if (!options?.signal?.aborted)
|
|
125
|
+
failure ??= CEILING_MESSAGE;
|
|
126
|
+
deadline.abort();
|
|
127
|
+
}, deps.requestCeilingMs ?? REQUEST_CEILING_MS);
|
|
128
|
+
const timeoutMs = options?.timeoutMs;
|
|
129
|
+
const requestOptions = {
|
|
130
|
+
...options,
|
|
131
|
+
signal: options?.signal ? AbortSignal.any([options.signal, deadline.signal]) : deadline.signal,
|
|
132
|
+
timeoutMs: timeoutMs !== undefined && timeoutMs > 0 && timeoutMs < REQUEST_CEILING_MS
|
|
133
|
+
? timeoutMs
|
|
134
|
+
: REQUEST_CEILING_MS,
|
|
135
|
+
// Gateway reports request cost in `response.completed.response.usage.cost`.
|
|
136
|
+
onProviderStreamEvent: async (data, streamModel) => {
|
|
137
|
+
if (isObject(data) && data.type === "response.completed" && isObject(data.response)) {
|
|
138
|
+
const cost = isObject(data.response.usage) ? data.response.usage.cost : undefined;
|
|
139
|
+
if (typeof cost === "number" && Number.isFinite(cost) && cost >= 0)
|
|
140
|
+
reportedCost = cost;
|
|
141
|
+
}
|
|
142
|
+
await options?.onProviderStreamEvent?.(data, streamModel);
|
|
143
|
+
},
|
|
144
|
+
// Retries are owned below; SDK retries could resend a billed request.
|
|
145
|
+
maxRetries: 0,
|
|
146
|
+
fetch: async (input, init) => {
|
|
147
|
+
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
|
|
148
|
+
if (key)
|
|
149
|
+
headers.set("Authorization", `Bearer ${key}`);
|
|
150
|
+
headers.delete("x-api-key");
|
|
151
|
+
headers.set("User-Agent", GATEWAY_USER_AGENT);
|
|
152
|
+
let body = init?.body;
|
|
153
|
+
if (typeof body === "string") {
|
|
154
|
+
body = stripCallId(body);
|
|
155
|
+
if (Buffer.byteLength(body) > MAX_BODY_BYTES) {
|
|
156
|
+
failure = OVERSIZE_MESSAGE;
|
|
157
|
+
throw new Error(OVERSIZE_MESSAGE);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const signal = init?.signal ?? options?.signal;
|
|
161
|
+
for (let attempt = 0;; attempt++) {
|
|
162
|
+
const response = await fetcher(input, { ...init, body, headers, redirect: "error" });
|
|
163
|
+
const requestId = response.headers.get("x-litellm-call-id");
|
|
164
|
+
if (requestId)
|
|
165
|
+
httpError.requestId = requestId;
|
|
166
|
+
else
|
|
167
|
+
delete httpError.requestId;
|
|
168
|
+
const cost = Number(response.headers.get("x-litellm-response-cost") ?? Number.NaN);
|
|
169
|
+
responseCost = Number.isFinite(cost) && cost >= 0 ? cost : undefined;
|
|
170
|
+
if (response.ok)
|
|
171
|
+
return response;
|
|
172
|
+
const responseBody = await readErrorBody(response);
|
|
173
|
+
const decision = classifyGatewayRetry(response.status, responseBody, response.headers, model.id);
|
|
174
|
+
if (!decision.retry || attempt + 1 >= MAX_ATTEMPTS) {
|
|
175
|
+
httpError.status = response.status;
|
|
176
|
+
const error = isObject(responseBody) ? responseBody.error : undefined;
|
|
177
|
+
const code = isObject(error) ? (error.code ?? error.type) : undefined;
|
|
178
|
+
if (typeof code === "string")
|
|
179
|
+
httpError.code = key ? code.replaceAll(key, "[redacted]") : code;
|
|
180
|
+
else
|
|
181
|
+
delete httpError.code;
|
|
182
|
+
const responseHeaders = new Headers(response.headers);
|
|
183
|
+
responseHeaders.set("x-should-retry", "false");
|
|
184
|
+
return new Response(response.body, {
|
|
185
|
+
status: response.status,
|
|
186
|
+
statusText: response.statusText,
|
|
187
|
+
headers: responseHeaders,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
await response.body?.cancel().catch(() => undefined);
|
|
191
|
+
const backoff = Math.min(MAX_DELAY_MS, 1000 * 2 ** attempt) * (0.5 + random() / 2);
|
|
192
|
+
await wait(Math.max(decision.delayMs ?? 0, backoff), signal ?? undefined);
|
|
193
|
+
}
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
const source = simple
|
|
197
|
+
? api.streamSimple(model, context, requestOptions)
|
|
198
|
+
: api.stream(model, context, requestOptions);
|
|
199
|
+
const finish = (event) => {
|
|
200
|
+
if (event.type !== "done" && event.type !== "error")
|
|
201
|
+
return;
|
|
202
|
+
const message = event.type === "done" ? event.message : event.error;
|
|
203
|
+
const cost = reportedCost ?? responseCost;
|
|
204
|
+
if (cost !== undefined && message.usage.cost.total === 0)
|
|
205
|
+
message.usage.cost.total = cost;
|
|
206
|
+
if (event.type === "error") {
|
|
207
|
+
// A ceiling abort is a Gateway failure, not a user cancellation.
|
|
208
|
+
if (failure === CEILING_MESSAGE && !options?.signal?.aborted) {
|
|
209
|
+
event.reason = "error";
|
|
210
|
+
event.error.stopReason = "error";
|
|
211
|
+
}
|
|
212
|
+
const requestId = httpError.requestId;
|
|
213
|
+
event.error.errorMessage = [
|
|
214
|
+
failure ?? event.error.errorMessage ?? "HUMAIN Gateway request failed",
|
|
215
|
+
typeof httpError.code === "string" && `code: ${httpError.code}`,
|
|
216
|
+
typeof requestId === "string" && `x-litellm-call-id: ${requestId}`,
|
|
217
|
+
]
|
|
218
|
+
.filter(Boolean)
|
|
219
|
+
.join("; ");
|
|
220
|
+
// Gateway retries already happened above; agent-level retry must never resend.
|
|
221
|
+
event.error.diagnostics = [
|
|
222
|
+
...(event.error.diagnostics ?? []),
|
|
223
|
+
{ type: "provider_http_error", timestamp: Date.now(), details: { ...httpError } },
|
|
224
|
+
];
|
|
225
|
+
}
|
|
226
|
+
redactAssistantMessage(message, key);
|
|
227
|
+
};
|
|
228
|
+
return (async function* () {
|
|
229
|
+
let ended = false;
|
|
230
|
+
try {
|
|
231
|
+
for await (const event of source) {
|
|
232
|
+
finish(event);
|
|
233
|
+
ended ||= event.type === "done" || event.type === "error";
|
|
234
|
+
yield event;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
if (ended)
|
|
239
|
+
throw error;
|
|
240
|
+
// lazyStream would turn this throw into an error without the non-retryable diagnostic.
|
|
241
|
+
const message = {
|
|
242
|
+
role: "assistant",
|
|
243
|
+
content: [],
|
|
244
|
+
api: model.api,
|
|
245
|
+
provider: model.provider,
|
|
246
|
+
model: model.id,
|
|
247
|
+
usage: {
|
|
248
|
+
usageIncomplete: true,
|
|
249
|
+
input: 0,
|
|
250
|
+
output: 0,
|
|
251
|
+
cacheRead: 0,
|
|
252
|
+
cacheWrite: 0,
|
|
253
|
+
totalTokens: 0,
|
|
254
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
255
|
+
},
|
|
256
|
+
stopReason: "error",
|
|
257
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
258
|
+
timestamp: Date.now(),
|
|
259
|
+
};
|
|
260
|
+
const event = { type: "error", reason: "error", error: message };
|
|
261
|
+
finish(event);
|
|
262
|
+
yield event;
|
|
263
|
+
}
|
|
264
|
+
finally {
|
|
265
|
+
clearTimeout(timer);
|
|
266
|
+
}
|
|
267
|
+
})();
|
|
268
|
+
});
|
|
269
|
+
return {
|
|
270
|
+
stream: (model, context, options) => run(model, context, options, false),
|
|
271
|
+
streamSimple: (model, context, options) => run(model, context, options, true),
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
//# sourceMappingURL=http.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/humain/gateway/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,UAAU,GAKV,MAAM,uBAAuB,CAAC;A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,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"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ApiKeyCredential, ProviderAuthInteraction } from "@earendil-works/pi-ai";
|
|
2
|
+
import { type GatewayEnvironment } from "./constants.ts";
|
|
3
|
+
import type { GatewaySessionStore } from "./session-store.ts";
|
|
4
|
+
interface GatewayLoginDeps {
|
|
5
|
+
environment: GatewayEnvironment;
|
|
6
|
+
sessions: GatewaySessionStore;
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
}
|
|
9
|
+
export declare function loginToGateway(interaction: ProviderAuthInteraction, deps: GatewayLoginDeps): Promise<ApiKeyCredential>;
|
|
10
|
+
/** Best effort: failures leave records pending for a later attempt and never fail sign-in. */
|
|
11
|
+
export declare function revokePendingSessions(base: string, environment: GatewayEnvironment, sessions: GatewaySessionStore, fetchImpl: typeof fetch | undefined): Promise<void>;
|
|
12
|
+
export {};
|
|
13
|
+
//# sourceMappingURL=login.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"login.d.ts","sourceRoot":"","sources":["../../../src/humain/gateway/login.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAIvF,OAAO,EAMN,KAAK,kBAAkB,EACvB,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,UAAU,gBAAgB;IACzB,WAAW,EAAE,kBAAkB,CAAC;IAChC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACrB;AAcD,wBAAsB,cAAc,CACnC,WAAW,EAAE,uBAAuB,EACpC,IAAI,EAAE,gBAAgB,GACpB,OAAO,CAAC,gBAAgB,CAAC,CAsF3B;AAED,8FAA8F;AAC9F,wBAAsB,qBAAqB,CAC1C,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,kBAAkB,EAC/B,QAAQ,EAAE,mBAAmB,EAC7B,SAAS,EAAE,OAAO,KAAK,GAAG,SAAS,GACjC,OAAO,CAAC,IAAI,CAAC,CAoBf"}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { startOAuthCallbackServer, waitForCallbackOrManualInput } from "@earendil-works/pi-ai/oauth-callback-server";
|
|
3
|
+
import { SafeCredentialError } from "../../core/safe-credential-error.js";
|
|
4
|
+
import { exchangeHandoffCode, revokeSession } from "./client.js";
|
|
5
|
+
import { GATEWAY_BASE_URLS, GATEWAY_ENV_EMAIL, GATEWAY_ENV_ENVIRONMENT, GATEWAY_ENV_SESSION_ID, GATEWAY_ENV_USER_ID, } from "./constants.js";
|
|
6
|
+
const CALLBACK_TIMEOUT_MS = 300_000;
|
|
7
|
+
const REVOKE_TIMEOUT_MS = 10_000;
|
|
8
|
+
function handoffUrl(base, state, redirectUri) {
|
|
9
|
+
const params = new URLSearchParams({ cli_capability: "cli-session-v1", client: "cli" });
|
|
10
|
+
if (redirectUri !== undefined)
|
|
11
|
+
params.set("redirect_uri", redirectUri);
|
|
12
|
+
params.set("state", state);
|
|
13
|
+
return `${base}/handoff?${params.toString()}`;
|
|
14
|
+
}
|
|
15
|
+
export async function loginToGateway(interaction, deps) {
|
|
16
|
+
const { environment, sessions } = deps;
|
|
17
|
+
const base = GATEWAY_BASE_URLS[environment];
|
|
18
|
+
// Fail before the browser opens when the token could never be stored.
|
|
19
|
+
await sessions.probe();
|
|
20
|
+
const state = randomBytes(32).toString("base64url");
|
|
21
|
+
const exchange = (code) => exchangeHandoffCode(base, { code, state }, { fetch: deps.fetch, signal: interaction.signal });
|
|
22
|
+
const callback = await startOAuthCallbackServer({
|
|
23
|
+
providerName: "HUMAIN Gateway",
|
|
24
|
+
host: "127.0.0.1",
|
|
25
|
+
port: 0,
|
|
26
|
+
path: "/callback",
|
|
27
|
+
state,
|
|
28
|
+
// Exchange before the browser page is sent, so the page reports the real outcome.
|
|
29
|
+
complete: exchange,
|
|
30
|
+
signal: interaction.signal,
|
|
31
|
+
timeoutMs: CALLBACK_TIMEOUT_MS,
|
|
32
|
+
});
|
|
33
|
+
let result;
|
|
34
|
+
try {
|
|
35
|
+
interaction.notify({
|
|
36
|
+
type: "auth_url",
|
|
37
|
+
url: handoffUrl(base, state, callback.redirectUri),
|
|
38
|
+
instructions: "Complete sign-in to HUMAIN Gateway in your browser.",
|
|
39
|
+
});
|
|
40
|
+
interaction.notify({
|
|
41
|
+
type: "info",
|
|
42
|
+
message: "If the browser runs on another machine, open this link there and paste the sign-in code here.",
|
|
43
|
+
links: [{ url: handoffUrl(base, state), label: "HUMAIN Gateway sign-in (paste code)" }],
|
|
44
|
+
});
|
|
45
|
+
result = await waitForCallbackOrManualInput(interaction, callback, {
|
|
46
|
+
message: "Complete sign-in in your browser, or paste the HUMAIN Gateway sign-in code here:",
|
|
47
|
+
placeholder: "hc_...",
|
|
48
|
+
secret: true,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
callback.close();
|
|
53
|
+
}
|
|
54
|
+
let exchanged;
|
|
55
|
+
if (result.type === "callback") {
|
|
56
|
+
exchanged = result.value;
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
const code = result.input.trim();
|
|
60
|
+
if (!code)
|
|
61
|
+
throw new SafeCredentialError("Missing HUMAIN Gateway sign-in code.");
|
|
62
|
+
interaction.notify({ type: "progress", message: "Completing HUMAIN Gateway sign-in..." });
|
|
63
|
+
exchanged = await exchange(code);
|
|
64
|
+
}
|
|
65
|
+
const { token, identity } = exchanged;
|
|
66
|
+
let id;
|
|
67
|
+
try {
|
|
68
|
+
({ id } = await sessions.commitNewSession(environment, token));
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
// The token cannot be stored, so end it server-side; a fresh signal survives a cancelled login.
|
|
72
|
+
const outcome = await revokeSession(base, token, {
|
|
73
|
+
fetch: deps.fetch,
|
|
74
|
+
signal: AbortSignal.timeout(REVOKE_TIMEOUT_MS),
|
|
75
|
+
});
|
|
76
|
+
if (outcome === "unavailable") {
|
|
77
|
+
const reason = error instanceof SafeCredentialError
|
|
78
|
+
? error.message
|
|
79
|
+
: "Could not store the HUMAIN Gateway session in the OS keychain.";
|
|
80
|
+
throw new SafeCredentialError(`${reason} The new HUMAIN Gateway session could not be revoked and may stay active on the server.`);
|
|
81
|
+
}
|
|
82
|
+
throw error instanceof SafeCredentialError
|
|
83
|
+
? error
|
|
84
|
+
: new SafeCredentialError("Could not store the HUMAIN Gateway session in the OS keychain.");
|
|
85
|
+
}
|
|
86
|
+
await revokePendingSessions(base, environment, sessions, deps.fetch);
|
|
87
|
+
return {
|
|
88
|
+
type: "api_key",
|
|
89
|
+
env: {
|
|
90
|
+
[GATEWAY_ENV_ENVIRONMENT]: environment,
|
|
91
|
+
[GATEWAY_ENV_SESSION_ID]: id,
|
|
92
|
+
[GATEWAY_ENV_EMAIL]: identity.email,
|
|
93
|
+
[GATEWAY_ENV_USER_ID]: identity.userId,
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
/** Best effort: failures leave records pending for a later attempt and never fail sign-in. */
|
|
98
|
+
export async function revokePendingSessions(base, environment, sessions, fetchImpl) {
|
|
99
|
+
let pending;
|
|
100
|
+
try {
|
|
101
|
+
pending = await sessions.pendingRevocations(environment);
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
for (const record of pending) {
|
|
107
|
+
try {
|
|
108
|
+
const token = await sessions.getToken(record.id);
|
|
109
|
+
// No stored token: nothing left to revoke from this machine.
|
|
110
|
+
const outcome = token === undefined
|
|
111
|
+
? "unknown"
|
|
112
|
+
: await revokeSession(base, token, { fetch: fetchImpl, signal: AbortSignal.timeout(REVOKE_TIMEOUT_MS) });
|
|
113
|
+
if (outcome !== "unavailable")
|
|
114
|
+
await sessions.forget(record.id);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
// Keep the record pending.
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
//# sourceMappingURL=login.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"login.js","sourceRoot":"","sources":["../../../src/humain/gateway/login.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,6CAA6C,CAAC;AACrH,OAAO,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EACN,iBAAiB,EACjB,iBAAiB,EACjB,uBAAuB,EACvB,sBAAsB,EACtB,mBAAmB,GAEnB,MAAM,gBAAgB,CAAC;AAWxB,MAAM,mBAAmB,GAAG,OAAO,CAAC;AACpC,MAAM,iBAAiB,GAAG,MAAM,CAAC;AAEjC,SAAS,UAAU,CAAC,IAAY,EAAE,KAAa,EAAE,WAAoB;IACpE,MAAM,MAAM,GAAG,IAAI,eAAe,CAAC,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;IACxF,IAAI,WAAW,KAAK,SAAS;QAAE,MAAM,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IACvE,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC3B,OAAO,GAAG,IAAI,YAAY,MAAM,CAAC,QAAQ,EAAE,EAAE,CAAC;AAC/C,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CACnC,WAAoC,EACpC,IAAsB;IAEtB,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;I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,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACjE,CAAC;QAAC,MAAM,CAAC;YACR,2BAA2B;QAC5B,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport type { ApiKeyCredential, ProviderAuthInteraction } from \"@earendil-works/pi-ai\";\nimport { startOAuthCallbackServer, waitForCallbackOrManualInput } from \"@earendil-works/pi-ai/oauth-callback-server\";\nimport { SafeCredentialError } from \"../../core/safe-credential-error.ts\";\nimport { exchangeHandoffCode, revokeSession } from \"./client.ts\";\nimport {\n\tGATEWAY_BASE_URLS,\n\tGATEWAY_ENV_EMAIL,\n\tGATEWAY_ENV_ENVIRONMENT,\n\tGATEWAY_ENV_SESSION_ID,\n\tGATEWAY_ENV_USER_ID,\n\ttype GatewayEnvironment,\n} from \"./constants.ts\";\nimport type { GatewaySessionStore } from \"./session-store.ts\";\n\ninterface GatewayLoginDeps {\n\tenvironment: GatewayEnvironment;\n\tsessions: GatewaySessionStore;\n\tfetch?: typeof fetch;\n}\n\ntype ExchangeResult = Awaited<ReturnType<typeof exchangeHandoffCode>>;\n\nconst CALLBACK_TIMEOUT_MS = 300_000;\nconst REVOKE_TIMEOUT_MS = 10_000;\n\nfunction handoffUrl(base: string, state: string, redirectUri?: string): string {\n\tconst params = new URLSearchParams({ cli_capability: \"cli-session-v1\", client: \"cli\" });\n\tif (redirectUri !== undefined) params.set(\"redirect_uri\", redirectUri);\n\tparams.set(\"state\", state);\n\treturn `${base}/handoff?${params.toString()}`;\n}\n\nexport async function loginToGateway(\n\tinteraction: ProviderAuthInteraction,\n\tdeps: GatewayLoginDeps,\n): Promise<ApiKeyCredential> {\n\tconst { environment, sessions } = deps;\n\tconst base = GATEWAY_BASE_URLS[environment];\n\t// Fail before the browser opens when the token could never be stored.\n\tawait sessions.probe();\n\n\tconst state = randomBytes(32).toString(\"base64url\");\n\tconst exchange = (code: string) =>\n\t\texchangeHandoffCode(base, { code, state }, { fetch: deps.fetch, signal: interaction.signal });\n\tconst callback = await startOAuthCallbackServer({\n\t\tproviderName: \"HUMAIN Gateway\",\n\t\thost: \"127.0.0.1\",\n\t\tport: 0,\n\t\tpath: \"/callback\",\n\t\tstate,\n\t\t// Exchange before the browser page is sent, so the page reports the real outcome.\n\t\tcomplete: exchange,\n\t\tsignal: interaction.signal,\n\t\ttimeoutMs: CALLBACK_TIMEOUT_MS,\n\t});\n\n\tlet result: { type: \"callback\"; value: ExchangeResult } | { type: \"manual\"; input: string };\n\ttry {\n\t\tinteraction.notify({\n\t\t\ttype: \"auth_url\",\n\t\t\turl: handoffUrl(base, state, callback.redirectUri),\n\t\t\tinstructions: \"Complete sign-in to HUMAIN Gateway in your browser.\",\n\t\t});\n\t\tinteraction.notify({\n\t\t\ttype: \"info\",\n\t\t\tmessage: \"If the browser runs on another machine, open this link there and paste the sign-in code here.\",\n\t\t\tlinks: [{ url: handoffUrl(base, state), label: \"HUMAIN Gateway sign-in (paste code)\" }],\n\t\t});\n\t\tresult = await waitForCallbackOrManualInput(interaction, callback, {\n\t\t\tmessage: \"Complete sign-in in your browser, or paste the HUMAIN Gateway sign-in code here:\",\n\t\t\tplaceholder: \"hc_...\",\n\t\t\tsecret: true,\n\t\t});\n\t} finally {\n\t\tcallback.close();\n\t}\n\tlet exchanged: ExchangeResult;\n\tif (result.type === \"callback\") {\n\t\texchanged = result.value;\n\t} else {\n\t\tconst code = result.input.trim();\n\t\tif (!code) throw new SafeCredentialError(\"Missing HUMAIN Gateway sign-in code.\");\n\t\tinteraction.notify({ type: \"progress\", message: \"Completing HUMAIN Gateway sign-in...\" });\n\t\texchanged = await exchange(code);\n\t}\n\tconst { token, identity } = exchanged;\n\n\tlet id: string;\n\ttry {\n\t\t({ id } = await sessions.commitNewSession(environment, token));\n\t} catch (error) {\n\t\t// The token cannot be stored, so end it server-side; a fresh signal survives a cancelled login.\n\t\tconst outcome = await revokeSession(base, token, {\n\t\t\tfetch: deps.fetch,\n\t\t\tsignal: AbortSignal.timeout(REVOKE_TIMEOUT_MS),\n\t\t});\n\t\tif (outcome === \"unavailable\") {\n\t\t\tconst reason =\n\t\t\t\terror instanceof SafeCredentialError\n\t\t\t\t\t? error.message\n\t\t\t\t\t: \"Could not store the HUMAIN Gateway session in the OS keychain.\";\n\t\t\tthrow new SafeCredentialError(\n\t\t\t\t`${reason} The new HUMAIN Gateway session could not be revoked and may stay active on the server.`,\n\t\t\t);\n\t\t}\n\t\tthrow error instanceof SafeCredentialError\n\t\t\t? error\n\t\t\t: new SafeCredentialError(\"Could not store the HUMAIN Gateway session in the OS keychain.\");\n\t}\n\n\tawait revokePendingSessions(base, environment, sessions, deps.fetch);\n\n\treturn {\n\t\ttype: \"api_key\",\n\t\tenv: {\n\t\t\t[GATEWAY_ENV_ENVIRONMENT]: environment,\n\t\t\t[GATEWAY_ENV_SESSION_ID]: id,\n\t\t\t[GATEWAY_ENV_EMAIL]: identity.email,\n\t\t\t[GATEWAY_ENV_USER_ID]: identity.userId,\n\t\t},\n\t};\n}\n\n/** Best effort: failures leave records pending for a later attempt and never fail sign-in. */\nexport async function revokePendingSessions(\n\tbase: string,\n\tenvironment: GatewayEnvironment,\n\tsessions: GatewaySessionStore,\n\tfetchImpl: typeof fetch | undefined,\n): Promise<void> {\n\tlet pending: Awaited<ReturnType<GatewaySessionStore[\"pendingRevocations\"]>>;\n\ttry {\n\t\tpending = await sessions.pendingRevocations(environment);\n\t} catch {\n\t\treturn;\n\t}\n\tfor (const record of pending) {\n\t\ttry {\n\t\t\tconst token = await sessions.getToken(record.id);\n\t\t\t// No stored token: nothing left to revoke from this machine.\n\t\t\tconst outcome =\n\t\t\t\ttoken === undefined\n\t\t\t\t\t? \"unknown\"\n\t\t\t\t\t: await revokeSession(base, token, { fetch: fetchImpl, signal: AbortSignal.timeout(REVOKE_TIMEOUT_MS) });\n\t\t\tif (outcome !== \"unavailable\") await sessions.forget(record.id);\n\t\t} catch {\n\t\t\t// Keep the record pending.\n\t\t}\n\t}\n}\n"]}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type Credential, type Provider } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { AppMode } from "../../core/project-trust.ts";
|
|
3
|
+
import { type GatewayEnvironment } from "./constants.ts";
|
|
4
|
+
import { GatewaySessionStore } from "./session-store.ts";
|
|
5
|
+
interface HumainGatewayProviderDeps {
|
|
6
|
+
environment?: () => GatewayEnvironment;
|
|
7
|
+
sessions?: GatewaySessionStore;
|
|
8
|
+
fetch?: typeof fetch;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Global user settings only: a repository's project settings must never redirect Gateway credentials.
|
|
12
|
+
* `ok` is false when the global settings read failed (e.g. a lock held by another process), so the
|
|
13
|
+
* production fallback must not be cached.
|
|
14
|
+
*/
|
|
15
|
+
export declare function readGatewayEnvironment(cwd: string, agentDir: string): {
|
|
16
|
+
environment: GatewayEnvironment;
|
|
17
|
+
ok: boolean;
|
|
18
|
+
};
|
|
19
|
+
export declare function resetGatewayEnvironmentCacheForTests(): void;
|
|
20
|
+
/**
|
|
21
|
+
* Only interactive sessions reconcile at startup: print, JSON and RPC processes are short-lived, and a
|
|
22
|
+
* background revocation would keep them alive.
|
|
23
|
+
*/
|
|
24
|
+
export declare function shouldReconcileGatewayOnStartup(mode: AppMode, offline: boolean, listModels?: boolean): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Startup reconciliation: revokes sessions orphaned by `/logout`, which leaves no credential and so
|
|
27
|
+
* never reaches the refresh network phase. Touches the keychain only when pending records exist.
|
|
28
|
+
*/
|
|
29
|
+
export declare function revokeGatewayOrphans(deps?: HumainGatewayProviderDeps & {
|
|
30
|
+
readCredential?: () => Promise<Credential | undefined>;
|
|
31
|
+
}): Promise<void>;
|
|
32
|
+
export declare function createHumainGatewayProvider(deps?: HumainGatewayProviderDeps): Provider;
|
|
33
|
+
export {};
|
|
34
|
+
//# sourceMappingURL=provider.d.ts.map
|
|
@@ -0,0 +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;AAW3D,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;AA4DD,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;AAiCD;;;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,CAkI1F"}
|