@ouro.bot/cli 0.1.0-alpha.1010 → 0.1.0-alpha.1013

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.
@@ -0,0 +1,549 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.AccountPool = exports.accountKey = void 0;
37
+ exports.apiBaseForHost = apiBaseForHost;
38
+ exports.isWorkAccount = isWorkAccount;
39
+ exports.globMatch = globMatch;
40
+ exports.isEligible = isEligible;
41
+ exports.readAppAccounts = readAppAccounts;
42
+ exports.readGhAccounts = readGhAccounts;
43
+ exports.discoverAccount = discoverAccount;
44
+ exports.discoverAccountPool = discoverAccountPool;
45
+ exports.serializeAccountPool = serializeAccountPool;
46
+ exports.parseAccountPool = parseAccountPool;
47
+ exports.chooseAccount = chooseAccount;
48
+ exports.refusalUntil = refusalUntil;
49
+ exports.fetchDirectReadings = fetchDirectReadings;
50
+ exports.createPooledCaller = createPooledCaller;
51
+ exports.getAccountPool = getAccountPool;
52
+ exports.resetAccountPools = resetAccountPools;
53
+ const child_process_1 = require("child_process");
54
+ const fs = __importStar(require("fs"));
55
+ const os = __importStar(require("os"));
56
+ const path = __importStar(require("path"));
57
+ const runtime_1 = require("../../nerves/runtime");
58
+ const tranche_1 = require("../quota/tranche");
59
+ const fleet_readings_1 = require("../quota/fleet-readings");
60
+ const accountKey = (account) => `${account.login}@${account.host}`;
61
+ exports.accountKey = accountKey;
62
+ function apiBaseForHost(host) {
63
+ return host === "github.com" ? "https://api.github.com" : `https://api.${host}`;
64
+ }
65
+ /** A Microsoft account: a GitHub Enterprise (ghe.com) host, or the EMU `_microsoft` login on github.com. */
66
+ function isWorkAccount(key) {
67
+ const at = key.lastIndexOf("@");
68
+ const login = key.slice(0, at);
69
+ const host = key.slice(at + 1).toLowerCase();
70
+ return host.endsWith(".ghe.com") || /_microsoft$/i.test(login);
71
+ }
72
+ function globMatch(pattern, value) {
73
+ const escaped = pattern.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
74
+ return new RegExp(`^${escaped}$`, "i").test(value);
75
+ }
76
+ function isEligible(key, eligible = "work") {
77
+ if (eligible === "work")
78
+ return isWorkAccount(key);
79
+ if (eligible === "personal")
80
+ return !isWorkAccount(key);
81
+ return eligible.some((pattern) => globMatch(pattern, key));
82
+ }
83
+ /* v8 ignore next -- tests always inject spawnSync; the default is for production @preserve */
84
+ const spawnOf = (deps) => deps.spawnSync ?? child_process_1.spawnSync;
85
+ function cleanGhEnv() {
86
+ const env = { ...process.env, PATH: ["/opt/homebrew/bin", "/usr/local/bin", process.env.PATH].filter(Boolean).join(":") };
87
+ delete env.GH_TOKEN;
88
+ delete env.GITHUB_TOKEN;
89
+ delete env.GH_ENTERPRISE_TOKEN;
90
+ delete env.GH_HOST;
91
+ return env;
92
+ }
93
+ /**
94
+ * The accounts signed in to the Copilot app, from its own database, in the app's order (default first, then
95
+ * sign-in order): the order accounts are filled in. Null when the app isn't installed.
96
+ */
97
+ function readAppAccounts(deps = {}) {
98
+ const spawnSync = spawnOf(deps);
99
+ const db = path.join(deps.homeDir ?? os.homedir(), ".copilot", "data.db");
100
+ const result = spawnSync("/usr/bin/sqlite3", ["-readonly", "-json", "-cmd", ".timeout 3000", db,
101
+ "SELECT login, host, settings_json FROM accounts WHERE kind = 'github' ORDER BY is_default DESC, created_at, rowid"], { encoding: "utf8", timeout: 15000 });
102
+ if (result.status !== 0 || typeof result.stdout !== "string")
103
+ return null;
104
+ try {
105
+ const rows = result.stdout.trim() ? JSON.parse(result.stdout) : [];
106
+ return rows.map((row) => {
107
+ let settings = {};
108
+ try {
109
+ settings = JSON.parse(String(row.settings_json ?? "{}"));
110
+ }
111
+ catch {
112
+ settings = {};
113
+ }
114
+ return {
115
+ login: String(row.login),
116
+ host: String(row.host),
117
+ copilot: settings.copilotAccess !== false && settings.copilotAppEnabled !== false,
118
+ };
119
+ });
120
+ }
121
+ catch {
122
+ return null;
123
+ }
124
+ }
125
+ /** The accounts the GitHub CLI is signed in to, for machines without the Copilot app. */
126
+ function readGhAccounts(deps = {}) {
127
+ const spawnSync = spawnOf(deps);
128
+ const result = spawnSync("gh", ["auth", "status", "--json", "hosts"], { encoding: "utf8", timeout: 15000, env: cleanGhEnv() });
129
+ try {
130
+ const hosts = JSON.parse(String(result.stdout)).hosts ?? {};
131
+ return Object.entries(hosts).flatMap(([host, users]) => users
132
+ .filter((user) => user.state === "success" && typeof user.login === "string")
133
+ .map((user) => ({ login: user.login, host, copilot: true })));
134
+ }
135
+ catch {
136
+ return [];
137
+ }
138
+ }
139
+ /**
140
+ * One account, on its own host: its token from `gh auth token --hostname <host> --user <login>`, then
141
+ * `/copilot_internal/user` on that host for its Copilot API endpoint. A token for another login is refused.
142
+ */
143
+ async function discoverAccount(login, host, deps = {}) {
144
+ const spawnSync = spawnOf(deps);
145
+ const doFetch = deps.fetch ?? fetch;
146
+ const key = (0, exports.accountKey)({ login, host });
147
+ const tokenResult = spawnSync("gh", ["auth", "token", "--hostname", host, "--user", login], { encoding: "utf8", timeout: 10000, env: cleanGhEnv() });
148
+ const githubToken = tokenResult.status === 0 ? String(tokenResult.stdout ?? "").trim() : "";
149
+ if (!githubToken)
150
+ throw new Error(`${key}: the GitHub CLI has no token for this account (run \`gh auth login --hostname ${host}\`)`);
151
+ const response = await doFetch(`${apiBaseForHost(host)}/copilot_internal/user`, {
152
+ headers: { Authorization: `token ${githubToken}`, Accept: "application/json", "User-Agent": "ouro-account-pool" },
153
+ signal: AbortSignal.timeout(15000),
154
+ });
155
+ if (!response.ok)
156
+ throw new Error(`${key}: Copilot discovery failed (HTTP ${response.status})`);
157
+ const body = await response.json();
158
+ if (typeof body.login === "string" && body.login.toLowerCase() !== login.toLowerCase()) {
159
+ throw new Error(`${key}: the token belongs to ${body.login}, so it is refused`);
160
+ }
161
+ const baseUrl = body.endpoints?.api;
162
+ if (!baseUrl)
163
+ throw new Error(`${key}: Copilot discovery returned no endpoints.api`);
164
+ const at = (deps.now ?? (() => new Date()))().toISOString();
165
+ return { login, host, baseUrl, githubToken, reading: (0, fleet_readings_1.directReading)(key, body, at) };
166
+ }
167
+ /** Discover every eligible account the Copilot app (or, without it, the GitHub CLI) is signed in to. */
168
+ async function discoverAccountPool(settings, deps = {}) {
169
+ const signedIn = readAppAccounts(deps) ?? readGhAccounts(deps);
170
+ const skipped = [];
171
+ const candidates = [];
172
+ for (const account of signedIn) {
173
+ const key = (0, exports.accountKey)(account);
174
+ if (!account.copilot)
175
+ skipped.push({ key, reason: "Copilot is off for this account" });
176
+ else if (!isEligible(key, settings.eligible))
177
+ skipped.push({ key, reason: "not eligible for this agent" });
178
+ else if (!candidates.some((seen) => (0, exports.accountKey)(seen) === key))
179
+ candidates.push(account);
180
+ }
181
+ const results = await Promise.all(candidates.map(async (account) => {
182
+ try {
183
+ return await discoverAccount(account.login, account.host, deps);
184
+ }
185
+ catch (error) {
186
+ skipped.push({ key: (0, exports.accountKey)(account), reason: error instanceof Error ? error.message : String(error) });
187
+ return null;
188
+ }
189
+ }));
190
+ const found = results.filter((account) => account !== null);
191
+ (0, runtime_1.emitNervesEvent)({
192
+ component: "engine",
193
+ event: "engine.account_pool_discovered",
194
+ message: "discovered the provider account pool",
195
+ meta: { accounts: found.map(exports.accountKey), skipped: skipped.map((entry) => `${entry.key}: ${entry.reason}`) },
196
+ });
197
+ return {
198
+ accounts: found.map(({ login, host, baseUrl, githubToken }) => ({ login, host, baseUrl, githubToken })),
199
+ readings: found.flatMap((account) => (account.reading ? [account.reading] : [])),
200
+ skipped,
201
+ };
202
+ }
203
+ function serializeAccountPool(accounts) {
204
+ return JSON.stringify(accounts.map(({ login, host, baseUrl, githubToken }) => ({ login, host, baseUrl, githubToken })));
205
+ }
206
+ function parseAccountPool(raw) {
207
+ if (typeof raw !== "string" || !raw.trim())
208
+ return [];
209
+ try {
210
+ const parsed = JSON.parse(raw);
211
+ if (!Array.isArray(parsed))
212
+ return [];
213
+ return parsed.filter((entry) => !!entry && typeof entry === "object"
214
+ && typeof entry.login === "string" && typeof entry.host === "string"
215
+ && typeof entry.baseUrl === "string" && typeof entry.githubToken === "string");
216
+ }
217
+ catch {
218
+ return [];
219
+ }
220
+ }
221
+ /**
222
+ * The account for the next turn among accounts not refused right now, in pool order: by tranche; when every
223
+ * account with a reading is spent, enterprise overage (the current account first); then an account with no
224
+ * reading yet. Null when none can serve.
225
+ */
226
+ function chooseAccount(pool, readings, options = {}) {
227
+ const now = options.now ?? Date.now();
228
+ const refused = options.refused ?? {};
229
+ const current = options.current ?? null;
230
+ const order = pool.map(exports.accountKey);
231
+ const eligible = order.filter((key) => !(refused[key] > now));
232
+ const cap = (0, tranche_1.trancheCap)(readings, eligible, options.caps ?? tranche_1.DEFAULT_TRANCHE_CAPS);
233
+ const map = new Map(readings.map((reading) => [reading.key, reading]));
234
+ const overage = (key) => key !== null && eligible.includes(key) && map.get(key)?.overageOk === true;
235
+ const key = (0, tranche_1.pickByTranche)(current, readings, eligible, order, cap)
236
+ ?? (overage(current) ? current : eligible.find(overage))
237
+ ?? eligible.find((candidate) => (0, tranche_1.usedPct)(map.get(candidate)) === null);
238
+ return pool.find((account) => (0, exports.accountKey)(account) === key) ?? null;
239
+ }
240
+ /** Until when an account refuses requests: Retry-After when given, the quota reset for a spent quota, else 5 minutes. */
241
+ function refusalUntil(status, error, reset, now) {
242
+ const headers = error?.headers;
243
+ const retryAfter = headers && typeof headers.get === "function"
244
+ ? headers.get("retry-after")
245
+ : headers?.["retry-after"];
246
+ const seconds = Number(retryAfter);
247
+ if (retryAfter && Number.isFinite(seconds) && seconds > 0)
248
+ return now + seconds * 1000;
249
+ const message = error instanceof Error ? error.message : String(error);
250
+ // Only a spent quota waits for the reset; a plain "rate limit exceeded" is a short throttle.
251
+ if (status === 402 || /quota|billing/i.test(message)) {
252
+ const resetAt = Date.parse(reset ?? "");
253
+ if (Number.isFinite(resetAt) && resetAt > now)
254
+ return resetAt;
255
+ const date = new Date(now);
256
+ return Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1);
257
+ }
258
+ return now + 5 * 60 * 1000;
259
+ }
260
+ function defaultAppendLine(file, line) {
261
+ fs.mkdirSync(path.dirname(file), { recursive: true });
262
+ fs.appendFileSync(file, line, "utf8");
263
+ }
264
+ const HOUR_MS = 60 * 60 * 1000;
265
+ class AccountPool {
266
+ accounts;
267
+ readings = [];
268
+ refused = {};
269
+ currentKey = null;
270
+ requests = [];
271
+ lastRefresh = -Infinity;
272
+ lastPublish = -Infinity;
273
+ loadedReadings = false;
274
+ refreshing = null;
275
+ options;
276
+ constructor(accounts, options) {
277
+ if (accounts.length === 0)
278
+ throw new Error("an account pool needs at least one account");
279
+ this.accounts = accounts;
280
+ this.options = options;
281
+ }
282
+ now() {
283
+ return (this.options.now ?? Date.now)();
284
+ }
285
+ find(key) {
286
+ return this.accounts.find((account) => (0, exports.accountKey)(account) === key);
287
+ }
288
+ leftPct(key) {
289
+ return this.readings.find((reading) => reading.key === key)?.leftPct ?? null;
290
+ }
291
+ currentKeyOrNull() {
292
+ return this.currentKey;
293
+ }
294
+ current() {
295
+ return this.find(this.currentKey) ?? this.accounts[0];
296
+ }
297
+ setReadings(readings) {
298
+ this.readings = (0, fleet_readings_1.mergeReadings)(this.readings, [...readings]);
299
+ }
300
+ /** Refresh readings in the background when they are stale; never blocks a turn. */
301
+ refreshIfStale() {
302
+ const load = this.options.loadReadings;
303
+ if (!load || this.refreshing || this.now() - this.lastRefresh < (this.options.refreshMs ?? 5 * 60 * 1000)) {
304
+ return this.refreshing ?? Promise.resolve();
305
+ }
306
+ this.lastRefresh = this.now();
307
+ this.refreshing = load()
308
+ .then((readings) => {
309
+ this.setReadings(readings);
310
+ this.loadedReadings = true;
311
+ this.publishIfDue();
312
+ })
313
+ .catch((error) => {
314
+ (0, runtime_1.emitNervesEvent)({
315
+ level: "warn",
316
+ component: "engine",
317
+ event: "engine.account_pool_refresh_failed",
318
+ message: "could not refresh account pool readings",
319
+ meta: { agent: this.options.agent, error: error instanceof Error ? error.message : String(error) },
320
+ });
321
+ })
322
+ .finally(() => {
323
+ this.refreshing = null;
324
+ });
325
+ return this.refreshing;
326
+ }
327
+ /** Called between turns: stay on the current account until it reaches the tranche cap. */
328
+ beforeTurn() {
329
+ void this.refreshIfStale();
330
+ const previous = this.currentKey;
331
+ const caps = this.options.caps ?? tranche_1.DEFAULT_TRANCHE_CAPS;
332
+ const next = chooseAccount(this.accounts, this.readings, { current: previous, refused: this.refused, now: this.now(), caps })
333
+ ?? this.current();
334
+ const nextKey = (0, exports.accountKey)(next);
335
+ if (nextKey !== previous) {
336
+ const eligible = this.accounts.map(exports.accountKey).filter((key) => !(this.refused[key] > this.now()));
337
+ this.currentKey = nextKey;
338
+ this.logSwitch({ from: previous, to: nextKey, reason: previous === null ? "start" : "tranche", cap: (0, tranche_1.trancheCap)(this.readings, eligible, caps) });
339
+ }
340
+ return next;
341
+ }
342
+ /**
343
+ * The account `key` refused a request with a 402 or 429: mark it refused until it can serve again and
344
+ * move to the next account. Returns the account to retry on, or null when no other account can serve.
345
+ */
346
+ onRefusal(key, status, error) {
347
+ const reset = this.readings.find((reading) => reading.key === key)?.reset;
348
+ const until = refusalUntil(status, error, reset, this.now());
349
+ this.refused[key] = until;
350
+ const next = chooseAccount(this.accounts, this.readings, { current: null, refused: this.refused, now: this.now(), caps: this.options.caps });
351
+ if (!next || (0, exports.accountKey)(next) === key) {
352
+ (0, runtime_1.emitNervesEvent)({
353
+ level: "warn",
354
+ component: "engine",
355
+ event: "engine.account_pool_exhausted",
356
+ message: "no other account in the pool can take this turn",
357
+ meta: { agent: this.options.agent, refused: key, status },
358
+ });
359
+ return null;
360
+ }
361
+ const nextKey = (0, exports.accountKey)(next);
362
+ this.currentKey = nextKey;
363
+ this.logSwitch({ from: key, to: nextKey, reason: String(status), refusedUntil: new Date(until).toISOString() });
364
+ return next;
365
+ }
366
+ /** Count one model request against `key`, and publish this agent's burn when it is due. */
367
+ recordRequest(key) {
368
+ const now = this.now();
369
+ this.requests = [...this.requests.filter((entry) => now - entry.at < HOUR_MS), { key, at: now }];
370
+ this.shareRequests();
371
+ this.publishIfDue();
372
+ }
373
+ /**
374
+ * Rewrite this agent's file in the fleet gist every few minutes while it runs, once readings have loaded
375
+ * (so a process that just started never blanks the agent's published readings).
376
+ */
377
+ publishIfDue() {
378
+ const now = this.now();
379
+ const publish = this.options.publishBurn;
380
+ const loaded = this.loadedReadings || !this.options.loadReadings;
381
+ if (!publish || !loaded || now - this.lastPublish < (this.options.publishMs ?? 5 * 60 * 1000))
382
+ return;
383
+ this.lastPublish = now;
384
+ void publish({
385
+ agent: this.options.agent,
386
+ machine: this.options.machine ?? os.hostname().split(".")[0].toLowerCase().replace(/\./g, "-"),
387
+ at: new Date(now).toISOString(),
388
+ current: this.currentKey,
389
+ requestsPerH: this.agentBurnPerH(now),
390
+ readings: this.accounts.map(exports.accountKey).flatMap((key) => {
391
+ const found = this.readings.find((reading) => reading.key === key);
392
+ return found ? [found] : [];
393
+ }),
394
+ });
395
+ }
396
+ /** Share this process's last-hour request times with the agent's other processes. */
397
+ shareRequests() {
398
+ const dir = this.options.burnDir;
399
+ if (!dir)
400
+ return;
401
+ try {
402
+ fs.mkdirSync(dir, { recursive: true });
403
+ fs.writeFileSync(path.join(dir, `${process.pid}.json`), JSON.stringify({ requests: this.requests }));
404
+ }
405
+ catch (error) {
406
+ (0, runtime_1.emitNervesEvent)({
407
+ level: "warn",
408
+ component: "engine",
409
+ event: "engine.account_burn_share_failed",
410
+ message: "could not share this process's burn with the agent's other processes",
411
+ // fs only throws Errors.
412
+ meta: { agent: this.options.agent, error: error.message },
413
+ });
414
+ }
415
+ }
416
+ /** Requests in the hour before `now` across all of this agent's processes, counted from each one's request times. */
417
+ agentBurnPerH(now) {
418
+ const total = {};
419
+ const count = (requests) => {
420
+ for (const entry of requests) {
421
+ if (typeof entry.key !== "string" || typeof entry.at !== "number" || now - entry.at >= HOUR_MS || entry.at > now)
422
+ continue;
423
+ total[entry.key] = (total[entry.key] ?? 0) + 1;
424
+ }
425
+ };
426
+ count(this.requests);
427
+ const dir = this.options.burnDir;
428
+ let names = [];
429
+ try {
430
+ names = dir ? fs.readdirSync(dir) : [];
431
+ }
432
+ catch {
433
+ names = [];
434
+ }
435
+ for (const name of names) {
436
+ if (name === `${process.pid}.json` || !name.endsWith(".json"))
437
+ continue;
438
+ try {
439
+ const other = JSON.parse(fs.readFileSync(path.join(dir, name), "utf8"));
440
+ if (Array.isArray(other.requests))
441
+ count(other.requests);
442
+ }
443
+ catch {
444
+ // Another process is mid-write; its counts join the next publish.
445
+ }
446
+ }
447
+ return total;
448
+ }
449
+ burnPerH() {
450
+ const now = this.now();
451
+ const out = {};
452
+ for (const entry of this.requests)
453
+ if (now - entry.at < HOUR_MS)
454
+ out[entry.key] = (out[entry.key] ?? 0) + 1;
455
+ return out;
456
+ }
457
+ logSwitch(change) {
458
+ const record = {
459
+ at: new Date(this.now()).toISOString(),
460
+ agent: this.options.agent,
461
+ ...change,
462
+ fromLeftPct: this.leftPct(change.from),
463
+ toLeftPct: this.leftPct(change.to),
464
+ };
465
+ try {
466
+ (this.options.appendLine ?? defaultAppendLine)(this.options.switchLog, `${JSON.stringify(record)}\n`);
467
+ }
468
+ catch (error) {
469
+ (0, runtime_1.emitNervesEvent)({
470
+ level: "warn",
471
+ component: "engine",
472
+ event: "engine.account_switch_log_failed",
473
+ message: "could not write the account switch log",
474
+ meta: { agent: this.options.agent, error: error instanceof Error ? error.message : String(error) },
475
+ });
476
+ }
477
+ (0, runtime_1.emitNervesEvent)({
478
+ component: "engine",
479
+ event: "engine.account_switched",
480
+ message: `switched account ${record.from ?? "(none)"} -> ${record.to} (${record.reason})`,
481
+ meta: { ...record },
482
+ });
483
+ }
484
+ }
485
+ exports.AccountPool = AccountPool;
486
+ /** Each pool account's own reading, from its host's `/copilot_internal/user`. */
487
+ async function fetchDirectReadings(accounts, deps = {}) {
488
+ const doFetch = deps.fetch ?? fetch;
489
+ const at = (deps.now ?? (() => new Date()))().toISOString();
490
+ const readings = await Promise.all(accounts.map(async (account) => {
491
+ try {
492
+ const response = await doFetch(`${apiBaseForHost(account.host)}/copilot_internal/user`, {
493
+ headers: { Authorization: `token ${account.githubToken}`, Accept: "application/json", "User-Agent": "ouro-account-pool" },
494
+ signal: AbortSignal.timeout(15000),
495
+ });
496
+ return response.ok ? (0, fleet_readings_1.directReading)((0, exports.accountKey)(account), await response.json(), at) : null;
497
+ }
498
+ catch {
499
+ return null;
500
+ }
501
+ }));
502
+ return readings.filter((reading) => reading !== null);
503
+ }
504
+ /** One turn's view of the pool: the account is chosen once, between turns, and changes only on a refusal. */
505
+ function createPooledCaller(pool, makeClient) {
506
+ let account = pool.beforeTurn();
507
+ const clients = new Map();
508
+ const clientFor = (target) => {
509
+ const key = (0, exports.accountKey)(target);
510
+ if (!clients.has(key))
511
+ clients.set(key, makeClient(target));
512
+ return clients.get(key);
513
+ };
514
+ return {
515
+ account: () => account,
516
+ client: () => clientFor(account),
517
+ async call(request) {
518
+ pool.recordRequest((0, exports.accountKey)(account));
519
+ try {
520
+ return await request(clientFor(account), account);
521
+ }
522
+ catch (error) {
523
+ const status = error?.status;
524
+ if (status !== 402 && status !== 429)
525
+ throw error;
526
+ const next = pool.onRefusal((0, exports.accountKey)(account), status, error);
527
+ if (!next)
528
+ throw error;
529
+ account = next;
530
+ pool.recordRequest((0, exports.accountKey)(account));
531
+ return await request(clientFor(account), account);
532
+ }
533
+ },
534
+ };
535
+ }
536
+ const pools = new Map();
537
+ /** One pool per agent per process, kept across turns so the current account and refusals persist. */
538
+ function getAccountPool(accounts, options) {
539
+ const fingerprint = serializeAccountPool(accounts);
540
+ const cached = pools.get(options.agent);
541
+ if (cached && cached.fingerprint === fingerprint)
542
+ return cached.pool;
543
+ const pool = new AccountPool(accounts, options);
544
+ pools.set(options.agent, { fingerprint, pool });
545
+ return pool;
546
+ }
547
+ function resetAccountPools() {
548
+ pools.clear();
549
+ }
@@ -1,9 +1,43 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
37
  };
