@indigoai-us/hq-cli 5.345.263 → 5.345.264

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 (62) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/contracts/host-canary-release.json +7 -7
  3. package/dist/command-catalog.generated.d.ts +37 -0
  4. package/dist/command-catalog.generated.js +46 -0
  5. package/dist/command-registration-plan.d.ts +6 -0
  6. package/dist/command-registration-plan.js +1 -0
  7. package/dist/commands/bot.d.ts +2 -0
  8. package/dist/commands/bot.js +4 -3
  9. package/dist/commands/sync-held.d.ts +11 -0
  10. package/dist/commands/sync-held.js +65 -1
  11. package/dist/commands/sync-telemetry-report.d.ts +5 -0
  12. package/dist/commands/sync-telemetry-report.js +239 -0
  13. package/dist/commands/sync-telemetry.d.ts +47 -0
  14. package/dist/commands/sync-telemetry.js +309 -0
  15. package/dist/index.js +107 -43
  16. package/dist/lib/bot/runnable.d.ts +17 -7
  17. package/dist/lib/bot/runnable.js +17 -10
  18. package/dist/lib/capacity/available.js +6 -2
  19. package/dist/lib/capacity/collectors/claude-oauth.d.ts +10 -256
  20. package/dist/lib/capacity/collectors/claude-oauth.js +19 -1078
  21. package/dist/lib/capacity/ledger.d.ts +12 -1
  22. package/dist/lib/capacity/ledger.js +15 -5
  23. package/dist/lib/capacity/route.d.ts +2 -0
  24. package/dist/lib/capacity/route.js +21 -4
  25. package/dist/lib/capacity/scheduler.js +2 -3
  26. package/dist/lib/capacity/sign-in.js +4 -4
  27. package/dist/lib/daemon/ops/skill-command.d.ts +2 -0
  28. package/dist/lib/daemon/ops/skill-command.js +7 -1
  29. package/dist/lib/doctor/checks/antigravity-wiring.d.ts +2 -1
  30. package/dist/lib/doctor/checks/antigravity-wiring.js +59 -3
  31. package/dist/lib/doctor/checks/hook-engine.d.ts +2 -0
  32. package/dist/lib/doctor/checks/hook-engine.js +100 -1
  33. package/dist/lib/doctor/checks/host-core.d.ts +1 -1
  34. package/dist/lib/doctor/checks/host-core.js +11 -4
  35. package/dist/lib/hook-engine/coverage.d.ts +19 -10
  36. package/dist/lib/hook-engine/coverage.js +103 -24
  37. package/dist/lib/hook-engine/native-precompact-compatibility.json +7 -1
  38. package/dist/lib/hook-engine/native-stop-compatibility.json +8 -4
  39. package/dist/lib/hook-engine/reconcile.js +49 -1
  40. package/dist/lib/install/antigravity-targets.d.ts +22 -0
  41. package/dist/lib/install/antigravity-targets.js +82 -0
  42. package/dist/main.js +8 -3
  43. package/dist/sentry-init.d.ts +7 -1
  44. package/dist/sentry-init.js +6 -2
  45. package/dist/sentry.d.ts +7 -0
  46. package/dist/sentry.js +16 -1
  47. package/dist/started-version.d.ts +13 -0
  48. package/dist/started-version.js +34 -0
  49. package/dist/startup-registration.d.ts +9 -9
  50. package/dist/startup-registration.js +42 -18
  51. package/dist/utils/client-health.d.ts +1 -0
  52. package/dist/utils/client-health.js +54 -11
  53. package/dist/utils/core-next-kill.d.ts +9 -0
  54. package/dist/utils/core-next-kill.js +22 -0
  55. package/dist/utils/host-registration.d.ts +4 -2
  56. package/dist/utils/host-registration.js +55 -7
  57. package/dist/utils/install-tree-recovery-markers.d.ts +45 -0
  58. package/dist/utils/install-tree-recovery-markers.js +70 -0
  59. package/dist/utils/install-tree-torn.d.ts +102 -5
  60. package/dist/utils/install-tree-torn.js +199 -2
  61. package/dist/utils/sentry-fingerprint.js +3 -0
  62. package/package.json +7 -7
