@mycadet/cli 0.13.0-dev.202611012320.cea2f8a → 0.13.0-dev.202611022129.ce2988d

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 (116) hide show
  1. package/node_modules/@mycadet/assistant-api/node_modules/@mycadet/service-contracts/package.json +1 -1
  2. package/node_modules/@mycadet/avatar-manifest/package.json +1 -1
  3. package/node_modules/@mycadet/environments/package.json +1 -1
  4. package/node_modules/@mycadet/ipc-server-utils/package.json +1 -1
  5. package/node_modules/@mycadet/local-mode/node_modules/@mycadet/avatar-manifest/package.json +1 -1
  6. package/node_modules/@mycadet/local-mode/node_modules/@mycadet/environments/package.json +1 -1
  7. package/node_modules/@mycadet/local-mode/node_modules/@mycadet/ipc-server-utils/package.json +1 -1
  8. package/node_modules/@mycadet/local-mode/node_modules/@mycadet/service-contracts/package.json +1 -1
  9. package/node_modules/@mycadet/local-mode/node_modules/@mycadet/shared/package.json +1 -1
  10. package/node_modules/@mycadet/local-mode/package.json +1 -1
  11. package/node_modules/@mycadet/local-mode/src/__tests__/guardian-token-refresh.test.ts +0 -1
  12. package/node_modules/@mycadet/local-mode/src/__tests__/guardian-token.test.ts +0 -1
  13. package/{src/__tests__/config-utils.test.ts → node_modules/@mycadet/local-mode/src/__tests__/hatch-config.test.ts} +1 -1
  14. package/{src/__tests__/local-hatch-lock.test.ts → node_modules/@mycadet/local-mode/src/__tests__/hatch-lock.test.ts} +1 -1
  15. package/{src/__tests__/random-name.test.ts → node_modules/@mycadet/local-mode/src/__tests__/naming.test.ts} +1 -4
  16. package/node_modules/@mycadet/local-mode/src/__tests__/operations-hatch.test.ts +60 -0
  17. package/node_modules/@mycadet/local-mode/src/__tests__/operations-resolution.test.ts +340 -0
  18. package/node_modules/@mycadet/local-mode/src/__tests__/operations-retire.test.ts +7 -7
  19. package/node_modules/@mycadet/local-mode/src/__tests__/operations-routes.test.ts +634 -0
  20. package/node_modules/@mycadet/local-mode/src/__tests__/operations-sleep.test.ts +12 -4
  21. package/node_modules/@mycadet/local-mode/src/__tests__/operations-wake.test.ts +9 -3
  22. package/node_modules/@mycadet/local-mode/src/__tests__/pair.test.ts +0 -2
  23. package/node_modules/@mycadet/local-mode/src/__tests__/remotes-docker-pair.test.ts +3 -3
  24. package/node_modules/@mycadet/local-mode/src/__tests__/remotes-local-pair.test.ts +2 -2
  25. package/node_modules/@mycadet/local-mode/src/__tests__/remotes-local-retire.test.ts +0 -11
  26. package/node_modules/@mycadet/local-mode/src/__tests__/status.test.ts +1 -129
  27. package/node_modules/@mycadet/local-mode/src/cloud-registration.ts +614 -0
  28. package/node_modules/@mycadet/local-mode/src/daemon-readiness.ts +87 -11
  29. package/node_modules/@mycadet/local-mode/src/gateway-proxy.ts +0 -1
  30. package/node_modules/@mycadet/local-mode/src/guardian-token.ts +276 -6
  31. package/node_modules/@mycadet/local-mode/src/hatch.ts +0 -1
  32. package/node_modules/@mycadet/local-mode/src/index.ts +72 -18
  33. package/node_modules/@mycadet/local-mode/src/lockfile-contract.ts +5 -5
  34. package/node_modules/@mycadet/local-mode/src/lockfile.ts +1 -2
  35. package/node_modules/@mycadet/local-mode/src/operations/hatch.ts +50 -0
  36. package/node_modules/@mycadet/local-mode/src/operations/list.ts +33 -0
  37. package/node_modules/@mycadet/local-mode/src/operations/machine.ts +1 -1
  38. package/node_modules/@mycadet/local-mode/src/operations/resolve.ts +56 -0
  39. package/node_modules/@mycadet/local-mode/src/operations/routes.ts +487 -32
  40. package/node_modules/@mycadet/local-mode/src/pair.ts +0 -5
  41. package/node_modules/@mycadet/local-mode/src/process.ts +1 -1
  42. package/node_modules/@mycadet/local-mode/src/provider-credentials.ts +495 -0
  43. package/node_modules/@mycadet/local-mode/src/provider-env-vars.ts +22 -0
  44. package/node_modules/@mycadet/local-mode/src/remotes/apple-container/retire.ts +0 -5
  45. package/node_modules/@mycadet/local-mode/src/remotes/docker/common.ts +1 -3
  46. package/node_modules/@mycadet/local-mode/src/remotes/docker/retire.ts +2 -10
  47. package/node_modules/@mycadet/local-mode/src/remotes/docker/wake.ts +0 -1
  48. package/node_modules/@mycadet/local-mode/src/remotes/local/common.ts +0 -4
  49. package/{src/lib/config-utils.ts → node_modules/@mycadet/local-mode/src/remotes/local/hatch-config.ts} +3 -3
  50. package/{src/lib/local-hatch-lock.ts → node_modules/@mycadet/local-mode/src/remotes/local/hatch-lock.ts} +6 -6
  51. package/node_modules/@mycadet/local-mode/src/remotes/local/hatch.ts +124 -0
  52. package/node_modules/@mycadet/local-mode/src/remotes/local/retire.ts +1 -6
  53. package/node_modules/@mycadet/local-mode/src/status.ts +1 -366
  54. package/node_modules/@mycadet/local-mode/src/upgrade.ts +0 -1
  55. package/node_modules/@mycadet/service-contracts/package.json +1 -1
  56. package/node_modules/@mycadet/shared/package.json +1 -1
  57. package/package.json +1 -2
  58. package/src/__tests__/app-command.test.ts +30 -45
  59. package/src/__tests__/app-server-state.test.ts +195 -0
  60. package/src/__tests__/app-tunnel-status.test.ts +1 -1
  61. package/src/__tests__/assistant-client-refresh.test.ts +0 -2
  62. package/src/__tests__/backup.test.ts +1 -1
  63. package/src/__tests__/bun.test.ts +1649 -0
  64. package/src/__tests__/client-tui-refresh.test.ts +0 -1
  65. package/src/__tests__/debug.test.ts +1 -1
  66. package/src/__tests__/devices.test.ts +1 -1
  67. package/src/__tests__/guardian-token.test.ts +5 -7
  68. package/src/__tests__/hatch-provider-secrets.test.ts +4 -2
  69. package/src/__tests__/helpers/guardian-token.ts +1 -2
  70. package/src/__tests__/host-teleport.test.ts +46 -26
  71. package/src/__tests__/llm-provider-env-var-parity.test.ts +1 -1
  72. package/src/__tests__/multi-local.test.ts +1 -1
  73. package/src/__tests__/provider-secrets.test.ts +2 -3
  74. package/src/__tests__/ps-cloud-status.test.ts +7 -7
  75. package/src/__tests__/root-restore-command.test.ts +1 -1
  76. package/src/__tests__/setup.test.ts +0 -3
  77. package/src/__tests__/tui-midsession-refresh.test.ts +0 -1
  78. package/src/__tests__/tunnel.test.ts +15 -296
  79. package/src/__tests__/upgrade-local.test.ts +4 -5
  80. package/src/__tests__/wake.test.ts +6 -544
  81. package/src/__tests__/web-dist.test.ts +39 -5
  82. package/src/commands/app.ts +25 -28
  83. package/src/commands/debug.ts +2 -1
  84. package/src/commands/devices.ts +2 -1
  85. package/src/commands/hatch.ts +70 -2
  86. package/src/commands/login.ts +3 -6
  87. package/src/commands/ps.ts +14 -12
  88. package/src/commands/setup.ts +3 -3
  89. package/src/commands/tunnel.ts +6 -9
  90. package/src/commands/upgrade.ts +1 -4
  91. package/src/commands/wake.ts +0 -11
  92. package/src/lib/api-key-check.ts +1 -1
  93. package/src/lib/assistant-config.ts +1 -43
  94. package/src/lib/cloud-client.ts +0 -404
  95. package/src/lib/cloud-login.ts +7 -110
  96. package/src/lib/guardian-token.ts +4 -297
  97. package/src/lib/host-teleport.ts +82 -51
  98. package/src/lib/provider-secrets.ts +7 -494
  99. package/src/lib/remotes/docker.ts +8 -8
  100. package/src/lib/remotes/local.ts +36 -150
  101. package/src/lib/root-backup.ts +1 -5
  102. package/src/lib/servers/bun.ts +1471 -0
  103. package/src/lib/sync-cloud-assistants.ts +2 -1
  104. package/src/lib/tunnel.ts +4 -239
  105. package/src/lib/tunnels/cloudflare.ts +6 -6
  106. package/src/lib/tunnels/ngrok.ts +3 -5
  107. package/src/lib/tunnels/tailscale.ts +1 -1
  108. package/src/lib/upgrade-lifecycle.ts +0 -35
  109. package/src/lib/web-dist.ts +47 -20
  110. package/src/shared/provider-env-vars.ts +3 -20
  111. package/node_modules/@mycadet/local-mode/src/ingress.ts +0 -229
  112. package/src/__tests__/assistant-api-key-resolution.test.ts +0 -102
  113. package/src/__tests__/nginx.test.ts +0 -2447
  114. package/src/lib/assistant-api-key-resolution.ts +0 -89
  115. package/src/lib/servers/nginx.ts +0 -1241
  116. /package/{src/lib/random-name.ts → node_modules/@mycadet/local-mode/src/naming.ts} +0 -0
