@indigoai-us/hq-cli 5.345.214 → 5.345.215-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/command-catalog.generated.d.ts +134 -7
  3. package/dist/command-catalog.generated.js +168 -7
  4. package/dist/commands/agents.d.ts +51 -1
  5. package/dist/commands/agents.js +154 -2
  6. package/dist/commands/bot-jobs.d.ts +2 -15
  7. package/dist/commands/bot-jobs.js +2 -94
  8. package/dist/commands/bot-runtime.d.ts +46 -5
  9. package/dist/commands/bot-runtime.js +228 -18
  10. package/dist/commands/bot.d.ts +16 -9
  11. package/dist/commands/bot.js +169 -51
  12. package/dist/commands/cloud.d.ts +66 -13
  13. package/dist/commands/cloud.js +120 -39
  14. package/dist/commands/company-restore.d.ts +23 -0
  15. package/dist/commands/company-restore.js +128 -0
  16. package/dist/commands/company.js +2 -0
  17. package/dist/commands/integrations-connect.d.ts +10 -3
  18. package/dist/commands/integrations-connect.js +87 -13
  19. package/dist/commands/lanes.js +26 -9
  20. package/dist/commands/sources.js +6 -0
  21. package/dist/commands/storage-offload.d.ts +12 -0
  22. package/dist/commands/storage-offload.js +41 -3
  23. package/dist/commands/sync-mode.js +5 -0
  24. package/dist/commands/whoami.js +4 -0
  25. package/dist/lib/bot/config.d.ts +1 -0
  26. package/dist/lib/bot/config.js +10 -0
  27. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  28. package/dist/lib/bot/eventbridge-cron.js +104 -0
  29. package/dist/lib/bot/fleet-local.d.ts +33 -1
  30. package/dist/lib/bot/fleet-local.js +215 -31
  31. package/dist/lib/bot/fleet-python.d.ts +3 -0
  32. package/dist/lib/bot/fleet-python.js +34 -4
  33. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  34. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  35. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  36. package/dist/lib/bot/legacy-provider-login.js +19 -2
  37. package/dist/lib/bot/prompt.js +1 -1
  38. package/dist/lib/bot/readiness.d.ts +8 -0
  39. package/dist/lib/bot/readiness.js +17 -3
  40. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  41. package/dist/lib/bot/runtime-auth.js +94 -3
  42. package/dist/lib/bot/status.d.ts +2 -0
  43. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  44. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  45. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  46. package/dist/lib/capacity/collectors/grok.js +56 -5
  47. package/dist/lib/daemon/catalog.js +11 -1
  48. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  49. package/dist/lib/db/sqlite-binding.js +1 -1
  50. package/dist/lib/delivery/artifacts.d.ts +99 -0
  51. package/dist/lib/delivery/artifacts.js +548 -0
  52. package/dist/lib/delivery/backup.d.ts +78 -0
  53. package/dist/lib/delivery/backup.js +343 -0
  54. package/dist/lib/delivery/cache.d.ts +29 -0
  55. package/dist/lib/delivery/cache.js +33 -0
  56. package/dist/lib/delivery/contracts.d.ts +142 -0
  57. package/dist/lib/delivery/contracts.js +289 -0
  58. package/dist/lib/delivery/credentials.d.ts +54 -0
  59. package/dist/lib/delivery/credentials.js +119 -0
  60. package/dist/lib/delivery/enrollment.d.ts +142 -0
  61. package/dist/lib/delivery/enrollment.js +382 -0
  62. package/dist/lib/delivery/identity.d.ts +25 -0
  63. package/dist/lib/delivery/identity.js +82 -0
  64. package/dist/lib/delivery/inbox.d.ts +116 -0
  65. package/dist/lib/delivery/inbox.js +260 -0
  66. package/dist/lib/delivery/migrations.d.ts +139 -0
  67. package/dist/lib/delivery/migrations.js +623 -0
  68. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  69. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  70. package/dist/lib/delivery/mqtt.d.ts +61 -0
  71. package/dist/lib/delivery/mqtt.js +112 -0
  72. package/dist/lib/delivery/outbox.d.ts +95 -0
  73. package/dist/lib/delivery/outbox.js +187 -0
  74. package/dist/lib/delivery/provenance.d.ts +129 -0
  75. package/dist/lib/delivery/provenance.js +93 -0
  76. package/dist/lib/delivery/reconciler.d.ts +151 -0
  77. package/dist/lib/delivery/reconciler.js +492 -0
  78. package/dist/lib/delivery/restore.d.ts +35 -0
  79. package/dist/lib/delivery/restore.js +134 -0
  80. package/dist/lib/delivery/store.d.ts +161 -0
  81. package/dist/lib/delivery/store.js +940 -0
  82. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  83. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  84. package/dist/lib/delivery/workers/macos.d.ts +176 -0
  85. package/dist/lib/delivery/workers/macos.js +901 -0
  86. package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
  87. package/dist/lib/delivery/workers/windows-boundary.js +693 -0
  88. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  89. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  90. package/dist/lib/delivery/workers/windows.d.ts +241 -0
  91. package/dist/lib/delivery/workers/windows.js +608 -0
  92. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  93. package/dist/lib/install/provider-wrappers.js +68 -3
  94. package/dist/utils/cognito-callback-port.d.ts +14 -0
  95. package/dist/utils/cognito-callback-port.js +24 -0
  96. package/dist/utils/cognito-session.js +3 -3
  97. package/dist/utils/deleted-company-notice.d.ts +59 -0
  98. package/dist/utils/deleted-company-notice.js +156 -0
  99. package/dist/utils/login-browser.d.ts +1 -1
  100. package/dist/utils/login-browser.js +7 -5
  101. package/dist/utils/resident-package-preload.js +30 -15
  102. package/dist/utils/vault-api.js +7 -0
  103. package/package.json +7 -7
