@integrity-labs/agt-cli 0.28.1249 → 0.28.1251

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 (36) hide show
  1. package/dist/api-client-ECOBF6BM.js +39 -0
  2. package/dist/bin/agt.js +17 -15
  3. package/dist/bin/agt.js.map +1 -1
  4. package/dist/chunk-2VGFSHFP.js +471 -0
  5. package/dist/chunk-2VGFSHFP.js.map +1 -0
  6. package/dist/{chunk-COCLODTH.js → chunk-4AUE34MF.js} +162 -565
  7. package/dist/chunk-4AUE34MF.js.map +1 -0
  8. package/dist/{chunk-CMCT3LOQ.js → chunk-6KY5FKXC.js} +192 -1
  9. package/dist/chunk-6KY5FKXC.js.map +1 -0
  10. package/dist/{chunk-G5CNX4XF.js → chunk-O6WRX5FE.js} +26 -3
  11. package/dist/{chunk-G5CNX4XF.js.map → chunk-O6WRX5FE.js.map} +1 -1
  12. package/dist/{chunk-NNB7XNZA.js → chunk-OAAKFU3J.js} +2 -2
  13. package/dist/{chunk-IQ6MCAEK.js → chunk-VOMOPWFI.js} +2 -2
  14. package/dist/{claude-code-updater-EWJ6B5HX.js → claude-code-updater-2TZ4TSOB.js} +3 -3
  15. package/dist/{claude-pair-runtime-BJLV7HMD.js → claude-pair-runtime-CTJCJNK4.js} +3 -3
  16. package/dist/lib/manager-worker.js +484 -146
  17. package/dist/lib/manager-worker.js.map +1 -1
  18. package/dist/mcp/direct-chat-channel.js +5 -0
  19. package/dist/mcp/index.js +5 -0
  20. package/dist/mcp/origami.js +5 -0
  21. package/dist/mcp/slack-channel.js +5 -0
  22. package/dist/mcp/telegram-channel.js +367 -186
  23. package/dist/{persistent-session-ZTDFRERR.js → persistent-session-TBE4KP4K.js} +4 -4
  24. package/dist/persistent-session-TBE4KP4K.js.map +1 -0
  25. package/dist/{responsiveness-probe-SVSMKLYS.js → responsiveness-probe-J7DA3AB4.js} +4 -4
  26. package/dist/{session-auth-dead-K63LMSKK.js → session-auth-dead-OL5ODQRN.js} +3 -3
  27. package/package.json +1 -1
  28. package/dist/chunk-CMCT3LOQ.js.map +0 -1
  29. package/dist/chunk-COCLODTH.js.map +0 -1
  30. /package/dist/{claude-code-updater-EWJ6B5HX.js.map → api-client-ECOBF6BM.js.map} +0 -0
  31. /package/dist/{chunk-NNB7XNZA.js.map → chunk-OAAKFU3J.js.map} +0 -0
  32. /package/dist/{chunk-IQ6MCAEK.js.map → chunk-VOMOPWFI.js.map} +0 -0
  33. /package/dist/{persistent-session-ZTDFRERR.js.map → claude-code-updater-2TZ4TSOB.js.map} +0 -0
  34. /package/dist/{claude-pair-runtime-BJLV7HMD.js.map → claude-pair-runtime-CTJCJNK4.js.map} +0 -0
  35. /package/dist/{responsiveness-probe-SVSMKLYS.js.map → responsiveness-probe-J7DA3AB4.js.map} +0 -0
  36. /package/dist/{session-auth-dead-K63LMSKK.js.map → session-auth-dead-OL5ODQRN.js.map} +0 -0
