@crvouga/homelab 0.23.13 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/.mise/locks/npm-vercel/{68.0.0 → 68.2.0}/aube-lock.yaml +73 -297
  2. package/.mise/locks/npm-vercel/{68.0.0 → 68.2.0}/package.json +1 -1
  3. package/.mise/locks/npm-wrangler/{4.169.0 → 4.170.0}/aube-lock.yaml +42 -42
  4. package/.mise/locks/npm-wrangler/{4.169.0 → 4.170.0}/package.json +1 -1
  5. package/README.md +54 -76
  6. package/ansible/ubuntu/agent-tool.py +106 -1
  7. package/ansible/ubuntu/heavy.py +142 -0
  8. package/ansible/ubuntu/idle-reboot.py +125 -0
  9. package/ansible/ubuntu/policy.json +58 -3
  10. package/ansible/ubuntu/t3-desktop.yml +7 -0
  11. package/ansible/ubuntu/t3-hang-snapshot.sh +75 -0
  12. package/ansible/ubuntu/t3-headless.yml +7 -0
  13. package/ansible/ubuntu/t3-health.sh +71 -3
  14. package/ansible/ubuntu/t3-policy.yml +14 -5
  15. package/ansible/ubuntu/tasks/packages.yml +2 -0
  16. package/ansible/ubuntu/tasks/recovery.yml +16 -2
  17. package/ansible/ubuntu/tasks/resources.yml +25 -2
  18. package/ansible/ubuntu/tasks/unattended-upgrades.yml +24 -6
  19. package/ansible/ubuntu/tasks/updates.yml +59 -0
  20. package/ansible/ubuntu/wip-guard.py +141 -14
  21. package/bootstrap/doctor.ts +0 -4
  22. package/bootstrap/project-action.sh +4 -5
  23. package/bootstrap/shell-path.ts +17 -19
  24. package/cliproxy/README.md +5 -6
  25. package/cliproxy/config.template.yaml +1 -15
  26. package/cliproxy/docs/health-workflow.example.yml +6 -6
  27. package/cliproxy/docs/model-health.md +8 -8
  28. package/cliproxy/scripts/accounts.py +3 -4
  29. package/cliproxy/scripts/fleet_sync.py +2 -13
  30. package/cliproxy/scripts/ops +3 -21
  31. package/docs/authentication.md +21 -26
  32. package/docs/convergence.md +28 -32
  33. package/docs/declared.md +30 -31
  34. package/docs/durability.md +9 -0
  35. package/docs/github.md +0 -9
  36. package/docs/machine-setup.md +16 -17
  37. package/docs/manager-recovery.md +0 -2
  38. package/docs/operations.md +12 -11
  39. package/docs/releasing.md +18 -21
  40. package/docs/runbooks.md +22 -78
  41. package/docs/support-matrix.md +1 -1
  42. package/docs/ubuntu-sync.md +71 -65
  43. package/docs/worker-contract.md +112 -15
  44. package/examples/fleet.json +0 -1
  45. package/llms.txt +0 -2
  46. package/mise.lock +206 -780
  47. package/mise.toml +12 -27
  48. package/package.json +5 -6
  49. package/schema/check-ids.json +41 -482
  50. package/schema/fleet.schema.json +6 -57
  51. package/schema/roster.schema.json +0 -2
  52. package/src/agent-session-limit.ts +2 -7
  53. package/src/auth-checks.ts +1 -3
  54. package/src/check-owners.ts +0 -13
  55. package/src/check-registry.ts +13 -72
  56. package/src/cli/agent-guide.ts +3 -16
  57. package/src/cli/command-index.ts +0 -12
  58. package/src/cli/fleet-sync-manager.ts +4 -146
  59. package/src/cli/fleet-sync-output.ts +1 -4
  60. package/src/cli/fleet-sync-plan.ts +1 -24
  61. package/src/cli/fleet-sync-remote.ts +2 -1
  62. package/src/cli/fleet-sync-vault.ts +1 -2
  63. package/src/cli/fleet-sync.ts +8 -44
  64. package/src/cli/fleet.ts +1 -2
  65. package/src/cli/program.ts +3 -14
  66. package/src/cli/register-fleet.ts +1 -55
  67. package/src/cli/registry.ts +1 -43
  68. package/src/config.ts +0 -2
  69. package/src/definition.ts +8 -83
  70. package/src/fleet-config.ts +1 -1
  71. package/src/ide/definition.ts +2 -29
  72. package/src/ide/super.ts +4 -35
  73. package/src/ide/t3.ts +9 -38
  74. package/src/manager-sync.ts +1 -1
  75. package/src/node-converge-linux.ts +4 -47
  76. package/src/node-converge-shared.ts +1 -22
  77. package/src/{agents/toolchain.ts → pinned-path.ts} +0 -17
  78. package/src/platform/agent-oom-check.ts +104 -0
  79. package/src/platform/t3-policy.ts +23 -36
  80. package/src/platform/t3-service.ts +117 -0
  81. package/src/platform/wip-guard-check.ts +65 -0
  82. package/src/remote-entry.ts +2 -41
  83. package/src/repair-catalog.ts +0 -30
  84. package/src/schedule-check.ts +17 -4
  85. package/src/service-auth.ts +0 -50
  86. package/src/state/litestream.ts +1 -1
  87. package/src/t3/retire-providers.ts +79 -0
  88. package/src/t3/version.ts +1 -1
  89. package/src/transport.ts +2 -6
  90. package/src/types.ts +0 -2
  91. package/src/version-parity.ts +0 -8
  92. package/src/worker-access-checks.ts +0 -75
  93. package/src/worker-host-checks.ts +78 -1
  94. package/src/worker-policy.ts +0 -2
  95. package/src/worker-readiness.ts +2 -0
  96. package/src/worker-sizing.ts +25 -0
  97. package/.mise/locks/azure-cli/2.93.0~a837e014/pyproject.toml +0 -5
  98. package/.mise/locks/azure-cli/2.93.0~a837e014/uv.lock +0 -2841
  99. package/.mise/locks/gemini/0.71.1~84aac8e6/aube-lock.yaml +0 -124
  100. package/.mise/locks/gemini/0.71.1~84aac8e6/package.json +0 -12
  101. package/agents/antigravity-proxy.ts +0 -3
  102. package/agents/audit.md +0 -88
  103. package/agents/bin/agy +0 -10
  104. package/agents/bin/antigravity +0 -10
  105. package/agents/bin/claude +0 -10
  106. package/agents/bin/codex +0 -10
  107. package/agents/bin/grok +0 -10
  108. package/agents/bin/opencode +0 -10
  109. package/agents/claude-proxy +0 -5
  110. package/agents/claude-proxy.ts +0 -3
  111. package/agents/codex-proxy.ts +0 -3
  112. package/agents/grok-proxy.ts +0 -3
  113. package/agents/managed-proxy.ts +0 -109
  114. package/agents/opencode-proxy.ts +0 -3
  115. package/agents/registry.json +0 -209
  116. package/agents/registry.schema.json +0 -149
  117. package/agents/setup.md +0 -158
  118. package/agents/t3.json +0 -40
  119. package/ansible/agents/agents.yml +0 -135
  120. package/ansible/agents/commands.yml +0 -32
  121. package/ansible/agents/receipts.yml +0 -19
  122. package/ansible/agents/templates/antigravity.settings.json.j2 +0 -3
  123. package/ansible/agents/templates/claude.settings.json.j2 +0 -3
  124. package/ansible/agents/templates/codex.config.toml.j2 +0 -11
  125. package/ansible/agents/templates/gemini.settings.json.j2 +0 -14
  126. package/ansible/agents/templates/grok.config.toml.j2 +0 -25
  127. package/ansible/agents/templates/opencode.json.j2 +0 -24
  128. package/ansible/agents/templates/receipt.json.j2 +0 -10
  129. package/ansible/t3/provider-keys.yml +0 -24
  130. package/docs/accounts.md +0 -256
  131. package/src/accounts/checks.ts +0 -226
  132. package/src/accounts/context.ts +0 -77
  133. package/src/accounts/propagate.ts +0 -62
  134. package/src/accounts/roster.ts +0 -112
  135. package/src/accounts/selection.ts +0 -67
  136. package/src/accounts/sessions.ts +0 -354
  137. package/src/agents/account-relay.ts +0 -279
  138. package/src/agents/accounts.ts +0 -94
  139. package/src/agents/admission.ts +0 -65
  140. package/src/agents/audit.ts +0 -77
  141. package/src/agents/cli.ts +0 -13
  142. package/src/agents/command.ts +0 -257
  143. package/src/agents/commands.ts +0 -127
  144. package/src/agents/converge.ts +0 -339
  145. package/src/agents/doctor.ts +0 -107
  146. package/src/agents/errors.ts +0 -2
  147. package/src/agents/files.ts +0 -43
  148. package/src/agents/fleet-verify.ts +0 -195
  149. package/src/agents/launch.ts +0 -361
  150. package/src/agents/native-verify.ts +0 -738
  151. package/src/agents/provider-errors.ts +0 -57
  152. package/src/agents/registry.ts +0 -61
  153. package/src/agents/render.ts +0 -121
  154. package/src/agents/round-trip.ts +0 -192
  155. package/src/agents/secrets.ts +0 -48
  156. package/src/agents/verify-cache.ts +0 -164
  157. package/src/agents/verify.ts +0 -129
  158. package/src/cli/fleet-accounts.ts +0 -294
  159. package/src/cli/fleet-sync-accounts.ts +0 -62
  160. package/src/cli/node-deployment.ts +0 -34
  161. package/src/cli/node-sync.ts +0 -121
  162. package/src/cli/node-t3.ts +0 -35
  163. package/src/cli/t3/command.ts +0 -91
  164. package/src/cli/t3/register.ts +0 -56
  165. package/src/configure.ts +0 -271
  166. package/src/github/copilot.ts +0 -54
  167. package/src/t3/accounts.ts +0 -90
  168. package/src/t3/antigravity.ts +0 -93
  169. package/src/t3/desired.ts +0 -174
  170. package/src/t3/diagnostics.ts +0 -42
  171. package/src/t3/models.ts +0 -354
  172. package/src/t3/names-check.ts +0 -53
  173. package/src/t3/names.ts +0 -155
  174. package/src/t3/plan.ts +0 -106
  175. package/src/t3/provider-keys.ts +0 -49
  176. package/src/t3/providers.ts +0 -102
  177. package/src/t3/reconcile.ts +0 -133
