@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,57 +0,0 @@
1
- import { AgentConfigurationError } from './errors';
2
-
3
- export class ProviderVerificationError extends AgentConfigurationError {
4
- constructor(
5
- readonly code: string,
6
- message: string
7
- ) {
8
- super(message);
9
- }
10
- }
11
- /** The gateway has no such route, method or media type for this protocol:
12
- * the route as declared cannot work, whatever the account.
13
- */
14
- const INCOMPATIBLE = new Set([404, 405, 415, 501]);
15
-
16
- export function providerHttpFailure(status: number): ProviderVerificationError {
17
- const code = INCOMPATIBLE.has(status)
18
- ? 'PROVIDER_PROTOCOL_INCOMPATIBLE'
19
- : status === 401 || status === 403
20
- ? 'PROVIDER_AUTH_REJECTED'
21
- : status === 429
22
- ? 'PROVIDER_RATE_LIMITED'
23
- : status >= 500
24
- ? 'PROVIDER_UPSTREAM_UNAVAILABLE'
25
- : 'PROVIDER_PROTOCOL_REJECTED';
26
- return new ProviderVerificationError(
27
- code,
28
- 'The gateway rejected a bounded verification request; response content is withheld.'
29
- );
30
- }
31
- const SAFE_CODES = new Set([
32
- 'PROVIDER_AUTH_REJECTED',
33
- 'PROVIDER_RATE_LIMITED',
34
- 'PROVIDER_UPSTREAM_UNAVAILABLE',
35
- 'PROVIDER_PROTOCOL_REJECTED',
36
- 'PROVIDER_PROTOCOL_INCOMPATIBLE',
37
- 'PROVIDER_MODEL_UNAVAILABLE',
38
- 'PROVIDER_OUTPUT_UNVERIFIED',
39
- 'PROVIDER_TOOL_RESULT_UNVERIFIED',
40
- 'PROVIDER_EMPTY_RESPONSE',
41
- 'PROVIDER_RESPONSE_LIMIT',
42
- 'PROVIDER_TOOL_MISSING',
43
- 'PROVIDER_TOOL_INVALID',
44
- 'PROVIDER_TOOL_ARGUMENTS_INVALID',
45
- 'PROVIDER_STREAM_INCOMPLETE',
46
- ]);
47
- export function providerFailureCode(error: unknown): string {
48
- if (error instanceof ProviderVerificationError && SAFE_CODES.has(error.code))
49
- return error.code;
50
- if (error instanceof Error && SAFE_CODES.has(error.message))
51
- return error.message;
52
- if (error instanceof Error && error.name === 'TimeoutError')
53
- return 'PROVIDER_TIMEOUT';
54
- if (error instanceof TypeError) return 'PROVIDER_NETWORK_UNVERIFIED';
55
- if (error instanceof SyntaxError) return 'PROVIDER_RESPONSE_INVALID';
56
- return 'PROVIDER_ROUTE_UNVERIFIED';
57
- }
@@ -1,61 +0,0 @@
1
- import { AgentConfigurationError } from './errors';
2
- import source from '../../agents/registry.json';
3
- import { createHash } from 'node:crypto';
4
- import { fleet } from '../fleet-config';
5
-
6
- export type Tool = keyof typeof source.defaults;
7
- export type Profile = 'direct' | 'proxy';
8
- export type Selection = {
9
- node: string;
10
- tool: Tool;
11
- profile: Profile;
12
- model: string;
13
- };
14
- /** The tracked registry plus the proxy endpoint from this fleet's config. */
15
- export const registry = {
16
- ...source,
17
- proxy: {
18
- // Read on use: a command that reaches no proxy needs no configuration.
19
- get endpoint(): string {
20
- return fleet.services.proxy.endpoint;
21
- },
22
- ...source.proxy,
23
- },
24
- };
25
-
26
- export function select(node: string, tool: string, profile: string): Selection {
27
- if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(node))
28
- throw new AgentConfigurationError('Invalid node ID.');
29
- if (!(tool in source.defaults) || !['direct', 'proxy'].includes(profile))
30
- throw new AgentConfigurationError(
31
- 'Unsupported tool/profile; run bun src/agents/cli.ts agents inventory.'
32
- );
33
- const id = tool as Tool;
34
- const model = resolveModel(node, id, profile as Profile);
35
- if (!model || !/^[a-zA-Z0-9_./:+-]+$/.test(model))
36
- throw new AgentConfigurationError(
37
- 'No approved model. Add an exact model ID to agents/registry.json and review it.'
38
- );
39
- return { node, tool: id, profile: profile as Profile, model };
40
- }
41
-
42
- export function resolveModel(
43
- node: string,
44
- tool: Tool,
45
- profile: Profile,
46
- nodes = source.nodes as Record<
47
- string,
48
- Partial<Record<Tool, { direct?: string; proxy?: string }>>
49
- >
50
- ) {
51
- const override = nodes[node]?.[tool]?.[profile];
52
- const models = source.proxy.models as Partial<Record<Tool, string | null>>;
53
- return (
54
- override ??
55
- (profile === 'direct' ? source.defaults[tool].model : models[tool])
56
- );
57
- }
58
-
59
- export function digest(value: string): string {
60
- return createHash('sha256').update(value).digest('hex');
61
- }
@@ -1,121 +0,0 @@
1
- import { join, win32 } from 'node:path';
2
- import type { PlatformName } from '../platform/types';
3
- import { registry, type Selection } from './registry';
4
-
5
- /** Dedicated outputs; native login/state directories are never copied. */
6
- export function agentRoot(home: string, platform: PlatformName): string {
7
- return platform === 'windows'
8
- ? win32.join(home, 'AppData', 'Local', 'personal', 'agents')
9
- : join(home, '.config', 'personal', 'agents');
10
- }
11
-
12
- export function render(s: Selection): Record<string, string> {
13
- const model = JSON.stringify(s.model);
14
- if (s.tool === 'codex') {
15
- const provider =
16
- s.profile === 'proxy'
17
- ? '\nmodel_provider = "personal_proxy"\n[model_providers.personal_proxy]\nname = "Personal CLI Proxy"\nbase_url = ' +
18
- JSON.stringify(registry.proxy.endpoint + '/v1') +
19
- '\nenv_key = "CLIPROXY_API_KEY"\nwire_api = "responses"\nrequires_openai_auth = false\nsupports_websockets = false\n'
20
- : '\n';
21
- return { 'config.toml': `model = ${model}${provider}` };
22
- }
23
- if (s.tool === 'claude')
24
- return {
25
- 'settings.json': JSON.stringify({ model: s.model }, null, 2) + '\n',
26
- };
27
- if (s.tool === 'grok') return { 'config.toml': grokConfig(s) };
28
- if (s.tool === 'antigravity')
29
- return {
30
- // The fleet profile home for direct and one-shot runs (see launchArgs);
31
- // never the human's ~/.gemini. T3 keeps its own private GEMINI_HOME.
32
- '.gemini/antigravity-cli/settings.json':
33
- JSON.stringify({ modelProvider: 'gemini' }, null, 2) + '\n',
34
- };
35
- if (s.tool === 'gemini')
36
- return {
37
- '.gemini/settings.json':
38
- JSON.stringify(
39
- {
40
- model: { name: s.model },
41
- ...(s.profile === 'proxy'
42
- ? { security: { auth: { selectedType: 'gateway' } } }
43
- : {}),
44
- },
45
- null,
46
- 2
47
- ) + '\n',
48
- };
49
- const config =
50
- s.profile === 'proxy'
51
- ? {
52
- $schema: 'https://opencode.ai/config.json',
53
- model: `personal_proxy/${s.model}`,
54
- provider: {
55
- personal_proxy: {
56
- npm: '@ai-sdk/openai',
57
- options: {
58
- baseURL: registry.proxy.endpoint + '/v1',
59
- apiKey: '{env:CLIPROXY_API_KEY}',
60
- },
61
- models: Object.fromEntries(
62
- [
63
- ...Object.values(registry.proxy.routes).map(
64
- (route) => route.model
65
- ),
66
- s.model,
67
- ].map((id) => [id, { name: id }])
68
- ),
69
- },
70
- },
71
- }
72
- : { $schema: 'https://opencode.ai/config.json', model: s.model };
73
- return { 'opencode.json': JSON.stringify(config, null, 2) + '\n' };
74
- }
75
-
76
- /** Grok Build reads custom models only from GROK_HOME/config.toml. The key
77
- * comes from the environment (env_key), never the file; no grok login.
78
- */
79
- function grokConfig(s: Selection): string {
80
- // Grok writes its installer, a one-time skills migration and its UI defaults
81
- // into config.toml; declaring them up front keeps the rendered file
82
- // unchanged by the CLI (no profile drift).
83
- const lines = [
84
- '[cli]',
85
- 'auto_update = false',
86
- 'installer = "internal"',
87
- '',
88
- '[marketplace]',
89
- 'default_skills_installs_purged = true',
90
- '',
91
- ];
92
- const ui = [
93
- '[ui]',
94
- 'max_thoughts_width = 120',
95
- 'yolo = false',
96
- 'compact_mode = false',
97
- '',
98
- ];
99
- if (s.profile !== 'proxy')
100
- return [
101
- ...lines,
102
- '[models]',
103
- `default = ${JSON.stringify(s.model)}`,
104
- '',
105
- ...ui,
106
- ].join('\n');
107
- return [
108
- ...lines,
109
- '[models]',
110
- 'default = "personal-proxy"',
111
- '',
112
- '[model.personal-proxy]',
113
- `model = ${JSON.stringify(s.model)}`,
114
- `name = ${JSON.stringify(`${s.model} (Personal CLI Proxy)`)}`,
115
- `base_url = ${JSON.stringify(registry.proxy.endpoint + '/v1')}`,
116
- 'env_key = "CLIPROXY_API_KEY"',
117
- 'api_backend = "chat_completions"',
118
- '',
119
- ...ui,
120
- ].join('\n');
121
- }
@@ -1,192 +0,0 @@
1
- import { providerHttpFailure } from './provider-errors';
2
- import { randomUUID } from 'node:crypto';
3
- import { registry } from './registry';
4
- import { record } from '../config';
5
-
6
- /** Reasoning models spend output tokens thinking before any text or tool call,
7
- * so a tight cap ends the response without the tool call or text being
8
- * verified. Prompts are tiny; this is a ceiling, not an expected length.
9
- */
10
- export const VERIFY_OUTPUT_TOKENS = 1024;
11
-
12
- /** Supported OpenAI Responses harness route. The only tool is a local echo;
13
- * model output can never select a command, file, URL or other side effect.
14
- */
15
- export async function verifyRoundTrip(
16
- model: string,
17
- key: string,
18
- request = fetch
19
- ): Promise<void> {
20
- await verifyStream(model, key, request);
21
- const nonce = randomUUID();
22
- const tool = {
23
- type: 'function',
24
- name: 'fleet_echo',
25
- description: 'Return the provided verification nonce.',
26
- parameters: {
27
- type: 'object',
28
- properties: { nonce: { type: 'string', enum: [nonce] } },
29
- required: ['nonce'],
30
- additionalProperties: false,
31
- },
32
- strict: true,
33
- };
34
- const prompt = {
35
- role: 'user',
36
- content: `Call fleet_echo with nonce ${nonce}, then reply with its result.`,
37
- };
38
- const response = await call(
39
- model,
40
- key,
41
- {
42
- input: [prompt],
43
- tools: [tool],
44
- tool_choice: { type: 'function', name: 'fleet_echo' },
45
- max_output_tokens: VERIFY_OUTPUT_TOKENS,
46
- },
47
- request
48
- );
49
- const payload: unknown = JSON.parse(await boundedText(response));
50
- const invocation = validateInvocation(payload, nonce);
51
- const final = await call(
52
- model,
53
- key,
54
- {
55
- input: [
56
- prompt,
57
- invocation,
58
- {
59
- type: 'function_call_output',
60
- call_id: invocation.call_id,
61
- output: nonce,
62
- },
63
- ],
64
- tools: [tool],
65
- tool_choice: 'none',
66
- max_output_tokens: VERIFY_OUTPUT_TOKENS,
67
- },
68
- request
69
- );
70
- const completed: unknown = JSON.parse(await boundedText(final));
71
- if (
72
- !record(completed) ||
73
- completed['status'] !== 'completed' ||
74
- !Array.isArray(completed['output']) ||
75
- !JSON.stringify(completed['output']).includes(nonce)
76
- )
77
- throw new Error('PROVIDER_TOOL_RESULT_UNVERIFIED');
78
- }
79
- async function call(
80
- model: string,
81
- key: string,
82
- body: object,
83
- request: typeof fetch
84
- ): Promise<Response> {
85
- const response = await request(registry.proxy.endpoint + '/v1/responses', {
86
- method: 'POST',
87
- headers: {
88
- Authorization: `Bearer ${key}`,
89
- 'Content-Type': 'application/json',
90
- },
91
- body: JSON.stringify({ model, ...body }),
92
- redirect: 'error',
93
- signal: AbortSignal.timeout(45_000),
94
- });
95
- if (!response.ok) throw providerHttpFailure(response.status);
96
- return response;
97
- }
98
- async function boundedText(response: Response): Promise<string> {
99
- if (!response.body) throw new Error('PROVIDER_EMPTY_RESPONSE');
100
- const reader = response.body.getReader();
101
- const decoder = new TextDecoder();
102
- let size = 0;
103
- let text = '';
104
- try {
105
- while (true) {
106
- const chunk = await reader.read();
107
- if (chunk.done) break;
108
- size += chunk.value.byteLength;
109
- if (size > 512 * 1024) throw new Error('PROVIDER_RESPONSE_LIMIT');
110
- text += decoder.decode(chunk.value, { stream: true });
111
- }
112
- return text + decoder.decode();
113
- } finally {
114
- await reader.cancel();
115
- }
116
- }
117
- function validateInvocation(
118
- payload: unknown,
119
- nonce: string
120
- ): {
121
- type: 'function_call';
122
- call_id: string;
123
- name: 'fleet_echo';
124
- arguments: string;
125
- } {
126
- if (!record(payload)) throw new Error('PROVIDER_TOOL_MISSING');
127
- if (!Array.isArray(payload['output']))
128
- throw new Error('PROVIDER_TOOL_MISSING');
129
- const calls = payload['output'].filter(
130
- (item) => record(item) && item['type'] === 'function_call'
131
- );
132
- const call = calls[0];
133
- if (
134
- calls.length !== 1 ||
135
- !record(call) ||
136
- call['name'] !== 'fleet_echo' ||
137
- !stringFields(call, ['call_id', 'arguments'])
138
- )
139
- throw new Error('PROVIDER_TOOL_INVALID');
140
- const args: unknown = JSON.parse(String(call['arguments']));
141
- if (
142
- !record(args) ||
143
- Object.keys(args).length !== 1 ||
144
- args['nonce'] !== nonce
145
- )
146
- throw new Error('PROVIDER_TOOL_ARGUMENTS_INVALID');
147
- return {
148
- type: 'function_call',
149
- name: 'fleet_echo',
150
- call_id: String(call['call_id']),
151
- arguments: String(call['arguments']),
152
- };
153
- }
154
-
155
- async function verifyStream(
156
- model: string,
157
- key: string,
158
- request: typeof fetch
159
- ): Promise<void> {
160
- const response = await call(
161
- model,
162
- key,
163
- {
164
- input: 'Reply OK.',
165
- stream: true,
166
- max_output_tokens: VERIFY_OUTPUT_TOKENS,
167
- },
168
- request
169
- );
170
- const body = await boundedText(response);
171
- const events: unknown[] = body
172
- .split(/\r?\n/)
173
- .filter((line) => line.startsWith('data:'))
174
- .map((line) => line.slice(5).trim())
175
- .filter((line) => line !== '[DONE]')
176
- .map((line) => JSON.parse(line));
177
- const types = events.filter(record).map((event) => event['type']);
178
- if (
179
- !types.includes('response.completed') ||
180
- !types.includes('response.output_text.delta') ||
181
- types.includes('response.failed') ||
182
- types.includes('error')
183
- )
184
- throw new Error('PROVIDER_STREAM_INCOMPLETE');
185
- }
186
-
187
- function stringFields(
188
- value: Record<string, unknown>,
189
- fields: string[]
190
- ): boolean {
191
- return fields.every((field) => typeof value[field] === 'string');
192
- }
@@ -1,48 +0,0 @@
1
- import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
- import { homedir } from 'node:os';
3
- import { dirname, join } from 'node:path';
4
- import { AgentConfigurationError } from './errors';
5
- import { secret } from '../fleet-config';
6
-
7
- /** Where a node keeps the last proxy client key its secrets provider gave it,
8
- * readable by its user alone. Disposable: the next successful read rewrites it.
9
- */
10
- export const lastProxyKeyPath = (home = homedir()): string =>
11
- join(home, '.cache/homelab/proxy-client-key');
12
-
13
- /** The key every node presents to the CLI proxy, from this fleet's secrets
14
- * provider with this node's own access. The provider stays the source: a key
15
- * rotated there is used at the next launch. When the provider cannot answer
16
- * (Vault unreachable, or this node's session expired) the last key it gave is
17
- * used instead, so an outage of the secrets provider never takes every agent
18
- * down with it; the node's own Vault checks still fail until it is repaired.
19
- */
20
- export async function proxyKey(
21
- options: {
22
- read?: () => Promise<string | null>;
23
- path?: string;
24
- } = {}
25
- ): Promise<string> {
26
- const read = options.read ?? (() => secret('proxy-client-key'));
27
- const path = options.path ?? lastProxyKeyPath();
28
- const value = await read().catch(() => null);
29
- if (value) {
30
- await remember(path, value).catch(() => undefined);
31
- return value;
32
- }
33
- const last = (await readFile(path, 'utf8').catch(() => '')).trim();
34
- if (last) return last;
35
- throw new AgentConfigurationError(
36
- "Required secret unavailable: proxy-client-key. Restore this node's access to the fleet's secrets provider (see `secrets` in the fleet configuration)."
37
- );
38
- }
39
-
40
- async function remember(path: string, value: string): Promise<void> {
41
- if ((await readFile(path, 'utf8').catch(() => '')).trim() === value) return;
42
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
43
- await chmod(dirname(path), 0o700);
44
- // Written aside and renamed, so a launch never reads half a key.
45
- const staged = `${path}.${process.pid}`;
46
- await writeFile(staged, `${value}\n`, { mode: 0o600 });
47
- await rename(staged, path);
48
- }
@@ -1,164 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
3
- import { dirname, join, relative } from 'node:path';
4
- import { receiptDirectory } from '../platform/ansible-receipt';
5
- import type { Check } from '../types';
6
-
7
- /** A verified inference or agent session is re-proven at least this often. */
8
- export const VERIFY_MAX_AGE_MS = 6 * 60 * 60 * 1000;
9
-
10
- export interface VerifyCache {
11
- directory?: string;
12
- now?: number;
13
- /** Ignore cached results (a live probe failed, or a full check was asked). */
14
- bypass?: boolean;
15
- }
16
-
17
- /** Digest of everything a result depends on (never secrets). */
18
- export function cacheKey(...parts: (string | object)[]): string {
19
- const hash = createHash('sha256');
20
- for (const part of parts)
21
- hash
22
- .update(typeof part === 'string' ? part : JSON.stringify(part))
23
- .update('\0');
24
- return hash.digest('hex');
25
- }
26
-
27
- /** Digest of source files, so a code change re-verifies. */
28
- export async function sourceKey(
29
- root: string,
30
- paths: string[]
31
- ): Promise<string> {
32
- const hash = createHash('sha256');
33
- for (const path of [...paths].sort()) {
34
- const contents = await readFile(path).catch(() => null);
35
- hash.update(relative(root, path)).update('\0');
36
- hash
37
- .update(
38
- contents
39
- ? createHash('sha256').update(contents).digest('hex')
40
- : 'missing'
41
- )
42
- .update('\0');
43
- }
44
- return hash.digest('hex');
45
- }
46
-
47
- const entryPath = (name: string, options: VerifyCache): string =>
48
- join(
49
- options.directory ?? join(receiptDirectory(), 'verify'),
50
- `${name.replace(/[^a-z0-9-]/gi, '_')}.json`
51
- );
52
-
53
- /** Warm verification: a passing check with an unchanged key is reused until it
54
- * ages out. Only clean passes are reused; a failure, a skip or a quota-limited
55
- * pass (`reuse` false) clears the entry so the next sync checks it again.
56
- * With `keepFailure` a check that did not pass is kept instead of cleared:
57
- * never reused here, and read back with `lastFailure`.
58
- */
59
- export async function cachedCheck(
60
- name: string,
61
- key: string,
62
- compute: () => Promise<Check>,
63
- options: VerifyCache & {
64
- reuse?: (check: Check) => boolean;
65
- keepFailure?: boolean;
66
- } = {}
67
- ): Promise<Check> {
68
- const path = entryPath(name, options);
69
- const directory = dirname(path);
70
- const now = options.now ?? Date.now();
71
- const started = Date.now();
72
- if (!options.bypass) {
73
- const hit = await fresh(path, key, now);
74
- if (hit)
75
- return {
76
- ...hit,
77
- durationMs: Date.now() - started,
78
- reused: 'verify-cache',
79
- };
80
- }
81
- const computed = await compute();
82
- const check = { ...computed, durationMs: Date.now() - started };
83
- const reusable =
84
- check.status === 'pass' && (options.reuse ? options.reuse(check) : true);
85
- try {
86
- if (!reusable && !options.keepFailure) await rm(path, { force: true });
87
- else {
88
- await mkdir(directory, { recursive: true, mode: 0o700 });
89
- await writeFile(
90
- path,
91
- JSON.stringify({ version: 1, key, checkedAt: now, check: computed }) +
92
- '\n',
93
- { mode: 0o600 }
94
- );
95
- }
96
- } catch {
97
- /* A missing cache entry only means the next sync verifies again. */
98
- }
99
- return check;
100
- }
101
-
102
- async function fresh(
103
- path: string,
104
- key: string,
105
- now: number
106
- ): Promise<Check | null> {
107
- try {
108
- const entry = JSON.parse(await readFile(path, 'utf8')) as {
109
- version?: unknown;
110
- key?: unknown;
111
- checkedAt?: unknown;
112
- check?: Check;
113
- };
114
- if (
115
- entry.version !== 1 ||
116
- entry.key !== key ||
117
- typeof entry.checkedAt !== 'number' ||
118
- now - entry.checkedAt < 0 ||
119
- now - entry.checkedAt >= VERIFY_MAX_AGE_MS ||
120
- entry.check?.status !== 'pass'
121
- )
122
- return null;
123
- const minutes = Math.round((now - entry.checkedAt) / 60_000);
124
- return {
125
- ...entry.check,
126
- summary: `${entry.check.summary} (verified ${minutes}m ago; re-proven every 6h or on any change)`,
127
- };
128
- } catch {
129
- return null;
130
- }
131
- }
132
-
133
- /** What a check kept with `keepFailure` found when it last did not pass
134
- * under this key, and how long ago; nothing once it is as old as a pass may
135
- * get, when the cache is bypassed, or when the check passed since.
136
- */
137
- export async function lastFailure(
138
- name: string,
139
- key: string,
140
- options: VerifyCache = {}
141
- ): Promise<{ check: Check; ageMs: number } | null> {
142
- if (options.bypass) return null;
143
- try {
144
- const entry = JSON.parse(
145
- await readFile(entryPath(name, options), 'utf8')
146
- ) as {
147
- version?: unknown;
148
- key?: unknown;
149
- checkedAt?: unknown;
150
- check?: Check;
151
- };
152
- const ageMs = (options.now ?? Date.now()) - Number(entry.checkedAt);
153
- return entry.version === 1 &&
154
- entry.key === key &&
155
- entry.check &&
156
- entry.check.status !== 'pass' &&
157
- ageMs >= 0 &&
158
- ageMs < VERIFY_MAX_AGE_MS
159
- ? { check: entry.check, ageMs }
160
- : null;
161
- } catch {
162
- return null;
163
- }
164
- }