@@ -0,0 +1,471 @@
1
+ import {
2
+ HOST_ROTATE_KEY_CONFLICT
3
+ } from "./chunk-6KY5FKXC.js";
4
+
5
+ // src/lib/config.ts
6
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
7
+ import { join } from "path";
8
+ import { homedir } from "os";
9
+ var AUGMENTED_DIR = join(homedir(), ".augmented");
10
+ var CONFIG_PATH = join(AUGMENTED_DIR, "config.json");
11
+ function ensureAugmentedDir() {
12
+ if (!existsSync(AUGMENTED_DIR)) {
13
+ mkdirSync(AUGMENTED_DIR, { recursive: true });
14
+ }
15
+ }
16
+ function reloadFromShellProfile() {
17
+ return loadFromShellProfile(true);
18
+ }
19
+ function loadFromShellProfile(force = false) {
20
+ if (!force && process.env["AGT_HOST"] && process.env["AGT_API_KEY"]) return;
21
+ const shell = process.env["SHELL"] ?? "";
22
+ const home = homedir();
23
+ const candidates = shell.includes("zsh") ? [join(home, ".zshrc"), join(home, ".zprofile")] : shell.includes("fish") ? [join(home, ".config", "fish", "config.fish")] : [join(home, ".bashrc"), join(home, ".bash_profile")];
24
+ for (const profile of candidates) {
25
+ try {
26
+ const content = readFileSync(profile, "utf-8");
27
+ for (const key of ["AGT_HOST", "AGT_API_KEY", "AGT_TEAM"]) {
28
+ if (!force && process.env[key]) continue;
29
+ const match = content.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#")).map(
30
+ (line) => line.match(
31
+ new RegExp(
32
+ `^(?:export\\s+${key}\\s*=\\s*["']([^"']+)["']|set\\s+-gx\\s+${key}\\s+["']([^"']+)["'])$`
33
+ )
34
+ )
35
+ ).find(Boolean);
36
+ if (match) {
37
+ process.env[key] = match[1] ?? match[2];
38
+ }
39
+ }
40
+ } catch {
41
+ }
42
+ if (process.env["AGT_HOST"] && process.env["AGT_API_KEY"]) break;
43
+ }
44
+ }
45
+ loadFromShellProfile();
46
+ function getApiKey() {
47
+ return process.env["AGT_API_KEY"] ?? null;
48
+ }
49
+ function getConfig() {
50
+ try {
51
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
52
+ return JSON.parse(raw);
53
+ } catch {
54
+ return {};
55
+ }
56
+ }
57
+ function saveConfig(config) {
58
+ ensureAugmentedDir();
59
+ writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));
60
+ }
61
+ function getActiveTeam() {
62
+ const envTeam = process.env["AGT_TEAM"];
63
+ if (envTeam) return envTeam;
64
+ return getConfig().active_team;
65
+ }
66
+ function setActiveTeam(slug) {
67
+ const config = getConfig();
68
+ config.active_team = slug;
69
+ saveConfig(config);
70
+ }
71
+ var PROD_AGT_HOST = "https://api.augmented.team";
72
+ var AGT_HOST_UNSET_MESSAGE = "AGT_HOST is not set. Set it to the API URL for your stage before running this command:\n Production: export AGT_HOST=https://api.augmented.team\n Non-prod stage: export AGT_HOST=https://<stage>.api.staging.augmented.team\n Local development: export AGT_HOST=http://api.agt.localhost:1355\n\nFor first-time host setup, pass --api-host <url> to `agt setup` instead \u2014 the setup command does NOT silently default to prod (ENG-5831).";
73
+ function getHost() {
74
+ const envHost = process.env["AGT_HOST"]?.trim();
75
+ if (!envHost) {
76
+ throw new Error(AGT_HOST_UNSET_MESSAGE);
77
+ }
78
+ return envHost;
79
+ }
80
+ function requireHost() {
81
+ return getHost();
82
+ }
83
+
84
+ // src/lib/auth-exchange-error.ts
85
+ var ApiKeyExchangeError = class extends Error {
86
+ constructor(message, status, transient) {
87
+ super(message);
88
+ this.status = status;
89
+ this.transient = transient;
90
+ this.name = "ApiKeyExchangeError";
91
+ }
92
+ };
93
+ function isTransientExchangeStatus(status) {
94
+ return status >= 500 || status === 429;
95
+ }
96
+ function isTransientAuthFailure(err) {
97
+ return err instanceof ApiKeyExchangeError && err.transient;
98
+ }
99
+ function exchangeFailureKind(err) {
100
+ if (!(err instanceof ApiKeyExchangeError)) return "unclassified";
101
+ const status = err.status === null ? "transport" : String(err.status);
102
+ return err.transient ? `transient-${status}` : `verdict-${status}`;
103
+ }
104
+
105
+ // src/lib/api-client.ts
106
+ var agtCliVersion = true ? "0.28.1251" : "dev";
107
+ var lastConfigHash = null;
108
+ function setConfigHash(hash) {
109
+ lastConfigHash = hash && hash.length > 0 ? hash : null;
110
+ }
111
+ var cachedExchange = null;
112
+ var exchangeInFlight = null;
113
+ var exchangeForceCount = 0;
114
+ var consumedExchangeForceCount = 0;
115
+ function forceNextExchange() {
116
+ exchangeForceCount += 1;
117
+ }
118
+ function getCachedClaudeAuthMode() {
119
+ return cachedExchange?.claudeAuthMode ?? null;
120
+ }
121
+ function getCachedClaudeAuthModeRaw() {
122
+ return cachedExchange?.claudeAuthModeRaw ?? null;
123
+ }
124
+ function invalidateExchange() {
125
+ cachedExchange = null;
126
+ lastConfigHash = null;
127
+ }
128
+ async function exchangeApiKey(rawKey, retried = false, opts = {}) {
129
+ const withinMaxAge = opts.maxAgeMs === void 0 || cachedExchange !== null && Date.now() - cachedExchange.fetchedAt < opts.maxAgeMs;
130
+ const forcePending = exchangeForceCount > consumedExchangeForceCount;
131
+ if (!opts.forceRefresh && !forcePending && withinMaxAge && cachedExchange && Date.now() < cachedExchange.expiresAt - 6e4) {
132
+ return {
133
+ token: cachedExchange.token,
134
+ hostId: cachedExchange.hostId,
135
+ teamId: cachedExchange.teamId,
136
+ teamSlug: cachedExchange.teamSlug,
137
+ framework: cachedExchange.framework,
138
+ hostKind: cachedExchange.hostKind,
139
+ claudeAuthMode: cachedExchange.claudeAuthMode,
140
+ claudeAuthModeRaw: cachedExchange.claudeAuthModeRaw,
141
+ anthropicApiKeyFingerprint: cachedExchange.anthropicApiKeyFingerprint,
142
+ anthropicApiKey: cachedExchange.anthropicApiKey,
143
+ userEmail: cachedExchange.userEmail,
144
+ supabaseUrl: cachedExchange.supabaseUrl,
145
+ supabaseAnonKey: cachedExchange.supabaseAnonKey
146
+ };
147
+ }
148
+ const observedForceCount = exchangeForceCount;
149
+ if (exchangeInFlight) {
150
+ return exchangeInFlight;
151
+ }
152
+ exchangeInFlight = doExchange(rawKey, retried);
153
+ try {
154
+ const result = await exchangeInFlight;
155
+ consumedExchangeForceCount = observedForceCount;
156
+ return result;
157
+ } finally {
158
+ exchangeInFlight = null;
159
+ }
160
+ }
161
+ var DEFAULT_EXCHANGE_RETRY_ATTEMPTS = 2;
162
+ var DEFAULT_EXCHANGE_RETRY_BASE_MS = 500;
163
+ function exchangeRetryAttempts() {
164
+ const raw = process.env["AGT_AUTH_EXCHANGE_RETRY_ATTEMPTS"];
165
+ const parsed = raw ? parseInt(raw, 10) : NaN;
166
+ if (Number.isFinite(parsed) && parsed >= 0) return Math.min(parsed, 5);
167
+ return DEFAULT_EXCHANGE_RETRY_ATTEMPTS;
168
+ }
169
+ function exchangeRetryBaseMs() {
170
+ const raw = process.env["AGT_AUTH_EXCHANGE_RETRY_BASE_MS"];
171
+ const parsed = raw ? parseInt(raw, 10) : NaN;
172
+ if (Number.isFinite(parsed) && parsed > 0) return Math.min(parsed, 5e3);
173
+ return DEFAULT_EXCHANGE_RETRY_BASE_MS;
174
+ }
175
+ function asExchangeError(err) {
176
+ if (err instanceof ApiKeyExchangeError) return err;
177
+ const message = err instanceof Error ? err.message : String(err);
178
+ return new ApiKeyExchangeError(message, null, true);
179
+ }
180
+ async function doExchange(rawKey, retried) {
181
+ const maxRetries = exchangeRetryAttempts();
182
+ const baseMs = exchangeRetryBaseMs();
183
+ let lastErr;
184
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
185
+ try {
186
+ return await attemptExchange(rawKey, retried);
187
+ } catch (err) {
188
+ const exchangeErr = asExchangeError(err);
189
+ if (!exchangeErr.transient || attempt === maxRetries) throw exchangeErr;
190
+ lastErr = exchangeErr;
191
+ await new Promise((resolve) => setTimeout(resolve, baseMs * 2 ** attempt));
192
+ }
193
+ }
194
+ throw lastErr ?? new ApiKeyExchangeError("API key exchange failed", null, true);
195
+ }
196
+ async function attemptExchange(rawKey, retried) {
197
+ const res = await fetch(`${requireHost()}/host/exchange`, {
198
+ method: "POST",
199
+ headers: { "Content-Type": "application/json" },
200
+ body: JSON.stringify({ host_key: rawKey })
201
+ });
202
+ if (!res.ok) {
203
+ const body = await res.json().catch(() => ({}));
204
+ const errorMsg = String(body["error"] ?? res.statusText);
205
+ const host = requireHost();
206
+ const obfuscated = rawKey.length > 12 ? `${rawKey.slice(0, 8)}${"*".repeat(rawKey.length - 12)}${rawKey.slice(-4)}` : rawKey.slice(0, 4) + "****";
207
+ if (res.status >= 502 && res.status <= 504) {
208
+ throw new ApiKeyExchangeError(
209
+ `API unreachable (${res.status}): ${host} \u2014 is the API server running?`,
210
+ res.status,
211
+ true
212
+ );
213
+ }
214
+ if (errorMsg.includes("revoked") && !retried) {
215
+ reloadFromShellProfile();
216
+ const freshKey = getApiKey();
217
+ if (freshKey && freshKey !== rawKey) {
218
+ return attemptExchange(freshKey, true);
219
+ }
220
+ }
221
+ throw new ApiKeyExchangeError(
222
+ `API key exchange failed: ${errorMsg} (host=${host}, key=${obfuscated})`,
223
+ res.status,
224
+ isTransientExchangeStatus(res.status)
225
+ );
226
+ }
227
+ const data = await res.json();
228
+ if (!data.token) {
229
+ throw new ApiKeyExchangeError("API key exchange returned no token", null, true);
230
+ }
231
+ const claudeAuthMode = data.claude_auth_mode === "api_key" ? "api_key" : data.claude_auth_mode === "openrouter" ? "openrouter" : "subscription";
232
+ const claudeAuthModeRaw = data.claude_auth_mode ?? null;
233
+ cachedExchange = {
234
+ token: data.token,
235
+ hostId: data.host_id,
236
+ teamId: data.team_id,
237
+ teamSlug: data.team_slug,
238
+ framework: data.framework ?? null,
239
+ hostKind: data.host_kind ?? null,
240
+ claudeAuthMode,
241
+ claudeAuthModeRaw,
242
+ anthropicApiKeyFingerprint: data.anthropic_api_key_fingerprint ?? null,
243
+ anthropicApiKey: data.anthropic_api_key ?? null,
244
+ userEmail: data.user_email,
245
+ supabaseUrl: data.supabase_url,
246
+ supabaseAnonKey: data.supabase_anon_key,
247
+ expiresAt: new Date(data.expires_at).getTime(),
248
+ fetchedAt: Date.now()
249
+ };
250
+ return {
251
+ token: data.token,
252
+ hostId: data.host_id,
253
+ teamId: data.team_id,
254
+ teamSlug: data.team_slug,
255
+ framework: data.framework ?? null,
256
+ hostKind: data.host_kind ?? null,
257
+ claudeAuthMode,
258
+ claudeAuthModeRaw,
259
+ anthropicApiKeyFingerprint: data.anthropic_api_key_fingerprint ?? null,
260
+ anthropicApiKey: data.anthropic_api_key ?? null,
261
+ userEmail: data.user_email,
262
+ supabaseUrl: data.supabase_url,
263
+ supabaseAnonKey: data.supabase_anon_key
264
+ };
265
+ }
266
+ async function mintAgentKey(rawHostKey, agentId) {
267
+ const res = await fetch(`${requireHost()}/host/agent-key`, {
268
+ method: "POST",
269
+ headers: { "Content-Type": "application/json" },
270
+ body: JSON.stringify({ host_key: rawHostKey, agent_id: agentId })
271
+ });
272
+ if (!res.ok) {
273
+ const body = await res.json().catch(() => ({}));
274
+ const errorMsg = String(body["error"] ?? res.statusText);
275
+ throw new Error(`Per-agent key mint failed (${res.status}) for agent=${agentId}: ${errorMsg}`);
276
+ }
277
+ const data = await res.json();
278
+ if (!data.agent_key) {
279
+ throw new Error(`Per-agent key mint returned no key for agent=${agentId}`);
280
+ }
281
+ return data.agent_key;
282
+ }
283
+ async function mintRotatedHostKey(rawHostKey) {
284
+ const res = await fetch(`${requireHost()}/host/rotate-key`, {
285
+ method: "POST",
286
+ headers: { "Content-Type": "application/json" },
287
+ body: JSON.stringify({ host_key: rawHostKey }),
288
+ // BOUNDED, because this await is now on the poll cycle's critical path
289
+ // (CodeRabbit on #7114). The rotation moved onto the heartbeat handler,
290
+ // which `pollCycleInner` awaits, so an unanswered mint blocks the Claude
291
+ // Code updater, the responsiveness probe, the wedge and pane-fatal checks,
292
+ // the /host/agents fetch and every per-agent `processAgent` for as long as
293
+ // it hangs — and Node's built-in fetch waits 300s by default. The
294
+ // 5-minute retry backoff would then re-arm the same stall. 10s matches the
295
+ // other short calls in this process (`telegram-ingest.ts`). A timeout
296
+ // surfaces as a thrown error, which `adoptRotatedHostKey` reports as
297
+ // `error` and the manager retries after the backoff. The abort cancels the
298
+ // client, not the route, so the key may already be minted and recorded;
299
+ // a lost response after the commit is the same case. The retry still
300
+ // works: the server discards a minted key nobody has ever authenticated
301
+ // with once it is older than HOST_SELF_ROTATION_STALE_MINT_MS, which is
302
+ // shorter than the backoff, and mints again (ENG-11826; it used to need a
303
+ // `compromised` rotation, Obi Wan `9b564171021b` on #7114). That covers
304
+ // the backoff retry; a manager that restarts inside the window gets
305
+ // `mint_pending`, which this version retries and older versions do not.
306
+ signal: AbortSignal.timeout(1e4)
307
+ });
308
+ if (res.status === 403) {
309
+ return null;
310
+ }
311
+ if (res.status === 409) {
312
+ const body = await res.json().catch(() => ({}));
313
+ if (body["code"] === HOST_ROTATE_KEY_CONFLICT.mintPending) {
314
+ throw new Error(`Host key rotation mint deferred: ${String(body["error"] ?? "a mint is in flight")}`);
315
+ }
316
+ if (body["code"] === HOST_ROTATE_KEY_CONFLICT.alreadyHoldsMintedKey && typeof body["prefix"] === "string" && body["prefix"]) {
317
+ return { alreadyHolds: body["prefix"] };
318
+ }
319
+ return { refused: String(body["error"] ?? "conflict") };
320
+ }
321
+ if (!res.ok) {
322
+ const body = await res.json().catch(() => ({}));
323
+ throw new Error(`Host key rotation mint failed (${res.status}): ${String(body["error"] ?? res.statusText)}`);
324
+ }
325
+ const data = await res.json();
326
+ const prefix = data.key?.prefix;
327
+ const rawKey = data.key?.raw_key;
328
+ if (!prefix || !rawKey) return null;
329
+ return { prefix, rawKey };
330
+ }
331
+ async function probeHostKey(rawKey) {
332
+ let res;
333
+ try {
334
+ res = await fetch(`${requireHost()}/host/exchange`, {
335
+ method: "POST",
336
+ headers: { "Content-Type": "application/json" },
337
+ body: JSON.stringify({ host_key: rawKey }),
338
+ // Same bound as the mint, for the same reason: it runs on the poll cycle.
339
+ signal: AbortSignal.timeout(1e4)
340
+ });
341
+ } catch {
342
+ return "unknown";
343
+ }
344
+ if (res.ok) return "live";
345
+ if (res.status === 401) {
346
+ const body = await res.json().catch(() => ({}));
347
+ if (body["code"] === "key_revoked" || body["code"] === "invalid_key" || body["code"] === "key_expired") {
348
+ return "unusable";
349
+ }
350
+ }
351
+ return "unknown";
352
+ }
353
+ function adoptHostKeyInProcess(rawKey) {
354
+ process.env["AGT_API_KEY"] = rawKey;
355
+ forceNextExchange();
356
+ }
357
+ async function resolveAuth() {
358
+ const apiKey = getApiKey();
359
+ if (!apiKey) {
360
+ throw new Error("AGT_API_KEY is not set. Export it with your host API key (tlk_...)");
361
+ }
362
+ const exchange = await exchangeApiKey(apiKey);
363
+ return { token: exchange.token, hostId: exchange.hostId };
364
+ }
365
+ async function buildHeaders() {
366
+ const apiKey = getApiKey();
367
+ if (!apiKey) {
368
+ throw new Error("AGT_API_KEY is not set. Export it with your host API key (tlk_...)");
369
+ }
370
+ const exchange = await exchangeApiKey(apiKey);
371
+ const headers = {
372
+ "Authorization": `Bearer ${exchange.token}`,
373
+ "Content-Type": "application/json",
374
+ // ENG-6410: lets the API stamp audit_log.agt_cli_version for host-runtime
375
+ // actions so bug rates can be tracked per CLI version.
376
+ "X-Agt-Cli-Version": agtCliVersion
377
+ };
378
+ if (lastConfigHash) {
379
+ headers["X-Config-Hash"] = lastConfigHash;
380
+ }
381
+ const team = getActiveTeam() ?? exchange.teamSlug;
382
+ if (team) {
383
+ headers["X-Team-Slug"] = team;
384
+ }
385
+ return headers;
386
+ }
387
+ var ApiError = class extends Error {
388
+ constructor(status, body) {
389
+ super(body["error"] ?? `HTTP ${status}`);
390
+ this.status = status;
391
+ this.body = body;
392
+ this.name = "ApiError";
393
+ }
394
+ };
395
+ async function fetchWithRetry(path, method, body, extraHeaders) {
396
+ const baseHeaders = await buildHeaders();
397
+ const headers = extraHeaders ? { ...baseHeaders, ...extraHeaders } : baseHeaders;
398
+ const url = `${requireHost()}${path}`;
399
+ const init = {
400
+ method,
401
+ headers,
402
+ body: body !== void 0 ? JSON.stringify(body) : void 0
403
+ };
404
+ const res = await fetch(url, init);
405
+ if (res.status === 401) {
406
+ invalidateExchange();
407
+ const freshBase = await buildHeaders();
408
+ const freshHeaders = extraHeaders ? { ...freshBase, ...extraHeaders } : freshBase;
409
+ return fetch(url, { ...init, headers: freshHeaders });
410
+ }
411
+ return res;
412
+ }
413
+ async function handleResponse(res) {
414
+ const body = await res.json().catch(() => ({}));
415
+ if (!res.ok) {
416
+ throw new ApiError(res.status, body);
417
+ }
418
+ return body;
419
+ }
420
+ var api = {
421
+ async get(path) {
422
+ const res = await fetchWithRetry(path, "GET");
423
+ return handleResponse(res);
424
+ },
425
+ async post(path, body, extraHeaders) {
426
+ const res = await fetchWithRetry(path, "POST", body, extraHeaders);
427
+ return handleResponse(res);
428
+ },
429
+ async patch(path, body) {
430
+ const res = await fetchWithRetry(path, "PATCH", body);
431
+ return handleResponse(res);
432
+ },
433
+ async put(path, body) {
434
+ const res = await fetchWithRetry(path, "PUT", body);
435
+ return handleResponse(res);
436
+ },
437
+ async del(path) {
438
+ const res = await fetchWithRetry(path, "DELETE");
439
+ return handleResponse(res);
440
+ }
441
+ };
442
+ async function getHostId() {
443
+ const { hostId } = await resolveAuth();
444
+ return hostId;
445
+ }
446
+
447
+ export {
448
+ getApiKey,
449
+ getActiveTeam,
450
+ setActiveTeam,
451
+ PROD_AGT_HOST,
452
+ getHost,
453
+ requireHost,
454
+ ApiKeyExchangeError,
455
+ isTransientAuthFailure,
456
+ exchangeFailureKind,
457
+ setConfigHash,
458
+ forceNextExchange,
459
+ getCachedClaudeAuthMode,
460
+ getCachedClaudeAuthModeRaw,
461
+ invalidateExchange,
462
+ exchangeApiKey,
463
+ mintAgentKey,
464
+ mintRotatedHostKey,
465
+ probeHostKey,
466
+ adoptHostKeyInProcess,
467
+ ApiError,
468
+ api,
469
+ getHostId
470
+ };
471
+ //# sourceMappingURL=chunk-2VGFSHFP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/config.ts","../src/lib/auth-exchange-error.ts","../src/lib/api-client.ts"],"sourcesContent":["import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\n// ---------------------------------------------------------------------------\n// Paths\n// ---------------------------------------------------------------------------\n\nconst AUGMENTED_DIR = join(homedir(), '.augmented');\nconst CONFIG_PATH = join(AUGMENTED_DIR, 'config.json');\n\nfunction ensureAugmentedDir(): void {\n if (!existsSync(AUGMENTED_DIR)) {\n mkdirSync(AUGMENTED_DIR, { recursive: true });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Shell profile env loader — reads AGT_* vars from shell profile if not in env\n// ---------------------------------------------------------------------------\n\n/**\n * If AGT_HOST or AGT_API_KEY are missing from the environment, try to\n * extract them from the user's shell profile. This handles the case where\n * `agt setup` wrote the vars but the user hasn't sourced the profile yet.\n */\nexport function reloadFromShellProfile(): void {\n return loadFromShellProfile(true);\n}\n\nfunction loadFromShellProfile(force = false): void {\n if (!force && process.env['AGT_HOST'] && process.env['AGT_API_KEY']) return;\n\n const shell = process.env['SHELL'] ?? '';\n const home = homedir();\n const candidates = shell.includes('zsh')\n ? [join(home, '.zshrc'), join(home, '.zprofile')]\n : shell.includes('fish')\n ? [join(home, '.config', 'fish', 'config.fish')]\n : [join(home, '.bashrc'), join(home, '.bash_profile')];\n\n for (const profile of candidates) {\n try {\n const content = readFileSync(profile, 'utf-8');\n for (const key of ['AGT_HOST', 'AGT_API_KEY', 'AGT_TEAM'] as const) {\n if (!force && process.env[key]) continue;\n // Match active (non-comment) lines only.\n const match = content\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith('#'))\n .map((line) =>\n line.match(\n new RegExp(\n `^(?:export\\\\s+${key}\\\\s*=\\\\s*[\"']([^\"']+)[\"']|set\\\\s+-gx\\\\s+${key}\\\\s+[\"']([^\"']+)[\"'])$`,\n ),\n ),\n )\n .find(Boolean);\n if (match) {\n process.env[key] = match[1] ?? match[2];\n }\n }\n } catch {\n // Profile doesn't exist\n }\n if (process.env['AGT_HOST'] && process.env['AGT_API_KEY']) break;\n }\n}\n\n// Auto-load on module import\nloadFromShellProfile();\n\n// ---------------------------------------------------------------------------\n// API key\n// ---------------------------------------------------------------------------\n\n/**\n * Returns the host API key (`tlk_...`) from `AGT_API_KEY` env var, or null.\n */\nexport function getApiKey(): string | null {\n return process.env['AGT_API_KEY'] ?? null;\n}\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\nexport interface AugmentedConfig {\n active_team?: string; // team slug\n}\n\nexport function getConfig(): AugmentedConfig {\n try {\n const raw = readFileSync(CONFIG_PATH, 'utf-8');\n return JSON.parse(raw) as AugmentedConfig;\n } catch {\n return {};\n }\n}\n\nexport function saveConfig(config: AugmentedConfig): void {\n ensureAugmentedDir();\n writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));\n}\n\nexport function getActiveTeam(): string | undefined {\n // Check env var first (headless / agent mode)\n const envTeam = process.env['AGT_TEAM'];\n if (envTeam) return envTeam;\n\n return getConfig().active_team;\n}\n\nexport function setActiveTeam(slug: string): void {\n const config = getConfig();\n config.active_team = slug;\n saveConfig(config);\n}\n\n// ---------------------------------------------------------------------------\n// API host\n// ---------------------------------------------------------------------------\n\n/**\n * The Production API URL. Use this when a call site needs to *explicitly*\n * target prod regardless of the operator's `AGT_HOST` (impersonate's redeem\n * exchange, ENG-5773). NEVER use as a silent fallback for unset AGT_HOST —\n * that's the ENG-5831 bug: a non-prod-stage operator who hasn't sourced their\n * profile yet would silently exchange a stage token against prod.\n */\nexport const PROD_AGT_HOST = 'https://api.augmented.team';\n\n/**\n * Actionable error message thrown by `getHost()` / `requireHost()` when\n * `AGT_HOST` is not in the environment (and the shell-profile loader didn't\n * find it either). Lists every legitimate way to set it, plus a pointer to\n * the `--api-host` flag for first-time setup (where AGT_HOST is by\n * definition not yet on disk).\n */\nexport const AGT_HOST_UNSET_MESSAGE =\n 'AGT_HOST is not set. Set it to the API URL for your stage before running this command:\\n' +\n ' Production: export AGT_HOST=https://api.augmented.team\\n' +\n ' Non-prod stage: export AGT_HOST=https://<stage>.api.staging.augmented.team\\n' +\n ' Local development: export AGT_HOST=http://api.agt.localhost:1355\\n' +\n '\\n' +\n 'For first-time host setup, pass --api-host <url> to `agt setup` instead — the ' +\n 'setup command does NOT silently default to prod (ENG-5831).';\n\n/**\n * Augmented API server URL.\n *\n * Reads `AGT_HOST` from the environment. Throws if unset — ENG-5831\n * established that a silent prod default routes non-prod-stage callers to\n * prod and looks like an opaque connectivity failure. Treats blank /\n * whitespace values as unset so a stray `export AGT_HOST=` can't propagate\n * an invalid host.\n */\nexport function getHost(): string {\n const envHost = process.env['AGT_HOST']?.trim();\n if (!envHost) {\n throw new Error(AGT_HOST_UNSET_MESSAGE);\n }\n return envHost;\n}\n\nexport function requireHost(): string {\n return getHost();\n}\n","// Auth key-exchange failure classification (ENG-8260).\n//\n// A leaf module — no imports — so both the API client (which throws these) and\n// the manager's persistent-session decision path (which reads them) can depend\n// on it without a cycle, and so the classifier is cheap to unit-test.\n//\n// WHY THIS EXISTS\n// ---------------\n// `/host/exchange` failures used to surface to the manager as a bare `Error`\n// carrying only a message string. That left the caller unable to tell\n// \"the platform API is unwell right now\" (HTTP 5xx, socket reset) from\n// \"this credential is not valid\" (401/403, revoked key) — so it treated both\n// as an auth verdict and tore down the agent's running tmux session. A ~2s API\n// blip on `alyve-host-1` on 2026-07-29 was therefore enough to kill a healthy,\n// mid-turn session for `dwight` and cancel its runs. See ENG-8260.\n//\n// The distinction is the whole fix, so it is modelled in the type system rather\n// than recovered by matching on message text.\n\n/**\n * A failure of the `tlk_` host-key → JWT exchange.\n *\n * `transient` is the load-bearing field: true means \"retry, this says nothing\n * about the credential\", false means \"this is a verdict on the credential and\n * callers may act on it\".\n *\n * The `message` format is deliberately unchanged from the pre-ENG-8260 bare\n * `Error` so operator-facing manager.log lines and any log greps keep working.\n */\nexport class ApiKeyExchangeError extends Error {\n constructor(\n message: string,\n /** HTTP status of the failed exchange, or null for a transport-level failure. */\n public readonly status: number | null,\n /**\n * True when the failure carries no information about the credential's\n * validity (5xx, 429, or a transport error) and is therefore worth\n * retrying. False for a genuine auth verdict (401/403/revoked).\n */\n public readonly transient: boolean,\n ) {\n super(message);\n this.name = 'ApiKeyExchangeError';\n }\n}\n\n/**\n * Classify an HTTP status from the exchange endpoint as transient or a verdict.\n *\n * - `>= 500` — the API is unwell (500 Internal Server Error, 502/503/504 from a\n * proxy or a restarting server). Says nothing about the key.\n * - `429` — rate limited. Also says nothing about the key.\n * - everything else (notably 400/401/403/404) — a verdict. 401/403 mean the\n * credential was rejected; those must keep their current fail-closed\n * behaviour.\n */\nexport function isTransientExchangeStatus(status: number): boolean {\n return status >= 500 || status === 429;\n}\n\n/**\n * True when an error thrown out of the auth-exchange path is a transient\n * platform fault rather than a verdict on the credential.\n *\n * Deliberately conservative: an error shape we do not recognise returns\n * `false`. The caller's `false` branch is the pre-ENG-8260 fail-closed\n * behaviour (refuse to spawn, stop a running session), so defaulting to\n * `false` means the new session-preserving branch only ever fires on positive\n * evidence of a transient fault — never on the absence of evidence. An\n * unclassifiable auth error must not be able to talk us into keeping a session\n * alive under credentials we cannot vouch for.\n */\nexport function isTransientAuthFailure(err: unknown): boolean {\n return err instanceof ApiKeyExchangeError && err.transient;\n}\n\n/**\n * Short, non-secret tag for the decision log line. Never includes the message\n * body (which carries the API host and an obfuscated key).\n */\nexport function exchangeFailureKind(err: unknown): string {\n if (!(err instanceof ApiKeyExchangeError)) return 'unclassified';\n const status = err.status === null ? 'transport' : String(err.status);\n return err.transient ? `transient-${status}` : `verdict-${status}`;\n}\n","import { requireHost, getApiKey, getActiveTeam, reloadFromShellProfile } from './config.js';\nimport { ApiKeyExchangeError, isTransientExchangeStatus } from './auth-exchange-error.js';\nimport { HOST_ROTATE_KEY_CONFLICT } from '@augmented/core';\n\n// ENG-8260: re-exported so existing importers of the API client can reach the\n// exchange-failure classifier without also importing the leaf module.\nexport { ApiKeyExchangeError, isTransientAuthFailure, exchangeFailureKind } from './auth-exchange-error.js';\n\n// ENG-6410: stamped into the X-Agt-Cli-Version header on every authenticated\n// host-runtime request so the API can record which agt-cli version produced a\n// given audit_log row (per-version bug-rate monitoring). Resolved from the same\n// tsup `define` build global the rest of the CLI uses; 'dev' in local/unbundled\n// runs.\ndeclare const __CLI_VERSION__: string;\nconst agtCliVersion = typeof __CLI_VERSION__ !== 'undefined' ? __CLI_VERSION__ : 'dev';\n\n// ENG-6412: the authoritative host config_hash is computed API-side (it includes\n// server-resolved flags), returned on each /host/heartbeat, and cached here so\n// every subsequent authenticated request carries X-Config-Hash. That lets the\n// API stamp audit_log.config_hash for host-runtime actions — the same rail as\n// X-Agt-Cli-Version above. Null until the first heartbeat returns one (an older\n// API omits it ⇒ header absent ⇒ audit config_hash NULL, null-safe).\nlet lastConfigHash: string | null = null;\nexport function setConfigHash(hash: string | null): void {\n lastConfigHash = hash && hash.length > 0 ? hash : null;\n}\n\n/** Cached exchange result for API key -> JWT. */\nlet cachedExchange: {\n token: string;\n hostId: string;\n teamId: string;\n teamSlug: string | null;\n framework: string | null;\n hostKind: string | null;\n claudeAuthMode: 'subscription' | 'api_key' | 'openrouter';\n claudeAuthModeRaw: string | null;\n anthropicApiKeyFingerprint: string | null;\n anthropicApiKey: string | null;\n userEmail: string | null;\n supabaseUrl: string | null;\n supabaseAnonKey: string | null;\n expiresAt: number;\n /**\n * When this entry was minted. Distinct from `expiresAt`, which is the JWT's\n * own lifetime — `maxAgeMs` callers ask \"how stale is what you are telling me\n * about the HOST\", and that question is not answerable from a token expiry.\n */\n fetchedAt: number;\n} | null = null;\n\n/** Mutex: in-flight exchange promise to prevent concurrent re-exchanges. */\nlet exchangeInFlight: Promise<ExchangeResult> | null = null;\n\n/**\n * ENG-10093: outstanding forces from `forceNextExchange()`, counted rather than\n * flagged.\n *\n * COUNTERS, NOT A BOOLEAN, for the same reason `createFetchGate` uses them\n * (`fetch-cadence.ts`): an exchange is not atomic, so a rotation push can land\n * after the request goes out and before the response comes back. That response\n * was produced BEFORE the change, and clearing a flag with it would consume the\n * very force the push exists to demand — leaving the old credential in place for\n * a full `maxAgeMs` window, with no error and nothing in the log. A successful\n * exchange consumes exactly the count it observed when it STARTED, so a force\n * that arrives mid-flight survives into the next call.\n */\nlet exchangeForceCount = 0;\nlet consumedExchangeForceCount = 0;\n\n/**\n * Make the next exchange go to the network regardless of how recently the cache\n * was filled — WHATEVER CALLER issues it, not only a `maxAgeMs` one.\n *\n * That breadth is deliberate. The force means \"what you hold is stale\", which is\n * true for every reader of the cache, and it costs nothing extra: the first\n * caller after the force refreshes, and the bounded caller behind it then reads\n * a fresh entry, so one network call serves both. Restricting it to `maxAgeMs`\n * callers would leave the ordinary token lookups serving the credential the push\n * just superseded, for up to the JWT's full lifetime.\n *\n * Deliberately NOT `invalidateExchange()`: that nulls the whole entry, so\n * `getCachedClaudeAuthMode()` would report \"mode unknown\" until the next\n * exchange landed, and its callers are documented to treat null conservatively.\n * A push must not degrade a synchronous read it was never about.\n */\nexport function forceNextExchange(): void {\n exchangeForceCount += 1;\n}\n\nexport interface ExchangeResult {\n token: string;\n hostId: string;\n teamId: string;\n teamSlug: string | null;\n framework: string | null;\n /**\n * ENG-7587 (ADR-0042 Option-1 pt3a): the host's tenancy model ('dedicated' |\n * 'pool'), from the exchange response. null against an older API that doesn't\n * return it — callers must treat null conservatively as 'dedicated' (the\n * shared-host-key behaviour), never as pool.\n */\n hostKind: string | null;\n /**\n * Operator-configured Claude Code auth mode. 'subscription' (default) uses\n * OAuth creds from `claude /login`; 'api_key' uses anthropicApiKey below.\n */\n claudeAuthMode: 'subscription' | 'api_key' | 'openrouter';\n /**\n * ENG-9486: what the SERVER actually said, before the narrowing above.\n *\n * The normalisation is correct and must stay — collapsing an unrecognised\n * mode to `subscription` is the safe default for anything that DECIDES, and\n * the comment at the assignment explains what breaks otherwise. But it makes\n * the narrowed value unfit for DISPLAY: `agt whoami` reported \"subscription\"\n * for an `openrouter` host, and ADR-0074 adds `gateway_token` and `aws_role`,\n * which would land in the same bucket and read as a subscription too.\n *\n * So: decisions read `claudeAuthMode`, humans read this. Null only if the\n * server omitted the field entirely.\n */\n claudeAuthModeRaw: string | null;\n /**\n * First 8 hex chars of sha256(anthropicApiKey). Always returned when an\n * api_key is stored for this host — the manager uses it to detect key\n * rotation without re-decrypting every poll.\n */\n anthropicApiKeyFingerprint: string | null;\n /**\n * Decrypted Anthropic API key. Populated ONLY when claudeAuthMode=api_key\n * AND decrypt succeeded server-side. NEVER log this — the manager should\n * pass it directly to claude's env and nothing else.\n */\n anthropicApiKey: string | null;\n userEmail: string | null;\n supabaseUrl: string | null;\n supabaseAnonKey: string | null;\n}\n\n/**\n * ENG-7235: cheap synchronous read of the last-exchanged host Claude auth mode,\n * for host-side gates that must not pay a network round-trip per call (e.g. the\n * per-poll conversation-eval / memory-extraction cost gate). Returns null only\n * before the first /host/exchange of the process; the manager exchanges very\n * early (heartbeat, realtime subscriptions, spawn) so steady state is always\n * populated. claude_auth_mode is a host-level identity (every agent on the host\n * shares it), so a single cached value is authoritative for the whole fleet on\n * this host. Callers should treat null conservatively as \"mode unknown\" and not\n * change behaviour until it is known.\n */\nexport function getCachedClaudeAuthMode(): 'subscription' | 'api_key' | 'openrouter' | null {\n return cachedExchange?.claudeAuthMode ?? null;\n}\n\n/**\n * The server's OWN `claude_auth_mode`, un-narrowed.\n *\n * Use this for any PERSISTED or operator-visible decision. The narrowed\n * accessor above collapses every mode it does not recognise into\n * `'subscription'` - including the live `'xai'` value - which is safe for a\n * spawn decision and NOT safe for anything that writes a durable label\n * (Obi Wan `433a498c6bcd` on #6382). `claudeAuthModeRaw` already existed on the\n * interface for exactly this reason; it simply had no synchronous accessor.\n */\nexport function getCachedClaudeAuthModeRaw(): string | null {\n return cachedExchange?.claudeAuthModeRaw ?? null;\n}\n\n/**\n * Invalidate the cached exchange JWT so the next call re-exchanges.\n */\nexport function invalidateExchange(): void {\n cachedExchange = null;\n // ENG-6412: the cached config_hash is bound to the host/auth context the last\n // heartbeat ran under. Drop it when the exchange is invalidated (token expiry,\n // key rotation, host re-exchange) so a stale hash can't ride a new auth\n // context until the next heartbeat returns a fresh one.\n lastConfigHash = null;\n}\n\n/**\n * Exchange a `tlk_` API key for a short-lived JWT via the Hono API.\n * Concurrent callers share a single in-flight request to avoid races.\n *\n * `forceRefresh: true` bypasses the JWT cache — callers that need to detect\n * server-side state changes (e.g. claude_auth_mode rotation, ENG-4417) must\n * pass this, otherwise they'll read stale values for up to ~50 minutes.\n * Concurrent in-flight requests are still coalesced either way.\n *\n * `maxAgeMs` is the BOUNDED form of that force, added by ENG-10093, and it\n * exists because the unbounded one turned a per-poll call site into the single\n * highest-volume endpoint on the API: `/host/exchange` served 284,884\n * requests/day on 2026-09-05 (10.3% of everything) against a steady-state need\n * of roughly 1.2/hour/host. Pass it when the reason for forcing is \"do not act\n * on auth I learned about a long time ago\" rather than \"this exact call must\n * hit the network\". The cache is served while it is younger than `maxAgeMs`;\n * past that, the call goes out.\n *\n * Precedence, stated because the combination is expressible: `forceRefresh`\n * WINS. It is the unconditional form, and a caller that passes both is asking\n * for the network.\n */\nexport async function exchangeApiKey(\n rawKey: string,\n retried = false,\n opts: { forceRefresh?: boolean; maxAgeMs?: number } = {},\n): Promise<ExchangeResult> {\n // Return cached result if still valid (with 60s buffer), the caller didn't\n // explicitly request a refresh, no force is outstanding, and — for a\n // `maxAgeMs` caller — the entry is younger than the age it asked for.\n const withinMaxAge =\n opts.maxAgeMs === undefined ||\n (cachedExchange !== null && Date.now() - cachedExchange.fetchedAt < opts.maxAgeMs);\n const forcePending = exchangeForceCount > consumedExchangeForceCount;\n if (\n !opts.forceRefresh &&\n !forcePending &&\n withinMaxAge &&\n cachedExchange &&\n Date.now() < cachedExchange.expiresAt - 60_000\n ) {\n return {\n token: cachedExchange.token,\n hostId: cachedExchange.hostId,\n teamId: cachedExchange.teamId,\n teamSlug: cachedExchange.teamSlug,\n framework: cachedExchange.framework,\n hostKind: cachedExchange.hostKind,\n claudeAuthMode: cachedExchange.claudeAuthMode,\n claudeAuthModeRaw: cachedExchange.claudeAuthModeRaw,\n anthropicApiKeyFingerprint: cachedExchange.anthropicApiKeyFingerprint,\n anthropicApiKey: cachedExchange.anthropicApiKey,\n userEmail: cachedExchange.userEmail,\n supabaseUrl: cachedExchange.supabaseUrl,\n supabaseAnonKey: cachedExchange.supabaseAnonKey,\n };\n }\n\n // Captured BEFORE the request goes out, so a force that lands while it is in\n // flight is not consumed by a response that predates it (see the counters'\n // declaration). Read here rather than after the await for that reason alone.\n const observedForceCount = exchangeForceCount;\n\n // Coalesce concurrent exchange calls into a single request — covers both\n // the natural-expiry refresh and the forceRefresh path.\n if (exchangeInFlight) {\n return exchangeInFlight;\n }\n\n exchangeInFlight = doExchange(rawKey, retried);\n try {\n const result = await exchangeInFlight;\n // Only a SUCCESSFUL exchange consumes a force. A transport blip must leave\n // the force outstanding so the next pass retries immediately rather than\n // treating the failure as though the refresh had happened.\n consumedExchangeForceCount = observedForceCount;\n return result;\n } finally {\n exchangeInFlight = null;\n }\n}\n\n// ENG-8260: a 5xx on /host/exchange is \"the API is unwell\", not \"this key is\n// invalid\" — but the manager's persistent-session path treated any thrown error\n// as an auth verdict and tore down running sessions. Retry transient failures\n// here so a short blip never reaches a session-affecting decision at all.\n//\n// Bounded deliberately: the manager polls on a ~30s cadence and awaits this on\n// the spawn path, so the retry budget must stay well inside a tick. Defaults\n// give ~0.5s + ~1.0s of sleep across 2 retries (~1.5s worst case, 3 requests\n// total), which covers the ~2s alyve-host-1 blip that motivated the ticket\n// without risking a tick overrun. Both are tunables, not gates.\nconst DEFAULT_EXCHANGE_RETRY_ATTEMPTS = 2;\nconst DEFAULT_EXCHANGE_RETRY_BASE_MS = 500;\n\nfunction exchangeRetryAttempts(): number {\n const raw = process.env['AGT_AUTH_EXCHANGE_RETRY_ATTEMPTS'];\n const parsed = raw ? parseInt(raw, 10) : NaN;\n // Clamp to [0, 5]: 0 disables retries (restores pre-ENG-8260 timing for a\n // host that needs it), 5 caps the worst case at ~15s.\n if (Number.isFinite(parsed) && parsed >= 0) return Math.min(parsed, 5);\n return DEFAULT_EXCHANGE_RETRY_ATTEMPTS;\n}\n\nfunction exchangeRetryBaseMs(): number {\n const raw = process.env['AGT_AUTH_EXCHANGE_RETRY_BASE_MS'];\n const parsed = raw ? parseInt(raw, 10) : NaN;\n if (Number.isFinite(parsed) && parsed > 0) return Math.min(parsed, 5_000);\n return DEFAULT_EXCHANGE_RETRY_BASE_MS;\n}\n\n/**\n * Normalise anything thrown out of `attemptExchange` into an\n * `ApiKeyExchangeError`. A raw `fetch` rejection (DNS failure, socket reset,\n * TLS error) has no HTTP status and is transient by definition — the request\n * never reached the API, so it says nothing about the credential.\n */\nfunction asExchangeError(err: unknown): ApiKeyExchangeError {\n if (err instanceof ApiKeyExchangeError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new ApiKeyExchangeError(message, null, true);\n}\n\n/**\n * ENG-8260: retry wrapper around a single exchange attempt. Transient failures\n * (5xx / 429 / transport) are retried with exponential backoff; a verdict\n * (401/403/revoked/400) is rethrown on the first attempt so genuine auth\n * failures are still acted on immediately, exactly as before.\n */\nasync function doExchange(rawKey: string, retried: boolean): Promise<ExchangeResult> {\n const maxRetries = exchangeRetryAttempts();\n const baseMs = exchangeRetryBaseMs();\n let lastErr: ApiKeyExchangeError | undefined;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await attemptExchange(rawKey, retried);\n } catch (err) {\n const exchangeErr = asExchangeError(err);\n if (!exchangeErr.transient || attempt === maxRetries) throw exchangeErr;\n lastErr = exchangeErr;\n await new Promise((resolve) => setTimeout(resolve, baseMs * 2 ** attempt));\n }\n }\n\n // Unreachable — the loop either returns or throws. Kept so the function is\n // total for the type checker without an `as` cast.\n throw lastErr ?? new ApiKeyExchangeError('API key exchange failed', null, true);\n}\n\nasync function attemptExchange(rawKey: string, retried: boolean): Promise<ExchangeResult> {\n const res = await fetch(`${requireHost()}/host/exchange`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ host_key: rawKey }),\n });\n\n if (!res.ok) {\n const body = await res.json().catch(() => ({})) as Record<string, unknown>;\n const errorMsg = String(body['error'] ?? res.statusText);\n const host = requireHost();\n const obfuscated = rawKey.length > 12\n ? `${rawKey.slice(0, 8)}${'*'.repeat(rawKey.length - 12)}${rawKey.slice(-4)}`\n : rawKey.slice(0, 4) + '****';\n\n // 502/503/504 = API unreachable (proxy error, server restarting, etc.)\n // ENG-8260: message text unchanged; now carries the status + transient flag\n // so the manager can tell this apart from a credential verdict.\n if (res.status >= 502 && res.status <= 504) {\n throw new ApiKeyExchangeError(\n `API unreachable (${res.status}): ${host} — is the API server running?`,\n res.status,\n true,\n );\n }\n\n // If key was revoked, try reloading from shell profile (agt setup may have\n // written a new key that the current process hasn't picked up yet).\n if (errorMsg.includes('revoked') && !retried) {\n reloadFromShellProfile();\n const freshKey = getApiKey();\n if (freshKey && freshKey !== rawKey) {\n // ENG-8260 (CodeRabbit, PR #3900): call `attemptExchange`, NOT\n // `doExchange`. Re-entering the retry wrapper from inside one of its own\n // attempts nests the budgets — a transient failure on the fresh key\n // would return to the outer loop, which retries with the STALE key and\n // re-enters here, making the worst case (maxRetries+1)^2 requests (9 at\n // the defaults) and blowing well past the ~1.5s the spawn path can\n // afford. The outer loop owns retries for this exchange; this hop just\n // swaps the key inside the current attempt.\n return attemptExchange(freshKey, true);\n }\n }\n\n // ENG-8260: message text unchanged (the operator-facing manager.log line and\n // any log greps depend on it) — the classification rides alongside it.\n // `isTransientExchangeStatus` puts 500 and 429 on the transient side and\n // leaves 400/401/403/404 as verdicts, preserving today's fail-closed\n // behaviour for a genuinely rejected credential.\n throw new ApiKeyExchangeError(\n `API key exchange failed: ${errorMsg} (host=${host}, key=${obfuscated})`,\n res.status,\n isTransientExchangeStatus(res.status),\n );\n }\n\n const data = await res.json() as {\n token: string;\n expires_at: string;\n host_id: string;\n team_id: string;\n team_slug: string | null;\n framework?: string | null;\n host_kind?: string | null;\n claude_auth_mode?: string | null;\n anthropic_api_key_fingerprint?: string | null;\n anthropic_api_key?: string | null;\n user_email: string | null;\n supabase_url: string | null;\n supabase_anon_key: string | null;\n };\n\n if (!data.token) {\n // ENG-8260: a 200 with no token is a server-side fault, not a verdict on the\n // credential — classify transient so it is retried rather than treated as an\n // auth failure that stops a running session.\n throw new ApiKeyExchangeError('API key exchange returned no token', null, true);\n }\n\n // ENG-7152: preserve the host-level 'openrouter' mode — collapsing it to\n // 'subscription' would make the manager run the agent on the operator\n // subscription instead of OpenRouter (or, on a host with no `claude /login`,\n // skip the spawn for \"not authenticated\").\n const claudeAuthMode: 'subscription' | 'api_key' | 'openrouter' =\n data.claude_auth_mode === 'api_key'\n ? 'api_key'\n : data.claude_auth_mode === 'openrouter'\n ? 'openrouter'\n : 'subscription';\n\n // ENG-9486: keep the server's own value alongside the narrowed one. See\n // `claudeAuthModeRaw` on the ExchangeResult interface for why both exist.\n const claudeAuthModeRaw = data.claude_auth_mode ?? null;\n\n cachedExchange = {\n token: data.token,\n hostId: data.host_id,\n teamId: data.team_id,\n teamSlug: data.team_slug,\n framework: data.framework ?? null,\n hostKind: data.host_kind ?? null,\n claudeAuthMode,\n claudeAuthModeRaw,\n anthropicApiKeyFingerprint: data.anthropic_api_key_fingerprint ?? null,\n anthropicApiKey: data.anthropic_api_key ?? null,\n userEmail: data.user_email,\n supabaseUrl: data.supabase_url,\n supabaseAnonKey: data.supabase_anon_key,\n expiresAt: new Date(data.expires_at).getTime(),\n fetchedAt: Date.now(),\n };\n\n return {\n token: data.token,\n hostId: data.host_id,\n teamId: data.team_id,\n teamSlug: data.team_slug,\n framework: data.framework ?? null,\n hostKind: data.host_kind ?? null,\n claudeAuthMode,\n claudeAuthModeRaw,\n anthropicApiKeyFingerprint: data.anthropic_api_key_fingerprint ?? null,\n anthropicApiKey: data.anthropic_api_key ?? null,\n userEmail: data.user_email,\n supabaseUrl: data.supabase_url,\n supabaseAnonKey: data.supabase_anon_key,\n };\n}\n\n/**\n * ENG-7587 (ADR-0042 Option-1 pt3a): mint a PER-AGENT host key for one bound\n * agent on a POOL host, via the pt2a `POST /host/agent-key` endpoint.\n *\n * Auth is the RAW host-wide key in the body (the same primitive `/host/exchange`\n * uses) — a pool host cannot obtain a claim-less host JWT, and only a host-wide\n * key may mint (the endpoint's escalation guard). The manager's pool spawn\n * branch (pt3b) calls this and injects the returned per-agent key into the\n * agent's container as `AGT_API_KEY` instead of forwarding the shared host key,\n * so a credential reachable from tenant A's container cannot mint tenant B's\n * token. No caller yet — this is the tool pt3b wires in.\n *\n * The endpoint is gated on `host_kind='pool'` server-side, so calling it against\n * a dedicated host returns 403 (the manager only calls it when hostKind==='pool').\n * Throws on any non-2xx so the caller can fail closed rather than fall back to\n * the shared key.\n */\nexport async function mintAgentKey(rawHostKey: string, agentId: string): Promise<string> {\n const res = await fetch(`${requireHost()}/host/agent-key`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ host_key: rawHostKey, agent_id: agentId }),\n });\n if (!res.ok) {\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n const errorMsg = String(body['error'] ?? res.statusText);\n throw new Error(`Per-agent key mint failed (${res.status}) for agent=${agentId}: ${errorMsg}`);\n }\n const data = (await res.json()) as { agent_key?: string; agent_id?: string; host_id?: string };\n if (!data.agent_key) {\n throw new Error(`Per-agent key mint returned no key for agent=${agentId}`);\n }\n return data.agent_key;\n}\n\n/**\n * ENG-11642: mint a REPLACEMENT host-wide key, authenticating with the key\n * currently in force.\n *\n * Same shape as `mintAgentKey` above and for the same reason: the credential\n * travels in the body, so this cannot go through the authenticated client.\n *\n * The control plane refuses unless an operator has armed a rotation for this\n * host, and the refusal is a uniform 403 — so a caller cannot tell \"not armed\"\n * from \"not permitted\". That gate is what stops a stolen key minting itself a\n * successor to survive revocation; see the route's own header.\n *\n * Returns null on a 403 rather than throwing, because that is the ORDINARY\n * state: every host polls with no rotation armed, and the caller should do\n * nothing rather than treat it as a fault. A 409 returns `{ refused }`, which\n * the caller treats as final for the request, EXCEPT code `mint_pending`,\n * which throws so the caller retries (ENG-11826). A transport or server\n * failure still throws.\n */\nexport async function mintRotatedHostKey(\n rawHostKey: string,\n): Promise<{ prefix: string; rawKey: string } | { refused: string } | { alreadyHolds: string } | null> {\n const res = await fetch(`${requireHost()}/host/rotate-key`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ host_key: rawHostKey }),\n // BOUNDED, because this await is now on the poll cycle's critical path\n // (CodeRabbit on #7114). The rotation moved onto the heartbeat handler,\n // which `pollCycleInner` awaits, so an unanswered mint blocks the Claude\n // Code updater, the responsiveness probe, the wedge and pane-fatal checks,\n // the /host/agents fetch and every per-agent `processAgent` for as long as\n // it hangs — and Node's built-in fetch waits 300s by default. The\n // 5-minute retry backoff would then re-arm the same stall. 10s matches the\n // other short calls in this process (`telegram-ingest.ts`). A timeout\n // surfaces as a thrown error, which `adoptRotatedHostKey` reports as\n // `error` and the manager retries after the backoff. The abort cancels the\n // client, not the route, so the key may already be minted and recorded;\n // a lost response after the commit is the same case. The retry still\n // works: the server discards a minted key nobody has ever authenticated\n // with once it is older than HOST_SELF_ROTATION_STALE_MINT_MS, which is\n // shorter than the backoff, and mints again (ENG-11826; it used to need a\n // `compromised` rotation, Obi Wan `9b564171021b` on #7114). That covers\n // the backoff retry; a manager that restarts inside the window gets\n // `mint_pending`, which this version retries and older versions do not.\n signal: AbortSignal.timeout(10_000),\n });\n if (res.status === 403) {\n // No rotation armed (or not permitted): the ordinary state, do nothing.\n return null;\n }\n if (res.status === 409) {\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n // `mint_pending` (ENG-11826): a mint for this request is too recent to\n // discard, or another ask got there first. Asking again after the backoff\n // can succeed, so it is THROWN, which the manager backs off and retries,\n // rather than returned as a refusal it would never ask past. Keyed on the\n // code, never the message.\n if (body['code'] === HOST_ROTATE_KEY_CONFLICT.mintPending) {\n throw new Error(`Host key rotation mint deferred: ${String(body['error'] ?? 'a mint is in flight')}`);\n }\n // `already_holds_minted_key`: the key this process presented IS the one\n // this request minted, so there is nothing to mint, only an ack to send.\n // Returned with the prefix the server recorded, which is what the ack must\n // name (Obi Wan `69040aab1cc7` on #7308). Without a prefix it falls through\n // to a refusal rather than acking something unnamed.\n if (\n body['code'] === HOST_ROTATE_KEY_CONFLICT.alreadyHoldsMintedKey &&\n typeof body['prefix'] === 'string' &&\n body['prefix']\n ) {\n return { alreadyHolds: body['prefix'] };\n }\n // Anything else is final for this request: a minted key is in use, or the\n // host is at its active-key cap. A retry gets the same answer, so the\n // caller stops rather than backing off and asking again forever\n // (CodeRabbit on #7114).\n return { refused: String(body['error'] ?? 'conflict') };\n }\n if (!res.ok) {\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n throw new Error(`Host key rotation mint failed (${res.status}): ${String(body['error'] ?? res.statusText)}`);\n }\n const data = (await res.json()) as { key?: { prefix?: string; raw_key?: string } };\n const prefix = data.key?.prefix;\n const rawKey = data.key?.raw_key;\n if (!prefix || !rawKey) return null;\n return { prefix, rawKey };\n}\n\n/**\n * ENG-11826: is this exact raw host key still usable?\n *\n * The manager calls it on a key it minted earlier and is HOLDING (it could not\n * persist it the first time), before persisting it again. The API discards a\n * minted key nobody has used once it is old enough, so a held key can be\n * revoked under the manager; persisting it would then bring the host back on a\n * revoked key at its next restart.\n *\n * Deliberately NOT the authenticated client's exchange: that one reloads the\n * shell profile and retries with whatever key it finds, which would answer\n * about a different key. This POSTs the held key once and reports only on it.\n *\n * A successful probe also stamps the key's `last_used_at`, which is what stops\n * the API discarding it afterwards; `exchange_api_key` makes that stamp and a\n * concurrent discard mutually exclusive.\n *\n * - `live`: the exchange succeeded.\n * - `unusable`: the API said the key is revoked, unknown or expired.\n * - `unknown`: anything else (network, 5xx, a refusal about the host rather\n * than the key). The caller keeps the key and tries again later.\n */\nexport async function probeHostKey(rawKey: string): Promise<'live' | 'unusable' | 'unknown'> {\n let res: Response;\n try {\n res = await fetch(`${requireHost()}/host/exchange`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ host_key: rawKey }),\n // Same bound as the mint, for the same reason: it runs on the poll cycle.\n signal: AbortSignal.timeout(10_000),\n });\n } catch {\n return 'unknown';\n }\n if (res.ok) return 'live';\n if (res.status === 401) {\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (body['code'] === 'key_revoked' || body['code'] === 'invalid_key' || body['code'] === 'key_expired') {\n return 'unusable';\n }\n }\n return 'unknown';\n}\n\n/**\n * ENG-11642: make the running process use a newly adopted host key.\n *\n * Two steps, and the second is not optional: the exchange cache is a single\n * slot that is NOT keyed by the raw key, so without forcing it the manager\n * would keep presenting a JWT minted from the old credential until that token\n * expired on its own.\n */\nexport function adoptHostKeyInProcess(rawKey: string): void {\n process.env['AGT_API_KEY'] = rawKey;\n forceNextExchange();\n}\n\n/**\n * Resolve the Bearer token from AGT_API_KEY via exchange.\n */\nasync function resolveAuth(): Promise<{ token: string; hostId: string }> {\n const apiKey = getApiKey();\n if (!apiKey) {\n throw new Error('AGT_API_KEY is not set. Export it with your host API key (tlk_...)');\n }\n\n const exchange = await exchangeApiKey(apiKey);\n return { token: exchange.token, hostId: exchange.hostId };\n}\n\n/**\n * Build standard request headers for authenticated API calls.\n * Team slug auto-resolves from the exchange, with AGT_TEAM\n * or config as an override.\n */\nasync function buildHeaders(): Promise<Record<string, string>> {\n const apiKey = getApiKey();\n if (!apiKey) {\n throw new Error('AGT_API_KEY is not set. Export it with your host API key (tlk_...)');\n }\n\n const exchange = await exchangeApiKey(apiKey);\n const headers: Record<string, string> = {\n 'Authorization': `Bearer ${exchange.token}`,\n 'Content-Type': 'application/json',\n // ENG-6410: lets the API stamp audit_log.agt_cli_version for host-runtime\n // actions so bug rates can be tracked per CLI version.\n 'X-Agt-Cli-Version': agtCliVersion,\n };\n\n // ENG-6412: carry the last heartbeat-returned config_hash so the API can stamp\n // audit_log.config_hash for host-runtime actions (config-correlation join).\n if (lastConfigHash) {\n headers['X-Config-Hash'] = lastConfigHash;\n }\n\n // Explicit team override takes precedence, then exchange auto-resolve\n const team = getActiveTeam() ?? exchange.teamSlug;\n if (team) {\n headers['X-Team-Slug'] = team;\n }\n\n return headers;\n}\n\nexport class ApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly body: Record<string, unknown>,\n ) {\n super((body['error'] as string) ?? `HTTP ${status}`);\n this.name = 'ApiError';\n }\n}\n\n/**\n * Execute a fetch request with automatic retry on 401 (expired token).\n * Invalidates the cached exchange and rebuilds headers on retry.\n */\nasync function fetchWithRetry(\n path: string,\n method: string,\n body?: unknown,\n extraHeaders?: Record<string, string>,\n): Promise<Response> {\n const baseHeaders = await buildHeaders();\n const headers: Record<string, string> = extraHeaders\n ? { ...baseHeaders, ...extraHeaders }\n : baseHeaders;\n const url = `${requireHost()}${path}`;\n const init: RequestInit = {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n };\n\n const res = await fetch(url, init);\n\n if (res.status === 401) {\n // Token may have expired between cache check and server verification.\n // Invalidate and retry once with a fresh token.\n invalidateExchange();\n const freshBase = await buildHeaders();\n const freshHeaders: Record<string, string> = extraHeaders\n ? { ...freshBase, ...extraHeaders }\n : freshBase;\n return fetch(url, { ...init, headers: freshHeaders });\n }\n\n return res;\n}\n\nasync function handleResponse<T>(res: Response): Promise<T> {\n const body = await res.json().catch(() => ({})) as Record<string, unknown>;\n\n if (!res.ok) {\n throw new ApiError(res.status, body);\n }\n\n return body as T;\n}\n\n/**\n * Typed HTTP client for the Augmented API.\n */\nexport const api = {\n async get<T = Record<string, unknown>>(path: string): Promise<T> {\n const res = await fetchWithRetry(path, 'GET');\n return handleResponse<T>(res);\n },\n\n async post<T = Record<string, unknown>>(\n path: string,\n body?: unknown,\n /**\n * ENG-5688: optional headers merged on top of the standard\n * Authorization + Content-Type + X-Team-Slug set. Used by the\n * impersonation flow to send `X-Agent-Impersonation` on /stop.\n * Extra headers win on key collision, by design.\n */\n extraHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await fetchWithRetry(path, 'POST', body, extraHeaders);\n return handleResponse<T>(res);\n },\n\n async patch<T = Record<string, unknown>>(path: string, body?: unknown): Promise<T> {\n const res = await fetchWithRetry(path, 'PATCH', body);\n return handleResponse<T>(res);\n },\n\n async put<T = Record<string, unknown>>(path: string, body?: unknown): Promise<T> {\n const res = await fetchWithRetry(path, 'PUT', body);\n return handleResponse<T>(res);\n },\n\n async del<T = Record<string, unknown>>(path: string): Promise<T> {\n const res = await fetchWithRetry(path, 'DELETE');\n return handleResponse<T>(res);\n },\n};\n\n/**\n * Resolve auth and return the host ID.\n */\nexport async function getHostId(): Promise<string | null> {\n const { hostId } = await resolveAuth();\n return hostId;\n}\n"],"mappings":";;;;;AAAA,SAAS,cAAc,eAAe,WAAW,kBAAkB;AACnE,SAAS,YAAY;AACrB,SAAS,eAAe;AAMxB,IAAM,gBAAgB,KAAK,QAAQ,GAAG,YAAY;AAClD,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