5
38
  Object.defineProperty(exports, "__esModule", { value: true });
6
39
  exports.classifyGithubCopilotError = classifyGithubCopilotError;
40
+ exports.createGithubCopilotPooledCaller = createGithubCopilotPooledCaller;
7
41
  exports.createGithubCopilotProviderRuntime = createGithubCopilotProviderRuntime;
8
42
  const openai_1 = __importDefault(require("openai"));
9
43
  const config_1 = require("../config");
@@ -11,10 +45,38 @@ const runtime_1 = require("../../nerves/runtime");
11
45
  const streaming_1 = require("../streaming");
12
46
  const model_capabilities_1 = require("../model-capabilities");
13
47
  const error_classification_1 = require("./error-classification");
48
+ const path = __importStar(require("path"));
49
+ const account_pool_1 = require("./account-pool");
50
+ const fleet_readings_1 = require("../quota/fleet-readings");
14
51
  function classifyGithubCopilotError(error) {
15
52
  return (0, error_classification_1.classifyHttpError)(error);
16
53
  }
17
- function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGithubCopilotConfig)()) {
54
+ /**
55
+ * The agent's account pool for this turn, when `ouro auth` discovered one; null for a single account.
56
+ * Without an owning agent (a daemon-side ping, provider discovery) the pool still switches on a 402 or 429,
57
+ * but keeps no state between calls, writes no switch log and publishes nothing.
58
+ */
59
+ function createGithubCopilotPooledCaller(config, owner) {
60
+ const accounts = (0, account_pool_1.parseAccountPool)(config.accountPool);
61
+ if (accounts.length === 0)
62
+ return null;
63
+ const makeClient = (account) => new openai_1.default({ apiKey: account.githubToken, baseURL: account.baseUrl, maxRetries: 0 });
64
+ if (!owner)
65
+ return (0, account_pool_1.createPooledCaller)(new account_pool_1.AccountPool(accounts, { agent: "(unowned)", switchLog: "", appendLine: () => { } }), makeClient);
66
+ const gist = config.fleetGistId && config.fleetGistToken ? { gistId: config.fleetGistId, token: config.fleetGistToken } : null;
67
+ const pool = (0, account_pool_1.getAccountPool)(accounts, {
68
+ agent: owner.agentName,
69
+ machine: config.fleetMachine,
70
+ switchLog: path.join(owner.agentRoot, "state", "account-switches.jsonl"),
71
+ burnDir: path.join(owner.agentRoot, "state", "account-burn"),
72
+ /* v8 ignore start -- network readers and publisher: each is tested in its own module @preserve */
73
+ loadReadings: async () => (0, fleet_readings_1.mergeReadings)(await (0, fleet_readings_1.loadFleetQuota)(gist), await (0, account_pool_1.fetchDirectReadings)(accounts)),
74
+ publishBurn: gist ? (burn) => (0, fleet_readings_1.publishAgentBurn)(gist, burn) : undefined,
75
+ /* v8 ignore stop */
76
+ });
77
+ return (0, account_pool_1.createPooledCaller)(pool, makeClient);
78
+ }
79
+ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGithubCopilotConfig)(), owner) {
18
80
  (0, runtime_1.emitNervesEvent)({
19
81
  component: "engine",
20
82
  event: "engine.provider_init",
@@ -33,11 +95,14 @@ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGith
33
95
  /* v8 ignore next -- branch: capability detection tested via unit test @preserve */
34
96
  if (modelCaps.reasoningEffort)
35
97
  capabilities.add("reasoning-effort");
36
- const client = new openai_1.default({
98
+ // With an account pool the account is chosen here, between turns; a 402 or 429 moves it mid-request.
99
+ const pooled = createGithubCopilotPooledCaller(config, owner);
100
+ const client = pooled ? pooled.client() : new openai_1.default({
37
101
  apiKey: config.githubToken,
38
102
  baseURL: config.baseUrl,
39
103
  maxRetries: 0,
40
104
  });
105
+ const callModel = (fallback, request) => pooled ? pooled.call((pooledClient) => request(pooledClient)) : request(fallback);
41
106
  if (isCompletionsModel) {
42
107
  // Chat completions path (Claude models via Copilot)
43
108
  return {
@@ -69,7 +134,7 @@ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGith
69
134
  if (request.toolChoiceRequired)
70
135
  params.tool_choice = "auto";
71
136
  try {
72
- return await (0, streaming_1.streamChatCompletion)(this.client, params, request.callbacks, request.signal, request.eagerSettleStreaming);
137
+ return await callModel(this.client, (turnClient) => (0, streaming_1.streamChatCompletion)(turnClient, params, request.callbacks, request.signal, request.eagerSettleStreaming));
73
138
  }
74
139
  catch (error) {
75
140
  throw error instanceof Error ? error : new Error(String(error));
@@ -78,7 +143,7 @@ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGith
78
143
  /* v8 ignore stop */
79
144
  /* v8 ignore start -- ping: tested via provider-ping.test.ts @preserve */
80
145
  async ping(signal) {
81
- await this.client.chat.completions.create({ model: this.model, max_tokens: 1, messages: [{ role: "user", content: "ping" }] }, { signal });
146
+ await callModel(this.client, (turnClient) => turnClient.chat.completions.create({ model: this.model, max_tokens: 1, messages: [{ role: "user", content: "ping" }] }, { signal }));
82
147
  },
83
148
  /* v8 ignore stop */
84
149
  /* v8 ignore next 3 -- delegation: classification logic tested via classifyGithubCopilotError @preserve */
@@ -125,7 +190,7 @@ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGith
125
190
  if (request.toolChoiceRequired)
126
191
  params.tool_choice = "required";
127
192
  try {
128
- const result = await (0, streaming_1.streamResponsesApi)(this.client, params, request.callbacks, request.signal, request.eagerSettleStreaming);
193
+ const result = await callModel(this.client, (turnClient) => (0, streaming_1.streamResponsesApi)(turnClient, params, request.callbacks, request.signal, request.eagerSettleStreaming));
129
194
  for (const item of result.outputItems)
130
195
  nativeInput.push(item);
131
196
  return result;
@@ -137,7 +202,7 @@ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGith
137
202
  /* v8 ignore stop */
138
203
  /* v8 ignore start -- ping: tested via provider-ping.test.ts @preserve */
139
204
  async ping(signal) {
140
- await this.client.responses.create({ model: this.model, input: "ping", max_output_tokens: 16 }, { signal });
205
+ await callModel(this.client, (turnClient) => turnClient.responses.create({ model: this.model, input: "ping", max_output_tokens: 16 }, { signal }));
141
206
  },
142
207
  /* v8 ignore stop */
143
208
  /* v8 ignore next 3 -- delegation: classification logic tested via classifyGithubCopilotError @preserve */