@indigoai-us/hq-cli 5.345.215 → 5.345.217

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 (135) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/README.md +45 -0
  3. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  4. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  5. package/dist/command-catalog.generated.d.ts +59 -4
  6. package/dist/command-catalog.generated.js +74 -4
  7. package/dist/command-help.js +3 -1
  8. package/dist/command-registration-plan.d.ts +6 -0
  9. package/dist/command-registration-plan.js +1 -0
  10. package/dist/commands/auth.d.ts +1 -1
  11. package/dist/commands/auth.js +11 -52
  12. package/dist/commands/bot.js +11 -4
  13. package/dist/commands/cloud-demote.d.ts +19 -4
  14. package/dist/commands/cloud-demote.js +85 -12
  15. package/dist/commands/cloud-provision.d.ts +5 -1
  16. package/dist/commands/cloud-provision.js +6 -2
  17. package/dist/commands/cloud.d.ts +36 -0
  18. package/dist/commands/cloud.js +109 -26
  19. package/dist/commands/core.js +1 -0
  20. package/dist/commands/daemon.js +4 -1
  21. package/dist/commands/dm.js +7 -0
  22. package/dist/commands/doctor-usage.d.ts +8 -0
  23. package/dist/commands/doctor-usage.js +20 -0
  24. package/dist/commands/doctor.js +7 -1
  25. package/dist/commands/env.d.ts +18 -0
  26. package/dist/commands/env.js +82 -0
  27. package/dist/commands/install-global.js +2 -2
  28. package/dist/commands/lanes.js +100 -24
  29. package/dist/commands/logout.d.ts +7 -0
  30. package/dist/commands/logout.js +41 -34
  31. package/dist/commands/sources.d.ts +8 -2
  32. package/dist/commands/sources.js +65 -9
  33. package/dist/commands/whoami.js +26 -1
  34. package/dist/data/command-states.json +15 -0
  35. package/dist/index.js +52 -4
  36. package/dist/lazy-commands.js +2 -1
  37. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  38. package/dist/lib/anywhere-person-setting.js +6 -3
  39. package/dist/lib/billing/usage-card.d.ts +25 -4
  40. package/dist/lib/billing/usage-card.js +76 -9
  41. package/dist/lib/billing/usage-cost.d.ts +3 -3
  42. package/dist/lib/billing/usage-cost.js +35 -13
  43. package/dist/lib/billing/usage-only.js +4 -2
  44. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  45. package/dist/lib/billing/usage-rate-card.js +3 -0
  46. package/dist/lib/bot/fleet-cron.js +93 -6
  47. package/dist/lib/bot/inflight.d.ts +9 -0
  48. package/dist/lib/bot/inflight.js +10 -0
  49. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  50. package/dist/lib/bot/runtime/grok-acp.d.ts +1 -0
  51. package/dist/lib/bot/runtime/grok-acp.js +26 -11
  52. package/dist/lib/bot/runtime/grok.js +1 -1
  53. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  54. package/dist/lib/daemon/flag-monitor.js +17 -6
  55. package/dist/lib/daemon/flag.d.ts +65 -1
  56. package/dist/lib/daemon/flag.js +190 -40
  57. package/dist/lib/daemon/ops/policy.js +62 -5
  58. package/dist/lib/daemon/paths.d.ts +72 -2
  59. package/dist/lib/daemon/paths.js +154 -3
  60. package/dist/lib/daemon/run.js +25 -20
  61. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  62. package/dist/lib/daemon/selfcheck.js +40 -1
  63. package/dist/lib/daemon/server.d.ts +3 -1
  64. package/dist/lib/daemon/server.js +7 -22
  65. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  66. package/dist/lib/daemon/state-file-switch.js +88 -0
  67. package/dist/lib/daemon/state-file.d.ts +198 -0
  68. package/dist/lib/daemon/state-file.js +419 -0
  69. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  70. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  71. package/dist/lib/doctor/checks/host-core.d.ts +50 -0
  72. package/dist/lib/doctor/checks/host-core.js +269 -0
  73. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  74. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  75. package/dist/lib/doctor/registry.js +4 -0
  76. package/dist/lib/environment/profile.d.ts +239 -0
  77. package/dist/lib/environment/profile.js +251 -0
  78. package/dist/lib/hook-engine/reconcile.js +39 -13
  79. package/dist/lib/hook-engine/registration.d.ts +9 -0
  80. package/dist/lib/hook-engine/registration.js +19 -0
  81. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  82. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  83. package/dist/lib/hot-channels/alert.d.ts +2 -0
  84. package/dist/lib/hot-channels/alert.js +8 -1
  85. package/dist/lib/hot-channels/contract.d.ts +12 -0
  86. package/dist/lib/hot-channels/contract.js +7 -0
  87. package/dist/lib/hot-channels/loop.js +1 -0
  88. package/dist/lib/hot-channels/run.d.ts +6 -0
  89. package/dist/lib/hot-channels/run.js +4 -0
  90. package/dist/lib/hot-channels/signals-pass.d.ts +64 -1
  91. package/dist/lib/hot-channels/signals-pass.js +21 -49
  92. package/dist/lib/install/claude-targets.d.ts +12 -1
  93. package/dist/lib/install/claude-targets.js +57 -5
  94. package/dist/lib/install/codex-targets.d.ts +2 -2
  95. package/dist/lib/install/codex-targets.js +36 -6
  96. package/dist/lib/install/hook-target.d.ts +3 -0
  97. package/dist/lib/install/hook-target.js +11 -0
  98. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  99. package/dist/lib/lanes/canonical-host.js +65 -0
  100. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  101. package/dist/lib/lanes/host-capacity.js +29 -3
  102. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  103. package/dist/lib/mesh/live/daemon/run.js +5 -2
  104. package/dist/lib/mesh/live/flush.d.ts +5 -1
  105. package/dist/lib/mesh/live/flush.js +12 -6
  106. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  107. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  108. package/dist/lib/mesh/live/spool.d.ts +7 -0
  109. package/dist/lib/mesh/live/spool.js +25 -0
  110. package/dist/lib/person-setting-cache.d.ts +38 -0
  111. package/dist/lib/person-setting-cache.js +98 -0
  112. package/dist/lib/safe-store.d.ts +245 -0
  113. package/dist/lib/safe-store.js +777 -0
  114. package/dist/lib/signals/engine.d.ts +29 -2
  115. package/dist/lib/signals/engine.js +103 -4
  116. package/dist/lib/signals/reply.js +73 -18
  117. package/dist/lib/signals/steps/adapters.js +7 -2
  118. package/dist/lib/signals/steps/extract.d.ts +13 -0
  119. package/dist/lib/signals/steps/extract.js +84 -4
  120. package/dist/main.js +46 -3
  121. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  122. package/dist/utils/auth-expiry.d.ts +8 -0
  123. package/dist/utils/auth-expiry.js +53 -0
  124. package/dist/utils/cli-telemetry.d.ts +21 -0
  125. package/dist/utils/cli-telemetry.js +34 -0
  126. package/dist/utils/command-usage.d.ts +275 -0
  127. package/dist/utils/command-usage.js +797 -0
  128. package/dist/utils/hook-trust.d.ts +7 -0
  129. package/dist/utils/hook-trust.js +31 -4
  130. package/dist/utils/host-registration.d.ts +126 -0
  131. package/dist/utils/host-registration.js +378 -0
  132. package/dist/utils/resident-package-preload.js +2 -0
  133. package/package.json +10 -8
  134. package/scripts/bench-core.mjs +1096 -0
  135. package/scripts/check-function-manifest.mjs +702 -0
@@ -66,7 +66,8 @@ import { OUTPOST_DIR, OUTPOST_ID_PATH, readOutpostIdentity, resolveAdmissionHost
66
66
  export { OUTPOST_DIR, OUTPOST_ID_PATH, readOutpostIdentity } from "../lib/lanes/admission-host.js";
67
67
  import { buildOutpostCapacityCommand, buildOutpostIdentityBackfillCommand, buildOutpostLaneCommand, buildOutpostQuestionListCommand, buildOutpostPickupCommand, createOutpostsClient, dispatchErrorMessage, dispatchOutpostPickup, buildOutpostLaneListCommand, buildOutpostLegacyLaneUlidListCommand, REMOTE_LANE_READ_ENV, outpostRejectedEffortOption, parseOutpostPickupPayload, PICKUP_WAIT_MS, stageOutpostPayload, } from "../lib/lanes/outpost-dispatch.js";
68
68
  import { outpostHireSummaryCacheKey, OUTPOST_HIRE_SUMMARY_CACHE_TTL_MS, readOutpostHireSummaryCache, readOutpostHireSummaryCacheIncludingStale, writeOutpostHireSummaryCache, } from "../lib/lanes/outpost-hire-cache.js";
69
- import { buildHostCapacitySnapshot, chooseHostForLane, parseHostCapacitySnapshot, } from "../lib/lanes/host-capacity.js";
69
+ import { buildHostCapacitySnapshot, chooseHostForLane, hostCapacitySnapshotToWire, parseHostCapacitySnapshot, } from "../lib/lanes/host-capacity.js";
70
+ import { resolveCanonicalHost } from "../lib/lanes/canonical-host.js";
70
71
  import { BALANCE_MOVABLE_STATES, selectClaudeAccount, } from "../lib/lanes/claude-balance.js";
71
72
  import { parseUserYaml } from "../utils/user-yaml-error.js";
72
73
  import { backfillOutpostIdentityMarker as backfillOutpostIdentityMarkerImpl, createOutpostIdentityMarkerIfMissing, validateOutpostIdentityId, } from "../lib/lanes/outpost-identity.js";
@@ -3142,18 +3143,38 @@ function askDeliveryFailedPath(hqRoot, laneId) {
3142
3143
  async function emitLaneMeshEvent(ctx, company, threadId, event, payload) {
3143
3144
  if (!company)
3144
3145
  return;
3145
- let targetThreadId = threadId;
3146
- let eventPayload = payload;
3147
- const laneId = typeof payload.lane_id === "string" ? payload.lane_id.trim() : "";
3148
- if (laneId && ctx.mesh.ensureLaneThread) {
3149
- const lane = readLane(ctx.hqRoot(), laneId);
3150
- const ready = await ensureLaneThreadRecord(ctx, lane, lane.project_id, lane.story_id, "running");
3151
- targetThreadId = ready.thread_id;
3152
- eventPayload = { ...laneMeshEventIdentity(ready), ...payload };
3153
- }
3154
- if (!targetThreadId)
3155
- return;
3156
- await ctx.mesh.appendThreadEvent(company, targetThreadId, event, eventPayload);
3146
+ // lane_started races the just-spawned worker, which bumps the lane record.
3147
+ // The server rejects a stale lane.laneVersion on the append, so re-read the
3148
+ // lane and retry that one event once. Only this event is retried, so other
3149
+ // stories' lane_started events are never duplicated.
3150
+ const attempts = event === "lane_started" ? 2 : 1;
3151
+ for (let attempt = 1;; attempt++) {
3152
+ let targetThreadId = threadId;
3153
+ let eventPayload = payload;
3154
+ const laneId = typeof payload.lane_id === "string" ? payload.lane_id.trim() : "";
3155
+ if (laneId && ctx.mesh.ensureLaneThread) {
3156
+ const lane = readLane(ctx.hqRoot(), laneId);
3157
+ const ready = await ensureLaneThreadRecord(ctx, lane, lane.project_id, lane.story_id, "running");
3158
+ targetThreadId = ready.thread_id;
3159
+ eventPayload = {
3160
+ ...laneMeshEventIdentity(ready),
3161
+ ...payload,
3162
+ // A caller-supplied identity snapshot may predate a worker bump; the
3163
+ // fresh read wins for the version the server compares.
3164
+ ...("lane_version" in payload ? { lane_version: ready.version } : {}),
3165
+ };
3166
+ }
3167
+ if (!targetThreadId)
3168
+ return;
3169
+ try {
3170
+ await ctx.mesh.appendThreadEvent(company, targetThreadId, event, eventPayload);
3171
+ return;
3172
+ }
3173
+ catch (err) {
3174
+ if (attempt >= attempts || !isStaleLaneVersionError(err))
3175
+ throw err;
3176
+ }
3177
+ }
3157
3178
  }
3158
3179
  async function emitLaneTerminalStateSoft(ctx, lane) {
3159
3180
  if (lane.state !== "failed" && lane.state !== "interrupted" &&
@@ -3166,7 +3187,37 @@ async function emitLaneTerminalStateSoft(ctx, lane) {
3166
3187
  process.stderr.write(`hq lanes: terminal mesh update failed for ${lane.lane_id}: ${err instanceof Error ? err.message : String(err)}\n`);
3167
3188
  }
3168
3189
  }
3190
+ /**
3191
+ * The Work Mesh rejects a lane event whose lane.laneVersion is older than the
3192
+ * thread's copy. hq-pro work-mesh/thread-store.ts (appendThreadEvent lane
3193
+ * checks) throws WorkThreadPayloadValidationError("lane.laneVersion is stale"),
3194
+ * a 400-class error (work-mesh/events.ts). The CLI client (meshJson in
3195
+ * lib/mesh/api.ts) rethrows it with `status = 400` and a message of
3196
+ * `400 WorkThread payload validation failed [kind=lane_started]: lane.laneVersion is stale`.
3197
+ */
3198
+ function isStaleLaneVersionError(err) {
3199
+ if (!(err instanceof Error))
3200
+ return false;
3201
+ const status = err.status;
3202
+ return status === 400 && /lane\.laneVersion is stale/i.test(err.message);
3203
+ }
3204
+ /**
3205
+ * Post-spawn Work Mesh update for a started lane. The worker is already
3206
+ * running, so nothing here may fail the create: a non-zero exit would invite a
3207
+ * conductor to retry and spawn a second worker. Existing convention for mesh
3208
+ * trouble after the lane is live (story_not_on_board, emitLaneTerminalStateSoft)
3209
+ * is to keep going and report. Every failure is therefore returned as a
3210
+ * warning naming what did not sync and the manual fix, and also written to
3211
+ * stderr. Nothing claims the mesh will reconcile: no reconcile path was found.
3212
+ */
3169
3213
  async function emitLaneStartedForStories(ctx, company, lane, threadId, knownAbsentStories = new Set()) {
3214
+ const prefix = `Lane ${lane.lane_id} is RUNNING (do not re-run create).`;
3215
+ const warnings = [];
3216
+ const fail = (text) => {
3217
+ process.stderr.write(`hq lanes: ${prefix} ${text}\n`);
3218
+ warnings.push(`${prefix} ${text}`);
3219
+ };
3220
+ const storyFix = (story) => `hq mesh story --company ${company.slug} --project ${story.project_id} --story ${story.story_id} --status in_progress`;
3170
3221
  let ready = lane;
3171
3222
  if (ctx.mesh.ensureLaneThread) {
3172
3223
  try {
@@ -3176,14 +3227,13 @@ async function emitLaneStartedForStories(ctx, company, lane, threadId, knownAbse
3176
3227
  const warning = storyNotOnBoardWarning(err);
3177
3228
  if (warning !== undefined)
3178
3229
  return [warning];
3179
- throw err;
3230
+ fail(`Work Mesh lane registration failed (${err instanceof Error ? err.message : String(err)}), so the lane is not registered on the mesh and its stories were not moved to in_progress. Fix the mesh error and set story status by hand with the hq mesh story command.`);
3231
+ return warnings;
3180
3232
  }
3181
3233
  }
3182
3234
  const stableThreadId = ready.thread_id ?? threadId;
3183
3235
  if (!stableThreadId)
3184
3236
  return [];
3185
- const failures = [];
3186
- const warnings = [];
3187
3237
  for (const story of laneStories(ready)) {
3188
3238
  try {
3189
3239
  await emitLaneMeshEvent(ctx, company, stableThreadId, "lane_started", {
@@ -3199,7 +3249,10 @@ async function emitLaneStartedForStories(ctx, company, lane, threadId, knownAbse
3199
3249
  warnings.push(warning);
3200
3250
  continue;
3201
3251
  }
3202
- failures.push(err);
3252
+ const message = err instanceof Error ? err.message : String(err);
3253
+ fail(isStaleLaneVersionError(err)
3254
+ ? `The Work Mesh still rejected the lane_started event for story ${story.story_id} as stale after a re-read and retry (${message}). Set story status by hand: ${storyFix(story)}`
3255
+ : `The Work Mesh lane_started event for story ${story.story_id} failed (${message}). Set story status by hand: ${storyFix(story)}`);
3203
3256
  continue;
3204
3257
  }
3205
3258
  if (!story.project_id?.trim() || !story.story_id?.trim())
@@ -3213,12 +3266,11 @@ async function emitLaneStartedForStories(ctx, company, lane, threadId, knownAbse
3213
3266
  const warning = storyNotOnBoardWarning(err);
3214
3267
  if (warning !== undefined)
3215
3268
  warnings.push(warning);
3216
- else
3217
- failures.push(err);
3269
+ else {
3270
+ fail(`Story ${story.story_id} status was not set to in_progress (${err instanceof Error ? err.message : String(err)}). Set it by hand: ${storyFix(story)}`);
3271
+ }
3218
3272
  }
3219
3273
  }
3220
- if (failures.length > 0)
3221
- throw failures[0];
3222
3274
  return warnings;
3223
3275
  }
3224
3276
  async function assertStoriesOnBoard(ctx, company, projectId, storyIds) {
@@ -4699,6 +4751,9 @@ async function runCreate(ctx, opts) {
4699
4751
  locateTranscript: ctx.locateTranscript,
4700
4752
  });
4701
4753
  if (meshCompany) {
4754
+ // The worker is already running, so this never fails the create (see
4755
+ // emitLaneStartedForStories). The lane_started append re-reads the lane
4756
+ // and retries once on a stale laneVersion (emitLaneMeshEvent).
4702
4757
  createStoryWarnings.push(...await emitLaneStartedForStories(ctx, meshCompany, started, started.thread_id, knownAbsentStories));
4703
4758
  }
4704
4759
  }
@@ -6288,6 +6343,7 @@ async function runList(ctx, opts) {
6288
6343
  const placementEnabled = !remoteRead && await readLanePlacementEnabled(ctx, placementCompany);
6289
6344
  const host_capacity = placementEnabled
6290
6345
  ? (await loadHostCapacitySnapshots(ctx, hqRoot, undefined, allLanes)).entries
6346
+ .map((entry) => "schema_version" in entry ? hostCapacitySnapshotToWire(entry) : entry)
6291
6347
  : undefined;
6292
6348
  const result = {
6293
6349
  ok: true,
@@ -6419,20 +6475,40 @@ async function runCapacity(ctx) {
6419
6475
  const host = laneHostFromCtx(ctx);
6420
6476
  const admissionHost = reconcileHostFromCtx(ctx);
6421
6477
  const lanes = loadAllLanes(hqRoot);
6478
+ const now = ctx.now();
6479
+ const hostname = ctx.hostname();
6480
+ // Read only: this command also runs as the remote capacity probe.
6481
+ const localIdentity = observeLocalHostIdentity({ homedir: ctx.homedir(), hostname: hostname.trim() });
6482
+ const canonical = resolveCanonicalHost({
6483
+ host,
6484
+ hostname,
6485
+ ...(localIdentity
6486
+ ? { identityAliases: localIdentity.aliases, localIdentityId: localIdentity.id }
6487
+ : {}),
6488
+ lanes,
6489
+ now,
6490
+ });
6422
6491
  const snapshot = buildHostCapacitySnapshot({
6423
6492
  host,
6493
+ aliases: canonical.aliases,
6494
+ // Count what lane admission and `queued_lanes` below accept, no wider.
6495
+ localMatch: {
6496
+ hostname: admissionHost.hostname,
6497
+ ...(admissionHost.machineId !== undefined ? { machineId: admissionHost.machineId } : {}),
6498
+ ...(admissionHost.aliases !== undefined ? { aliases: admissionHost.aliases } : {}),
6499
+ },
6424
6500
  lanes,
6425
6501
  config: loadLanesConfig(hqRoot),
6426
6502
  existsSync: ctx.existsSync,
6427
6503
  probe: ctx.probeProvider,
6428
6504
  readClaudeCredential: ctx.readClaudeCredential,
6429
6505
  env: ctx.env,
6430
- hostname: ctx.hostname(),
6431
- now: ctx.now(),
6506
+ hostname,
6507
+ now,
6432
6508
  quotaState: loadQuotaState(hqRoot),
6433
6509
  });
6434
6510
  printJson({
6435
- ...snapshot,
6511
+ ...hostCapacitySnapshotToWire(snapshot),
6436
6512
  queued_lanes: lanes
6437
6513
  .filter((lane) => lane.state === "queued" && laneRunsHere(lane, admissionHost))
6438
6514
  .map((lane) => ({
@@ -4,8 +4,15 @@
4
4
  *
5
5
  * The refresh token is revoked first so a copied token file stops working.
6
6
  * Local tokens are always deleted, even when the server can't be reached.
7
+ *
8
+ * `hq auth logout` is a second name for this command and runs the
9
+ * same {@link runLogout}, so both names revoke the person session's refresh
10
+ * token. Machine sessions are out of scope: they carry no refresh token, and
11
+ * the machine token cache in the daemon state folder is not cleared here.
7
12
  */
8
13
  import { Command } from 'commander';
9
14
  export declare const REVOKE_FAILED_MESSAGE = "Signed out on this device. Couldn't reach HQ to end the session everywhere; it will expire on its own.";
15
+ /** Sign out: revoke the refresh token on the server, then delete local tokens. */
16
+ export declare function runLogout(): Promise<void>;
10
17
  export declare function registerLogoutCommand(program: Command): void;
11
18
  //# sourceMappingURL=logout.d.ts.map
@@ -4,6 +4,11 @@
4
4
  *
5
5
  * The refresh token is revoked first so a copied token file stops working.
6
6
  * Local tokens are always deleted, even when the server can't be reached.
7
+ *
8
+ * `hq auth logout` is a second name for this command and runs the
9
+ * same {@link runLogout}, so both names revoke the person session's refresh
10
+ * token. Machine sessions are out of scope: they carry no refresh token, and
11
+ * the machine token cache in the daemon state folder is not cleared here.
7
12
  */
8
13
  import chalk from 'chalk';
9
14
  import { clearCachedTokens, loadCachedTokens } from '@indigoai-us/hq-cloud';
@@ -12,43 +17,45 @@ import { workContextRoot } from '../lib/work-context/paths.js';
12
17
  import { DEFAULT_COGNITO } from '../utils/cognito-config.js';
13
18
  import { revokeRefreshToken } from '../utils/cognito-revoke.js';
14
19
  export const REVOKE_FAILED_MESSAGE = "Signed out on this device. Couldn't reach HQ to end the session everywhere; it will expire on its own.";
15
- export function registerLogoutCommand(program) {
16
- program
17
- .command('logout')
18
- .description('Log out and clear cached credentials')
19
- .action(async () => {
20
+ /** Sign out: revoke the refresh token on the server, then delete local tokens. */
21
+ export async function runLogout() {
22
+ try {
23
+ const { clearMcpOAuthCaches } = await import('../lib/daemon/mcp-oauth.js');
24
+ clearMcpOAuthCaches();
25
+ // Signing out withdraws the opt-in to count no-company usage toward the
26
+ // default company; the next account must opt in for itself.
20
27
  try {
21
- const { clearMcpOAuthCaches } = await import('../lib/daemon/mcp-oauth.js');
22
- clearMcpOAuthCaches();
23
- // Signing out withdraws the opt-in to count no-company usage toward the
24
- // default company; the next account must opt in for itself.
25
- try {
26
- retainUsageAttributionForPerson(null, { root: workContextRoot() });
27
- }
28
- catch (error) {
29
- console.error(chalk.yellow('Could not withdraw the usage opt-in:'), error instanceof Error ? error.message : 'Unknown error');
30
- }
31
- const existing = loadCachedTokens();
32
- if (!existing) {
33
- console.log(chalk.yellow('No cached HQ session'));
34
- return;
35
- }
36
- // Machine-minted sessions carry no refresh token; nothing to revoke.
37
- const revoked = existing.refreshToken
38
- ? (await revokeRefreshToken(existing.refreshToken, DEFAULT_COGNITO)).ok
39
- : true;
40
- clearCachedTokens();
41
- if (revoked) {
42
- console.log(chalk.green('Logged out successfully'));
43
- }
44
- else {
45
- console.log(chalk.yellow(REVOKE_FAILED_MESSAGE));
46
- }
28
+ retainUsageAttributionForPerson(null, { root: workContextRoot() });
47
29
  }
48
30
  catch (error) {
49
- console.error(chalk.red('Logout failed:'), error instanceof Error ? error.message : 'Unknown error');
50
- process.exit(1);
31
+ console.error(chalk.yellow('Could not withdraw the usage opt-in:'), error instanceof Error ? error.message : 'Unknown error');
32
+ }
33
+ const existing = loadCachedTokens();
34
+ if (!existing) {
35
+ console.log(chalk.yellow('No cached HQ session'));
36
+ return;
37
+ }
38
+ // Machine-minted sessions carry no refresh token; nothing to revoke.
39
+ const revoked = existing.refreshToken
40
+ ? (await revokeRefreshToken(existing.refreshToken, DEFAULT_COGNITO)).ok
41
+ : true;
42
+ clearCachedTokens();
43
+ if (revoked) {
44
+ console.log(chalk.green('Logged out successfully'));
51
45
  }
52
- });
46
+ else {
47
+ console.log(chalk.yellow(REVOKE_FAILED_MESSAGE));
48
+ }
49
+ }
50
+ catch (error) {
51
+ console.error(chalk.red('Logout failed:'), error instanceof Error ? error.message : 'Unknown error');
52
+ process.exit(1);
53
+ }
54
+ }
55
+ export function registerLogoutCommand(program) {
56
+ program
57
+ .command('logout')
58
+ .description('Log out and clear cached credentials')
59
+ .action(runLogout);
53
60
  }
54
61
  //# sourceMappingURL=logout.js.map
@@ -56,6 +56,8 @@ export interface SyncOptions {
56
56
  company?: string;
57
57
  hqRoot: string;
58
58
  json?: boolean;
59
+ /** What the ledger lines record: `scheduled` for the bot's daily job, `on-demand` by default. */
60
+ trigger?: RunTrigger;
59
61
  }
60
62
  export interface SyncOverrides {
61
63
  /** Adapters to run. This build registers none, so the default is empty. */
@@ -124,8 +126,8 @@ export interface SignalsAlertSenders {
124
126
  export declare function runCompanyHotChannelSync(input: CompanyHotChannelSyncInput): Promise<OnDemandSyncReport>;
125
127
  /**
126
128
  * Run every hot channel for the signed-in person now: each adapter once per
127
- * usable connection. Writes cursors, landed sources and an `on-demand` ledger
128
- * line under `companies/{company}/sources/`, and nothing else.
129
+ * usable connection. Writes cursors, landed sources and a ledger line (trigger
130
+ * `on-demand` unless `--trigger` says `scheduled`) under `companies/{company}/sources/`, and nothing else.
129
131
  */
130
132
  export declare function runSync(options: SyncOptions, overrides?: SyncOverrides): Promise<OnDemandSyncReport>;
131
133
  export interface SignalsRedoOptions {
@@ -160,7 +162,10 @@ export interface SignalsRedoReport {
160
162
  /** Keys still waiting in each channel's pending file after the run. */
161
163
  pendingLeft: Record<string, number>;
162
164
  notices: string[];
165
+ /** The message of an error that stopped the run, else the first failed channel's pass error code. */
163
166
  error: string | null;
167
+ /** Pass error code per channel whose pass failed; the other channels still ran. */
168
+ failedChannels: Record<string, string>;
164
169
  exitCode: number;
165
170
  }
166
171
  /**
@@ -201,6 +206,7 @@ export declare class NoHotSignalSyncJobError extends Error {
201
206
  * first. Exits non-zero when `--at` is given and no job exists.
202
207
  */
203
208
  export declare function runSchedule(options: ScheduleOptions, overrides?: ScheduleOverrides): Promise<ScheduleReport>;
209
+ export declare function describeThrownError(err: unknown): string;
204
210
  export declare function registerSourcesCommand(program: Command): void;
205
211
  export {};
206
212
  //# sourceMappingURL=sources.d.ts.map
@@ -23,7 +23,7 @@
23
23
  import { randomUUID } from "node:crypto";
24
24
  import * as fs from "node:fs";
25
25
  import * as path from "node:path";
26
- import { InvalidArgumentError } from "commander";
26
+ import { InvalidArgumentError, Option } from "commander";
27
27
  import chalk from "chalk";
28
28
  import { printDeletedCompanyNotices } from "../utils/deleted-company-notice.js";
29
29
  import { SOURCE_CHANNELS, assertSourceChannel, resolveEntity, listAvailableEntities, listSources, getSource, VaultClient, } from "@indigoai-us/hq-cloud";
@@ -35,7 +35,7 @@ import { Sentry } from "../sentry.js";
35
35
  import { resolveUploadAuthor } from "../utils/upload-author.js";
36
36
  import { createSignalsAlertChannelPoster, raiseSignalsFailureAlerts } from "../lib/hot-channels/alert.js";
37
37
  import { audienceKey } from "../lib/hot-channels/audience.js";
38
- import { appendRunLedgerEntry, ledgerDay, readRunLedger, summarizeRunLedger, } from "../lib/hot-channels/ledger.js";
38
+ import { appendRunLedgerEntry, ledgerDay, readRunLedger, RUN_TRIGGERS, summarizeRunLedger, } from "../lib/hot-channels/ledger.js";
39
39
  import { createClaudeSignalsPass, DEFAULT_MAX_SIGNAL_DOCS, readPendingSignals, SignalsPassError, } from "../lib/hot-channels/signals-pass.js";
40
40
  import { backlogRunResult, parseSince, queueSignalsRedo, selectSignalsRedo, SignalsRedoUsageError, } from "../lib/hot-channels/signals-redo.js";
41
41
  import { assertSafeSegment } from "../lib/hot-channels/landing.js";
@@ -47,6 +47,8 @@ import { createPersonVaultReader } from "../lib/hot-channels/person-vault-reader
47
47
  import { S3Client } from "@aws-sdk/client-s3";
48
48
  import { resolveCanonicalPersonUid } from "./cloud.js";
49
49
  import { botsRoot as defaultBotsRoot } from "../lib/bot/paths.js";
50
+ // The same main-bot runtime the signals engine's extract step uses.
51
+ import { defaultResolveBotRuntime } from "../lib/signals/steps/extract.js";
50
52
  import { ensureHotSignalSyncJob } from "../lib/bot/jobs/hot-signal-sync.js";
51
53
  import { resolveExecutiveBot } from "../lib/bot/executive.js";
52
54
  import { companyOfHotSignalSyncJob, fleetCronOps } from "../lib/bot/fleet-cron.js";
@@ -589,8 +591,8 @@ async function runLockedCompanySync(input, vaultRoot, personKey, author, session
589
591
  }
590
592
  /**
591
593
  * Run every hot channel for the signed-in person now: each adapter once per
592
- * usable connection. Writes cursors, landed sources and an `on-demand` ledger
593
- * line under `companies/{company}/sources/`, and nothing else.
594
+ * usable connection. Writes cursors, landed sources and a ledger line (trigger
595
+ * `on-demand` unless `--trigger` says `scheduled`) under `companies/{company}/sources/`, and nothing else.
594
596
  */
595
597
  export async function runSync(options, overrides = {}) {
596
598
  const company = options.company ?? readActiveCompanySlug(options.hqRoot);
@@ -601,10 +603,11 @@ export async function runSync(options, overrides = {}) {
601
603
  hqRoot: options.hqRoot,
602
604
  company,
603
605
  ...(options.adapter !== undefined ? { adapter: options.adapter } : {}),
606
+ ...(options.trigger !== undefined ? { trigger: options.trigger } : {}),
604
607
  ...(overrides.registry ? { registry: overrides.registry } : {}),
605
608
  ...(overrides.now ? { now: overrides.now } : {}),
606
609
  ...(overrides.createSelections ? { createSelections: overrides.createSelections } : {}),
607
- signalsGenerated: overrides.signalsGenerated ?? createClaudeSignalsPass({ hqRoot: options.hqRoot, company }),
610
+ signalsGenerated: overrides.signalsGenerated ?? createClaudeSignalsPass({ hqRoot: options.hqRoot, company, botRuntime: defaultResolveBotRuntime }),
608
611
  // The CLI has no owner-DM sender: the terminal is the primary alert here.
609
612
  signalsAlert: {
610
613
  sendOwnerDm: async (text) => {
@@ -697,6 +700,7 @@ export async function runSignalsRedo(options, overrides = {}) {
697
700
  pendingLeft: {},
698
701
  notices: [...selection.notices],
699
702
  error: null,
703
+ failedChannels: {},
700
704
  exitCode: 0,
701
705
  };
702
706
  const channels = [...new Set([...selection.pending.keys(), ...selection.worklist.keys()])];
@@ -719,9 +723,23 @@ export async function runSignalsRedo(options, overrides = {}) {
719
723
  });
720
724
  const pass = overrides.createPass
721
725
  ? overrides.createPass(maxDocs)
722
- : createClaudeSignalsPass({ hqRoot: options.hqRoot, company, maxDocs });
726
+ : createClaudeSignalsPass({ hqRoot: options.hqRoot, company, maxDocs, botRuntime: defaultResolveBotRuntime });
723
727
  for (const channel of channels) {
724
- report.signalsWritten += await pass(backlogRunResult(channel), { beforeWrite: lock.assertHeld });
728
+ try {
729
+ report.signalsWritten += await pass(backlogRunResult(channel), { beforeWrite: lock.assertHeld });
730
+ }
731
+ catch (err) {
732
+ // A pass failure on one channel does not skip the others, the way
733
+ // `hq sources sync` goes on to the next adapter. The signals this
734
+ // channel wrote before it failed still count. Any other error (a
735
+ // lost lock, a crash) stops the run below.
736
+ if (!(err instanceof SignalsPassError))
737
+ throw err;
738
+ report.signalsWritten += err.written;
739
+ report.failedChannels[channel] = err.code;
740
+ report.error ??= err.code;
741
+ report.exitCode = 1;
742
+ }
725
743
  }
726
744
  }
727
745
  catch (err) {
@@ -774,8 +792,13 @@ function renderSignalsRedo(report) {
774
792
  if (left > 0)
775
793
  lines.push(`${left} document(s) still queued in sources/${channel}; the next run picks them up.`);
776
794
  }
777
- if (report.error)
795
+ const failed = Object.entries(report.failedChannels);
796
+ for (const [channel, code] of failed) {
797
+ lines.push(chalk.red(`The signals pass for sources/${channel} failed: ${code}. Its queued documents stay queued.`));
798
+ }
799
+ if (report.error && !failed.some(([, code]) => code === report.error)) {
778
800
  lines.push(chalk.red(`The signals pass stopped: ${report.error}. Queued documents stay queued.`));
801
+ }
779
802
  }
780
803
  return lines.join("\n");
781
804
  }
@@ -912,6 +935,36 @@ async function finishScheduleReport(options, overrides, company, job, extraBots,
912
935
  // ---------------------------------------------------------------------------
913
936
  // Registration
914
937
  // ---------------------------------------------------------------------------
938
+ function innerErrorText(value) {
939
+ if (value instanceof Error)
940
+ return typeof value.message === "string" ? value.message : "";
941
+ return typeof value === "string" ? value : "";
942
+ }
943
+ function describeThrownErrorUnguarded(err) {
944
+ if (!(err instanceof Error))
945
+ return String(err) || "an empty error";
946
+ const name = typeof err.name === "string" && err.name ? err.name : "Error";
947
+ if (typeof err.message !== "string")
948
+ return `${name} with an unreadable message`;
949
+ if (err.message.trim())
950
+ return err.message;
951
+ const label = [name];
952
+ const code = err.code;
953
+ if (typeof code === "string" && code)
954
+ label.push(code);
955
+ const members = err instanceof AggregateError ? err.errors : [err.cause];
956
+ const inner = Array.isArray(members) ? members : [];
957
+ const details = [...new Set(inner.map(innerErrorText).filter((m) => m.trim()))].slice(0, 3);
958
+ return `${label.join(" ")} with no message${details.length > 0 ? `: ${details.join("; ")}` : ""}`;
959
+ }
960
+ export function describeThrownError(err) {
961
+ try {
962
+ return describeThrownErrorUnguarded(err);
963
+ }
964
+ catch {
965
+ return "an error that could not be described";
966
+ }
967
+ }
915
968
  /** Wrap an action so caught errors print red + capture to Sentry + exit 1. */
916
969
  function withErrorHandling(fn) {
917
970
  return async (...args) => {
@@ -919,7 +972,7 @@ function withErrorHandling(fn) {
919
972
  await fn(...args);
920
973
  }
921
974
  catch (err) {
922
- const message = err instanceof Error ? err.message : String(err);
975
+ const message = describeThrownError(err);
923
976
  process.stderr.write(chalk.red(`✗ ${message}\n`));
924
977
  Sentry.captureException(err);
925
978
  process.exit(1);
@@ -1009,6 +1062,9 @@ export function registerSourcesCommand(program) {
1009
1062
  .option("--adapter <id>", "Run one adapter only (a catalog provider or adapter id)")
1010
1063
  .option("--company <slug>", "Company slug (defaults to .hq/config.json activeCompany)")
1011
1064
  .option("--json", "Print the run report as JSON")
1065
+ .addOption(new Option("--trigger <trigger>", "What the run ledger records as the trigger; the bot's daily job passes scheduled")
1066
+ .choices([...RUN_TRIGGERS])
1067
+ .default("on-demand"))
1012
1068
  .option("--hq-root <path>", `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`, DEFAULT_HQ_ROOT)
1013
1069
  .action(withErrorHandling(async (options) => {
1014
1070
  await runSync(options);
@@ -10,6 +10,7 @@ import { resolveCompanyFlagGate, } from "../lib/flag-registry.js";
10
10
  import { queuePlanLimitInviteTeammateExposure } from "../utils/cli-telemetry.js";
11
11
  import { resolveCallerPersonUid } from "../utils/vault-api.js";
12
12
  import { printDeletedCompanyNotices } from "../utils/deleted-company-notice.js";
13
+ import { authExpiryIso, formatAuthExpiry } from "../utils/auth-expiry.js";
13
14
  export const CLI_LIMIT_INVITE_TEAMMATE_FLAG = "cli.limit-invite-teammate-v1";
14
15
  /**
15
16
  * Resolves the person represented by an ID token without pairing a delegated
@@ -151,10 +152,21 @@ async function printPlanBlock(company) {
151
152
  queuePlanLimitInviteTeammateExposure(status.companyUid);
152
153
  }
153
154
  }
155
+ /**
156
+ * Whether the cached session is valid and when it expires: the line
157
+ * `hq auth status` printed, so one command answers "who am I and is my
158
+ * session good". Reads the expiry only; no token is printed.
159
+ */
160
+ function sessionStatusLine(cached) {
161
+ const expiry = formatAuthExpiry(cached.expiresAt);
162
+ return isExpiring(cached)
163
+ ? chalk.yellow(`HQ session cached but expiring (expiresAt=${expiry})`)
164
+ : chalk.green(`HQ session valid (expiresAt=${expiry})`);
165
+ }
154
166
  export function registerWhoamiCommand(program) {
155
167
  program
156
168
  .command('whoami')
157
- .description('Show the currently authenticated user')
169
+ .description('Show signed-in user and session expiry')
158
170
  .option('--json', 'Output identity metadata as JSON (never tokens)')
159
171
  .option('--company <slug>', 'Also report this company\'s billing and usage notice')
160
172
  .action(async (opts) => {
@@ -200,6 +212,11 @@ export function registerWhoamiCommand(program) {
200
212
  personUid,
201
213
  agentUid,
202
214
  username: machineCreds?.username ?? null,
215
+ // Additive (what `hq auth status` reported): when the cached
216
+ // session expires, and whether it is inside the refresh window.
217
+ // Both are null when no session is cached.
218
+ sessionExpiresAt: identityCache ? authExpiryIso(identityCache.expiresAt) : null,
219
+ sessionExpiring: identityCache ? isExpiring(identityCache) : null,
203
220
  planLimits,
204
221
  }, null, 2));
205
222
  return;
@@ -213,21 +230,29 @@ export function registerWhoamiCommand(program) {
213
230
  ? peekIdToken(cached.idToken).entityUid
214
231
  : undefined;
215
232
  console.log(`Machine identity ${username}${entityUid ? ` (agent ${entityUid})` : ''} — sessions mint automatically`);
233
+ // Machine tokens live in the daemon state dir, never ~/.hq.
234
+ const machineSession = loadMachineCachedTokens();
235
+ if (machineSession)
236
+ console.log(sessionStatusLine(machineSession));
216
237
  console.log(`token source: machine`);
217
238
  await printPlanBlock(opts.company);
218
239
  return;
219
240
  }
220
241
  if (!cached) {
242
+ // No session, so no session status or token source to report.
221
243
  console.log("Not logged in. Run 'hq login' to authenticate.");
222
244
  return;
223
245
  }
224
246
  if (isExpiring(cached, 0)) {
225
247
  const who = resolveWhoamiIdentity(peekIdToken(cached.idToken)).email ?? 'unknown';
226
248
  console.log(chalk.yellow(`Session expired for ${who}. Run 'hq login' to re-authenticate.`));
249
+ console.log(chalk.dim('token source: person'));
227
250
  return;
228
251
  }
229
252
  const { email, sub } = resolveWhoamiIdentity(peekIdToken(cached.idToken));
230
253
  console.log(`Logged in as ${email ?? 'unknown'}${sub ? ` (${sub})` : ''}`);
254
+ console.log(sessionStatusLine(cached));
255
+ console.log(chalk.dim('token source: person'));
231
256
  await printPlanBlock(opts.company);
232
257
  // Person sessions only: a deleted company is otherwise invisible here.
233
258
  // Bounded like the person-uid lookup, on stderr, and never a failure.
@@ -0,0 +1,15 @@
1
+ {
2
+ "schema": 1,
3
+ "commands": {
4
+ "crm entity get": { "state": "retiring" },
5
+ "crm entity list": { "state": "retiring" },
6
+ "packages packs list": { "state": "retiring", "replacedBy": "hq packs list" },
7
+ "packages packs uninstall": { "state": "retiring", "replacedBy": "hq packs uninstall" },
8
+ "packages packs update": { "state": "retiring", "replacedBy": "hq packs update" },
9
+ "packages remove": { "state": "retiring", "replacedBy": "hq remove" },
10
+ "report access": { "state": "retiring" },
11
+ "report discard-draft": { "state": "retiring" },
12
+ "report promote": { "state": "retiring" },
13
+ "report templates": { "state": "retiring" }
14
+ }
15
+ }