@@ -0,0 +1,239 @@
1
+ export const SUPPORTED_SCHEMA_VERSION = 1;
2
+ export const TELEMETRY_VIEWS = [
3
+ "summary",
4
+ "machines",
5
+ "errors",
6
+ "people",
7
+ "folders",
8
+ "loops",
9
+ "ranking",
10
+ ];
11
+ const VIEW_TITLES = {
12
+ summary: "Sync health summary",
13
+ machines: "Sync by machine",
14
+ errors: "Recent sync errors",
15
+ people: "Sync use by person",
16
+ folders: "Uploads and downloads by folder",
17
+ loops: "Paths rewritten in a loop",
18
+ ranking: "Companies ranked by sync use",
19
+ };
20
+ const NOT_RECORDED_YET = "not_recorded_yet";
21
+ const NO_DATA = "no data";
22
+ const MAX_DEPTH = 6;
23
+ const FAILING_STATUSES = new Set(["failing", "failed", "error", "stalled", "unhealthy"]);
24
+ const HEALTHY_STATUSES = new Set(["ok", "healthy"]);
25
+ const NO_DATA_SINCE_KEYS = ["noDataSince", "no_data_since", "asOf", "lastSeenAt"];
26
+ const MACHINE_NAME_KEYS = ["hostname", "label", "name"];
27
+ const VALUE_WRAPPER_KEYS = new Set(["value", "reason", "asOf", "unit"]);
28
+ function isRecord(value) {
29
+ return value !== null && typeof value === "object" && !Array.isArray(value);
30
+ }
31
+ function clean(text) {
32
+ let result = "";
33
+ for (const char of text) {
34
+ const code = char.codePointAt(0) ?? 0;
35
+ result += code <= 0x1f || (code >= 0x7f && code <= 0x9f) ? " " : char;
36
+ }
37
+ return result;
38
+ }
39
+ function label(key) {
40
+ return clean(key)
41
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
42
+ .replace(/[_-]+/g, " ")
43
+ .toLowerCase();
44
+ }
45
+ function capitalize(text) {
46
+ return text.length === 0 ? text : text[0].toUpperCase() + text.slice(1);
47
+ }
48
+ function isScalar(value) {
49
+ return value === null || value === undefined || typeof value !== "object";
50
+ }
51
+ function scalarText(value) {
52
+ if (value === null || value === undefined)
53
+ return NO_DATA;
54
+ if (typeof value === "boolean")
55
+ return value ? "yes" : "no";
56
+ if (typeof value === "string")
57
+ return value.length === 0 ? NO_DATA : clean(value);
58
+ return clean(String(value));
59
+ }
60
+ function isValueWrapper(value) {
61
+ if (!isRecord(value) || !("value" in value) || !isScalar(value.value))
62
+ return false;
63
+ return Object.keys(value).every((key) => VALUE_WRAPPER_KEYS.has(key));
64
+ }
65
+ function valueWrapperText(wrapper) {
66
+ if (wrapper.value === null || wrapper.value === undefined) {
67
+ return typeof wrapper.reason === "string" && wrapper.reason.length > 0
68
+ ? `${NO_DATA} (${clean(wrapper.reason)})`
69
+ : NO_DATA;
70
+ }
71
+ const unit = typeof wrapper.unit === "string" ? ` ${clean(wrapper.unit)}` : "";
72
+ return `${scalarText(wrapper.value)}${unit}`;
73
+ }
74
+ function inlineText(value) {
75
+ if (isScalar(value))
76
+ return scalarText(value);
77
+ if (isValueWrapper(value))
78
+ return valueWrapperText(value);
79
+ if (Array.isArray(value)) {
80
+ if (value.length === 0)
81
+ return "none";
82
+ if (value.every(isScalar))
83
+ return value.map(scalarText).join(", ");
84
+ }
85
+ return null;
86
+ }
87
+ function isMachine(value) {
88
+ return isRecord(value) && typeof value.installId === "string" && typeof value.status === "string";
89
+ }
90
+ function machineRank(machine) {
91
+ const status = typeof machine.status === "string" ? machine.status.toLowerCase() : "";
92
+ if (FAILING_STATUSES.has(status) || machine.lastCycleSuccess === false)
93
+ return 0;
94
+ if (HEALTHY_STATUSES.has(status))
95
+ return 2;
96
+ return 1;
97
+ }
98
+ function failingFirst(items) {
99
+ if (!items.some(isMachine))
100
+ return [...items];
101
+ return items
102
+ .map((item, index) => ({ item, index, rank: isMachine(item) ? machineRank(item) : 1 }))
103
+ .sort((a, b) => a.rank - b.rank || a.index - b.index)
104
+ .map((entry) => entry.item);
105
+ }
106
+ function machineName(machine) {
107
+ const id = clean(String(machine.installId));
108
+ for (const key of MACHINE_NAME_KEYS) {
109
+ const name = machine[key];
110
+ if (typeof name === "string" && name.length > 0)
111
+ return `${id} (${clean(name)})`;
112
+ }
113
+ return id;
114
+ }
115
+ function truncatedLine(indent) {
116
+ return `${indent}List cut short by the server (truncated). Narrow it with --machine or a shorter --window.`;
117
+ }
118
+ function renderItem(item, indent, depth) {
119
+ if (!isRecord(item)) {
120
+ const inline = inlineText(item);
121
+ return inline !== null ? [`${indent}- ${inline}`] : [`${indent}-`, ...renderValue(item, `${indent} `, depth + 1)];
122
+ }
123
+ const skipped = new Set(["truncated"]);
124
+ let head = null;
125
+ if (isMachine(item)) {
126
+ skipped.add("installId");
127
+ for (const key of MACHINE_NAME_KEYS)
128
+ skipped.add(key);
129
+ skipped.add("status");
130
+ if (item.status === "no_data") {
131
+ const since = NO_DATA_SINCE_KEYS.map((key) => item[key]).find((value) => typeof value === "string" && value.length > 0);
132
+ return [`${indent}- ${machineName(item)}: no data since ${since ? clean(String(since)) : "an unknown time"}`];
133
+ }
134
+ const status = typeof item.status === "string" && item.status.length > 0 ? clean(item.status) : "status not reported";
135
+ head = `${machineName(item)}: ${status}`;
136
+ }
137
+ const inlineParts = [];
138
+ const nested = [];
139
+ for (const [key, value] of Object.entries(item)) {
140
+ if (skipped.has(key))
141
+ continue;
142
+ const inline = inlineText(value);
143
+ if (inline !== null) {
144
+ inlineParts.push(`${label(key)} ${inline}`);
145
+ }
146
+ else {
147
+ nested.push(`${indent} ${label(key)}:`, ...renderValue(value, `${indent} `, depth + 1));
148
+ }
149
+ }
150
+ const first = [head, inlineParts.join(", ")].filter((part) => part !== null && part.length > 0).join(", ");
151
+ const lines = [`${indent}- ${first.length > 0 ? first : "(no fields)"}`, ...nested];
152
+ if (item.truncated === true)
153
+ lines.push(truncatedLine(`${indent} `));
154
+ return lines;
155
+ }
156
+ function renderValue(value, indent, depth) {
157
+ if (depth > MAX_DEPTH)
158
+ return [`${indent}(more detail than this report shows; use --json)`];
159
+ const inline = inlineText(value);
160
+ if (inline !== null)
161
+ return [`${indent}${inline}`];
162
+ if (Array.isArray(value)) {
163
+ return failingFirst(value).flatMap((item) => renderItem(item, indent, depth));
164
+ }
165
+ const record = value;
166
+ const lines = [];
167
+ for (const [key, entry] of Object.entries(record)) {
168
+ if (key === "truncated")
169
+ continue;
170
+ const entryInline = inlineText(entry);
171
+ if (entryInline !== null) {
172
+ lines.push(`${indent}${label(key)}: ${entryInline}`);
173
+ }
174
+ else {
175
+ lines.push(`${indent}${label(key)}:`, ...renderValue(entry, `${indent} `, depth + 1));
176
+ }
177
+ }
178
+ if (lines.length === 0)
179
+ lines.push(`${indent}${NO_DATA}`);
180
+ if (record.truncated === true)
181
+ lines.push(truncatedLine(indent));
182
+ return lines;
183
+ }
184
+ function renderSection(name, section) {
185
+ const title = capitalize(label(name));
186
+ if (!isRecord(section))
187
+ return [`${title}: ${NO_DATA}`];
188
+ if (section.available === false) {
189
+ const reason = typeof section.reason === "string" ? section.reason : "";
190
+ if (reason.length === 0 || reason === NOT_RECORDED_YET)
191
+ return [`${title}: not recorded yet`];
192
+ return [`${title}: not available (${clean(reason)})`];
193
+ }
194
+ const asOf = typeof section.asOf === "string" && section.asOf.length > 0 ? ` (as of ${clean(section.asOf)})` : "";
195
+ const lines = [];
196
+ const inline = inlineText(section.data);
197
+ if (inline !== null) {
198
+ lines.push(`${title}${asOf}: ${inline}`);
199
+ }
200
+ else {
201
+ lines.push(`${title}${asOf}:`, ...renderValue(section.data, " ", 1));
202
+ }
203
+ if (section.truncated === true)
204
+ lines.push(truncatedLine(" "));
205
+ return lines;
206
+ }
207
+ export function renderTelemetryReport(body, view) {
208
+ const lines = [VIEW_TITLES[view]];
209
+ if (!isRecord(body)) {
210
+ lines.push("The server sent no report for this view.");
211
+ return lines;
212
+ }
213
+ const facts = [];
214
+ if (typeof body.companyUid === "string" && body.companyUid.length > 0)
215
+ facts.push(`company ${clean(body.companyUid)}`);
216
+ if (typeof body.window === "string" && body.window.length > 0)
217
+ facts.push(`window ${clean(body.window)}`);
218
+ if (typeof body.scope === "string" && body.scope.length > 0)
219
+ facts.push(`scope ${clean(body.scope)}`);
220
+ if (typeof body.generatedAt === "string" && body.generatedAt.length > 0) {
221
+ facts.push(`generated ${clean(body.generatedAt)}`);
222
+ }
223
+ if (facts.length > 0)
224
+ lines.push(capitalize(facts.join(", ")));
225
+ if (typeof body.schemaVersion === "number" && body.schemaVersion > SUPPORTED_SCHEMA_VERSION) {
226
+ lines.push(`This HQ CLI is older than the server (response schema ${body.schemaVersion}, this CLI reads ${SUPPORTED_SCHEMA_VERSION}). It shows the fields it understands; update HQ to see the rest.`);
227
+ }
228
+ lines.push("");
229
+ const sections = isRecord(body.sections) ? Object.entries(body.sections) : [];
230
+ if (sections.length === 0) {
231
+ lines.push("The server sent no sections for this view.");
232
+ }
233
+ for (const [name, section] of sections)
234
+ lines.push(...renderSection(name, section));
235
+ if (body.truncated === true)
236
+ lines.push(truncatedLine(""));
237
+ return lines;
238
+ }
239
+ //# sourceMappingURL=sync-telemetry-report.js.map
@@ -0,0 +1,47 @@
1
+ import { Command } from "commander";
2
+ import { type VaultApiOptions } from "../utils/vault-api.js";
3
+ export declare const TELEMETRY_WINDOWS: readonly ["1h", "24h", "7d", "30d"];
4
+ export type TelemetryWindow = (typeof TELEMETRY_WINDOWS)[number];
5
+ export declare const SYNC_TELEMETRY_PATH = "/v1/sync-telemetry";
6
+ export declare const SYNC_TELEMETRY_COMMAND = "hq sync telemetry";
7
+ export declare const SYNC_TELEMETRY_TIMEOUT_MS = 20000;
8
+ export declare const SYNC_TELEMETRY_MAX_RETRIES = 2;
9
+ export declare const SYNC_TELEMETRY_BACKOFF_MS: readonly [500, 1500];
10
+ export declare const SYNC_TELEMETRY_EXIT: {
11
+ readonly ok: 0;
12
+ readonly badArguments: 2;
13
+ readonly notSignedIn: 3;
14
+ readonly refused: 4;
15
+ readonly rateLimited: 5;
16
+ readonly unavailable: 6;
17
+ };
18
+ export interface SyncTelemetryOptions {
19
+ company?: string;
20
+ view?: string;
21
+ window?: string;
22
+ machine?: string;
23
+ json?: boolean;
24
+ }
25
+ export interface SyncTelemetryFailure {
26
+ ok: false;
27
+ code: string;
28
+ message: string;
29
+ status: number | null;
30
+ }
31
+ export interface SyncTelemetryDeps {
32
+ token: () => Promise<string>;
33
+ activeCompany: () => string | undefined;
34
+ companyUid: (token: string, company: string | undefined) => Promise<string>;
35
+ request: (options: VaultApiOptions) => Promise<Response>;
36
+ sleep: (ms: number) => Promise<void>;
37
+ timeoutMs: number;
38
+ out: (text: string) => void;
39
+ err: (text: string) => void;
40
+ }
41
+ export declare class PersonLoginRequiredError extends Error {
42
+ constructor();
43
+ }
44
+ export declare function runSyncTelemetry(options: SyncTelemetryOptions, deps: SyncTelemetryDeps): Promise<number>;
45
+ export declare function createDefaultSyncTelemetryDeps(): SyncTelemetryDeps;
46
+ export declare function registerSyncTelemetryCommand(syncCmd: Command): void;
47
+ //# sourceMappingURL=sync-telemetry.d.ts.map
@@ -0,0 +1,309 @@
1
+ import { isAuthError } from "../utils/auth-error.js";
2
+ import { isCompanySelectionError } from "../utils/company-selection-error.js";
3
+ import { ensureCognitoToken } from "../utils/cognito-session.js";
4
+ import { isExpectedUserError } from "../utils/expected-cli-error.js";
5
+ import { findHqRootAncestor } from "../utils/hq-roots-core.js";
6
+ import { networkTransportErrorCode } from "../utils/network-transport-error.js";
7
+ import { isPlanGateError } from "../utils/plan-gate-error.js";
8
+ import { peekHqApiKey } from "../utils/resolve-vault-credential.js";
9
+ import { getCompanyUid, looksLikeCompanyUid, vaultApiFetch } from "../utils/vault-api.js";
10
+ import { readActiveCompanySlug } from "./sync-mode.js";
11
+ import { TELEMETRY_VIEWS, renderTelemetryReport } from "./sync-telemetry-report.js";
12
+ export const TELEMETRY_WINDOWS = ["1h", "24h", "7d", "30d"];
13
+ export const SYNC_TELEMETRY_PATH = "/v1/sync-telemetry";
14
+ export const SYNC_TELEMETRY_COMMAND = "hq sync telemetry";
15
+ export const SYNC_TELEMETRY_TIMEOUT_MS = 20_000;
16
+ export const SYNC_TELEMETRY_MAX_RETRIES = 2;
17
+ export const SYNC_TELEMETRY_BACKOFF_MS = [500, 1_500];
18
+ const RETRY_AFTER_CAP_MS = 5_000;
19
+ export const SYNC_TELEMETRY_EXIT = {
20
+ ok: 0,
21
+ badArguments: 2,
22
+ notSignedIn: 3,
23
+ refused: 4,
24
+ rateLimited: 5,
25
+ unavailable: 6,
26
+ };
27
+ const COMPANY_UID_PATTERN = /^cmp_[A-Za-z0-9_-]{1,80}$/;
28
+ const MACHINE_ID_PATTERN = /^[A-Za-z0-9._:-]{1,200}$/;
29
+ const SERVER_CODE_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/;
30
+ export class PersonLoginRequiredError extends Error {
31
+ constructor() {
32
+ super("sync telemetry needs a person sign-in");
33
+ this.name = "PersonLoginRequiredError";
34
+ }
35
+ }
36
+ class TelemetryTimeoutError extends Error {
37
+ constructor() {
38
+ super("sync telemetry request timed out");
39
+ this.name = "TelemetryTimeoutError";
40
+ }
41
+ }
42
+ function outcome(code, message, status, exitCode, retry = {}) {
43
+ return {
44
+ failure: { ok: false, code, message, status },
45
+ exitCode,
46
+ retryable: retry.retryable === true,
47
+ ...(retry.retryAfterMs !== undefined ? { retryAfterMs: retry.retryAfterMs } : {}),
48
+ };
49
+ }
50
+ function badArguments(message) {
51
+ return outcome("bad_arguments", message, null, SYNC_TELEMETRY_EXIT.badArguments);
52
+ }
53
+ function notSignedIn(status = null) {
54
+ return outcome("not_signed_in", "You are not signed in to HQ, or the session has expired. Run `hq login` and try again.", status, SYNC_TELEMETRY_EXIT.notSignedIn);
55
+ }
56
+ function transportOutcome(err) {
57
+ if (err instanceof TelemetryTimeoutError) {
58
+ return outcome("timeout", "HQ did not answer in time. Check the connection and try again.", null, SYNC_TELEMETRY_EXIT.unavailable, { retryable: true });
59
+ }
60
+ if (isPlanGateError(err) || isExpectedUserError(err)) {
61
+ return outcome("request_not_sent", "HQ could not serve this request for the current sign-in. Sign in as a person with `hq login` and try again.", null, SYNC_TELEMETRY_EXIT.unavailable);
62
+ }
63
+ const code = networkTransportErrorCode(err);
64
+ return outcome("network_error", `Could not reach HQ${code ? ` (${code})` : ""}. Check the connection and try again.`, null, SYNC_TELEMETRY_EXIT.unavailable, { retryable: true });
65
+ }
66
+ function serverCodeFrom(text) {
67
+ let body;
68
+ try {
69
+ body = JSON.parse(text);
70
+ }
71
+ catch {
72
+ return undefined;
73
+ }
74
+ if (body === null || typeof body !== "object" || Array.isArray(body))
75
+ return undefined;
76
+ const root = body;
77
+ const nested = root.error !== null && typeof root.error === "object" && !Array.isArray(root.error)
78
+ ? root.error.code
79
+ : undefined;
80
+ for (const candidate of [root.code, nested, root.error]) {
81
+ if (typeof candidate === "string" && SERVER_CODE_PATTERN.test(candidate))
82
+ return candidate;
83
+ }
84
+ return undefined;
85
+ }
86
+ function retryAfterMs(response) {
87
+ const raw = response.headers.get("retry-after");
88
+ if (!raw)
89
+ return undefined;
90
+ const seconds = Number(raw);
91
+ if (!Number.isFinite(seconds) || seconds < 0)
92
+ return undefined;
93
+ return Math.min(RETRY_AFTER_CAP_MS, Math.round(seconds * 1000));
94
+ }
95
+ async function statusOutcome(response) {
96
+ const status = response.status;
97
+ if (status === 400) {
98
+ const code = serverCodeFrom(await response.text().catch(() => ""));
99
+ return outcome("bad_arguments", `HQ rejected the request arguments${code ? ` (${code})` : ""}. Check --company, --view, --window and --machine.`, status, SYNC_TELEMETRY_EXIT.badArguments);
100
+ }
101
+ await response.body?.cancel().catch(() => undefined);
102
+ if (status === 401)
103
+ return notSignedIn(status);
104
+ if (status === 403) {
105
+ return outcome("refused", "HQ refused this request. Sync telemetry is open to a signed-in person who is an owner or admin of the company. Agent and machine sign-ins are refused.", status, SYNC_TELEMETRY_EXIT.refused);
106
+ }
107
+ if (status === 404) {
108
+ return outcome("not_available", "This HQ server does not serve sync telemetry yet.", status, SYNC_TELEMETRY_EXIT.unavailable);
109
+ }
110
+ if (status === 429) {
111
+ return outcome("rate_limited", "HQ is limiting sync telemetry requests for this sign-in (60 a minute). Wait a minute and try again.", status, SYNC_TELEMETRY_EXIT.rateLimited, { retryable: true, retryAfterMs: retryAfterMs(response) });
112
+ }
113
+ if (status >= 500) {
114
+ return outcome("server_error", `HQ returned a server error (HTTP ${status}). Try again shortly.`, status, SYNC_TELEMETRY_EXIT.unavailable, { retryable: true });
115
+ }
116
+ return outcome("unexpected_status", `HQ answered with an unexpected status (HTTP ${status}).`, status, SYNC_TELEMETRY_EXIT.unavailable);
117
+ }
118
+ async function attempt(deps, token, query) {
119
+ const controller = new AbortController();
120
+ const timeout = new TelemetryTimeoutError();
121
+ let timer;
122
+ const expired = new Promise((_, reject) => {
123
+ timer = setTimeout(() => {
124
+ controller.abort(timeout);
125
+ reject(timeout);
126
+ }, deps.timeoutMs);
127
+ });
128
+ const exchange = (async () => {
129
+ const response = await deps.request({ token, path: SYNC_TELEMETRY_PATH, query, signal: controller.signal });
130
+ if (!response.ok)
131
+ return statusOutcome(response);
132
+ return { text: await response.text() };
133
+ })();
134
+ exchange.catch(() => undefined);
135
+ try {
136
+ return await Promise.race([exchange, expired]);
137
+ }
138
+ catch (err) {
139
+ return transportOutcome(controller.signal.aborted ? timeout : err);
140
+ }
141
+ finally {
142
+ clearTimeout(timer);
143
+ }
144
+ }
145
+ async function fetchTelemetry(deps, token, query) {
146
+ for (let retries = 0;; retries++) {
147
+ const result = await attempt(deps, token, query);
148
+ if ("text" in result)
149
+ return result;
150
+ if (!result.retryable || retries >= SYNC_TELEMETRY_MAX_RETRIES)
151
+ return result;
152
+ const backoff = SYNC_TELEMETRY_BACKOFF_MS[retries] ?? SYNC_TELEMETRY_BACKOFF_MS[SYNC_TELEMETRY_BACKOFF_MS.length - 1];
153
+ await deps.sleep(Math.max(backoff, result.retryAfterMs ?? 0));
154
+ }
155
+ }
156
+ function tokenOutcome(err) {
157
+ if (err instanceof PersonLoginRequiredError) {
158
+ return outcome("person_login_required", `${SYNC_TELEMETRY_COMMAND} uses a person's HQ sign-in and does not accept an API key. Unset HQ_API_KEY and run \`hq login\`.`, null, SYNC_TELEMETRY_EXIT.notSignedIn);
159
+ }
160
+ if (networkTransportErrorCode(err))
161
+ return transportOutcome(err);
162
+ return notSignedIn();
163
+ }
164
+ function companyOutcome(err) {
165
+ if (isAuthError(err))
166
+ return notSignedIn(401);
167
+ if (isCompanySelectionError(err)) {
168
+ return badArguments("More than one company, or none, matches this sign-in. Pass --company <slug>.");
169
+ }
170
+ if (isExpectedUserError(err)) {
171
+ return badArguments("That company was not found among the companies this sign-in can reach. Check --company.");
172
+ }
173
+ return outcome("company_lookup_failed", "Could not look up the company on HQ. Check the connection and try again.", null, SYNC_TELEMETRY_EXIT.unavailable);
174
+ }
175
+ function report(deps, json, result) {
176
+ if (json)
177
+ deps.out(`${JSON.stringify(result.failure)}\n`);
178
+ else
179
+ deps.err(`${result.failure.message}\n`);
180
+ return result.exitCode;
181
+ }
182
+ export async function runSyncTelemetry(options, deps) {
183
+ const json = options.json === true;
184
+ const view = (options.view ?? "summary");
185
+ const window = options.window ?? "24h";
186
+ if (!TELEMETRY_VIEWS.includes(view)) {
187
+ return report(deps, json, badArguments(`--view must be one of: ${TELEMETRY_VIEWS.join(", ")}.`));
188
+ }
189
+ if (!TELEMETRY_WINDOWS.includes(window)) {
190
+ return report(deps, json, badArguments(`--window must be one of: ${TELEMETRY_WINDOWS.join(", ")}.`));
191
+ }
192
+ if (options.machine !== undefined && !MACHINE_ID_PATTERN.test(options.machine)) {
193
+ return report(deps, json, badArguments("--machine must be an install id (letters, digits, '.', '_', ':' or '-')."));
194
+ }
195
+ if (view === "ranking" && options.company !== undefined) {
196
+ return report(deps, json, badArguments("--view ranking covers every company and takes no --company."));
197
+ }
198
+ if (options.company !== undefined && looksLikeCompanyUid(options.company) && !COMPANY_UID_PATTERN.test(options.company)) {
199
+ return report(deps, json, badArguments("--company is not a valid company uid."));
200
+ }
201
+ let token;
202
+ try {
203
+ token = await deps.token();
204
+ }
205
+ catch (err) {
206
+ return report(deps, json, tokenOutcome(err));
207
+ }
208
+ const query = { view, window };
209
+ if (view !== "ranking") {
210
+ try {
211
+ query.companyUid = await deps.companyUid(token, options.company ?? deps.activeCompany());
212
+ }
213
+ catch (err) {
214
+ return report(deps, json, companyOutcome(err));
215
+ }
216
+ }
217
+ if (options.machine !== undefined)
218
+ query.machine = options.machine;
219
+ const result = await fetchTelemetry(deps, token, query);
220
+ if (!("text" in result))
221
+ return report(deps, json, result);
222
+ let body;
223
+ try {
224
+ body = JSON.parse(result.text);
225
+ }
226
+ catch {
227
+ body = undefined;
228
+ }
229
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
230
+ return report(deps, json, outcome("invalid_response", "HQ answered with something that is not a sync telemetry report. Try again shortly.", 200, SYNC_TELEMETRY_EXIT.unavailable));
231
+ }
232
+ if (json) {
233
+ deps.out(result.text.endsWith("\n") ? result.text : `${result.text}\n`);
234
+ }
235
+ else {
236
+ deps.out(`${renderTelemetryReport(body, view).join("\n")}\n`);
237
+ }
238
+ return SYNC_TELEMETRY_EXIT.ok;
239
+ }
240
+ export function createDefaultSyncTelemetryDeps() {
241
+ return {
242
+ token: async () => {
243
+ if (peekHqApiKey() !== undefined)
244
+ throw new PersonLoginRequiredError();
245
+ return ensureCognitoToken({ interactive: false });
246
+ },
247
+ activeCompany: () => {
248
+ const root = findHqRootAncestor(process.cwd());
249
+ return root ? readActiveCompanySlug(root) : undefined;
250
+ },
251
+ companyUid: async (token, company) => company !== undefined && looksLikeCompanyUid(company) ? company : getCompanyUid(token, company),
252
+ request: vaultApiFetch,
253
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
254
+ timeoutMs: SYNC_TELEMETRY_TIMEOUT_MS,
255
+ out: (text) => {
256
+ process.stdout.write(text);
257
+ },
258
+ err: (text) => {
259
+ process.stderr.write(text);
260
+ },
261
+ };
262
+ }
263
+ const HELP_TEXT = `
264
+ Reads sync health for a company from the HQ server. It changes nothing on this
265
+ computer or on the server, and it does not start or stop a sync.
266
+
267
+ You must be signed in as a person (hq login) who is an owner or admin of the
268
+ company. Agent and machine sign-ins are refused by the server.
269
+
270
+ Views:
271
+ summary overall health, held files and safety counters
272
+ machines one line per machine, failing machines first
273
+ errors recent sync errors with their codes
274
+ people billed sync use per person
275
+ folders uploads and downloads per folder
276
+ loops paths rewritten on a fixed interval
277
+ ranking companies ranked by sync use (Indigo staff; takes no --company)
278
+
279
+ A view or section the server does not record yet prints "not recorded yet".
280
+
281
+ Exit codes:
282
+ 0 report printed
283
+ 2 bad arguments
284
+ 3 not signed in
285
+ 4 refused by the server
286
+ 5 rate limited
287
+ 6 server or network failure
288
+
289
+ Examples:
290
+ hq sync telemetry --company acme
291
+ hq sync telemetry --company acme --view machines --window 7d
292
+ hq sync telemetry --company acme --view errors --machine <installId>
293
+ hq sync telemetry --company acme --json
294
+ `;
295
+ export function registerSyncTelemetryCommand(syncCmd) {
296
+ syncCmd
297
+ .command("telemetry")
298
+ .description("Show sync health, errors and usage for a company, read from the HQ server")
299
+ .option("--company <company>", "Company slug or cmp_ uid (defaults to the active company, else your only company)")
300
+ .option("--view <view>", `What to show: ${TELEMETRY_VIEWS.join(", ")}`, "summary")
301
+ .option("--window <window>", `Time window: ${TELEMETRY_WINDOWS.join(", ")}`, "24h")
302
+ .option("--machine <installId>", "Limit the report to one machine by its install id")
303
+ .option("--json", "Print the server response as JSON; failures print one JSON object")
304
+ .addHelpText("after", HELP_TEXT)
305
+ .action(async (options) => {
306
+ process.exitCode = await runSyncTelemetry(options, createDefaultSyncTelemetryDeps());
307
+ });
308
+ }
309
+ //# sourceMappingURL=sync-telemetry.js.map