@@ -0,0 +1,614 @@
1
+ /**
2
+ * The self-hosted assistant's cloud registration web: register (or
3
+ * re-confirm) the assistant with the platform, resolve which API key to
4
+ * hand it, and inject the credentials into its running secret store — the
5
+ * post-login half of the desktop app's LocalAssistantBootstrapService
6
+ * flow. `registerLocalAssistantWithCloud` is the one door; `cadet hatch`
7
+ * and `cadet login` both end here so the two injection paths cannot drift.
8
+ */
9
+ import {
10
+ type CloudCredentialVerificationStatus,
11
+ CloudVerifyCredentialResponseSchema,
12
+ } from "@mycadet/service-contracts/cloud-credential";
13
+ import { z } from "zod";
14
+
15
+ import {
16
+ fetchOrganizationId,
17
+ readCloudToken,
18
+ resolveCloudUrl,
19
+ } from "./cloud-auth";
20
+ import { computeDeviceId, loadGuardianToken } from "./guardian-token";
21
+ import { saveLockfileAssistant } from "./lockfile";
22
+ import { getGatewayUrl, type LockfileAssistant } from "./lockfile-contract";
23
+ import { loopbackSafeFetch } from "./loopback-fetch";
24
+ import { fetchCurrentVersion } from "./daemon-readiness";
25
+ import {
26
+ findAssistantByName,
27
+ getActiveAssistant,
28
+ loadAllAssistants,
29
+ } from "./operations/lookup";
30
+
31
+ /** The guardian bearer recorded beside the lockfile, for gateway calls. */
32
+ function guardianBearer(assistantId: string): string | undefined {
33
+ return loadGuardianToken(assistantId)?.accessToken;
34
+ }
35
+
36
+ /** The CLI's active-assistant resolution: explicit name, the active
37
+ * pointer, then the single-entry fallback. */
38
+ function resolveAssistant(): LockfileAssistant | null {
39
+ const active = getActiveAssistant();
40
+ if (active) {
41
+ const entry = findAssistantByName(active);
42
+ if (entry) return entry;
43
+ }
44
+ const all = loadAllAssistants();
45
+ if (all.length === 1) return all[0];
46
+ return null;
47
+ }
48
+
49
+ export interface EnsureRegistrationResponse {
50
+ assistant: { id: string; name: string };
51
+ registration: {
52
+ client_installation_id: string;
53
+ runtime_assistant_id: string;
54
+ client_platform: string;
55
+ };
56
+ assistant_api_key: string | null;
57
+ webhook_secret: string;
58
+ }
59
+
60
+ /**
61
+ * Register (or re-confirm) a self-hosted local assistant with the cloud.
62
+ *
63
+ * Calls `POST /v1/assistants/self-hosted-local/ensure-registration/`.
64
+ * The endpoint is idempotent: the first call provisions an API key;
65
+ * subsequent calls return `assistant_api_key: null`.
66
+ */
67
+ export async function ensureSelfHostedLocalRegistration(
68
+ token: string,
69
+ organizationId: string,
70
+ clientInstallationId: string,
71
+ runtimeAssistantId: string,
72
+ clientPlatform: string,
73
+ assistantVersion?: string,
74
+ cloudUrl?: string,
75
+ publicBaseUrl?: string,
76
+ ): Promise<EnsureRegistrationResponse> {
77
+ const resolvedUrl = cloudUrl || resolveCloudUrl();
78
+ const body: Record<string, string> = {
79
+ client_installation_id: clientInstallationId,
80
+ runtime_assistant_id: runtimeAssistantId,
81
+ client_platform: clientPlatform,
82
+ };
83
+ if (assistantVersion) {
84
+ body.assistant_version = assistantVersion;
85
+ }
86
+ if (publicBaseUrl) {
87
+ body.public_ingress_url = publicBaseUrl;
88
+ }
89
+
90
+ const response = await loopbackSafeFetch(
91
+ `${resolvedUrl}/v1/assistants/self-hosted-local/ensure-registration/`,
92
+ {
93
+ method: "POST",
94
+ headers: {
95
+ "Content-Type": "application/json",
96
+ Accept: "application/json",
97
+ "X-Session-Token": token,
98
+ "Cadet-Organization-Id": organizationId,
99
+ },
100
+ body: JSON.stringify(body),
101
+ },
102
+ );
103
+
104
+ if (response.status === 401 || response.status === 403) {
105
+ throw new Error("Authentication required for assistant registration.");
106
+ }
107
+
108
+ if (!response.ok) {
109
+ const detail = await response.text().catch(() => "");
110
+ throw new Error(
111
+ `Registration failed (${response.status}): ${detail || response.statusText}`,
112
+ );
113
+ }
114
+
115
+ return (await response.json()) as EnsureRegistrationResponse;
116
+ }
117
+
118
+ export interface ReprovisionApiKeyResponse {
119
+ provisioning: {
120
+ assistant_api_key: string;
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Reprovision (rotate) the API key for a self-hosted local assistant.
126
+ *
127
+ * Calls `POST /v1/assistants/self-hosted-local/reprovision-api-key/`.
128
+ * Returns a fresh API key. The cloud keeps the previous key valid for a
129
+ * grace period rather than revoking it on the spot, so a rotation whose
130
+ * replacement never gets stored leaves the assistant on a key that still
131
+ * works until that window closes.
132
+ */
133
+ export async function reprovisionAssistantApiKey(
134
+ token: string,
135
+ organizationId: string,
136
+ clientInstallationId: string,
137
+ runtimeAssistantId: string,
138
+ clientPlatform: string,
139
+ cloudUrl?: string,
140
+ ): Promise<ReprovisionApiKeyResponse> {
141
+ const resolvedUrl = cloudUrl || resolveCloudUrl();
142
+ const body: Record<string, string> = {
143
+ client_installation_id: clientInstallationId,
144
+ runtime_assistant_id: runtimeAssistantId,
145
+ client_platform: clientPlatform,
146
+ };
147
+
148
+ const response = await loopbackSafeFetch(
149
+ `${resolvedUrl}/v1/assistants/self-hosted-local/reprovision-api-key/`,
150
+ {
151
+ method: "POST",
152
+ headers: {
153
+ "Content-Type": "application/json",
154
+ Accept: "application/json",
155
+ "X-Session-Token": token,
156
+ "Cadet-Organization-Id": organizationId,
157
+ },
158
+ body: JSON.stringify(body),
159
+ },
160
+ );
161
+
162
+ if (response.status === 401 || response.status === 403) {
163
+ throw new Error("Authentication required for API key reprovisioning.");
164
+ }
165
+
166
+ if (!response.ok) {
167
+ const detail = await response.text().catch(() => "");
168
+ throw new Error(
169
+ `API key reprovisioning failed (${response.status}): ${detail || response.statusText}`,
170
+ );
171
+ }
172
+
173
+ return ReprovisionApiKeyResponseSchema.parse(await response.json());
174
+ }
175
+
176
+ const ReprovisionApiKeyResponseSchema = z.object({
177
+ provisioning: z.object({ assistant_api_key: z.string() }),
178
+ });
179
+
180
+ const SecretReadResponseSchema = z
181
+ .object({
182
+ found: z.boolean(),
183
+ value: z.string().optional(),
184
+ unreachable: z.boolean().optional(),
185
+ })
186
+ .catch({ found: false });
187
+
188
+ export interface GatewayCredentialResult {
189
+ /** The credential value, if found. */
190
+ value: string | null;
191
+ /** True when the gateway/daemon was unreachable (network error, timeout, etc.). */
192
+ unreachable: boolean;
193
+ }
194
+
195
+ /**
196
+ * Ask a running assistant to check its stored cloud credential against the
197
+ * platform, via the gateway-proxied `POST /v1/cloud/verify-credential`.
198
+ *
199
+ * Returns `"rejected"` only when the cloud settled that answer. Every other
200
+ * case, including a daemon too old to serve the route and any failure to reach
201
+ * one, returns null: the answer decides whether a key is rotated, so an absent
202
+ * answer must never read as a rejection.
203
+ *
204
+ * Never throws.
205
+ */
206
+ export async function verifyGatewayCloudCredential(
207
+ gatewayUrl: string,
208
+ bearerToken?: string,
209
+ ): Promise<CloudCredentialVerificationStatus | null> {
210
+ try {
211
+ const headers: Record<string, string> = { Accept: "application/json" };
212
+ if (bearerToken) {
213
+ headers["Authorization"] = `Bearer ${bearerToken}`;
214
+ }
215
+
216
+ const response = await loopbackSafeFetch(
217
+ `${gatewayUrl}/v1/cloud/verify-credential`,
218
+ {
219
+ method: "POST",
220
+ headers,
221
+ signal: AbortSignal.timeout(10_000),
222
+ },
223
+ );
224
+ if (!response.ok) {
225
+ return null;
226
+ }
227
+
228
+ const parsed = CloudVerifyCredentialResponseSchema.safeParse(
229
+ await response.json(),
230
+ );
231
+ if (parsed.success) {
232
+ return parsed.data.status;
233
+ }
234
+ return null;
235
+ } catch {
236
+ return null;
237
+ }
238
+ }
239
+
240
+ /**
241
+ * Read an existing credential from the assistant's secret store via the
242
+ * gateway-proxied `POST /v1/secrets/read` endpoint (with `reveal: true`).
243
+ *
244
+ * Returns a result distinguishing a key-not-found read (value null,
245
+ * unreachable false) from a gateway-unreachable read (value null,
246
+ * unreachable true). Callers should only reprovision when the gateway
247
+ * is reachable: the cloud keeps the outgoing key valid for a grace
248
+ * period, so reprovisioning while the gateway is down does not break the
249
+ * assistant immediately, but it starts a clock on a key the caller cannot
250
+ * yet replace.
251
+ *
252
+ * Never throws.
253
+ */
254
+ export async function readGatewayCredential(
255
+ gatewayUrl: string,
256
+ name: string,
257
+ bearerToken?: string,
258
+ ): Promise<GatewayCredentialResult> {
259
+ try {
260
+ const headers: Record<string, string> = {
261
+ "Content-Type": "application/json",
262
+ Accept: "application/json",
263
+ };
264
+ if (bearerToken) {
265
+ headers["Authorization"] = `Bearer ${bearerToken}`;
266
+ }
267
+
268
+ const response = await loopbackSafeFetch(`${gatewayUrl}/v1/secrets/read`, {
269
+ method: "POST",
270
+ headers,
271
+ body: JSON.stringify({ type: "credential", name, reveal: true }),
272
+ signal: AbortSignal.timeout(10_000),
273
+ });
274
+
275
+ if (!response.ok) {
276
+ // 5xx means the gateway/daemon backend is down — treat as unreachable
277
+ // so callers don't rotate away from a working key they cannot replace.
278
+ return { value: null, unreachable: response.status >= 500 };
279
+ }
280
+
281
+ const json = SecretReadResponseSchema.parse(await response.json());
282
+ // The daemon's /v1/secrets/read returns `unreachable: true` when the
283
+ // credential backend (CES) can't be reached. Respect that signal.
284
+ if (json.unreachable) {
285
+ return { value: null, unreachable: true };
286
+ }
287
+ return {
288
+ value: json.found && json.value ? json.value : null,
289
+ unreachable: false,
290
+ };
291
+ } catch {
292
+ // Network error, timeout, or gateway down
293
+ return { value: null, unreachable: true };
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Inject a single credential into the assistant's secret store via the
299
+ * gateway's `POST /v1/secrets` endpoint.
300
+ *
301
+ * Mirrors the desktop app's `GatewayHTTPClient.post(path: "secrets", …)`
302
+ * calls in `LocalAssistantBootstrapService.swift`.
303
+ */
304
+ async function injectGatewayCredential(
305
+ gatewayUrl: string,
306
+ name: string,
307
+ value: string,
308
+ bearerToken?: string,
309
+ ): Promise<boolean> {
310
+ const headers: Record<string, string> = {
311
+ "Content-Type": "application/json",
312
+ Accept: "application/json",
313
+ };
314
+ if (bearerToken) {
315
+ headers["Authorization"] = `Bearer ${bearerToken}`;
316
+ }
317
+
318
+ const response = await loopbackSafeFetch(`${gatewayUrl}/v1/secrets`, {
319
+ method: "POST",
320
+ headers,
321
+ body: JSON.stringify({ type: "credential", name, value }),
322
+ signal: AbortSignal.timeout(10_000),
323
+ });
324
+ return response.ok;
325
+ }
326
+
327
+ export interface CredentialInjectionParams {
328
+ gatewayUrl: string;
329
+ bearerToken?: string;
330
+ assistantApiKey?: string | null;
331
+ cloudAssistantId: string;
332
+ organizationId: string;
333
+ userId?: string;
334
+ webhookSecret?: string | null;
335
+ }
336
+
337
+ /**
338
+ * Inject cloud credentials into a running assistant via the gateway,
339
+ * mirroring `LocalAssistantBootstrapService.injectKeyIntoAssistant` et al.
340
+ *
341
+ * Each credential is posted individually. Failures are collected but do
342
+ * not prevent the remaining credentials from being injected.
343
+ *
344
+ * Returns true if all injections succeeded.
345
+ */
346
+ export async function injectCredentialsIntoAssistant(
347
+ params: CredentialInjectionParams,
348
+ ): Promise<boolean> {
349
+ const inject = (name: string, value: string) =>
350
+ injectGatewayCredential(params.gatewayUrl, name, value, params.bearerToken);
351
+
352
+ const promises: Promise<boolean>[] = [];
353
+
354
+ if (params.assistantApiKey) {
355
+ promises.push(inject("cadet:assistant_api_key", params.assistantApiKey));
356
+ }
357
+
358
+ if (params.webhookSecret) {
359
+ promises.push(inject("cadet:webhook_secret", params.webhookSecret));
360
+ }
361
+
362
+ const results = await Promise.all(promises);
363
+ return results.every(Boolean);
364
+ }
365
+
366
+ /** Where the key came from, so callers can report what they did. */
367
+ export type AssistantApiKeySource =
368
+ | "registration"
369
+ | "stored"
370
+ | "reprovisioned"
371
+ | "unavailable";
372
+
373
+ export interface ResolveAssistantApiKeyArgs {
374
+ /** Key the registration returned, set only when it had none before. */
375
+ registrationApiKey: string | null;
376
+ runtimeUrl: string;
377
+ bearerToken?: string;
378
+ token: string;
379
+ organizationId: string;
380
+ clientInstallationId: string;
381
+ runtimeAssistantId: string;
382
+ clientPlatform: string;
383
+ }
384
+
385
+ export interface ResolvedAssistantApiKey {
386
+ apiKey: string | null;
387
+ source: AssistantApiKeySource;
388
+ }
389
+
390
+ /**
391
+ * Three steps, in order: the key the registration just issued, the key the
392
+ * assistant already holds, then a rotation.
393
+ *
394
+ * A stored key the cloud has rejected is skipped, because reinjecting it
395
+ * repairs nothing while looking like a repair. The verdict is asked for
396
+ * before the key is read, so the key returned is one the verdict covers: a
397
+ * repair that lands between the two requests is then read, not overwritten
398
+ * by the value it replaced. Rotation is still withheld when the gateway is
399
+ * merely unreachable: rotating without being able to store the replacement
400
+ * would start the cloud's grace clock on a key the assistant still needs,
401
+ * with nothing to hand it in exchange.
402
+ */
403
+ export async function resolveAssistantApiKeyForInjection(
404
+ args: ResolveAssistantApiKeyArgs,
405
+ ): Promise<ResolvedAssistantApiKey> {
406
+ if (args.registrationApiKey) {
407
+ return { apiKey: args.registrationApiKey, source: "registration" };
408
+ }
409
+
410
+ const status = await verifyGatewayCloudCredential(
411
+ args.runtimeUrl,
412
+ args.bearerToken,
413
+ );
414
+ // A settled rejection came from a gateway that answered, so the
415
+ // replacement can be stored; the rejected key is not worth reading.
416
+ if (status !== "rejected") {
417
+ const cached = await readGatewayCredential(
418
+ args.runtimeUrl,
419
+ "cadet:assistant_api_key",
420
+ args.bearerToken,
421
+ );
422
+ if (cached.value) {
423
+ return { apiKey: cached.value, source: "stored" };
424
+ }
425
+ if (cached.unreachable) {
426
+ return { apiKey: null, source: "unavailable" };
427
+ }
428
+ }
429
+
430
+ const reprovision = await reprovisionAssistantApiKey(
431
+ args.token,
432
+ args.organizationId,
433
+ args.clientInstallationId,
434
+ args.runtimeAssistantId,
435
+ args.clientPlatform,
436
+ );
437
+ return {
438
+ apiKey: reprovision.provisioning.assistant_api_key,
439
+ source: "reprovisioned",
440
+ };
441
+ }
442
+
443
+ /**
444
+ * The self-hosted assistant's own ingress URL, read from its running
445
+ * gateway (`/integrations/ingress/config`). Managed-callback URLs belong
446
+ * to the cloud, not the assistant, and yield undefined. Best-effort:
447
+ * any failure is undefined.
448
+ */
449
+ export async function fetchAssistantIngressUrl(
450
+ runtimeUrl: string,
451
+ bearerToken?: string,
452
+ ): Promise<string | undefined> {
453
+ if (!bearerToken) return undefined;
454
+ try {
455
+ const resp = await loopbackSafeFetch(
456
+ `${runtimeUrl}/integrations/ingress/config`,
457
+ {
458
+ headers: { Authorization: `Bearer ${bearerToken}` },
459
+ signal: AbortSignal.timeout(5000),
460
+ },
461
+ );
462
+ if (resp.ok) {
463
+ const body = (await resp.json()) as {
464
+ publicBaseUrl?: string;
465
+ managedCallbacks?: boolean;
466
+ };
467
+ // Ignore managed-callback URLs — those belong to the cloud, not the
468
+ // self-hosted assistant's own ingress.
469
+ if (body.managedCallbacks) return undefined;
470
+ return body.publicBaseUrl || undefined;
471
+ }
472
+ } catch {
473
+ // Best-effort
474
+ }
475
+ return undefined;
476
+ }
477
+
478
+ export interface PlatformUser {
479
+ id: string;
480
+ email: string;
481
+ display: string;
482
+ }
483
+
484
+ const AllauthSessionResponseSchema = z.object({
485
+ status: z.number(),
486
+ data: z.object({
487
+ user: z.object({ id: z.string(), email: z.string(), display: z.string() }),
488
+ }),
489
+ });
490
+
491
+ const PLATFORM_FETCH_TIMEOUT_MS = 10_000;
492
+
493
+ export async function fetchCurrentUser(
494
+ token: string,
495
+ cloudUrl?: string,
496
+ ): Promise<PlatformUser> {
497
+ const resolvedUrl = cloudUrl || resolveCloudUrl();
498
+ const url = `${resolvedUrl}/_allauth/app/v1/auth/session`;
499
+
500
+ const controller = new AbortController();
501
+ const timeoutId = setTimeout(
502
+ () => controller.abort(),
503
+ PLATFORM_FETCH_TIMEOUT_MS,
504
+ );
505
+
506
+ try {
507
+ const response = await loopbackSafeFetch(url, {
508
+ signal: controller.signal,
509
+ headers: { "X-Session-Token": token },
510
+ });
511
+
512
+ if (!response.ok) {
513
+ if (
514
+ response.status === 401 ||
515
+ response.status === 403 ||
516
+ response.status === 410
517
+ ) {
518
+ throw new Error("Invalid or expired token. Please login again.");
519
+ }
520
+ throw new Error(
521
+ `Platform API error: ${response.status} ${response.statusText}`,
522
+ );
523
+ }
524
+
525
+ const body = AllauthSessionResponseSchema.parse(await response.json());
526
+ return body.data.user;
527
+ } finally {
528
+ clearTimeout(timeoutId);
529
+ }
530
+ }
531
+
532
+ /**
533
+ * Register the active self-hosted assistant with the cloud and inject
534
+ * cloud credentials into its runtime. Non-fatal by design; callers log
535
+ * failures. Reads the cloud session token and the guardian bearer from
536
+ * their disk files.
537
+ */
538
+ export async function registerLocalAssistantWithCloud(
539
+ user: { id: string; email: string },
540
+ log: (message: string) => void = console.log,
541
+ ): Promise<void> {
542
+ // Both credentials come from disk: the cloud session token saved by
543
+ // `cadet login`, and the guardian bearer beside the lockfile — the same
544
+ // credential the assistant's gateway leases.
545
+ const token = readCloudToken();
546
+ if (!token) return;
547
+ const entry = resolveAssistant();
548
+
549
+ // Skip managed ("cadet") assistants — they are handled by the cloud.
550
+ if (!entry || entry.cloud === "cloud") return;
551
+
552
+ const gatewayUrl = getGatewayUrl(entry);
553
+
554
+ const orgId = await fetchOrganizationId(token);
555
+ const clientInstallationId = computeDeviceId();
556
+ const [assistantVersion, ingressUrl] = await Promise.all([
557
+ fetchCurrentVersion(gatewayUrl),
558
+ fetchAssistantIngressUrl(gatewayUrl, guardianBearer(entry.assistantId)),
559
+ ]);
560
+ const cloudUrl = resolveCloudUrl();
561
+ const registration = await ensureSelfHostedLocalRegistration(
562
+ token,
563
+ orgId,
564
+ clientInstallationId,
565
+ entry.assistantId,
566
+ "cli",
567
+ assistantVersion,
568
+ cloudUrl,
569
+ ingressUrl,
570
+ );
571
+ saveLockfileAssistant({
572
+ ...entry,
573
+ cloudAssistantId: registration.assistant.id,
574
+ cloudBaseUrl: cloudUrl,
575
+ cloudOrganizationId: orgId,
576
+ });
577
+ log(
578
+ `Registered assistant: ${registration.assistant.name} (${registration.assistant.id})`,
579
+ );
580
+
581
+ // Which key to hand the assistant, and why. Shared with teleport so
582
+ // the two injection paths cannot drift.
583
+ const resolved = await resolveAssistantApiKeyForInjection({
584
+ registrationApiKey: registration.assistant_api_key,
585
+ runtimeUrl: gatewayUrl,
586
+ bearerToken: guardianBearer(entry.assistantId),
587
+ token,
588
+ organizationId: orgId,
589
+ clientInstallationId,
590
+ runtimeAssistantId: entry.assistantId,
591
+ clientPlatform: "cli",
592
+ });
593
+ const assistantApiKey = resolved.apiKey;
594
+ if (resolved.source === "reprovisioned") {
595
+ log("Provisioning a replacement API key...");
596
+ }
597
+
598
+ // Inject credentials into the running assistant via the gateway,
599
+ // mirroring the desktop app's LocalAssistantBootstrapService flow.
600
+ const allInjected = await injectCredentialsIntoAssistant({
601
+ gatewayUrl: gatewayUrl,
602
+ bearerToken: guardianBearer(entry.assistantId),
603
+ assistantApiKey,
604
+ cloudAssistantId: registration.assistant.id,
605
+ organizationId: orgId,
606
+ userId: user.id,
607
+ webhookSecret: registration.webhook_secret,
608
+ });
609
+ if (allInjected) {
610
+ log("Injected cloud credentials into assistant.");
611
+ } else {
612
+ console.warn("Some credentials could not be injected into the assistant.");
613
+ }
614
+ }