@@ -1,112 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import type { Account } from '../agents/accounts';
3
-
4
- /** Provider accounts exist only as the CLI proxy's credential files. Every
5
- * node and IDE gets a view derived from them; nothing on a node holds a
6
- * provider login. See docs/accounts.md.
7
- */
8
- export type AccountState =
9
- 'usable' | 'cooling-down' | 'needs-login' | 'refresh-failing' | 'removed';
10
-
11
- const STATES: AccountState[] = [
12
- 'usable',
13
- 'cooling-down',
14
- 'needs-login',
15
- 'refresh-failing',
16
- 'removed',
17
- ];
18
-
19
- /** One model the proxy holds back on one account, while the account serves
20
- * its other models. `reason` is the proxy's own word for why (`quota`,
21
- * `payment_required`, …), never what a provider answered.
22
- */
23
- export interface ModelCooldown {
24
- model: string;
25
- reason: string;
26
- /** When it clears (ISO 8601). */
27
- until: string;
28
- }
29
-
30
- /** One account as the manager reports it. `index` is opaque: the position of
31
- * the account among its provider's, the only way checks name it.
32
- */
33
- export interface RosterAccount {
34
- provider: string;
35
- index: number;
36
- label: string;
37
- /** The routing prefix every node offers it under; null if not routed. */
38
- prefix: string | null;
39
- state: AccountState;
40
- /** While cooling down: when it clears (ISO 8601), when known. */
41
- until: string | null;
42
- /** The models held back on this account alone; empty when none is. */
43
- cooldowns: ModelCooldown[];
44
- }
45
-
46
- /** What `homelab proxy accounts --json` prints on the manager. */
47
- export interface ProxyRoster {
48
- version: 1;
49
- rosterVersion: string;
50
- /** Whether the proxy's management API answered: without it, cooldowns and
51
- * refresh failures are not known.
52
- */
53
- managementApi: boolean;
54
- accounts: RosterAccount[];
55
- }
56
-
57
- export function parseRoster(text: string): ProxyRoster {
58
- const value = JSON.parse(text) as Partial<ProxyRoster>;
59
- if (
60
- value.version !== 1 ||
61
- typeof value.rosterVersion !== 'string' ||
62
- !Array.isArray(value.accounts) ||
63
- !value.accounts.every(
64
- (account) =>
65
- typeof account.provider === 'string' &&
66
- Number.isInteger(account.index) &&
67
- typeof account.label === 'string' &&
68
- STATES.includes(account.state)
69
- )
70
- )
71
- throw new Error('The proxy reported an unreadable account roster.');
72
- return {
73
- version: 1,
74
- rosterVersion: value.rosterVersion,
75
- managementApi: value.managementApi === true,
76
- accounts: value.accounts.map((account) => ({
77
- ...account,
78
- prefix: account.prefix ?? null,
79
- until: account.until ?? null,
80
- cooldowns: modelCooldowns(account.cooldowns),
81
- })),
82
- };
83
- }
84
-
85
- /** A proxy that lists none, or an older one, reports no model cooldown. */
86
- function modelCooldowns(value: unknown): ModelCooldown[] {
87
- if (!Array.isArray(value)) return [];
88
- return (value as Partial<ModelCooldown>[]).flatMap(
89
- ({ model, reason, until }) =>
90
- typeof model === 'string' &&
91
- typeof reason === 'string' &&
92
- typeof until === 'string'
93
- ? [{ model, reason, until }]
94
- : []
95
- );
96
- }
97
-
98
- /** The roster version: a digest of the routing prefixes of the accounts
99
- * every node offers. The manager computes it from the credential files
100
- * (cliproxy/scripts/accounts.py) and every node from the proxy's model list;
101
- * the two agree exactly when the node offers what the proxy holds.
102
- */
103
- export function rosterVersion(prefixes: Iterable<string>): string {
104
- return createHash('sha256')
105
- .update([...new Set(prefixes)].sort().join('\n'))
106
- .digest('hex')
107
- .slice(0, 16);
108
- }
109
-
110
- /** The version of the accounts a node reads from the proxy's model list. */
111
- export const liveVersion = (accounts: Account[]): string =>
112
- rosterVersion(accounts.map((account) => account.prefix));
@@ -1,67 +0,0 @@
1
- import type { AccountSelection } from '../definition';
2
-
3
- /** Which account an unpinned request goes to first, per the policy the fleet
4
- * declares for the provider. The order is deterministic: the accounts the
5
- * policy names, in its order, then the others in the order of their routing
6
- * prefix. Accounts cooling down are skipped while any other is left.
7
- */
8
- export class AccountSelector {
9
- private readonly cooling = new Map<string, number>();
10
- private readonly limitedAt = new Map<string, number>();
11
- private turn = 0;
12
- readonly order: string[];
13
-
14
- constructor(
15
- prefixes: string[],
16
- private readonly policy: AccountSelection,
17
- private readonly now: () => number = Date.now
18
- ) {
19
- const label = (prefix: string) => prefix.slice(prefix.indexOf('-') + 1);
20
- const named = policy.order ?? [];
21
- const rank = (prefix: string) => {
22
- const position = named.indexOf(label(prefix));
23
- return position < 0 ? named.length : position;
24
- };
25
- this.order = [...new Set(prefixes)].sort(
26
- (a, b) => rank(a) - rank(b) || a.localeCompare(b)
27
- );
28
- }
29
-
30
- /** The accounts to try for the next request, in order. */
31
- candidates(): string[] {
32
- const now = this.now();
33
- let order = [...this.order];
34
- if (this.policy.strategy === 'round-robin' && order.length) {
35
- const start = this.turn++ % order.length;
36
- order = [...order.slice(start), ...order.slice(0, start)];
37
- }
38
- if (this.policy.strategy === 'least-recently-limited')
39
- order.sort(
40
- (a, b) => (this.limitedAt.get(a) ?? 0) - (this.limitedAt.get(b) ?? 0)
41
- );
42
- return order.filter((prefix) => (this.cooling.get(prefix) ?? 0) <= now);
43
- }
44
-
45
- /** The provider limited this account; `seconds` from its Retry-After. */
46
- limited(prefix: string, seconds = 60): void {
47
- const now = this.now();
48
- this.limitedAt.set(prefix, now);
49
- this.cooling.set(prefix, now + seconds * 1000);
50
- }
51
-
52
- /** When this account's cooldown clears, if it is cooling down. */
53
- coolingUntil(prefix: string): number | null {
54
- const until = this.cooling.get(prefix) ?? 0;
55
- return until > this.now() ? until : null;
56
- }
57
- }
58
-
59
- /** A quota or authentication answer: the next account may still serve. */
60
- export const accountRefused = (status: number): boolean =>
61
- status === 429 || status === 401 || status === 403;
62
-
63
- /** Seconds a refused account cools down for: its Retry-After, or a minute. */
64
- export function retryAfter(headers: Headers): number {
65
- const value = Number(headers.get('retry-after'));
66
- return Number.isFinite(value) && value > 0 ? Math.min(value, 3600) : 60;
67
- }
@@ -1,354 +0,0 @@
1
- import { readFile } from 'node:fs/promises';
2
- import type { Account } from '../agents/accounts';
3
- import { registry, type Selection } from '../agents/registry';
4
- import { inferenceRequest } from '../agents/verify';
5
- import type { Check } from '../types';
6
-
7
- /** The tools T3 offers once per proxy account, by T3 driver. */
8
- const DRIVERS: Record<string, string> = {
9
- claudeAgent: 'claude',
10
- codex: 'codex',
11
- antigravity: 'antigravity',
12
- };
13
-
14
- /** One per-account instance a node offers: its tool and account. */
15
- export interface Instance {
16
- tool: string;
17
- account: string;
18
- }
19
-
20
- /** The per-account instances this node's T3 settings offer, read from the
21
- * account each one pins (WS_AGENT_ACCOUNT). An unreadable file offers none.
22
- */
23
- export async function exposedInstances(settings: string): Promise<Instance[]> {
24
- try {
25
- const parsed = JSON.parse(await readFile(settings, 'utf8')) as {
26
- providerInstances?: Record<
27
- string,
28
- {
29
- driver?: unknown;
30
- environment?: { name?: unknown; value?: unknown }[];
31
- }
32
- >;
33
- };
34
- return Object.values(parsed.providerInstances ?? {}).flatMap((instance) => {
35
- const tool = DRIVERS[String(instance.driver)];
36
- const account = (instance.environment ?? []).find(
37
- (variable) => variable.name === 'WS_AGENT_ACCOUNT'
38
- )?.value;
39
- return tool && typeof account === 'string' ? [{ tool, account }] : [];
40
- });
41
- } catch {
42
- return [];
43
- }
44
- }
45
-
46
- /** What a session says about its account. Only `ok` passes and only
47
- * `cooling-down` warns: the provider limited the account, which clears on
48
- * its own. `verification-required` and `rejected` are the account's and need
49
- * a person; `timed-out` is a session that never ended, which says nothing
50
- * about the sign-in.
51
- */
52
- export type SessionResult =
53
- | 'ok'
54
- | 'cooling-down'
55
- | 'verification-required'
56
- | 'rejected'
57
- | 'timed-out'
58
- | 'failed';
59
-
60
- /** What a session found, and when a cooldown clears: the instant the proxy
61
- * named (`2027-01-15T09:30:00Z`), absent when it named none.
62
- */
63
- export interface SessionOutcome {
64
- result: SessionResult;
65
- clears?: string;
66
- /** Set when no session was run: how many minutes ago this was found. */
67
- foundMinutesAgo?: number;
68
- }
69
-
70
- /** Runs one real, cheap session through the instance's launcher. */
71
- export type Session = (
72
- instance: Instance
73
- ) => Promise<SessionResult | SessionOutcome>;
74
-
75
- /** What is reported for a session that did not answer, for `who` (the tool
76
- * and the account's index): a summary that starts with a stable code, and
77
- * what to do about it.
78
- */
79
- const UNANSWERED: Record<
80
- Exclude<SessionResult, 'ok'>,
81
- {
82
- status: Check['status'];
83
- summary: (who: string, clears?: string) => string;
84
- action?: string;
85
- }
86
- > = {
87
- 'cooling-down': {
88
- status: 'warn',
89
- summary: (who, clears) =>
90
- `AGENT_ACCOUNT_COOLING_DOWN: ${who} is rate limited${clears ? ` until ${clears}` : ''}; checked again on the next status.`,
91
- },
92
- 'verification-required': {
93
- status: 'fail',
94
- summary: (who) =>
95
- `AGENT_ACCOUNT_VERIFICATION_REQUIRED: ${who} must be verified with its provider before it serves requests.`,
96
- action:
97
- 'Sign in to the provider as this account and complete the verification it asks for. Signing in again on the proxy does not replace it. Find the account by its index.',
98
- },
99
- rejected: {
100
- status: 'fail',
101
- summary: (who) =>
102
- `AGENT_ACCOUNT_AUTH_REJECTED: ${who} was refused its credentials.`,
103
- action:
104
- 'Read the state of this account on the proxy; one that needs a login is signed in again with --relogin.',
105
- },
106
- 'timed-out': {
107
- status: 'fail',
108
- summary: (who) =>
109
- `AGENT_ACCOUNT_SESSION_TIMED_OUT: ${who} did not end a session before the deadline; the proxy named no cooldown and no refusal for it.`,
110
- action:
111
- 'Read which models the proxy holds back on this account, then run status again; signing in again does not help a session that hangs.',
112
- },
113
- failed: {
114
- status: 'fail',
115
- summary: (who) =>
116
- `AGENT_ACCOUNT_SESSION_FAILED: ${who} did not run a session.`,
117
- action: 'Check this account on the proxy.',
118
- },
119
- };
120
-
121
- /** Said of a result no session was run for, so it never reads as fresh. */
122
- const remembered = (minutes: number | undefined): string =>
123
- minutes === undefined
124
- ? ''
125
- : ` (found ${minutes}m ago; a session that does not pass is run again after 10m or on any change)`;
126
-
127
- /** `agent:<tool>:account-<index>:session`, one per account instance: the
128
- * accounts the proxy holds and any instance the node still offers. An
129
- * instance whose account the proxy no longer holds fails without being run;
130
- * a rate-limited account is `cooling-down`, a warning and never a pass. The
131
- * index is the account's position among its provider's, never its name.
132
- */
133
- export async function accountSessionChecks(
134
- live: Account[],
135
- exposed: Instance[],
136
- session: Session
137
- ): Promise<Check[]> {
138
- const key = (instance: Instance) => `${instance.tool}\0${instance.account}`;
139
- const held = new Set(
140
- live.map((account) => key({ tool: account.tool, account: account.email }))
141
- );
142
- const index = (instance: Instance) =>
143
- live
144
- .filter((account) => account.tool === instance.tool)
145
- .findIndex((account) => account.email === instance.account) + 1;
146
- const removed = exposed.filter((instance) => !held.has(key(instance)));
147
- const checks = await Promise.all(
148
- live.map(async (account): Promise<Check> => {
149
- const instance = { tool: account.tool, account: account.email };
150
- const id = `agent:${account.tool}:account-${index(instance)}:session`;
151
- const started = Date.now();
152
- const answer = await session(instance);
153
- // Its own time: one session can be most of what a node's sync took.
154
- const durationMs = Date.now() - started;
155
- const { result, clears, foundMinutesAgo }: SessionOutcome =
156
- typeof answer === 'string' ? { result: answer } : answer;
157
- if (result === 'ok')
158
- return {
159
- id,
160
- status: 'pass',
161
- summary: `${account.tool} account ${index(instance)} runs a session through its T3 launcher.`,
162
- durationMs,
163
- };
164
- const { status, summary, action } = UNANSWERED[result];
165
- return {
166
- id,
167
- status,
168
- summary:
169
- summary(
170
- `${account.tool} account ${index(instance)}`,
171
- result === 'cooling-down' ? clears : undefined
172
- ) + remembered(foundMinutesAgo),
173
- ...(action ? { remedy: { action, command: 'homelab accounts' } } : {}),
174
- durationMs,
175
- // Nothing was run: what an earlier session found is repeated.
176
- ...(foundMinutesAgo === undefined
177
- ? {}
178
- : { reused: 'verify-cache' as const }),
179
- };
180
- })
181
- );
182
- const byTool = new Map<string, number>();
183
- for (const instance of removed) {
184
- const count = (byTool.get(instance.tool) ?? 0) + 1;
185
- byTool.set(instance.tool, count);
186
- checks.push({
187
- id: `agent:${instance.tool}:removed-${count}:session`,
188
- status: 'fail',
189
- summary: `AGENT_ACCOUNT_REMOVED: this node still offers a ${instance.tool} instance for an account the proxy no longer holds.`,
190
- remedy: {
191
- action: 'Propagate the accounts to every node.',
192
- command: 'homelab converge --only accounts',
193
- },
194
- });
195
- }
196
- return checks;
197
- }
198
-
199
- /** What a provider or the proxy said, by the condition it names. The text
200
- * itself is never reported: only which of these it matched. A provider that
201
- * wants an account verified says so in words ("Verify your account to
202
- * continue.") and, in the details of the same error, in the reason
203
- * `VALIDATION_REQUIRED`; a session prints only the words, the proxy repeats
204
- * both.
205
- */
206
- const SAID: [RegExp, SessionResult][] = [
207
- [/verify\s+your\s+account|\bVALIDATION_REQUIRED\b/i, 'verification-required'],
208
- [
209
- /cooling down until|model_cooldown|rate[ _-]?limit|\b429\b|quota|resource_exhausted/i,
210
- 'cooling-down',
211
- ],
212
- [
213
- /unauthori[sz]ed|invalid_grant|authentication_error|invalid api key/i,
214
- 'rejected',
215
- ],
216
- ];
217
-
218
- const said = (text: string): SessionResult | undefined =>
219
- SAID.find(([pattern]) => pattern.test(text))?.[1];
220
-
221
- /** Whether the lines a session printed so far already name a condition of
222
- * its account. Nothing it prints afterwards changes the result: OpenCode
223
- * only retries a refused request quietly until the deadline. So a session is
224
- * ended as soon as this holds. Only whole lines are read, so a line cut
225
- * between two reads keeps the instant a cooldown clears.
226
- */
227
- export const namesCondition = (output: string): boolean =>
228
- said(output.slice(0, output.lastIndexOf('\n') + 1)) !== undefined;
229
-
230
- /** What a session's output says about its account. A session ended at its
231
- * deadline (`timedOut`) that printed nothing telling is `timed-out`: the
232
- * caller asks the proxy what holds the account back (`proxyVerdict`).
233
- */
234
- export function sessionResult(
235
- ok: boolean,
236
- output: string,
237
- timedOut = false
238
- ): SessionResult {
239
- if (ok && /\bOK\b/.test(output)) return 'ok';
240
- return said(output) ?? (timedOut ? 'timed-out' : 'failed');
241
- }
242
-
243
- /** An instant as a report names it: `2027-01-15T09:30:00Z`. */
244
- const instant = (at: number): string =>
245
- new Date(at).toISOString().replace(/\.\d{3}Z$/, 'Z');
246
-
247
- /** The longest cooldown a report repeats. A provider's quota resets within
248
- * weeks; anything further off is not a time to tell an operator to wait for.
249
- */
250
- const LONGEST_COOLDOWN_MS = 31 * 24 * 3600 * 1000;
251
-
252
- /** `at` when it is an instant still ahead of `now` and within the longest
253
- * cooldown; nothing otherwise, so no report names a time nobody gave.
254
- */
255
- const ahead = (at: number, now: number): string | undefined =>
256
- Number.isFinite(at) && at > now && at - now <= LONGEST_COOLDOWN_MS
257
- ? instant(at)
258
- : undefined;
259
-
260
- /** When the cooldown a session printed clears. The fleet's own relay refuses
261
- * a request for an account it holds back with "cooling down until" and an
262
- * ISO instant; nothing else a session prints is read as a time.
263
- */
264
- export function printedClears(output: string, now: number): string | undefined {
265
- const at =
266
- /cooling down until (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?Z)/i.exec(
267
- output
268
- )?.[1];
269
- return at ? ahead(Date.parse(at), now) : undefined;
270
- }
271
-
272
- /** When the cooldown of a 429 clears: its `Retry-After` (seconds, or an HTTP
273
- * date), else the `reset_seconds` of the proxy's `model_cooldown` error.
274
- * Nothing when the answer names neither.
275
- */
276
- export function answeredClears(
277
- retryAfter: string | null,
278
- body: string,
279
- now: number
280
- ): string | undefined {
281
- const header = retryAfter?.trim() ?? '';
282
- if (/^\d+$/.test(header)) return ahead(now + Number(header) * 1000, now);
283
- if (header) return ahead(Date.parse(header), now);
284
- try {
285
- const seconds = (
286
- JSON.parse(body) as { error?: { reset_seconds?: unknown } } | null
287
- )?.error?.reset_seconds;
288
- return typeof seconds === 'number'
289
- ? ahead(now + seconds * 1000, now)
290
- : undefined;
291
- } catch {
292
- return undefined;
293
- }
294
- }
295
-
296
- /** What the proxy answers when it is asked for one account's model directly,
297
- * read after a session of that account timed out. OpenCode retries a refused
298
- * request quietly until the deadline, so only the proxy still knows why. A
299
- * model the proxy holds back for a limit answers 429 at once, without a
300
- * request to the provider; an account it holds back because the provider
301
- * refused it answers 503 with the provider's last words. One it does not
302
- * hold back is asked of the provider once, with the bounded request the
303
- * provider checks send. `features/accounts/proxy-box.feature` holds the
304
- * pinned proxy to these answers. Anything else leaves the
305
- * session `timed-out`: the account answered, or nothing said why it does
306
- * not. The answer is read for its condition and for when a cooldown clears,
307
- * and never kept.
308
- */
309
- export async function proxyVerdict(
310
- account: Account,
311
- key: string,
312
- send: typeof fetch = fetch,
313
- now: () => number = Date.now
314
- ): Promise<SessionOutcome> {
315
- const { path, body } = inferenceRequest({
316
- tool: account.tool as Selection['tool'],
317
- model: `${account.prefix}/${account.models[0]}`,
318
- });
319
- try {
320
- const response = await send(registry.proxy.endpoint + path, {
321
- method: 'POST',
322
- headers: {
323
- Authorization: `Bearer ${key}`,
324
- 'Content-Type': 'application/json',
325
- 'anthropic-version': '2023-06-01',
326
- },
327
- body: JSON.stringify(body),
328
- redirect: 'error',
329
- signal: AbortSignal.timeout(30_000),
330
- });
331
- if (response.status === 429) {
332
- const clears = answeredClears(
333
- response.headers.get('retry-after'),
334
- (await response.text().catch(() => '')).slice(0, 4096),
335
- now()
336
- );
337
- return { result: 'cooling-down', ...(clears ? { clears } : {}) };
338
- }
339
- if (response.ok) {
340
- await response.body?.cancel().catch(() => undefined);
341
- return { result: 'timed-out' };
342
- }
343
- const reason = said((await response.text()).slice(0, 4096));
344
- if (reason) return { result: reason };
345
- return {
346
- result:
347
- response.status === 401 || response.status === 403
348
- ? 'rejected'
349
- : 'timed-out',
350
- };
351
- } catch {
352
- return { result: 'timed-out' };
353
- }
354
- }