@ouro.bot/cli 0.1.0-alpha.1011 → 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.
package/changelog.json CHANGED
@@ -1,6 +1,12 @@
1
1
  {
2
2
  "_note": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1013",
6
+ "changes": [
7
+ "github-copilot can bill a discovered pool of Copilot accounts: with accountPool in agent.json, ouro auth discovers every eligible account signed in to the Copilot app (each checked on its own host), and the runtime fills them by quota tranche (30/60/90/100% used), moves to the next account at once on a 402 or 429 and retries that request once, logs every move to state/account-switches.jsonl, and publishes the agent's burn (summed across its processes) to the fleet gist."
8
+ ]
9
+ },
4
10
  {
5
11
  "version": "0.1.0-alpha.1011",
6
12
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1011",
2
+ "runtimeVersion": "0.1.0-alpha.1013",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1011</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1013</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -37,6 +37,8 @@ exports.readAgentConfigForAgent = readAgentConfigForAgent;
37
37
  exports.writeAgentProviderSelection = writeAgentProviderSelection;
38
38
  exports.storeProviderCredentials = storeProviderCredentials;
39
39
  exports.writeAgentModel = writeAgentModel;
40
+ exports.readAccountPoolSettings = readAccountPoolSettings;
41
+ exports.collectGithubCopilotPoolCredentials = collectGithubCopilotPoolCredentials;
40
42
  exports.collectRuntimeAuthCredentials = collectRuntimeAuthCredentials;
41
43
  exports.resolveHatchCredentials = resolveHatchCredentials;
42
44
  exports.runRuntimeAuthFlow = runRuntimeAuthFlow;
@@ -50,6 +52,7 @@ const identity_1 = require("../identity");
50
52
  const migrate_config_1 = require("../migrate-config");
51
53
  const provider_models_1 = require("../provider-models");
52
54
  const agent_presentation_1 = require("../../senses/shepherd/agent-presentation");
55
+ const account_pool_1 = require("../providers/account-pool");
53
56
  const provider_credentials_1 = require("../provider-credentials");
54
57
  const vault_unlock_1 = require("../../repertoire/vault-unlock");
55
58
  const ANTHROPIC_SETUP_TOKEN_PREFIX = "sk-ant-oat01-";
@@ -274,6 +277,60 @@ function validateAnthropicToken(token) {
274
277
  }
275
278
  return trimmed;
276
279
  }
280
+ /** The agent's `accountPool` settings, or null when it has none (or its bundle can't be read here). */
281
+ function readAccountPoolSettings(agentName, bundlesRoot) {
282
+ try {
283
+ const settings = readAgentConfigForAgent(agentName, bundlesRoot).config.accountPool;
284
+ return settings && typeof settings === "object" ? settings : null;
285
+ }
286
+ catch {
287
+ return null;
288
+ }
289
+ }
290
+ /**
291
+ * Discover the agent's Copilot account pool: every eligible account signed in to the Copilot app, each
292
+ * checked on its own host. The first account is also the single-account credential, so older runtimes
293
+ * keep working.
294
+ */
295
+ async function collectGithubCopilotPoolCredentials(input, settings, deps) {
296
+ /* v8 ignore next -- tests always inject spawnSync; the default is for production @preserve */
297
+ const spawnSync = deps.spawnSync ?? child_process_1.spawnSync;
298
+ writeAuthProgress(input, "discovering the Copilot accounts signed in on this machine...");
299
+ const discovery = await (0, account_pool_1.discoverAccountPool)(settings, { spawnSync, homeDir: deps.homeDir });
300
+ for (const skipped of discovery.skipped)
301
+ writeAuthProgress(input, `skipped ${skipped.key}: ${skipped.reason}`);
302
+ const [first] = discovery.accounts;
303
+ if (!first) {
304
+ throw new Error(`No eligible Copilot account is signed in on this machine for ${input.agentName}. Sign one in to the Copilot app and the GitHub CLI (\`gh auth login --hostname <host>\`), then retry.`);
305
+ }
306
+ const credentials = {
307
+ githubToken: first.githubToken,
308
+ baseUrl: first.baseUrl,
309
+ accountPool: (0, account_pool_1.serializeAccountPool)(discovery.accounts),
310
+ };
311
+ const fleet = settings.fleet;
312
+ if (fleet?.gistId) {
313
+ const result = spawnSync("gh", ["auth", "token", "--hostname", "github.com", ...(fleet.user ? ["--user", fleet.user] : [])], { encoding: "utf8" });
314
+ const token = result.status === 0 && result.stdout ? String(result.stdout).trim() : "";
315
+ if (token) {
316
+ credentials.fleetGistToken = token;
317
+ credentials.fleetGistId = fleet.gistId;
318
+ if (fleet.machine)
319
+ credentials.fleetMachine = fleet.machine;
320
+ }
321
+ else {
322
+ writeAuthProgress(input, "no github.com token for the fleet gist; burn publishing stays off");
323
+ }
324
+ }
325
+ writeAuthProgress(input, `account pool: ${discovery.accounts.map(account_pool_1.accountKey).join(", ")}`);
326
+ (0, runtime_1.emitNervesEvent)({
327
+ component: "daemon",
328
+ event: "daemon.auth_account_pool",
329
+ message: "discovered the github-copilot account pool for runtime auth",
330
+ meta: { agentName: input.agentName, accounts: discovery.accounts.map(account_pool_1.accountKey), fleet: Boolean(credentials.fleetGistToken) },
331
+ });
332
+ return credentials;
333
+ }
277
334
  async function collectRuntimeAuthCredentials(input, deps) {
278
335
  const spawnSync = deps.spawnSync ?? child_process_1.spawnSync;
279
336
  const homeDir = deps.homeDir ?? os.homedir();
@@ -292,6 +349,9 @@ async function collectRuntimeAuthCredentials(input, deps) {
292
349
  };
293
350
  }