@@ -1899,6 +1899,8 @@ export function registerCloudCommands(program) {
1899
1899
  .description("Show local sync journal summary")
1900
1900
  .option("--hq-root <path>", `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`, DEFAULT_HQ_ROOT)
1901
1901
  .option("--company <slug>", "Show only this company's journal (company slug)")
1902
+ .option("--all", "List every local-only file instead of the first 20 per company")
1903
+ .option("--json", "Print the full status as JSON (every list uncapped) instead of text")
1902
1904
  .action((options, command) => {
1903
1905
  const explicitHqRoot = command.getOptionValueSource("hqRoot") === "cli";
1904
1906
  try {
@@ -1944,6 +1946,11 @@ export function registerCloudCommands(program) {
1944
1946
  const journals = companyFilter
1945
1947
  ? listJournals().filter((j) => j.slug === companyFilter)
1946
1948
  : listJournals();
1949
+ if (options.json) {
1950
+ console.log(JSON.stringify(buildSyncStatusJson({ hqRoot, activeCompany, stateDir, companyFilter, journals }), null, 2));
1951
+ return;
1952
+ }
1953
+ const showAll = options.all === true;
1947
1954
  let grandFiles = 0;
1948
1955
  let grandBytes = 0;
1949
1956
  let grandLastSync = "";
@@ -1991,8 +1998,8 @@ export function registerCloudCommands(program) {
1991
1998
  console.log(` Total size: ${formatBytes(grandBytes)}`);
1992
1999
  console.log(` Last sync: ${grandLastSync || "never"}`);
1993
2000
  }
1994
- printReadOnlyLocalOnly(hqRoot, journals);
1995
- printServerOwnedLocalOnly(hqRoot, journals);
2001
+ printReadOnlyLocalOnly(hqRoot, journals, undefined, { all: showAll });
2002
+ printServerOwnedLocalOnly(hqRoot, journals, undefined, { all: showAll });
1996
2003
  }
1997
2004
  catch (err) {
1998
2005
  console.error(chalk.red("✗ Status failed:"), err instanceof Error ? err.message : String(err));
@@ -2838,23 +2845,20 @@ function readActiveCompanySlug(hqRoot) {
2838
2845
  return undefined;
2839
2846
  }
2840
2847
  }
2848
+ /** Max paths listed per company when `--all` is not passed. */
2849
+ const STATUS_LIST_CAP = 20;
2841
2850
  /**
2842
- * Human-friendly label for a journal slug in `hq sync status`. The
2843
- * personal-vault fanout slot and the legacy `companies/personal` company both
2844
- * carry opaque slugs; everything else is a real company slug shown as-is.
2851
+ * Collect local files under read-only vault prefixes that are not in the sync
2852
+ * journal. `all` lifts the per-company cap so every path is returned; `total`
2853
+ * always counts every match. Local reads only, no network.
2845
2854
  */
2846
- /**
2847
- * `hq sync status`: list local files under read-only vault prefixes that are
2848
- * not in the sync journal. Push never uploads them (feedback_510661bc,
2849
- * Shepherd #2813). Uses only the local vault-access manifest and the journals
2850
- * already loaded, with no network calls. Prints nothing when nothing applies.
2851
- */
2852
- export function printReadOnlyLocalOnly(hqRoot, journals, log = (line) => console.log(line)) {
2855
+ export function collectReadOnlyLocalOnly(hqRoot, journals, opts = {}) {
2853
2856
  const companies = readVaultAccessManifest(hqRoot)?.companies;
2854
2857
  if (!companies)
2855
- return 0;
2858
+ return [];
2859
+ const limit = opts.all ? Number.POSITIVE_INFINITY : STATUS_LIST_CAP;
2856
2860
  let shouldSync;
2857
- let grand = 0;
2861
+ const groups = [];
2858
2862
  for (const [slug, company] of Object.entries(companies)) {
2859
2863
  if (!isGrantEnforced(company))
2860
2864
  continue;
@@ -2870,16 +2874,109 @@ export function printReadOnlyLocalOnly(hqRoot, journals, log = (line) => console
2870
2874
  }
2871
2875
  const journal = journals.find((j) => j.slug === slug)?.journal;
2872
2876
  const journalKeys = new Set(Object.keys(journal?.files ?? {}));
2873
- const found = findReadOnlyLocalOnly({ hqRoot, slug, company, journalKeys, shouldSync });
2877
+ const found = findReadOnlyLocalOnly({ hqRoot, slug, company, journalKeys, shouldSync, limit });
2878
+ if (found.total === 0)
2879
+ continue;
2880
+ groups.push({ slug, total: found.total, files: found.files });
2881
+ }
2882
+ return groups;
2883
+ }
2884
+ /**
2885
+ * Collect local files under server-owned folders (sources/, signals/,
2886
+ * ontology/ outside entities/) that are not in the sync journal. `all` lifts
2887
+ * the per-company cap. Local reads only, no network.
2888
+ */
2889
+ export function collectServerOwnedLocalOnly(hqRoot, journals, opts = {}) {
2890
+ const limit = opts.all ? Number.POSITIVE_INFINITY : STATUS_LIST_CAP;
2891
+ let shouldSync;
2892
+ const groups = [];
2893
+ for (const { slug, journal } of journals) {
2894
+ if (slug === PERSONAL_VAULT_JOURNAL_SLUG)
2895
+ continue;
2896
+ if (!fs.existsSync(path.join(hqRoot, "companies", slug)))
2897
+ continue;
2898
+ if (!shouldSync) {
2899
+ try {
2900
+ shouldSync = createIgnoreFilter(hqRoot);
2901
+ }
2902
+ catch {
2903
+ shouldSync = () => true;
2904
+ }
2905
+ }
2906
+ const journalKeys = new Set(Object.keys(journal.files ?? {}));
2907
+ const found = findServerOwnedLocalOnly({ hqRoot, slug, journalKeys, shouldSync, limit });
2874
2908
  if (found.total === 0)
2875
2909
  continue;
2910
+ groups.push({ slug, total: found.total, files: found.files });
2911
+ }
2912
+ return groups;
2913
+ }
2914
+ /**
2915
+ * Full machine-readable `hq sync status`: scope summaries plus both local-only
2916
+ * lists with every path (no cap).
2917
+ */
2918
+ export function buildSyncStatusJson(input) {
2919
+ const { hqRoot, journals } = input;
2920
+ let totalFiles = 0;
2921
+ let totalBytes = 0;
2922
+ let lastSyncAll = "";
2923
+ const scopes = journals.map((j) => {
2924
+ const live = Object.values(j.journal.files ?? {}).filter((e) => !e.removedAt);
2925
+ const bytes = live.reduce((acc, e) => acc + (e.size ?? 0), 0);
2926
+ const lastSync = j.journal.lastSync ||
2927
+ live
2928
+ .map((e) => e.syncedAt)
2929
+ .filter((t) => typeof t === "string")
2930
+ .sort()
2931
+ .at(-1) ||
2932
+ "never";
2933
+ totalFiles += live.length;
2934
+ totalBytes += bytes;
2935
+ if (lastSync !== "never" && lastSync > lastSyncAll)
2936
+ lastSyncAll = lastSync;
2937
+ return {
2938
+ slug: j.slug,
2939
+ label: scopeLabel(j.slug),
2940
+ trackedFiles: live.length,
2941
+ totalBytes: bytes,
2942
+ lastSync,
2943
+ journalPath: j.path,
2944
+ };
2945
+ });
2946
+ const readOnly = collectReadOnlyLocalOnly(hqRoot, journals, { all: true });
2947
+ const serverOwned = collectServerOwnedLocalOnly(hqRoot, journals, { all: true });
2948
+ return {
2949
+ hqRoot,
2950
+ activeCompany: input.activeCompany ?? null,
2951
+ stateDir: input.stateDir,
2952
+ company: input.companyFilter ?? null,
2953
+ journals: journals.length,
2954
+ scopes,
2955
+ totals: { trackedFiles: totalFiles, totalBytes, lastSync: lastSyncAll || "never" },
2956
+ readOnlyLocalOnly: readOnly,
2957
+ serverOwnedLocalOnly: {
2958
+ folders: [...SERVER_OWNED_FOLDERS],
2959
+ companies: serverOwned,
2960
+ },
2961
+ };
2962
+ }
2963
+ /**
2964
+ * `hq sync status`: list local files under read-only vault prefixes that are
2965
+ * not in the sync journal. Push never uploads them (feedback_510661bc,
2966
+ * Shepherd #2813). Uses only the local vault-access manifest and the journals
2967
+ * already loaded, with no network calls. Prints nothing when nothing applies.
2968
+ * Capped at 20 per company unless `opts.all` (feedback_f29d004a).
2969
+ */
2970
+ export function printReadOnlyLocalOnly(hqRoot, journals, log = (line) => console.log(line), opts = {}) {
2971
+ let grand = 0;
2972
+ for (const found of collectReadOnlyLocalOnly(hqRoot, journals, opts)) {
2876
2973
  grand += found.total;
2877
- log(chalk.yellow(`\n ! ${slug}: ${found.total} local-only file(s) under read-only access will not upload`));
2974
+ log(chalk.yellow(`\n ! ${found.slug}: ${found.total} local-only file(s) under read-only access will not upload`));
2878
2975
  for (const f of found.files) {
2879
2976
  log(` ${f.path}${f.permission === "none" ? chalk.dim(" (no access)") : ""}`);
2880
2977
  }
2881
2978
  if (found.total > found.files.length) {
2882
- log(chalk.dim(` ... and ${found.total - found.files.length} more`));
2979
+ log(chalk.dim(` ... and ${found.total - found.files.length} more (use --all to list every file)`));
2883
2980
  }
2884
2981
  }
2885
2982
  if (grand > 0) {
@@ -2895,36 +2992,20 @@ export function printReadOnlyLocalOnly(hqRoot, journals, log = (line) => console
2895
2992
  * the recurring runner skips them quietly, so a file written locally there
2896
2993
  * never reaches the vault and `pendingFiles: 0` still reports a clean tree
2897
2994
  * (feedback_0414d71c). Uses only the journals already loaded, with no
2898
- * network calls. Prints nothing when nothing applies.
2995
+ * network calls. Prints nothing when nothing applies. Capped at 20 per
2996
+ * company unless `opts.all` (feedback_f29d004a).
2899
2997
  */
2900
- export function printServerOwnedLocalOnly(hqRoot, journals, log = (line) => console.log(line)) {
2901
- let shouldSync;
2998
+ export function printServerOwnedLocalOnly(hqRoot, journals, log = (line) => console.log(line), opts = {}) {
2902
2999
  let grand = 0;
2903
- for (const { slug, journal } of journals) {
2904
- if (slug === PERSONAL_VAULT_JOURNAL_SLUG)
2905
- continue;
2906
- if (!fs.existsSync(path.join(hqRoot, "companies", slug)))
2907
- continue;
2908
- if (!shouldSync) {
2909
- try {
2910
- shouldSync = createIgnoreFilter(hqRoot);
2911
- }
2912
- catch {
2913
- shouldSync = () => true;
2914
- }
2915
- }
2916
- const journalKeys = new Set(Object.keys(journal.files ?? {}));
2917
- const found = findServerOwnedLocalOnly({ hqRoot, slug, journalKeys, shouldSync });
2918
- if (found.total === 0)
2919
- continue;
3000
+ for (const found of collectServerOwnedLocalOnly(hqRoot, journals, opts)) {
2920
3001
  grand += found.total;
2921
- log(chalk.yellow(`\n ! ${slug}: ${found.total} local-only file(s) under server-owned folders ` +
3002
+ log(chalk.yellow(`\n ! ${found.slug}: ${found.total} local-only file(s) under server-owned folders ` +
2922
3003
  `(${SERVER_OWNED_FOLDERS.map((f) => `${f}/`).join(", ")}) never upload`));
2923
3004
  for (const rel of found.files) {
2924
3005
  log(` ${rel}`);
2925
3006
  }
2926
3007
  if (found.total > found.files.length) {
2927
- log(chalk.dim(` ... and ${found.total - found.files.length} more`));
3008
+ log(chalk.dim(` ... and ${found.total - found.files.length} more (use --all to list every file)`));
2928
3009
  }
2929
3010
  }
2930
3011
  if (grand > 0) {
@@ -0,0 +1,23 @@
1
+ import { Command } from "commander";
2
+ import { type DeletedCompanyEntry } from "../utils/deleted-company-notice.js";
3
+ export type CompanyRestoreErrorCode = "no_match" | "ambiguous" | "window_closed" | "forbidden" | "conflict" | "failed";
4
+ export type CompanyRestoreResult = {
5
+ restored: true;
6
+ uid: string;
7
+ name: string;
8
+ alreadyLive: boolean;
9
+ message: string;
10
+ } | {
11
+ restored: false;
12
+ error: CompanyRestoreErrorCode;
13
+ message: string;
14
+ /** Extra lines for a person: the deleted companies they could name. */
15
+ details: string[];
16
+ uid?: string;
17
+ };
18
+ /** Match by uid, then slug, then name. Slug and name ignore case. */
19
+ export declare function matchDeletedCompany(input: string, entries: DeletedCompanyEntry[]): DeletedCompanyEntry[];
20
+ /** Resolve `<company>` among the caller's deleted companies and restore it. */
21
+ export declare function restoreCompany(input: string, token: string): Promise<CompanyRestoreResult>;
22
+ export declare function registerCompanyRestoreCommand(company: Command): void;
23
+ //# sourceMappingURL=company-restore.d.ts.map
@@ -0,0 +1,128 @@
1
+ // src/commands/company-restore.ts
2
+ //
3
+ // `hq company restore <company>` brings back a company its owner deleted
4
+ // within the last 30 days (hq-pro `POST /entity/{uid}/restore`). The company
5
+ // is looked up among `deletedCompanies` on `GET /membership/me`, because a
6
+ // deleted company no longer resolves through the normal slug lookup.
7
+ //
8
+ // Every message is fixed copy. The server's error text is never printed.
9
+ import { ensureCognitoToken } from "../utils/cognito-session.js";
10
+ import { vaultApiFetch } from "../utils/vault-api.js";
11
+ import { DELETED_COMPANY_SUPPORT_POINTER, DELETED_COMPANY_SUPPORT_POINTER_INLINE, deletedCompanyDisplayName, fetchDeletedCompanies, formatDeletedCompanyNotice, } from "../utils/deleted-company-notice.js";
12
+ function normalize(value) {
13
+ return (value ?? "").trim().replace(/\s+/g, " ").toLowerCase();
14
+ }
15
+ /** Match by uid, then slug, then name. Slug and name ignore case. */
16
+ export function matchDeletedCompany(input, entries) {
17
+ const wanted = normalize(input);
18
+ if (!wanted)
19
+ return [];
20
+ const byUid = entries.filter((e) => e.companyUid === input.trim());
21
+ if (byUid.length > 0)
22
+ return byUid;
23
+ const bySlug = entries.filter((e) => normalize(e.companySlug) === wanted);
24
+ if (bySlug.length > 0)
25
+ return bySlug;
26
+ return entries.filter((e) => normalize(e.companyName) === wanted);
27
+ }
28
+ function failure(error, message, details = [], uid) {
29
+ return { restored: false, error, message, details, ...(uid ? { uid } : {}) };
30
+ }
31
+ function couldNotRestore(name, uid) {
32
+ return failure("failed", `Could not restore ${name}. Try again, or ${DELETED_COMPANY_SUPPORT_POINTER_INLINE}`, [], uid);
33
+ }
34
+ /** Resolve `<company>` among the caller's deleted companies and restore it. */
35
+ export async function restoreCompany(input, token) {
36
+ const typed = input.trim();
37
+ let entries;
38
+ try {
39
+ entries = await fetchDeletedCompanies({ token });
40
+ }
41
+ catch {
42
+ return couldNotRestore(typed || "the company");
43
+ }
44
+ const matches = matchDeletedCompany(typed, entries);
45
+ const listing = entries.flatMap((entry) => formatDeletedCompanyNotice(entry));
46
+ if (matches.length === 0) {
47
+ return failure("no_match", `No deleted company matches "${typed}".`, listing);
48
+ }
49
+ if (matches.length > 1) {
50
+ return failure("ambiguous", `More than one deleted company matches "${typed}". Run the command again with the company ID:`, matches.map((entry) => ` hq company restore ${entry.companyUid}`));
51
+ }
52
+ const entry = matches[0];
53
+ const name = deletedCompanyDisplayName(entry);
54
+ const uid = entry.companyUid;
55
+ let res;
56
+ try {
57
+ res = await vaultApiFetch({
58
+ token,
59
+ path: `/entity/${encodeURIComponent(uid)}/restore`,
60
+ method: "POST",
61
+ });
62
+ }
63
+ catch {
64
+ return couldNotRestore(name, uid);
65
+ }
66
+ if (res.ok) {
67
+ const body = (await res.json().catch(() => null));
68
+ if (body?.restored !== true)
69
+ return couldNotRestore(name, uid);
70
+ return {
71
+ restored: true,
72
+ uid,
73
+ name,
74
+ alreadyLive: body.alreadyLive === true,
75
+ message: `${name} is restored. Its paid plan was canceled when it was deleted, ` +
76
+ "so choose a plan again if you need one.",
77
+ };
78
+ }
79
+ if (res.status === 410) {
80
+ return failure("window_closed", `The 30-day restore window for ${name} has closed. ${DELETED_COMPANY_SUPPORT_POINTER}`, [], uid);
81
+ }
82
+ if (res.status === 403) {
83
+ return failure("forbidden", `${name} can only be restored by its owner or HQ support. ${DELETED_COMPANY_SUPPORT_POINTER}`, [], uid);
84
+ }
85
+ if (res.status === 409) {
86
+ return failure("conflict", `${name} changed while it was being restored. Run the command again.`, [], uid);
87
+ }
88
+ return couldNotRestore(name, uid);
89
+ }
90
+ export function registerCompanyRestoreCommand(company) {
91
+ company
92
+ .command("restore <company>")
93
+ .description("Restore a company you deleted in the last 30 days (name, slug or company ID)")
94
+ .option("--json", "Print the result as JSON")
95
+ .action(async (input, opts) => {
96
+ let result;
97
+ try {
98
+ // A sign-in failure keeps its own message (written by this CLI, for
99
+ // example "run `hq login`"); it is not server text.
100
+ const token = await ensureCognitoToken();
101
+ try {
102
+ result = await restoreCompany(input, token);
103
+ }
104
+ catch {
105
+ result = couldNotRestore(input.trim() || "the company");
106
+ }
107
+ }
108
+ catch (error) {
109
+ result = failure("failed", error instanceof Error && error.message
110
+ ? error.message
111
+ : "Could not sign in. Run `hq login` and try again.");
112
+ }
113
+ if (opts.json) {
114
+ console.log(JSON.stringify(result));
115
+ }
116
+ else if (result.restored) {
117
+ console.log(result.message);
118
+ }
119
+ else {
120
+ console.error(result.message);
121
+ for (const line of result.details)
122
+ console.error(line);
123
+ }
124
+ if (!result.restored)
125
+ process.exitCode = 1;
126
+ });
127
+ }
128
+ //# sourceMappingURL=company-restore.js.map
@@ -3,6 +3,7 @@ import { ensureCognitoToken } from "../utils/cognito-session.js";
3
3
  import { vaultApiFetch, getEntityUid } from "../utils/vault-api.js";
4
4
  import { registerCompanyTransferCommand } from "./company-transfer.js";
5
5
  import { registerCompanyRenameCommand } from "./company-rename.js";
6
+ import { registerCompanyRestoreCommand } from "./company-restore.js";
6
7
  import { describeRefreshOutcome, refreshCheckpointGateSetting, } from "./core-checkpoint-gate-setting.js";
7
8
  /** Both switches from a settings response body, or null unless both are booleans. */
8
9
  function workTrackingFromBody(body) {
@@ -102,6 +103,7 @@ export function registerCompanyCommand(program) {
102
103
  // `hq company transfer …` — ownership handover (client-service-pack US-010).
103
104
  registerCompanyTransferCommand(company);
104
105
  registerCompanyRenameCommand(company);
106
+ registerCompanyRestoreCommand(company);
105
107
  const settings = company
106
108
  .command("settings")
107
109
  .description("Per-company settings (owner-only)");
@@ -65,7 +65,9 @@ export declare function connectScopeFromOptions(opts: Pick<ConnectOptions, "pers
65
65
  * than fall through to a default.
66
66
  */
67
67
  export declare function assertAuthMode(value: string | undefined): void;
68
- /** RFC 7230 token characters accepted for an HTTP field name. */
68
+ /** True when hq-pro refuses to send a key in this (token-valid) header name. */
69
+ export declare function isDeniedAuthHeader(name: string): boolean;
70
+ /** RFC 7230 token, at most 64 characters, and not on hq-pro's denylist. */
69
71
  export declare function assertAuthHeader(value: string | undefined): void;
70
72
  /** Single-quote a value for a copy-pasteable shell command. */
71
73
  export declare function shellQuote(value: string): string;
@@ -79,9 +81,14 @@ export declare function shellQuote(value: string): string;
79
81
  * HQ-PRO-5QF: a key pasted from a doc or chat often arrives wrapped across
80
82
  * lines or with a tab, and sometimes with smart quotes. hq-pro sends the key
81
83
  * in an HTTP header, which can't carry those characters. Trim the ends, drop
82
- * inner line breaks and tabs, and refuse anything else outside visible ASCII
83
- * (an inner space is left for hq-pro to judge, since HTTP Basic allows it).
84
+ * inner line breaks and tabs, and refuse anything else outside visible ASCII.
84
85
  * The message never echoes the key.
86
+ *
87
+ * feedback_950d8abe: this is hq-pro's rule for every key the CLI sends. The
88
+ * CLI sends a key as Bearer or in a custom header (--auth-header), never as an
89
+ * HTTP Basic password, and hq-pro accepts only visible ASCII (0x21-0x7E) for
90
+ * those. An inner space used to pass here and come back from hq-pro as a 400
91
+ * DIRECT_MCP_INVALID_API_KEY_CHARACTERS.
85
92
  */
86
93
  export declare const API_KEY_UNSENDABLE_MESSAGE = "The key contains a character that can't be sent. Copy it again and paste only the key.";
87
94
  export declare function normalizePastedApiKey(raw: string): string;
@@ -235,18 +235,87 @@ export function assertAuthMode(value) {
235
235
  throw new IntegrationsCliError("--auth must be none, key, or oauth.", { expected: true });
236
236
  }
237
237
  }
238
- /** RFC 7230 token characters accepted for an HTTP field name. */
238
+ /**
239
+ * feedback_950d8abe: hq-pro's save-time rule for a custom key header
240
+ * (src/integration-factory/api-key-characters.ts). Kept identical so the CLI
241
+ * never sends a header name hq-pro refuses with DIRECT_MCP_INVALID_AUTH_SCHEME,
242
+ * and never refuses one hq-pro accepts. Authorization is allowed: a header
243
+ * placement named Authorization is the one way to send a raw key with no
244
+ * prefix.
245
+ */
246
+ const MAX_AUTH_HEADER_LENGTH = 64;
247
+ const DENIED_AUTH_HEADER_NAMES = new Set([
248
+ // hop-by-hop, framing and request target
249
+ "connection",
250
+ "keep-alive",
251
+ "proxy-connection",
252
+ "te",
253
+ "trailer",
254
+ "transfer-encoding",
255
+ "upgrade",
256
+ "http2-settings",
257
+ "content-length",
258
+ "expect",
259
+ "host",
260
+ "content-encoding",
261
+ // cookies, auth challenges, forwarding and client-IP headers
262
+ "cookie",
263
+ "set-cookie",
264
+ "www-authenticate",
265
+ "proxy-authorization",
266
+ "proxy-authenticate",
267
+ "forwarded",
268
+ "via",
269
+ "x-real-ip",
270
+ "true-client-ip",
271
+ "cf-connecting-ip",
272
+ "x-original-url",
273
+ // set by HQ's MCP client itself
274
+ "accept",
275
+ "accept-encoding",
276
+ "content-type",
277
+ "user-agent",
278
+ "mcp-protocol-version",
279
+ "mcp-session-id",
280
+ "last-event-id",
281
+ ]);
282
+ /** Case-insensitive prefixes: any Proxy-* (also listed by name above) and every X-Forwarded-*. */
283
+ const DENIED_AUTH_HEADER_PREFIXES = ["proxy-", "x-forwarded-"];
284
+ /** True when hq-pro refuses to send a key in this (token-valid) header name. */
285
+ export function isDeniedAuthHeader(name) {
286
+ const lower = name.toLowerCase();
287
+ return (DENIED_AUTH_HEADER_NAMES.has(lower) ||
288
+ DENIED_AUTH_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix)));
289
+ }
290
+ /** RFC 7230 token, at most 64 characters, and not on hq-pro's denylist. */
239
291
  export function assertAuthHeader(value) {
240
- if (value !== undefined && !/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(value)) {
292
+ if (value === undefined)
293
+ return;
294
+ if (!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(value)) {
241
295
  throw new IntegrationsCliError("--auth-header must be a non-empty HTTP header name using RFC 7230 token characters.", { expected: true });
242
296
  }
297
+ if (isDeniedAuthHeader(value)) {
298
+ throw new IntegrationsCliError(`HQ can't send a key in the ${value} header. Use the header name from the app's docs, such as X-API-Key.`, { expected: true });
299
+ }
300
+ if (value.length > MAX_AUTH_HEADER_LENGTH) {
301
+ throw new IntegrationsCliError(`--auth-header can be up to ${MAX_AUTH_HEADER_LENGTH} characters.`, { expected: true });
302
+ }
243
303
  }
244
304
  /** Single-quote a value for a copy-pasteable shell command. */
245
305
  export function shellQuote(value) {
246
306
  return `'${value.replace(/'/g, `'\\''`)}'`;
247
307
  }
248
- /** Read a secret from piped stdin, without echoing or trailing-newline noise. */
249
- function readStdin() {
308
+ /**
309
+ * Read a secret from stdin, without echoing or trailing-newline noise.
310
+ *
311
+ * When stdin is a terminal, a bare read waits in silence and looks frozen
312
+ * (feedback_86a49a5c). In that case print a one-line prompt to stderr and read
313
+ * with echo off. Piped stdin keeps the silent read.
314
+ */
315
+ function readStdin(promptLabel) {
316
+ if (process.stdin.isTTY) {
317
+ return promptForKey(`${promptLabel}, then press Enter (input is hidden)`, process.stderr);
318
+ }
250
319
  return new Promise((resolve, reject) => {
251
320
  let data = "";
252
321
  process.stdin.setEncoding("utf8");
@@ -263,9 +332,9 @@ function readStdin() {
263
332
  * reach argv (shell history, `ps` output) unless the caller insists via
264
333
  * `--token`.
265
334
  */
266
- function promptForKey(label) {
335
+ function promptForKey(label, out = process.stdout) {
267
336
  return new Promise((resolve, reject) => {
268
- process.stdout.write(`${label}: `);
337
+ out.write(`${label}: `);
269
338
  if (process.stdin.isTTY)
270
339
  process.stdin.setRawMode(true);
271
340
  process.stdin.setEncoding("utf8");
@@ -281,13 +350,13 @@ function promptForKey(label) {
281
350
  const codePoint = ch.codePointAt(0);
282
351
  if (ch === "\n" || ch === "\r" || codePoint === 4) {
283
352
  cleanup();
284
- process.stdout.write("\n");
353
+ out.write("\n");
285
354
  resolve(value);
286
355
  return;
287
356
  }
288
357
  if (codePoint === 3) {
289
358
  cleanup();
290
- process.stdout.write("\n");
359
+ out.write("\n");
291
360
  reject(new IntegrationsCliError("Cancelled.", { expected: true }));
292
361
  return;
293
362
  }
@@ -312,21 +381,26 @@ function promptForKey(label) {
312
381
  * HQ-PRO-5QF: a key pasted from a doc or chat often arrives wrapped across
313
382
  * lines or with a tab, and sometimes with smart quotes. hq-pro sends the key
314
383
  * in an HTTP header, which can't carry those characters. Trim the ends, drop
315
- * inner line breaks and tabs, and refuse anything else outside visible ASCII
316
- * (an inner space is left for hq-pro to judge, since HTTP Basic allows it).
384
+ * inner line breaks and tabs, and refuse anything else outside visible ASCII.
317
385
  * The message never echoes the key.
386
+ *
387
+ * feedback_950d8abe: this is hq-pro's rule for every key the CLI sends. The
388
+ * CLI sends a key as Bearer or in a custom header (--auth-header), never as an
389
+ * HTTP Basic password, and hq-pro accepts only visible ASCII (0x21-0x7E) for
390
+ * those. An inner space used to pass here and come back from hq-pro as a 400
391
+ * DIRECT_MCP_INVALID_API_KEY_CHARACTERS.
318
392
  */
319
393
  export const API_KEY_UNSENDABLE_MESSAGE = "The key contains a character that can't be sent. Copy it again and paste only the key.";
320
394
  export function normalizePastedApiKey(raw) {
321
395
  const cleaned = raw.trim().replace(/[\r\n\t]+/g, "");
322
- if (!/^[\x20-\x7e]*$/.test(cleaned)) {
396
+ if (!/^[\x21-\x7e]*$/.test(cleaned)) {
323
397
  throw new IntegrationsCliError(API_KEY_UNSENDABLE_MESSAGE, { expected: true });
324
398
  }
325
399
  return cleaned;
326
400
  }
327
401
  async function resolveKey(opts, appLabel) {
328
402
  if (opts.tokenStdin) {
329
- const piped = normalizePastedApiKey(await readStdin());
403
+ const piped = normalizePastedApiKey(await readStdin("Paste the API key"));
330
404
  if (!piped) {
331
405
  throw new IntegrationsCliError("--token-stdin was set but stdin was empty.", {
332
406
  expected: true,
@@ -1051,7 +1125,7 @@ async function resolveUserOAuthClient(opts, appLabel) {
1051
1125
  if (!clientId)
1052
1126
  return null;
1053
1127
  if (opts.clientSecretStdin) {
1054
- const piped = (await readStdin()).trim();
1128
+ const piped = (await readStdin("Paste the client secret")).trim();
1055
1129
  if (!piped) {
1056
1130
  throw new IntegrationsCliError("--client-secret-stdin was set but stdin was empty.", { expected: true });
1057
1131
  }
@@ -1507,17 +1507,17 @@ function laneHostFromCtx(ctx, expectedId) {
1507
1507
  return { kind: "outpost", id: identity.id };
1508
1508
  return recordedLocalHost(ctx);
1509
1509
  }
1510
- async function readOutpostCapacity(ctx, outpostId) {
1511
- return readOutpostCapacityUncached(ctx, outpostId);
1510
+ async function readOutpostCapacity(ctx, outpostId, waitMs = CAPACITY_PROBE_TIMEOUT_MS) {
1511
+ return readOutpostCapacityUncached(ctx, outpostId, waitMs);
1512
1512
  }
1513
- async function readOutpostCapacityUncached(ctx, outpostId) {
1513
+ async function readOutpostCapacityUncached(ctx, outpostId, waitMs = CAPACITY_PROBE_TIMEOUT_MS) {
1514
1514
  let result;
1515
1515
  try {
1516
1516
  result = await ctx.dispatchOutpostExec({
1517
1517
  outpostId,
1518
1518
  command: buildOutpostCapacityCommand(),
1519
- timeoutSeconds: CAPACITY_PROBE_TIMEOUT_MS / 1000,
1520
- waitMs: CAPACITY_PROBE_TIMEOUT_MS,
1519
+ timeoutSeconds: Math.ceil(waitMs / 1000),
1520
+ waitMs,
1521
1521
  });
1522
1522
  }
1523
1523
  catch (err) {
@@ -2268,12 +2268,27 @@ async function loadClaudeBalanceHostSnapshots(ctx, hqRoot, config, options = {})
2268
2268
  }
2269
2269
  const remoteIds = outpostIds.map((id) => id.trim())
2270
2270
  .filter((id) => !isControllerAliasOutpostId(id, localHost))
2271
- .filter((id) => localHost.kind !== "outpost" || id !== localHost.id)
2272
- .sort();
2271
+ .filter((id) => localHost.kind !== "outpost" || id !== localHost.id);
2272
+ const known = new Set(outpostIds.map((id) => id.trim()));
2273
+ const explicitIds = new Set();
2274
+ for (const id of options.includeOutpostIds ?? []) {
2275
+ const trimmed = id.trim();
2276
+ // An explicit target such as --outpost primary is measured even when
2277
+ // `primary` is the controller alias. The generic loop above stays closed.
2278
+ if (trimmed && known.has(trimmed) && !remoteIds.includes(trimmed) &&
2279
+ (localHost.kind !== "outpost" || trimmed !== localHost.id)) {
2280
+ remoteIds.push(trimmed);
2281
+ explicitIds.add(trimmed);
2282
+ }
2283
+ }
2284
+ remoteIds.sort();
2285
+ // An explicit target waits the single-lane pickup interval (120s by
2286
+ // default). The generic capacity loop above keeps the 15s probe.
2287
+ const explicitWaitMs = explicitIds.size > 0 ? outpostSingleLaneWaitMs(ctx.env) : CAPACITY_PROBE_TIMEOUT_MS;
2273
2288
  const remoteResults = await mapWithConcurrency(remoteIds, OUTPOST_HIRE_SUMMARY_CONCURRENCY, async (id) => {
2274
2289
  let capacity;
2275
2290
  try {
2276
- capacity = await readOutpostCapacity(ctx, id);
2291
+ capacity = await readOutpostCapacity(ctx, id, explicitIds.has(id) ? explicitWaitMs : CAPACITY_PROBE_TIMEOUT_MS);
2277
2292
  }
2278
2293
  catch (err) {
2279
2294
  if (isLanesError(err) && err.error !== "outpost_capacity_unavailable") {
@@ -4243,7 +4258,9 @@ async function runCreate(ctx, opts) {
4243
4258
  ? { kind: "outpost", id: outpostId }
4244
4259
  : persistedLocalHost);
4245
4260
  balanceTargetHost = targetHost;
4246
- balanceHostLoad = await loadClaudeBalanceHostSnapshots(ctx, hqRoot, config);
4261
+ balanceHostLoad = await loadClaudeBalanceHostSnapshots(ctx, hqRoot, config, {
4262
+ ...(outpostId !== undefined ? { includeOutpostIds: [outpostId] } : {}),
4263
+ });
4247
4264
  const selected = selectClaudeAccount({
4248
4265
  company: accountCompany,
4249
4266
  hosts: balanceHostLoad.snapshots,
@@ -25,6 +25,7 @@ import * as fs from "node:fs";
25
25
  import * as path from "node:path";
26
26
  import { InvalidArgumentError } from "commander";
27
27
  import chalk from "chalk";
28
+ import { printDeletedCompanyNotices } from "../utils/deleted-company-notice.js";
28
29
  import { SOURCE_CHANNELS, assertSourceChannel, resolveEntity, listAvailableEntities, listSources, getSource, VaultClient, } from "@indigoai-us/hq-cloud";
29
30
  import { ensureCognitoToken, ensureCognitoIdToken, buildVaultConfig, DEFAULT_COGNITO, DEFAULT_HQ_ROOT, } from "../utils/cognito-session.js";
30
31
  import { getCompanyUid, vaultApiFetch } from "../utils/vault-api.js";
@@ -221,6 +222,11 @@ async function runEntities(options) {
221
222
  const accessToken = await resolveAccessToken();
222
223
  const vaultConfig = buildVaultConfig(accessToken);
223
224
  const entities = await listAvailableEntities({ vaultConfig });
225
+ // An empty list may mean the person's company was deleted. Say so on stderr;
226
+ // stdout (including --json) is unchanged.
227
+ if (entities.length === 0) {
228
+ await printDeletedCompanyNotices({ token: accessToken });
229
+ }
224
230
  if (format === "json") {
225
231
  process.stdout.write(JSON.stringify(entities, null, 2) + "\n");
226
232
  return;