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

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 (119) hide show
  1. package/CHANGELOG.md +40 -1
  2. package/dist/bin/hq-auth-refresh.js +2 -1
  3. package/dist/command-catalog.generated.d.ts +308 -43
  4. package/dist/command-catalog.generated.js +373 -43
  5. package/dist/command-registration-plan.d.ts +15 -0
  6. package/dist/command-registration-plan.js +20 -1
  7. package/dist/commands/agent-inbox.d.ts +11 -1
  8. package/dist/commands/agent-inbox.js +128 -38
  9. package/dist/commands/agent-kit.js +2 -2
  10. package/dist/commands/agents.js +6 -1
  11. package/dist/commands/billing.js +17 -4
  12. package/dist/commands/core-handoff.js +1 -0
  13. package/dist/commands/core-hq-session-native.js +2 -2
  14. package/dist/commands/core-pin-native.js +1 -1
  15. package/dist/commands/core-policy.js +1 -1
  16. package/dist/commands/core-resolve-company-native.js +1 -1
  17. package/dist/commands/core-sentry-report-fast.d.ts +2 -0
  18. package/dist/commands/core-sentry-report-fast.js +3 -1
  19. package/dist/commands/daemon.js +68 -6
  20. package/dist/commands/files.js +2 -2
  21. package/dist/commands/integrations-api.d.ts +11 -0
  22. package/dist/commands/integrations-connect.d.ts +9 -1
  23. package/dist/commands/integrations-connect.js +154 -18
  24. package/dist/commands/integrations-core.d.ts +1 -1
  25. package/dist/commands/integrations-core.js +18 -10
  26. package/dist/commands/integrations.js +1 -1
  27. package/dist/commands/lanes-link.js +10 -5
  28. package/dist/commands/lanes.js +34 -16
  29. package/dist/commands/rescue.js +13 -0
  30. package/dist/commands/secrets.d.ts +11 -0
  31. package/dist/commands/secrets.js +41 -7
  32. package/dist/index.js +2 -0
  33. package/dist/lazy-commands.js +6 -1
  34. package/dist/lib/agent-kit/inbox-fetch.d.ts +122 -1
  35. package/dist/lib/agent-kit/inbox-fetch.js +215 -3
  36. package/dist/lib/agent-kit/inbox-redact.js +1 -1
  37. package/dist/lib/agent-kit/inbox-state.d.ts +98 -1
  38. package/dist/lib/agent-kit/inbox-state.js +261 -4
  39. package/dist/lib/agent-kit/mcp/tools.d.ts +3 -3
  40. package/dist/lib/agent-kit/mcp/tools.js +68 -25
  41. package/dist/lib/agent-kit/run/inbox.js +4 -2
  42. package/dist/lib/agent-kit/skills.js +4 -1
  43. package/dist/lib/agent-kit/wake.d.ts +9 -1
  44. package/dist/lib/agent-kit/wake.js +10 -3
  45. package/dist/lib/billing/usage-only.d.ts +4 -1
  46. package/dist/lib/billing/usage-only.js +7 -2
  47. package/dist/lib/bot/fleet-cron.js +193 -14
  48. package/dist/lib/bot/fleet-download.d.ts +2 -0
  49. package/dist/lib/bot/fleet-download.js +23 -0
  50. package/dist/lib/bot/fleet-local.d.ts +1 -0
  51. package/dist/lib/bot/fleet-local.js +41 -8
  52. package/dist/lib/capacity/ledger.d.ts +7 -0
  53. package/dist/lib/capacity/ledger.js +31 -1
  54. package/dist/lib/capacity/project.d.ts +1 -1
  55. package/dist/lib/capacity/project.js +13 -4
  56. package/dist/lib/capacity/route.d.ts +10 -0
  57. package/dist/lib/capacity/route.js +16 -0
  58. package/dist/lib/core-utils/session-id.d.ts +1 -1
  59. package/dist/lib/core-utils/session-id.js +4 -0
  60. package/dist/lib/daemon/install.d.ts +15 -0
  61. package/dist/lib/daemon/install.js +31 -0
  62. package/dist/lib/daemon/migrate.js +29 -4
  63. package/dist/lib/daemon/run.js +9 -1
  64. package/dist/lib/daemon/updater.d.ts +34 -2
  65. package/dist/lib/daemon/updater.js +51 -2
  66. package/dist/lib/doctor/__testing__/run-doctor.js +4 -0
  67. package/dist/lib/doctor/checks/jq.d.ts +27 -0
  68. package/dist/lib/doctor/checks/jq.js +82 -0
  69. package/dist/lib/doctor/checks/release-links.d.ts +50 -8
  70. package/dist/lib/doctor/checks/release-links.js +260 -24
  71. package/dist/lib/doctor/fix/apply.js +24 -8
  72. package/dist/lib/doctor/fix/remediation.js +15 -5
  73. package/dist/lib/doctor/registry.js +4 -0
  74. package/dist/lib/flag-snapshot-file.js +36 -8
  75. package/dist/lib/install/codex-targets.d.ts +52 -1
  76. package/dist/lib/install/codex-targets.js +77 -2
  77. package/dist/lib/lanes/autopilot-registry.d.ts +14 -0
  78. package/dist/lib/lanes/autopilot-registry.js +59 -7
  79. package/dist/lib/lanes/links.d.ts +14 -0
  80. package/dist/lib/lanes/links.js +320 -25
  81. package/dist/lib/lanes/monitor.d.ts +4 -1
  82. package/dist/lib/lanes/monitor.js +47 -10
  83. package/dist/lib/lanes/outpost-pruner-install.d.ts +10 -0
  84. package/dist/lib/lanes/outpost-pruner-install.js +4 -3
  85. package/dist/lib/lanes/spawn.js +8 -1
  86. package/dist/lib/lanes/watch.js +31 -0
  87. package/dist/lib/onboarding/checkpoint.d.ts +6 -0
  88. package/dist/lib/onboarding/checkpoint.js +6 -0
  89. package/dist/lib/onboarding/orchestrator.d.ts +3 -1
  90. package/dist/lib/onboarding/orchestrator.js +62 -9
  91. package/dist/lib/onboarding/types.d.ts +8 -0
  92. package/dist/lib/work-context/organize.d.ts +23 -1
  93. package/dist/lib/work-context/organize.js +25 -3
  94. package/dist/lib/work-context/reconcile.js +3 -2
  95. package/dist/main.js +3 -1
  96. package/dist/secrets-env-action.js +7 -5
  97. package/dist/sentry-init.d.ts +2 -0
  98. package/dist/sentry-init.js +13 -2
  99. package/dist/sentry.d.ts +2 -0
  100. package/dist/sentry.js +5 -1
  101. package/dist/startup-registration.js +7 -2
  102. package/dist/utils/billing-gate.d.ts +12 -16
  103. package/dist/utils/billing-gate.js +17 -18
  104. package/dist/utils/cli-network-lifecycle.d.ts +9 -0
  105. package/dist/utils/cli-network-lifecycle.js +52 -0
  106. package/dist/utils/install-tree-torn.d.ts +22 -4
  107. package/dist/utils/install-tree-torn.js +24 -0
  108. package/dist/utils/registration-plan-error.d.ts +22 -0
  109. package/dist/utils/registration-plan-error.js +27 -0
  110. package/dist/utils/safe-link.d.ts +63 -0
  111. package/dist/utils/safe-link.js +246 -0
  112. package/dist/utils/sentry-fingerprint.js +3 -0
  113. package/dist/utils/sentry-keepalive-transport.d.ts +28 -0
  114. package/dist/utils/sentry-keepalive-transport.js +70 -0
  115. package/dist/utils/unauthorized-error.d.ts +36 -0
  116. package/dist/utils/unauthorized-error.js +105 -0
  117. package/dist/utils/vault-api.js +7 -5
  118. package/package.json +7 -7
  119. package/scripts/install-hook-engine.mjs +17 -0
@@ -7,6 +7,12 @@
7
7
  import { readFile, writeFile, mkdir } from "node:fs/promises";
8
8
  import { join, dirname } from "node:path";
9
9
  const CHECKPOINT_FILE = "onboarding-state.json";
10
+ /**
11
+ * Checkpoint format version. 2: a join's invite token is saved only together
12
+ * with `inviteTokenPersonUid`, so an unbound token in a version-2 checkpoint is
13
+ * never the caller's. A checkpoint with no `version` predates that rule.
14
+ */
15
+ export const CHECKPOINT_VERSION = 2;
10
16
  export function getCheckpointPath(hqRoot) {
11
17
  return join(hqRoot, ".hq", CHECKPOINT_FILE);
12
18
  }
@@ -35,7 +35,9 @@ export declare function createCompanyFlow(input: CreateCompanyInput, config: Onb
35
35
  * 5. First sync to pull initial vault contents
36
36
  * 6. Write .hq/config.json
37
37
  */
38
- export declare function joinCompanyFlow(input: JoinCompanyInput, config: OnboardingConfig, onProgress?: ProgressCallback): Promise<OnboardingResult>;
38
+ export declare function joinCompanyFlow(input: JoinCompanyInput, config: OnboardingConfig, onProgress?: ProgressCallback, { resumed }?: {
39
+ resumed?: boolean;
40
+ }): Promise<OnboardingResult>;
39
41
  /**
40
42
  * Resume an interrupted onboarding flow from checkpoint.
41
43
  */
@@ -15,7 +15,7 @@ import { writeFile, mkdir } from "node:fs/promises";
15
15
  import { join, dirname } from "node:path";
16
16
  import { VaultClient, VaultConflictError, VaultNotFoundError, resolveEntityContext, sync, parseToken, } from "@indigoai-us/hq-cloud";
17
17
  import { PersonCreationError, CompanyCreationError, ProvisioningError, MembershipBootstrapError, StsVerifyError, InviteAcceptError, FirstSyncError, } from "./errors.js";
18
- import { readCheckpoint, writeCheckpoint, isStepComplete, deleteCheckpoint, } from "./checkpoint.js";
18
+ import { readCheckpoint, writeCheckpoint, isStepComplete, deleteCheckpoint, CHECKPOINT_VERSION, } from "./checkpoint.js";
19
19
  // ---------------------------------------------------------------------------
20
20
  // Public API
21
21
  // ---------------------------------------------------------------------------
@@ -271,17 +271,58 @@ export async function createCompanyFlow(input, config, onProgress) {
271
271
  * 5. First sync to pull initial vault contents
272
272
  * 6. Write .hq/config.json
273
273
  */
274
- export async function joinCompanyFlow(input, config, onProgress) {
274
+ export async function joinCompanyFlow(input, config, onProgress, { resumed = false } = {}) {
275
275
  const client = new VaultClient(config.vaultConfig);
276
276
  const checkpoint = await readCheckpoint(config.hqRoot) ?? makeCheckpoint("join-company");
277
- // Step 1: Parse token
277
+ // Read before any write below stamps the current version on the checkpoint.
278
+ const legacyCheckpoint = (checkpoint.version ?? 1) < CHECKPOINT_VERSION;
279
+ // Step 1: Parse token. The token is not written to the checkpoint here: it is
280
+ // saved only together with the person it belongs to, after the person step.
281
+ // A run interrupted before that leaves the previous token and its binding as
282
+ // they were, so a later resume never finds this run's token unbound
283
+ // (review of hq-cli #2545).
278
284
  emit(onProgress, "parse-token", "running");
279
285
  const token = parseToken(input.inviteToken);
280
- checkpoint.inviteToken = token;
281
- await writeCheckpoint(config.hqRoot, checkpoint);
282
286
  emit(onProgress, "parse-token", "done");
283
287
  // Step 2: Create person (same caller-owned resolution as createCompanyFlow)
284
- await runPersonStep(client, checkpoint, input, config, onProgress);
288
+ const person = await runPersonStep(client, checkpoint, input, config, onProgress);
289
+ // Resume reads the invite token from the checkpoint, and the checkpoint may
290
+ // have been left by another sign-in on this machine. Accepting that token
291
+ // under the caller would give the caller an invite meant for someone else
292
+ // (review of hq-cli #2516, minor 1; feedback_a169f6dc). Resume only uses a
293
+ // token saved for the caller's own person; any other token is dropped and the
294
+ // caller is asked to run `hq onboard join` with their own invite. Only a
295
+ // checkpoint written before tokens were bound (no `version`) may hold an
296
+ // unbound token; it counts as the caller's only when its saved person is one
297
+ // the caller owns. An unbound token in a current checkpoint is never used.
298
+ if (resumed && !isStepComplete(checkpoint, "accept-invite")) {
299
+ // The person step drops the saved token when it replaces the saved person,
300
+ // so a token that is gone from the checkpoint is never used either.
301
+ const bound = Boolean(checkpoint.inviteToken) &&
302
+ checkpoint.inviteToken === token &&
303
+ (checkpoint.inviteTokenPersonUid
304
+ ? checkpoint.inviteTokenPersonUid === checkpoint.personUid
305
+ : legacyCheckpoint && person === "kept" && Boolean(checkpoint.personUid));
306
+ if (!bound) {
307
+ delete checkpoint.inviteToken;
308
+ delete checkpoint.inviteTokenPersonUid;
309
+ checkpoint.failedStep = "accept-invite";
310
+ checkpoint.error = "saved invite token was not saved under this sign-in";
311
+ await writeCheckpoint(config.hqRoot, checkpoint);
312
+ emit(onProgress, "accept-invite", "failed");
313
+ throw new InviteAcceptError("The invite saved on this machine was not started under your sign-in, so resume will not accept it for you. " +
314
+ "If the invite is yours, run `hq onboard join <token>` with it.");
315
+ }
316
+ }
317
+ // Save the token with the person it belongs to, in one write.
318
+ if (checkpoint.inviteToken !== token ||
319
+ checkpoint.inviteTokenPersonUid !== checkpoint.personUid ||
320
+ checkpoint.version !== CHECKPOINT_VERSION) {
321
+ checkpoint.inviteToken = token;
322
+ checkpoint.inviteTokenPersonUid = checkpoint.personUid;
323
+ checkpoint.version = CHECKPOINT_VERSION;
324
+ await writeCheckpoint(config.hqRoot, checkpoint);
325
+ }
285
326
  // Step 3: Accept invite
286
327
  if (!isStepComplete(checkpoint, "accept-invite")) {
287
328
  emit(onProgress, "accept-invite", "running");
@@ -443,7 +484,7 @@ export async function resumeOnboarding(config, onProgress) {
443
484
  personEmail: "",
444
485
  inviteToken: checkpoint.inviteToken ?? "",
445
486
  };
446
- return joinCompanyFlow(input, config, onProgress);
487
+ return joinCompanyFlow(input, config, onProgress, { resumed: true });
447
488
  }
448
489
  }
449
490
  /**
@@ -465,6 +506,7 @@ function makeCheckpoint(mode) {
465
506
  const now = new Date().toISOString();
466
507
  return {
467
508
  mode,
509
+ version: CHECKPOINT_VERSION,
468
510
  startedAt: now,
469
511
  updatedAt: now,
470
512
  completedSteps: [],
@@ -558,6 +600,10 @@ async function resolveCallerPerson(client, checkpoint, input) {
558
600
  * membership state is dropped with it. When the caller owns a person it is
559
601
  * used; when the caller owns none yet, create-person is dropped too and runs
560
602
  * again to create the caller's own person.
603
+ *
604
+ * Returns how it settled: `kept` the saved person the caller owns, `relinked`
605
+ * away from a saved person another sign-in owns, or `resolved` a person for a
606
+ * run that had none saved.
561
607
  */
562
608
  async function runPersonStep(client, checkpoint, input, config, onProgress) {
563
609
  let previous;
@@ -566,17 +612,23 @@ async function runPersonStep(client, checkpoint, input, config, onProgress) {
566
612
  const stale = owned !== null && !owned.some((p) => p.uid === checkpoint.personUid);
567
613
  if (!stale) {
568
614
  emit(onProgress, "create-person", "skipped", "Already complete");
569
- return;
615
+ return "kept";
570
616
  }
571
617
  previous = checkpoint.personUid;
572
618
  forgetMembershipState(checkpoint);
619
+ // A saved invite token belonged to the previous person. Drop it in the same
620
+ // write as the relink, so a run that stops before the join saves its own
621
+ // token cannot leave the old one for the new person's resume, even in a
622
+ // legacy checkpoint with no binding (review of hq-cli #2545).
623
+ delete checkpoint.inviteToken;
624
+ delete checkpoint.inviteTokenPersonUid;
573
625
  const relinked = pickOwnedPerson(owned, input.personEmail);
574
626
  if (relinked) {
575
627
  checkpoint.personUid = relinked.uid;
576
628
  await writeCheckpoint(config.hqRoot, checkpoint);
577
629
  emit(onProgress, "create-person", "done", `Using your sign-in's person record ${relinked.uid}; the saved record ${previous} belongs to another sign-in, ` +
578
630
  `so the company and membership steps run again under your sign-in`);
579
- return;
631
+ return "relinked";
580
632
  }
581
633
  // The caller owns no person yet: forget the other sign-in's person as well,
582
634
  // so the step below creates the caller's own.
@@ -593,6 +645,7 @@ async function runPersonStep(client, checkpoint, input, config, onProgress) {
593
645
  emit(onProgress, "create-person", "done", previous
594
646
  ? `${detail}; the saved record ${previous} belongs to another sign-in, so the company and membership steps run again under your sign-in`
595
647
  : detail);
648
+ return previous ? "relinked" : "resolved";
596
649
  }
597
650
  catch (err) {
598
651
  checkpoint.failedStep = "create-person";
@@ -44,6 +44,8 @@ export interface OnboardingResult {
44
44
  }
45
45
  export interface OnboardingCheckpoint {
46
46
  mode: "create-company" | "join-company";
47
+ /** Checkpoint format version (`CHECKPOINT_VERSION`); absent on checkpoints from older CLIs. */
48
+ version?: number;
47
49
  startedAt: string;
48
50
  updatedAt: string;
49
51
  personUid?: string;
@@ -54,6 +56,12 @@ export interface OnboardingCheckpoint {
54
56
  /** Role on the caller's membership row, recorded when the membership step finds or makes it. */
55
57
  role?: string;
56
58
  inviteToken?: string;
59
+ /**
60
+ * The person the invite token was saved for. Resume only accepts a token
61
+ * bound to the caller's own person, so it never accepts an invite another
62
+ * sign-in left on this machine.
63
+ */
64
+ inviteTokenPersonUid?: string;
57
65
  completedSteps: OnboardingStep[];
58
66
  failedStep?: OnboardingStep;
59
67
  error?: string;
@@ -74,11 +74,33 @@ export type PostOrganizeFn = (input: {
74
74
  expectedVersion: number;
75
75
  decisionExpiresAt?: string;
76
76
  }) => Promise<OrganizeReceipt>;
77
+ /**
78
+ * The projects a session's own context points at: its bound project, the
79
+ * project hint its folder or registry resolved, and the local project
80
+ * candidates. Only server candidates for these projects become bind options.
81
+ */
82
+ export interface DecisionScope {
83
+ projectIds: readonly string[];
84
+ }
85
+ export declare function sessionDecisionScope(fields: {
86
+ projectId?: string;
87
+ projectHint?: string;
88
+ projectCandidates?: ReadonlyArray<{
89
+ projectId: string;
90
+ }>;
91
+ }): DecisionScope;
77
92
  /**
78
93
  * Build a pending decision from server candidates. Soft evidence ranks on the
79
94
  * server; the CLI never auto-binds from this list.
95
+ *
96
+ * With a scope, only candidates for the session's own projects become
97
+ * `bind_existing` options. The server list is the company's most active
98
+ * projects and carries no repo or folder match, so without this filter a
99
+ * session with no project context was offered unrelated projects
100
+ * (feedback_f81b23c2). A session with an empty scope gets only
101
+ * "Create new project" and "Leave untracked".
80
102
  */
81
- export declare function decisionFromCandidates(sessionId: string, response: CandidatesResponse): SessionDecision;
103
+ export declare function decisionFromCandidates(sessionId: string, response: CandidatesResponse, scope?: DecisionScope): SessionDecision;
82
104
  /**
83
105
  * Evaluate work-signal threshold and, when crossed for the first time, attach
84
106
  * a one-time decision (optionally from server candidates). Never invents a
@@ -38,12 +38,34 @@ function stableOrganizeOperationId(sessionId, decision) {
38
38
  .slice(0, 32);
39
39
  return `op_${h}`;
40
40
  }
41
+ export function sessionDecisionScope(fields) {
42
+ const ids = new Set();
43
+ if (fields.projectId)
44
+ ids.add(fields.projectId);
45
+ if (fields.projectHint)
46
+ ids.add(fields.projectHint);
47
+ for (const c of fields.projectCandidates ?? []) {
48
+ if (c?.projectId)
49
+ ids.add(c.projectId);
50
+ }
51
+ return { projectIds: [...ids] };
52
+ }
41
53
  /**
42
54
  * Build a pending decision from server candidates. Soft evidence ranks on the
43
55
  * server; the CLI never auto-binds from this list.
56
+ *
57
+ * With a scope, only candidates for the session's own projects become
58
+ * `bind_existing` options. The server list is the company's most active
59
+ * projects and carries no repo or folder match, so without this filter a
60
+ * session with no project context was offered unrelated projects
61
+ * (feedback_f81b23c2). A session with an empty scope gets only
62
+ * "Create new project" and "Leave untracked".
44
63
  */
45
- export function decisionFromCandidates(sessionId, response) {
46
- const options = response.candidates.map((c) => ({
64
+ export function decisionFromCandidates(sessionId, response, scope) {
65
+ const inScope = scope
66
+ ? response.candidates.filter((c) => scope.projectIds.includes(c.projectId))
67
+ : response.candidates;
68
+ const options = inScope.map((c) => ({
47
69
  optionId: c.candidateId,
48
70
  label: c.taskId
49
71
  ? `${c.projectName} / ${c.title}`
@@ -183,7 +205,7 @@ export async function prepareOrganizeDecision(input) {
183
205
  sessionId: input.sessionId,
184
206
  companyUid: state.companyUid,
185
207
  });
186
- const decision = decisionFromCandidates(input.sessionId, response);
208
+ const decision = decisionFromCandidates(input.sessionId, response, sessionDecisionScope(state));
187
209
  const updatedAt = nowFn().toISOString();
188
210
  const next = mergeLocalSessionFields({
189
211
  ...state,
@@ -9,7 +9,7 @@ import { companyBindingChanged, isNonCloudCompanySlug, presenceLeaveFromState, r
9
9
  import { invalidateDefaultCompanyMemberships, } from "./config.js";
10
10
  import { WORK_CONTEXT_CONTRACT_VERSION, normalizeTaskId, } from "./contract.js";
11
11
  import { EXIT_INVALID_IDENTITY, EXIT_NOT_TRACKING, EXIT_OK, InvalidDecisionOriginError, NotTrackingError, } from "./errors.js";
12
- import { decisionFromCandidates, } from "./organize.js";
12
+ import { decisionFromCandidates, sessionDecisionScope, } from "./organize.js";
13
13
  import { refineProjectBinding } from "./bind-best.js";
14
14
  import { foreignSessionOwnsLane } from "./lane-bind.js";
15
15
  import { rebindNeedsProjectOnPrompt } from "./prompt-rebind.js";
@@ -693,7 +693,8 @@ export async function reconcileObservation(obs, deps) {
693
693
  sessionId,
694
694
  companyUid: resolvedCompany.uid,
695
695
  });
696
- decision = decisionFromCandidates(sessionId, candidates);
696
+ // Offer only the session's own projects (feedback_f81b23c2).
697
+ decision = decisionFromCandidates(sessionId, candidates, sessionDecisionScope({ projectId, projectHint, projectCandidates }));
697
698
  diagnostics.push(`askAfter prepared decisionId=${decision.decisionId} options=${decision.options.length}`);
698
699
  }
699
700
  catch (err) {
package/dist/main.js CHANGED
@@ -10,7 +10,7 @@ import fs from "node:fs";
10
10
  import path from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { Command } from "commander";
13
- import { finishSentrySession, initSentry, Sentry } from "./sentry.js";
13
+ import { closeSentryTransport, finishSentrySession, initSentry, Sentry } from "./sentry.js";
14
14
  import { addCommandBreadcrumb } from "./utils/command-breadcrumb.js";
15
15
  import { environmentalFsErrorMessage, filesystemErrorCaptureContext, filesystemErrorMessage, } from "./utils/environmental-error.js";
16
16
  import { syncStateLockMessage } from "./utils/sync-state-lock-error.js";
@@ -366,6 +366,8 @@ export async function runCli() {
366
366
  ...limitNoticeExposureFlushes,
367
367
  ...limitNoticeEngagementFlushes,
368
368
  ], releaseHealthTimeoutMs);
369
+ // The flush above is bounded; do not leave its keep-alive socket open.
370
+ closeSentryTransport();
369
371
  });
370
372
  // Last, so it wins over anything the (skipped) command path would have
371
373
  // set: the re-exec'd child's status IS this invocation's result.
@@ -9,6 +9,7 @@ import { SECRET_NAME_PATTERN } from "./commands/_patterns.js";
9
9
  import { finishEnvExportsAndExit } from "./commands/secrets-env-exit.js";
10
10
  import { DELEGATED_MACHINE_SESSION_ENV, delegatedMachineSessionFilePath, loadDelegatedMachineSession, loadMachineCreds, } from "@indigoai-us/hq-cloud";
11
11
  import { AuthError, isAuthError } from "./utils/auth-error.js";
12
+ import { companyOutpostUnauthorizedMessage, unauthorizedServerCode } from "./utils/unauthorized-error.js";
12
13
  import { peekIdToken } from "./utils/id-token.js";
13
14
  import { wantsMachineCognitoTokens } from "./utils/machine-principal-state.js";
14
15
  import { getEntityUid, looksLikeCompanyUid, vaultApiFetch } from "./utils/vault-api.js";
@@ -305,7 +306,7 @@ export async function resolveCompanyOutpostSecretsCompany(token, outpost, scope)
305
306
  const body = (await res.json().catch(() => ({})));
306
307
  if (!res.ok) {
307
308
  if (res.status === 401)
308
- throw companyOutpostSessionRejected();
309
+ throw companyOutpostSessionRejected(outpost, body);
309
310
  const message = `Failed to resolve company '${ref}' for this Outpost: ${extractApiMessage(body, `HTTP ${res.status}`)}`;
310
311
  if (isUnavailableSecretLoadHttpStatus(res.status))
311
312
  throw new SecretLoadUnavailableError(message);
@@ -316,9 +317,10 @@ export async function resolveCompanyOutpostSecretsCompany(token, outpost, scope)
316
317
  }
317
318
  throw notBound();
318
319
  }
319
- function companyOutpostSessionRejected() {
320
- return new AuthError("HQ rejected this company Outpost session (HTTP 401). The job runner refreshes " +
321
- "HQ_MACHINE_SESSION_FILE; re-run the job, and if it persists check the Outpost's binding.");
320
+ // Same wording as every other company Outpost 401 (feedback_dfc0bb49), with
321
+ // the server's code and the Outpost uid from the token this read sent.
322
+ function companyOutpostSessionRejected(outpost, body) {
323
+ return new AuthError(companyOutpostUnauthorizedMessage({ kind: "company-outpost", entityUid: outpost.outpostUid }, unauthorizedServerCode(body)));
322
324
  }
323
325
  /**
324
326
  * The company uid a `secrets exec` / `env` / `get` call reads from. A company
@@ -414,7 +416,7 @@ async function loadRevealedSecretsForCompanyOutpost(token, outpost, companyUid,
414
416
  throw new Error(highSecuritySandboxOnlyMessage(name));
415
417
  }
416
418
  if (res.status === 401)
417
- throw companyOutpostSessionRejected();
419
+ throw companyOutpostSessionRejected(outpost, body);
418
420
  if (res.status === 404) {
419
421
  throw new Error(`Failed to fetch secret '${name}': Secret not found`);
420
422
  }
@@ -5,6 +5,8 @@ type SentryBreadcrumb = Parameters<SentryModule["addBreadcrumb"]>[0];
5
5
  export declare function createFlaggedBeforeSend(beforeSend: NodeOptions["beforeSend"], skipManualOnlyReportsEnabled?: () => Promise<boolean>): NonNullable<NodeOptions["beforeSend"]>;
6
6
  export declare function initSentryRuntime(beforeSend: NodeOptions["beforeSend"], overrides?: Partial<Pick<NodeOptions, "transport">>, pendingBreadcrumbs?: readonly SentryBreadcrumb[]): SentryModule | undefined;
7
7
  export declare function finishSentryRuntimeSession(): void;
8
+ /** Close the transport's sockets once the final flush is done. */
9
+ export declare function closeSentryRuntimeTransport(): void;
8
10
  export declare function addSentryRuntimeBreadcrumb(breadcrumb: SentryBreadcrumb): void;
9
11
  export declare function flushSentryRuntime(timeoutMs: number): PromiseLike<boolean>;
10
12
  export {};
@@ -2,7 +2,8 @@ import { createRequire } from "node:module";
2
2
  import { BUNDLED_DSN } from "./sentry-dsn.generated.js";
3
3
  import { CLI_VERSION } from "./cli-version.js";
4
4
  import { beforeBreadcrumb } from "./utils/breadcrumb-buffer.js";
5
- import { residentProcessSkipsSentry } from "./utils/cli-network-lifecycle.js";
5
+ import { isScheduledShortRunCommand, residentProcessSkipsSentry } from "./utils/cli-network-lifecycle.js";
6
+ import { closeSentryTransportAgents, sentryHttpModule } from "./utils/sentry-keepalive-transport.js";
6
7
  import { getCachedSentryUser } from "./utils/sentry-identity.js";
7
8
  const requireRuntime = createRequire(import.meta.url);
8
9
  let sentryModule;
@@ -135,6 +136,8 @@ export function initSentryRuntime(beforeSend, overrides = {}, pendingBreadcrumbs
135
136
  beforeSend: createFlaggedBeforeSend(beforeSend),
136
137
  beforeBreadcrumb,
137
138
  integrations: (defaults) => defaults.filter((integration) => integration.name !== "ProcessSession"),
139
+ // One keep-alive connection, capped, instead of a new socket per envelope.
140
+ transportOptions: { httpModule: sentryHttpModule },
138
141
  ...overrides,
139
142
  });
140
143
  const user = getCachedSentryUser();
@@ -142,12 +145,20 @@ export function initSentryRuntime(beforeSend, overrides = {}, pendingBreadcrumbs
142
145
  sdk.setUser(user);
143
146
  for (const breadcrumb of pendingBreadcrumbs)
144
147
  sdk.addBreadcrumb(breadcrumb);
145
- sdk.startSession();
148
+ // A scheduled run (a daemon unit or timer, every 15 s to 6 h) sends only
149
+ // what it captures. Its release-health session was an envelope, and so a
150
+ // new ingest socket, on every clean run.
151
+ if (!isScheduledShortRunCommand(process.argv))
152
+ sdk.startSession();
146
153
  return sdk;
147
154
  }
148
155
  export function finishSentryRuntimeSession() {
149
156
  sentryModule?.endSession();
150
157
  }
158
+ /** Close the transport's sockets once the final flush is done. */
159
+ export function closeSentryRuntimeTransport() {
160
+ closeSentryTransportAgents();
161
+ }
151
162
  export function addSentryRuntimeBreadcrumb(breadcrumb) {
152
163
  sentryModule?.addBreadcrumb(breadcrumb);
153
164
  }
package/dist/sentry.d.ts CHANGED
@@ -26,5 +26,7 @@ export declare function epipeAwareBeforeSend(event: ErrorEvent, hint: EventHint)
26
26
  export declare function initSentry(overrides?: Partial<Pick<NodeOptions, "transport">>): void;
27
27
  /** Finish HQ's one per-invocation release-health session. */
28
28
  export declare function finishSentrySession(): void;
29
+ /** Close the Sentry transport's sockets after the run's final flush. */
30
+ export declare function closeSentryTransport(): void;
29
31
  export {};
30
32
  //# sourceMappingURL=sentry.d.ts.map
package/dist/sentry.js CHANGED
@@ -5,7 +5,7 @@ import { companySkillWrapperSentryTagsFor } from "./lib/company-skill-wrapper.js
5
5
  import { environmentalFsErrorMessage } from "./utils/environmental-error.js";
6
6
  import { incompleteInstallCaptureContext, incompleteInstallMessage, } from "./utils/incomplete-install-error.js";
7
7
  import { installTreeTornSentryTagsFor, sentryFingerprintFor, sentryMcpCollisionContextFor, } from "./utils/sentry-fingerprint.js";
8
- import { finishSentryRuntimeSession, initSentryRuntime } from "./sentry-init.js";
8
+ import { closeSentryRuntimeTransport, finishSentryRuntimeSession, initSentryRuntime, } from "./sentry-init.js";
9
9
  const inertSentryScope = {
10
10
  setTag: () => inertSentryScope,
11
11
  setUser: () => inertSentryScope,
@@ -232,4 +232,8 @@ export function initSentry(overrides = {}) {
232
232
  export function finishSentrySession() {
233
233
  finishSentryRuntimeSession();
234
234
  }
235
+ /** Close the Sentry transport's sockets after the run's final flush. */
236
+ export function closeSentryTransport() {
237
+ closeSentryRuntimeTransport();
238
+ }
235
239
  //# sourceMappingURL=sentry.js.map
@@ -19,7 +19,7 @@
19
19
  import { spawnSync } from "node:child_process";
20
20
  import { stringDerivedPackageRoot } from "./utils/hq-roots.js";
21
21
  import { updateLockPath, UPDATE_LOCK_STALE_MS } from "./utils/update-lock.js";
22
- import { classifyEvalThrow, classifyModuleNotFound, installRewriteInProgress, InstallTreeTornError, waitForInstallTreeSettled, } from "./utils/install-tree-torn.js";
22
+ import { classifyEvalThrow, classifyMissingRegistrationPlan, classifyModuleNotFound, installRewriteInProgress, InstallTreeTornError, waitForInstallTreeSettled, } from "./utils/install-tree-torn.js";
23
23
  /**
24
24
  * Set on the re-exec'd child so it can NEVER wait or re-exec again — distinct
25
25
  * from self-update's HQ_RESCUE_SELF_UPDATED so the two recovery paths cannot
@@ -95,7 +95,12 @@ export async function registerCommandsWithRecovery(args) {
95
95
  // dialects (incl. HQ-CLI-1S resolve-enoent); classifyEvalThrow covers a
96
96
  // module-EVALUATION throw (HQ-CLI-1T). Anything unclassified is rethrown as the
97
97
  // SAME object to the existing boundary, preserving today's behaviour exactly.
98
- const classified = classifyModuleNotFound(err) ?? classifyEvalThrow(err, packageRoot);
98
+ // classifyMissingRegistrationPlan covers a startup catalog root that the
99
+ // lazily imported plan does not know (HQ-CLI-GM): the catalog and the plan
100
+ // came from different installs, so it takes the loader-race path (no gate).
101
+ const classified = classifyModuleNotFound(err) ??
102
+ classifyMissingRegistrationPlan(err) ??
103
+ classifyEvalThrow(err, packageRoot);
99
104
  if (!classified)
100
105
  throw err;
101
106
  const lockPath = (deps.lockPath ?? updateLockPath)();
@@ -15,22 +15,14 @@
15
15
  * 3. `hq billing checkout` (see commands/billing.ts) reuses `mintPaymentLink`
16
16
  * to hand out the same link proactively.
17
17
  *
18
- * Legacy prices mirror the console's authoritative constants
19
- * (hq-console `src/lib/billing-pricing.ts`): amounts are in the smallest
20
- * currency unit (US cents) to match Stripe's wire shape. They apply to
21
- * accounts on the plans that existed before usage pricing.
22
- *
23
- * Usage pricing (US-012): boxes are quoted by size from the usage card
24
- * (`src/lib/billing/usage-card.ts`, `GET /v1/pricing` with a bundled
25
- * fallback): small t3.small, medium t3.medium, large t3.large, xlarge
26
- * t3.xlarge. Use {@link usageBoxQuotes} / {@link usageBoxQuoteCents}, never
27
- * the legacy constants, for a usage-only account.
18
+ * This module holds no list price. Usage pricing (US-012): boxes are quoted
19
+ * by size from the usage card (`src/lib/billing/usage-card.ts`,
20
+ * `GET /v1/pricing` with a bundled fallback): small t3.small, medium
21
+ * t3.medium, large t3.large, xlarge t3.xlarge. Use {@link usageBoxQuotes} /
22
+ * {@link usageBoxQuoteCents}. Callers pass the unit price to
23
+ * {@link confirmChargeOrExit}.
28
24
  */
29
25
  import { type UsageCard } from "../lib/billing/usage-card.js";
30
- /** Legacy per-Agent monthly list price, in cents ($100.00 / agent / month). */
31
- export declare const AGENT_PRICE_CENTS = 10000;
32
- /** Legacy per-Outpost monthly list price, in cents ($80.00 / Outpost / month). */
33
- export declare const OUTPOST_PRICE_CENTS = 8000;
34
26
  /** Usage-pricing box sizes, in card order ("small (t3.small) $100/month, ..."). */
35
27
  export declare function usageBoxQuotes(card?: UsageCard): string;
36
28
  /**
@@ -87,8 +79,12 @@ export declare function mintPaymentLink(token: string, setup: BillingSetupAction
87
79
  * message so the user can add a card (or hand the link to whoever owns billing)
88
80
  * and re-run. Returns the URL, or `null` when the server gave no `setup` action
89
81
  * to act on. Never prints tokens or secrets.
82
+ *
83
+ * `isUsagePricing` (US-034) is asked only after the link is minted. A
84
+ * usage-pricing company is told a card is needed before HQ creates the box;
85
+ * every other company, and an unknown plan, keeps the legacy sentence.
90
86
  */
91
- export declare function surfaceBillingRequired(token: string, billing: BillingErrorPayload): Promise<string | null>;
87
+ export declare function surfaceBillingRequired(token: string, billing: BillingErrorPayload, isUsagePricing?: () => Promise<boolean>): Promise<string | null>;
92
88
  /**
93
89
  * Status-aware surface for a 402 billing block. hq-pro's envelope carries two
94
90
  * distinct remediations that must never be conflated (mirroring the server's
@@ -103,5 +99,5 @@ export declare function surfaceBillingRequired(token: string, billing: BillingEr
103
99
  * - anything else (`billing_required`) — genuinely no usable card on
104
100
  * file; the existing add-a-card copy is correct.
105
101
  */
106
- export declare function surfaceBillingBlocked(token: string, billing: BillingErrorPayload, serverMessage?: string): Promise<string | null>;
102
+ export declare function surfaceBillingBlocked(token: string, billing: BillingErrorPayload, serverMessage?: string, isUsagePricing?: () => Promise<boolean>): Promise<string | null>;
107
103
  //# sourceMappingURL=billing-gate.d.ts.map
@@ -15,24 +15,16 @@
15
15
  * 3. `hq billing checkout` (see commands/billing.ts) reuses `mintPaymentLink`
16
16
  * to hand out the same link proactively.
17
17
  *
18
- * Legacy prices mirror the console's authoritative constants
19
- * (hq-console `src/lib/billing-pricing.ts`): amounts are in the smallest
20
- * currency unit (US cents) to match Stripe's wire shape. They apply to
21
- * accounts on the plans that existed before usage pricing.
22
- *
23
- * Usage pricing (US-012): boxes are quoted by size from the usage card
24
- * (`src/lib/billing/usage-card.ts`, `GET /v1/pricing` with a bundled
25
- * fallback): small t3.small, medium t3.medium, large t3.large, xlarge
26
- * t3.xlarge. Use {@link usageBoxQuotes} / {@link usageBoxQuoteCents}, never
27
- * the legacy constants, for a usage-only account.
18
+ * This module holds no list price. Usage pricing (US-012): boxes are quoted
19
+ * by size from the usage card (`src/lib/billing/usage-card.ts`,
20
+ * `GET /v1/pricing` with a bundled fallback): small t3.small, medium
21
+ * t3.medium, large t3.large, xlarge t3.xlarge. Use {@link usageBoxQuotes} /
22
+ * {@link usageBoxQuoteCents}. Callers pass the unit price to
23
+ * {@link confirmChargeOrExit}.
28
24
  */
29
25
  import chalk from "chalk";
30
26
  import { vaultApiFetch } from "./vault-api.js";
31
27
  import { BUNDLED_USAGE_CARD, formatBoxQuotes, } from "../lib/billing/usage-card.js";
32
- /** Legacy per-Agent monthly list price, in cents ($100.00 / agent / month). */
33
- export const AGENT_PRICE_CENTS = 10_000;
34
- /** Legacy per-Outpost monthly list price, in cents ($80.00 / Outpost / month). */
35
- export const OUTPOST_PRICE_CENTS = 8_000;
36
28
  /** Usage-pricing box sizes, in card order ("small (t3.small) $100/month, ..."). */
37
29
  export function usageBoxQuotes(card = BUNDLED_USAGE_CARD) {
38
30
  return formatBoxQuotes(card);
@@ -128,15 +120,22 @@ export async function mintPaymentLink(token, setup) {
128
120
  * message so the user can add a card (or hand the link to whoever owns billing)
129
121
  * and re-run. Returns the URL, or `null` when the server gave no `setup` action
130
122
  * to act on. Never prints tokens or secrets.
123
+ *
124
+ * `isUsagePricing` (US-034) is asked only after the link is minted. A
125
+ * usage-pricing company is told a card is needed before HQ creates the box;
126
+ * every other company, and an unknown plan, keeps the legacy sentence.
131
127
  */
132
- export async function surfaceBillingRequired(token, billing) {
128
+ export async function surfaceBillingRequired(token, billing, isUsagePricing = async () => false) {
133
129
  if (!billing.setup) {
134
130
  console.error(chalk.yellow("Provisioning is blocked on billing, but the server didn't return a " +
135
131
  "payment link. Add a card in the console billing page, then re-run."));
136
132
  return null;
137
133
  }
138
134
  const url = await mintPaymentLink(token, billing.setup);
139
- console.log(chalk.yellow("No card on file — provisioning is blocked until one is added."));
135
+ const usage = await isUsagePricing().catch(() => false);
136
+ console.log(chalk.yellow(usage
137
+ ? "A card is needed before HQ creates this box. The box bills to the card each month."
138
+ : "No card on file — provisioning is blocked until one is added."));
140
139
  console.log("Add a card here (safe to share with whoever owns billing):\n " +
141
140
  chalk.cyan(url));
142
141
  console.log(chalk.dim("Once a card is added, re-run the same command."));
@@ -156,9 +155,9 @@ export async function surfaceBillingRequired(token, billing) {
156
155
  * - anything else (`billing_required`) — genuinely no usable card on
157
156
  * file; the existing add-a-card copy is correct.
158
157
  */
159
- export async function surfaceBillingBlocked(token, billing, serverMessage) {
158
+ export async function surfaceBillingBlocked(token, billing, serverMessage, isUsagePricing) {
160
159
  if (billing.status !== "payment_failed") {
161
- return surfaceBillingRequired(token, billing);
160
+ return surfaceBillingRequired(token, billing, isUsagePricing);
162
161
  }
163
162
  console.error(chalk.yellow(serverMessage?.trim() ||
164
163
  "Your payment failed. Try a different card or contact your bank."));
@@ -6,6 +6,15 @@ export declare function isHqDaemonRunCommand(argv: readonly string[]): boolean;
6
6
  */
7
7
  export declare function isLongLivedDaemonCommand(argv: readonly string[]): boolean;
8
8
  export declare function isLongLivedHelperCommand(argv: readonly string[]): boolean;
9
+ /**
10
+ * True for a scheduled short run. Such a run still reports errors, but it does
11
+ * not start a release-health session, so a run with nothing to report opens no
12
+ * connection to Sentry. One session per run was one new ingest socket per run:
13
+ * a 15 s reconcile timer alone left thousands of sockets in TIME_WAIT a day.
14
+ */
15
+ export declare function isScheduledShortRunCommand(argv: readonly string[], options?: {
16
+ interactive?: boolean;
17
+ }): boolean;
9
18
  /**
10
19
  * True when this process must not open the Sentry transport. `HQ_DAEMON_RESIDENT`
11
20
  * marks the long-running process the daemon started, including one whose