294
351
  if (input.provider === "github-copilot") {
352
+ const poolSettings = readAccountPoolSettings(input.agentName, deps.bundlesRoot);
353
+ if (poolSettings)
354
+ return collectGithubCopilotPoolCredentials(input, poolSettings, deps);
295
355
  let token = process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim() || "";
296
356
  let ghInstalled = true;
297
357
  if (!token) {
@@ -121,7 +121,7 @@ async function getProviderRuntimeFingerprint(facing, owner) {
121
121
  }
122
122
  function createProviderRegistry() {
123
123
  return {
124
- resolve(provider, model, credential) {
124
+ resolve(provider, model, credential, owner) {
125
125
  const providerConfig = { ...credential.config, ...credential.credentials };
126
126
  switch (provider) {
127
127
  case "azure":
@@ -133,7 +133,7 @@ function createProviderRegistry() {
133
133
  case "openai-codex":
134
134
  return (0, openai_codex_1.createOpenAICodexProviderRuntime)(model, providerConfig);
135
135
  case "github-copilot":
136
- return (0, github_copilot_1.createGithubCopilotProviderRuntime)(model, providerConfig);
136
+ return (0, github_copilot_1.createGithubCopilotProviderRuntime)(model, providerConfig, owner);
137
137
  case "openai-compatible":
138
138
  case "openai-compatible-gemini":
139
139
  return (0, openai_compatible_1.createOpenAICompatibleProviderRuntime)(provider, model, providerConfig);
@@ -148,7 +148,9 @@ async function getProviderRuntime(facing = "human", owner) {
148
148
  const { binding, fingerprint, credential } = await getProviderRuntimeFingerprint(facing, scope);
149
149
  const cached = _providerRuntimeFactories[facing];
150
150
  if (!cached || cached.fingerprint !== fingerprint) {
151
- const create = () => createProviderRegistry().resolve(binding.provider, binding.model, credential);
151
+ const agentName = scope?.agentName ?? (0, identity_2.getAgentName)();
152
+ const runtimeOwner = { agentName, agentRoot: scope?.agentRoot ?? (0, identity_2.getAgentRoot)(agentName) };
153
+ const create = () => createProviderRegistry().resolve(binding.provider, binding.model, credential, runtimeOwner);
152
154
  runtime = create();
153
155
  _providerRuntimeFactories[facing] = runtime ? { fingerprint, create } : null;
154
156
  }
@@ -75,8 +75,8 @@ const PROVIDER_FIELD_SPLITS = {
75
75
  config: [],
76
76
  },
77
77
  "github-copilot": {
78
- credentials: ["githubToken"],
79
- config: ["baseUrl"],
78
+ credentials: ["githubToken", "accountPool", "fleetGistToken"],
79
+ config: ["baseUrl", "fleetGistId", "fleetMachine"],
80
80
  },
81
81
  "openai-compatible": {
82
82
  credentials: ["apiKey"],
@@ -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 */
@@ -0,0 +1,222 @@
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.LOCAL_BALANCER_STATE = void 0;
37
+ exports.readingsFromBalancerState = readingsFromBalancerState;
38
+ exports.mergeReadings = mergeReadings;
39
+ exports.readFleetQuota = readFleetQuota;
40
+ exports.directReading = directReading;
41
+ exports.agentBurnFileName = agentBurnFileName;
42
+ exports.agentBurnContent = agentBurnContent;
43
+ exports.loadFleetQuota = loadFleetQuota;
44
+ exports.publishAgentBurn = publishAgentBurn;
45
+ const fs = __importStar(require("fs"));
46
+ const os = __importStar(require("os"));
47
+ const path = __importStar(require("path"));
48
+ const runtime_1 = require("../../nerves/runtime");
49
+ /**
50
+ * Quota readings for agents, from the same places the Copilot app balancer (`quota-balance.mjs`) keeps them:
51
+ * its local state first (`~/.config/mac-fleet/quota-balance.json`), then the fleet gist (`<machine>.quota.txt`).
52
+ * Agents publish their own burn to the same gist as `<machine>.<agent>.quota.txt`.
53
+ */
54
+ exports.LOCAL_BALANCER_STATE = path.join(".config", "mac-fleet", "quota-balance.json");
55
+ function isRecord(value) {
56
+ return !!value && typeof value === "object" && !Array.isArray(value);
57
+ }
58
+ const num = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
59
+ const str = (value) => (typeof value === "string" && value ? value : null);
60
+ /** Readings from one balancer state object: `{ readings: { "login@host": { pct, overage_permitted, at, reset } } }`. */
61
+ function readingsFromBalancerState(state, source) {
62
+ if (!isRecord(state) || !isRecord(state.readings))
63
+ return [];
64
+ const out = [];
65
+ for (const [key, raw] of Object.entries(state.readings)) {
66
+ if (!isRecord(raw) || num(raw.pct) === null)
67
+ continue;
68
+ out.push({
69
+ key,
70
+ leftPct: num(raw.pct),
71
+ burnPerH: num(raw.burn_per_h),
72
+ dryAt: str(raw.dry_at),
73
+ overageOk: raw.overage_permitted === true,
74
+ at: str(raw.at),
75
+ reset: str(raw.reset),
76
+ remaining: num(raw.remaining),
77
+ entitlement: num(raw.entitlement),
78
+ source,
79
+ });
80
+ }
81
+ return out;
82
+ }
83
+ const timeOf = (reading) => {
84
+ const at = Date.parse(reading.at ?? "");
85
+ return Number.isNaN(at) ? -Infinity : at;
86
+ };
87
+ /** Freshest reading per account. On a tie the earlier list wins, so pass local readings first. */
88
+ function mergeReadings(...lists) {
89
+ const out = new Map();
90
+ for (const list of lists) {
91
+ for (const reading of list) {
92
+ const prev = out.get(reading.key);
93
+ if (!prev || timeOf(reading) > timeOf(prev))
94
+ out.set(reading.key, reading);
95
+ }
96
+ }
97
+ return [...out.values()];
98
+ }
99
+ /** Every reading in the fleet: local balancer state first, then each other Mac's `<machine>.quota.txt` in the gist. */
100
+ function readFleetQuota(sources) {
101
+ const local = readingsFromBalancerState(sources.localState, "local");
102
+ const fleet = [];
103
+ const files = isRecord(sources.gist) && isRecord(sources.gist.files) ? sources.gist.files : {};
104
+ for (const [name, file] of Object.entries(files)) {
105
+ const match = /^([^.]+)\.quota\.txt$/.exec(name);
106
+ if (!match || !isRecord(file) || typeof file.content !== "string")
107
+ continue;
108
+ try {
109
+ fleet.push(readingsFromBalancerState(JSON.parse(file.content), `fleet:${match[1]}`));
110
+ }
111
+ catch {
112
+ // A half-written file is skipped; the next read picks it up.
113
+ }
114
+ }
115
+ const readings = mergeReadings(local, ...fleet);
116
+ (0, runtime_1.emitNervesEvent)({
117
+ component: "engine",
118
+ event: "engine.fleet_quota_read",
119
+ message: "read fleet quota readings",
120
+ meta: { local: local.length, gistFiles: fleet.length, accounts: readings.length },
121
+ });
122
+ return readings;
123
+ }
124
+ /** A reading from an account's own `/copilot_internal/user` answer. */
125
+ function directReading(key, body, at) {
126
+ if (!isRecord(body) || !isRecord(body.quota_snapshots) || !isRecord(body.quota_snapshots.premium_interactions))
127
+ return null;
128
+ const snap = body.quota_snapshots.premium_interactions;
129
+ const leftPct = snap.unlimited === true ? 100 : num(snap.percent_remaining);
130
+ if (leftPct === null)
131
+ return null;
132
+ return {
133
+ key,
134
+ leftPct,
135
+ burnPerH: null,
136
+ dryAt: null,
137
+ overageOk: snap.overage_permitted === true,
138
+ at,
139
+ reset: str(body.quota_reset_date_utc),
140
+ remaining: num(snap.remaining),
141
+ entitlement: num(snap.entitlement),
142
+ source: "direct",
143
+ };
144
+ }
145
+ function agentBurnFileName(machine, agent) {
146
+ return `${machine}.${agent}.quota.txt`;
147
+ }
148
+ /**
149
+ * The agent's file, in the shape the Copilot app balancer reads (`parseAgentQuota` in quota-balance.mjs):
150
+ * `{machine, agent, at, readings: [{key, leftPct, burnPerH, dryAt, overageOk, at, remaining, entitlement, reset}]}`.
151
+ * `burnPerH` is this agent's own requests an hour on that account.
152
+ */
153
+ function agentBurnContent(burn) {
154
+ const keys = [...new Set([...burn.readings.map((reading) => reading.key), ...Object.keys(burn.requestsPerH)])];
155
+ const readings = keys.map((key) => {
156
+ const reading = burn.readings.find((candidate) => candidate.key === key);
157
+ return {
158
+ key,
159
+ leftPct: reading?.leftPct ?? null,
160
+ burnPerH: burn.requestsPerH[key] ?? 0,
161
+ dryAt: reading?.dryAt ?? null,
162
+ overageOk: reading?.overageOk ?? false,
163
+ at: reading?.at ?? burn.at,
164
+ ...(reading?.remaining != null ? { remaining: reading.remaining } : {}),
165
+ ...(reading?.entitlement != null ? { entitlement: reading.entitlement } : {}),
166
+ ...(reading?.reset ? { reset: reading.reset } : {}),
167
+ };
168
+ });
169
+ return `${JSON.stringify({ machine: burn.machine, agent: burn.agent, at: burn.at, current: burn.current, readings }, null, 2)}\n`;
170
+ }
171
+ const gistUrl = (gistId) => `https://api.github.com/gists/${gistId}`;
172
+ const gistHeaders = (token) => ({
173
+ Authorization: `token ${token}`,
174
+ Accept: "application/vnd.github+json",
175
+ "User-Agent": "ouro-account-pool",
176
+ });
177
+ /** Load local balancer state and the fleet gist; either may be missing. */
178
+ async function loadFleetQuota(gist, io = {}) {
179
+ const readFile = io.readFile ?? ((file) => fs.readFileSync(file, "utf8"));
180
+ let localState;
181
+ try {
182
+ localState = JSON.parse(readFile(path.join(io.homeDir ?? os.homedir(), exports.LOCAL_BALANCER_STATE)));
183
+ }
184
+ catch {
185
+ localState = undefined;
186
+ }
187
+ let gistBody;
188
+ if (gist) {
189
+ try {
190
+ const response = await (io.fetch ?? fetch)(gistUrl(gist.gistId), { headers: gistHeaders(gist.token), signal: AbortSignal.timeout(15000) });
191
+ gistBody = response.ok ? await response.json() : undefined;
192
+ }
193
+ catch {
194
+ gistBody = undefined;
195
+ }
196
+ }
197
+ return readFleetQuota({ localState, gist: gistBody });
198
+ }
199
+ /** Write this agent's burn to the fleet gist. Returns false (never throws) when the gist can't be written. */
200
+ async function publishAgentBurn(gist, burn, io = {}) {
201
+ let ok = false;
202
+ try {
203
+ const response = await (io.fetch ?? fetch)(gistUrl(gist.gistId), {
204
+ method: "PATCH",
205
+ headers: { ...gistHeaders(gist.token), "Content-Type": "application/json" },
206
+ body: JSON.stringify({ files: { [agentBurnFileName(burn.machine, burn.agent)]: { content: agentBurnContent(burn) } } }),
207
+ signal: AbortSignal.timeout(15000),
208
+ });
209
+ ok = response.ok;
210
+ }
211
+ catch {
212
+ ok = false;
213
+ }
214
+ (0, runtime_1.emitNervesEvent)({
215
+ level: ok ? "info" : "warn",
216
+ component: "engine",
217
+ event: "engine.agent_burn_published",
218
+ message: ok ? "published agent burn to the fleet gist" : "could not publish agent burn to the fleet gist",
219
+ meta: { agent: burn.agent, machine: burn.machine, ok },
220
+ });
221
+ return ok;
222
+ }
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_TRANCHE_CAPS = void 0;
4
+ exports.usedPct = usedPct;
5
+ exports.trancheCap = trancheCap;
6
+ exports.pickByTranche = pickByTranche;
7
+ const runtime_1 = require("../../nerves/runtime");
8
+ /** Fill every account to 30% used, then 60%, then 90%, then squeeze the last 10% from each (Ari, 2026-11-09). */
9
+ exports.DEFAULT_TRANCHE_CAPS = [30, 60, 90, 100];
10
+ /**
11
+ * These mirror `usedPct`, `trancheCap` and `pickByTranche` in the Copilot app balancer
12
+ * (desk `setup/quota-balance.mjs`), so agents and the app fill accounts the same way.
13
+ */
14
+ /** Percent of included requests used, or null with no reading. */
15
+ function usedPct(reading) {
16
+ if (!reading || reading.leftPct === null)
17
+ return null;
18
+ return Math.max(0, Math.min(100, 100 - reading.leftPct));
19
+ }
20
+ function byKey(readings) {
21
+ return new Map(readings.map((reading) => [reading.key, reading]));
22
+ }
23
+ /**
24
+ * The current cap: the lowest cap that some eligible account with a reading is still below. It rises only once
25
+ * every eligible account has reached it. When every one is at 100 it stays 100.
26
+ */
27
+ function trancheCap(readings, eligible, caps = exports.DEFAULT_TRANCHE_CAPS) {
28
+ const map = byKey(readings);
29
+ const used = eligible.map((key) => usedPct(map.get(key))).filter((value) => value !== null);
30
+ const cap = caps.find((candidate) => used.some((value) => value < candidate)) ?? caps[caps.length - 1];
31
+ (0, runtime_1.emitNervesEvent)({
32
+ component: "engine",
33
+ event: "engine.quota_tranche_cap",
34
+ message: "computed the quota tranche cap",
35
+ meta: { cap, eligible: eligible.length },
36
+ });
37
+ return cap;
38
+ }
39
+ /**
40
+ * Stay on `current` while it is eligible and below the cap; else the first account in `order` that is eligible
41
+ * and below it, then any eligible one; null when none is (included requests spent everywhere: overage).
42
+ */
43
+ function pickByTranche(current, readings, eligible, order, cap) {
44
+ const map = byKey(readings);
45
+ const below = (key) => {
46
+ if (key === null || !eligible.includes(key))
47
+ return false;
48
+ const used = usedPct(map.get(key));
49
+ return used !== null && used < cap;
50
+ };
51
+ const picked = below(current) ? current : order.find(below) ?? eligible.find(below) ?? null;
52
+ (0, runtime_1.emitNervesEvent)({
53
+ component: "engine",
54
+ event: "engine.quota_tranche_pick",
55
+ message: "picked an account by quota tranche",
56
+ meta: { current, picked, cap },
57
+ });
58
+ return picked;
59
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1011",
3
+ "version": "0.1.0-alpha.1013",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1011",
9
+ "version": "0.1.0-alpha.1013",
10
10
  "dependencies": {
11
11
  "@anthropic-ai/sdk": "^0.78.0",
12
12
  "@azure/identity": "^4.13.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1011",
3
+ "version": "0.1.0-alpha.1013",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },