@indigoai-us/hq-cli 5.345.219 → 5.345.220

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 (88) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/command-catalog.generated.d.ts +25 -1
  3. package/dist/command-catalog.generated.js +31 -1
  4. package/dist/commands/bot.d.ts +48 -0
  5. package/dist/commands/bot.js +108 -8
  6. package/dist/commands/cloud.d.ts +16 -0
  7. package/dist/commands/cloud.js +112 -102
  8. package/dist/commands/core-checkpoint-native.d.ts +13 -0
  9. package/dist/commands/core-checkpoint-native.js +167 -52
  10. package/dist/commands/core-hook-registration-plan.js +5 -4
  11. package/dist/commands/daemon.js +21 -2
  12. package/dist/commands/integrations.js +84 -3
  13. package/dist/commands/packs.js +23 -0
  14. package/dist/commands/pkg-update.d.ts +6 -0
  15. package/dist/commands/pkg-update.js +15 -7
  16. package/dist/commands/run.js +55 -45
  17. package/dist/commands/sources.js +3 -2
  18. package/dist/lib/bot/fleet-cron.js +5 -2
  19. package/dist/lib/bot/inflight.d.ts +9 -0
  20. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +51 -0
  21. package/dist/lib/bot/jobs/hot-signal-sync.js +90 -9
  22. package/dist/lib/bot/run.d.ts +29 -5
  23. package/dist/lib/bot/run.js +203 -1
  24. package/dist/lib/bot/signals-try-now.d.ts +76 -0
  25. package/dist/lib/bot/signals-try-now.js +111 -0
  26. package/dist/lib/capacity/collectors/claude-oauth.d.ts +22 -3
  27. package/dist/lib/capacity/collectors/claude-oauth.js +78 -22
  28. package/dist/lib/capacity/scheduler.d.ts +8 -0
  29. package/dist/lib/capacity/scheduler.js +5 -2
  30. package/dist/lib/daemon/run.js +5 -0
  31. package/dist/lib/daemon/runtime-notifications.d.ts +7 -0
  32. package/dist/lib/daemon/runtime-notifications.js +50 -0
  33. package/dist/lib/doctor/checks/fleet-hook-core.d.ts +9 -1
  34. package/dist/lib/doctor/checks/fleet-hook-core.js +39 -15
  35. package/dist/lib/hook-engine/fleet-registration.d.ts +17 -5
  36. package/dist/lib/hook-engine/fleet-registration.js +53 -17
  37. package/dist/lib/hot-channels/alert.d.ts +10 -1
  38. package/dist/lib/hot-channels/alert.js +34 -7
  39. package/dist/lib/hot-channels/signals-claude-login.d.ts +53 -0
  40. package/dist/lib/hot-channels/signals-claude-login.js +96 -0
  41. package/dist/lib/hot-channels/signals-pass.d.ts +17 -0
  42. package/dist/lib/hot-channels/signals-pass.js +31 -3
  43. package/dist/lib/search-index/index.js +11 -1
  44. package/dist/lib/signals/engine.d.ts +1 -0
  45. package/dist/lib/signals/engine.js +7 -0
  46. package/dist/lib/signals/reply.d.ts +48 -0
  47. package/dist/lib/signals/reply.js +72 -11
  48. package/dist/lib/signals/steps/adapters.js +6 -0
  49. package/dist/lib/signals/steps/extract.d.ts +50 -3
  50. package/dist/lib/signals/steps/extract.js +100 -17
  51. package/dist/lib/signals/steps/types.d.ts +19 -0
  52. package/dist/lib/sync-core/engine-home.d.ts +6 -1
  53. package/dist/lib/sync-core/engine-home.js +13 -3
  54. package/dist/lib/sync-core/reconcile.js +1 -1
  55. package/dist/lib/sync-core/release-compare.d.ts +7 -0
  56. package/dist/lib/sync-core/release-compare.js +16 -0
  57. package/dist/lib/sync-core/release.d.ts +2 -1
  58. package/dist/lib/sync-core/release.js +2 -10
  59. package/dist/run/schema-env-overrides.d.ts +24 -0
  60. package/dist/run/schema-env-overrides.js +72 -0
  61. package/dist/utils/host-registration.d.ts +1 -1
  62. package/dist/utils/host-registration.js +4 -0
  63. package/package.json +13 -9
  64. package/scripts/check-function-manifest.mjs +5 -4
  65. package/dist/commands/__fixtures__/access-vault.d.ts +0 -95
  66. package/dist/commands/__fixtures__/access-vault.js +0 -166
  67. package/dist/commands/__fixtures__/make-tar.d.ts +0 -38
  68. package/dist/commands/__fixtures__/make-tar.js +0 -102
  69. package/dist/commands/secrets-public-types.test-d.d.ts +0 -2
  70. package/dist/commands/secrets-public-types.test-d.js +0 -18
  71. package/dist/lib/decisions/fixtures/us001.d.ts +0 -137
  72. package/dist/lib/decisions/fixtures/us001.js +0 -21
  73. package/dist/lib/doctor/__testing__/fake-hq-tree.d.ts +0 -226
  74. package/dist/lib/doctor/__testing__/fake-hq-tree.js +0 -408
  75. package/dist/lib/doctor/__testing__/run-doctor.d.ts +0 -8
  76. package/dist/lib/doctor/__testing__/run-doctor.js +0 -69
  77. package/dist/lib/fingerprint/fixtures.d.ts +0 -19
  78. package/dist/lib/fingerprint/fixtures.js +0 -61
  79. package/dist/lib/hot-channels/adapters/__fixtures__/dummy.d.ts +0 -33
  80. package/dist/lib/hot-channels/adapters/__fixtures__/dummy.js +0 -53
  81. package/dist/lib/hot-channels/adapters/__fixtures__/meeting-providers.d.ts +0 -38
  82. package/dist/lib/hot-channels/adapters/__fixtures__/meeting-providers.js +0 -64
  83. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.d.ts +0 -2
  84. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.js +0 -10
  85. package/dist/lib/test-utils/isolated-flag-company-context.d.ts +0 -3
  86. package/dist/lib/test-utils/isolated-flag-company-context.js +0 -18
  87. package/scripts/hook-engine-manifest.mjs +0 -22
  88. package/scripts/mesh-daemon-if-stale.mjs +0 -20
@@ -297,6 +297,44 @@ export async function waitForApprovalTerminal(token, companyUid, queueId, option
297
297
  }
298
298
  return null;
299
299
  }
300
+ /**
301
+ * True when the gateway says the call ran but its result was not kept. An
302
+ * explicit `resultAvailable` is authoritative (true can pair with a null
303
+ * result: a call may legitimately return null). Only gateways that omit it
304
+ * fall back to `callAlreadyRan` with no result.
305
+ */
306
+ function resultNotKept(r) {
307
+ if (r.resultAvailable !== undefined)
308
+ return r.resultAvailable === false;
309
+ return r.callAlreadyRan === true && (r.result === null || r.result === undefined);
310
+ }
311
+ /** Detail suffix such as " (reason: x, 12 bytes)"; empty when the gateway sent neither. */
312
+ function resultOmittedDetail(r) {
313
+ const parts = [];
314
+ if (typeof r.resultOmittedReason === "string" && r.resultOmittedReason) {
315
+ parts.push(`reason: ${terminalSafeText(r.resultOmittedReason)}`);
316
+ }
317
+ if (typeof r.resultBytes === "number")
318
+ parts.push(`${r.resultBytes} bytes`);
319
+ return parts.length ? ` (${parts.join(", ")})` : "";
320
+ }
321
+ /** Plain-text notice for a finished call whose result was not kept. */
322
+ function resultNotKeptNotice(r) {
323
+ const message = typeof r.message === "string" && r.message.trim()
324
+ ? terminalSafeText(r.message)
325
+ : "The call ran and will not run again, but its result was not kept.";
326
+ return `${message}${resultOmittedDetail(r)}`;
327
+ }
328
+ /**
329
+ * Server note printed after a result that is present: the live-result shape
330
+ * (the row did not keep it, so this response is the only copy). Undefined
331
+ * when the gateway sent no message.
332
+ */
333
+ function resultPresentNote(r) {
334
+ if (typeof r.message !== "string" || !r.message.trim())
335
+ return undefined;
336
+ return `${terminalSafeText(r.message)}${resultOmittedDetail(r)}`;
337
+ }
300
338
  /**
301
339
  * Read the stored result of an approved call that already ran. The confirm
302
340
  * route answers an approve for a `resumed` row from the queue row
@@ -316,7 +354,19 @@ async function fetchStoredApprovalResult(token, companyUid, connectionId, queueI
316
354
  const body = (await res.json().catch(() => ({})));
317
355
  if (body.status !== "resumed" || body.alreadyResumed !== true)
318
356
  return undefined;
319
- return { result: body.result };
357
+ const stored = { result: body.result };
358
+ // Newer gateways say why a finished call has no result to show.
359
+ if (body.callAlreadyRan !== undefined)
360
+ stored.callAlreadyRan = body.callAlreadyRan;
361
+ if (body.resultAvailable !== undefined)
362
+ stored.resultAvailable = body.resultAvailable;
363
+ if (body.resultOmittedReason !== undefined)
364
+ stored.resultOmittedReason = body.resultOmittedReason;
365
+ if (body.resultBytes !== undefined)
366
+ stored.resultBytes = body.resultBytes;
367
+ if (body.message !== undefined)
368
+ stored.message = body.message;
369
+ return stored;
320
370
  }
321
371
  catch {
322
372
  return undefined;
@@ -644,7 +694,17 @@ export function registerIntegrationsCommand(program) {
644
694
  ? await fetchStoredApprovalResult(token, companyUid, connection.id, queueId)
645
695
  : undefined;
646
696
  if (opts.json) {
647
- printJson(stored && stored.result !== undefined ? { ...terminal, result: stored.result } : terminal);
697
+ printJson(stored
698
+ ? {
699
+ ...terminal,
700
+ ...(stored.result !== undefined ? { result: stored.result } : {}),
701
+ ...(stored.callAlreadyRan !== undefined ? { callAlreadyRan: stored.callAlreadyRan } : {}),
702
+ ...(stored.resultAvailable !== undefined ? { resultAvailable: stored.resultAvailable } : {}),
703
+ ...(stored.resultOmittedReason !== undefined ? { resultOmittedReason: stored.resultOmittedReason } : {}),
704
+ ...(stored.resultBytes !== undefined ? { resultBytes: stored.resultBytes } : {}),
705
+ ...(stored.message !== undefined ? { message: stored.message } : {}),
706
+ }
707
+ : terminal);
648
708
  }
649
709
  else if (approvalOutcomeFailed(terminal)) {
650
710
  const unknown = terminal.status === "write_unknown" || terminal.outcome === "unknown";
@@ -658,6 +718,16 @@ export function registerIntegrationsCommand(program) {
658
718
  console.log(chalk.green("Approved — the call completed."));
659
719
  if (stored && stored.result !== undefined && stored.result !== null) {
660
720
  printJson(unwrapGatewayResult(stored.result));
721
+ const note = resultPresentNote(stored);
722
+ if (note)
723
+ console.log(chalk.yellow(note));
724
+ }
725
+ else if (stored && resultNotKept(stored)) {
726
+ console.log(chalk.yellow(resultNotKeptNotice(stored)));
727
+ }
728
+ else if (stored && stored.resultAvailable === true) {
729
+ // The call legitimately returned null; same as the sync path.
730
+ printJson(stored.result ?? null);
661
731
  }
662
732
  else if (ran) {
663
733
  console.log(chalk.yellow(`The call's result could not be read back. Run \`hq integrations approve ${queueId} --provider ${bareProvider(connection.provider)}${opts.company ? ` --company ${opts.company}` : ""}\` again to fetch it; the call will not run twice.`));
@@ -705,8 +775,19 @@ export function registerIntegrationsCommand(program) {
705
775
  else {
706
776
  console.log(chalk.yellow(`Approval ended with status ${body.status ?? "unknown"}.`));
707
777
  }
708
- if (result !== undefined)
778
+ if (result !== undefined && result !== null) {
709
779
  printJson(result);
780
+ const note = resultPresentNote(body);
781
+ if (note)
782
+ console.log(chalk.yellow(note));
783
+ }
784
+ else if (resultNotKept(body)) {
785
+ console.log(chalk.yellow(resultNotKeptNotice(body)));
786
+ }
787
+ else if (result === null) {
788
+ // Older gateways, or a call that legitimately returned null.
789
+ printJson(result);
790
+ }
710
791
  });
711
792
  }
712
793
  registerConnectCommands(integrations);
@@ -22,6 +22,7 @@ import { codexTargets } from '../lib/install/codex-targets.js';
22
22
  import * as path from 'path';
23
23
  import * as readline from 'readline';
24
24
  import { spawnSync } from 'child_process';
25
+ import { Option } from 'commander';
25
26
  import chalk from 'chalk';
26
27
  import semverSatisfies from 'semver/functions/satisfies.js';
27
28
  import { findHqRoot } from '../utils/manifest.js';
@@ -442,6 +443,20 @@ export function registerPacksListCommand(parent) {
442
443
  }
443
444
  });
444
445
  }
446
+ /**
447
+ * `packs update` options that only apply to content packs. Each is a usage
448
+ * error together with `--registry`, which takes none of them.
449
+ */
450
+ const CONTENT_PACK_UPDATE_OPTIONS = [
451
+ 'json',
452
+ 'hqRoot',
453
+ 'checkOnly',
454
+ 'refresh',
455
+ 'yes',
456
+ 'allowHooks',
457
+ 'allowMcp',
458
+ 'branch',
459
+ ];
445
460
  export function registerPacksCommand(parent) {
446
461
  const packs = parent.command('packs').description('Content-pack lifecycle (install via `hq install`)');
447
462
  registerPacksListCommand(packs);
@@ -456,7 +471,15 @@ export function registerPacksCommand(parent) {
456
471
  .option('--allow-hooks', 'Install pack hooks without prompting')
457
472
  .option('--allow-mcp', 'Register pack MCP servers without prompting')
458
473
  .option('--branch', 'Follow the source branch instead of SHA-pinning')
474
+ .addOption(new Option('--registry', 'Update installed registry packages instead (same as `hq packages update [slug]`; [name] is the package slug)').conflicts([...CONTENT_PACK_UPDATE_OPTIONS]))
459
475
  .action(async (name, opts) => {
476
+ if (opts.registry) {
477
+ // Exactly the `hq packages update [slug]` path: same function, lease,
478
+ // checks, output and exit status.
479
+ const { runPackageUpdateCommand } = await import('./pkg-update.js');
480
+ await runPackageUpdateCommand(name);
481
+ return;
482
+ }
460
483
  try {
461
484
  const results = await runUpdate(name, opts);
462
485
  if (wantsJson(opts)) {
@@ -7,5 +7,11 @@
7
7
  import { Command } from 'commander';
8
8
  import { type ResidentCommandLeaseOptions } from '../utils/resident-package-preload.js';
9
9
  export declare function registerPackageUpdateCommand(parent: Command): void;
10
+ /**
11
+ * The whole `hq packages update [slug]` action: lease, registry check,
12
+ * integrity checks, output and exit status. `hq packs update --registry [slug]`
13
+ * calls this same function so the two commands cannot drift apart.
14
+ */
15
+ export declare function runPackageUpdateCommand(slug?: string): Promise<void>;
10
16
  export declare function runPackageUpdateWithLease<T>(run: () => Promise<T>, leaseOptions?: ResidentCommandLeaseOptions): Promise<T>;
11
17
  //# sourceMappingURL=pkg-update.d.ts.map
@@ -21,15 +21,23 @@ export function registerPackageUpdateCommand(parent) {
21
21
  .command('update [slug]')
22
22
  .description('Check for and apply package updates')
23
23
  .action(async (slug) => {
24
- try {
25
- await runPackageUpdateWithLease(() => updatePackages(slug));
26
- }
27
- catch (error) {
28
- console.error(chalk.red('Update failed:'), error instanceof Error ? error.message : 'Unknown error');
29
- process.exit(1);
30
- }
24
+ await runPackageUpdateCommand(slug);
31
25
  });
32
26
  }
27
+ /**
28
+ * The whole `hq packages update [slug]` action: lease, registry check,
29
+ * integrity checks, output and exit status. `hq packs update --registry [slug]`
30
+ * calls this same function so the two commands cannot drift apart.
31
+ */
32
+ export async function runPackageUpdateCommand(slug) {
33
+ try {
34
+ await runPackageUpdateWithLease(() => updatePackages(slug));
35
+ }
36
+ catch (error) {
37
+ console.error(chalk.red('Update failed:'), error instanceof Error ? error.message : 'Unknown error');
38
+ process.exit(1);
39
+ }
40
+ }
33
41
  export function runPackageUpdateWithLease(run, leaseOptions) {
34
42
  return runResidentCommandWithPackageLease("pkg-update", run, leaseOptions);
35
43
  }
@@ -12,6 +12,7 @@ import { vaultApiFetch, getCompanyUid } from '../utils/vault-api.js';
12
12
  import { discoverSchemas } from '../run/discover-schemas.js';
13
13
  import { installHqPlugin, itemIsOptional, prewarmHqSecrets } from '../run/hq-plugin.js';
14
14
  import { assertEnvGraphLoaded, resolveEnvValuesOrThrow, EnvGraphLoadError, EnvResolutionError, } from '../run/env-graph-guard.js';
15
+ import { clearInheritedSchemaOverrides, schemaDeclaredKeys, withoutInheritedSchemaEnv, } from '../run/schema-env-overrides.js';
15
16
  import { hadFatalRejection } from '../unhandled-rejection-boundary.js';
16
17
  import { withRunSecretReadTelemetry } from './run-feature-telemetry.js';
17
18
  import { isHqCliChild, releaseChildWrapperPackageUseLeaseAfterStart } from '../utils/child-wrapper-lease.js';
@@ -196,52 +197,61 @@ export function registerRunCommand(program) {
196
197
  }
197
198
  else {
198
199
  let state;
199
- const graph = await internal.loadEnvGraph({
200
- entryFilePaths: paths,
201
- // hq run owns its short-lived in-memory resolution. Varlock's default
202
- // cache auto-detection can write ~/.config/varlock and initialize
203
- // the native local-encryption helper, neither of which belongs on
204
- // this command path.
205
- skipCache: true,
206
- afterInit: async (g) => { state = installHqPlugin(g, pluginOpts); },
200
+ // feedback_d5698e57: inherited process.env must not replace schema
201
+ // hq() values. Varlock treats process.env as overrides; secrets exec
202
+ // injects last. Drop schema keys from the env and from the graph's
203
+ // override set so the vault (or .env.local) wins. Keep them unset
204
+ // through resolve so a later process.env re-read cannot restore them.
205
+ const declaredKeys = schemaDeclaredKeys(paths);
206
+ resolvedEnv = await withoutInheritedSchemaEnv(declaredKeys, async () => {
207
+ const graph = await internal.loadEnvGraph({
208
+ entryFilePaths: paths,
209
+ // hq run owns its short-lived in-memory resolution. Varlock's default
210
+ // cache auto-detection can write ~/.config/varlock and initialize
211
+ // the native local-encryption helper, neither of which belongs on
212
+ // this command path.
213
+ skipCache: true,
214
+ afterInit: async (g) => { state = installHqPlugin(g, pluginOpts); },
215
+ });
216
+ clearInheritedSchemaOverrides(graph, declaredKeys);
217
+ // Refuse to resolve a graph varlock never finished loading (a malformed
218
+ // .env.schema / .env.local): resolving an unprocessed item whose key is
219
+ // also in process.env reaches varlock's `expected dataType to be set`
220
+ // invariant as a FLOATED, never-settling rejection — the CLI then exits
221
+ // 0 with the command never run (HQ-CLI-W). Run this BEFORE prewarm so a
222
+ // bad file can never trigger a secret fetch.
223
+ assertEnvGraphLoaded(graph);
224
+ await prewarmHqSecrets(graph, pluginOpts, state);
225
+ // Defence in depth: convert a floated resolution rejection into a thrown
226
+ // error instead of hanging on varlock's never-settling promise, in case
227
+ // the shape-dependent guard above ever silently degrades.
228
+ await resolveEnvValuesOrThrow(graph);
229
+ // varlock's item.errors includes warning-severity entries (isWarning),
230
+ // e.g. "Value is very short! Is it actually sensitive?" for a short
231
+ // sensitive value. Print those and carry on; only real errors are fatal.
232
+ const schemaItems = Object.entries(graph.configSchema);
233
+ const itemMessages = (wantWarnings) => schemaItems.flatMap(([k, item]) => (item.errors ?? [])
234
+ .filter((e) => Boolean(e?.isWarning) === wantWarnings)
235
+ .filter((e) => {
236
+ if (wantWarnings)
237
+ return true;
238
+ if (!itemIsOptional(item))
239
+ return true;
240
+ const msg = e?.message ?? '';
241
+ return !/No read permission|does not exist in company|not returned by vault/.test(msg);
242
+ })
243
+ .map((e) => ` ${k}: ${e?.message ?? String(e)}`));
244
+ const warningMsgs = itemMessages(true);
245
+ if (warningMsgs.length > 0) {
246
+ process.stderr.write(`Warning: env var checks reported warnings:\n${warningMsgs.join('\n')}\n`);
247
+ }
248
+ const errorMsgs = itemMessages(false);
249
+ if (errorMsgs.length > 0) {
250
+ process.stderr.write(`Error: failed to resolve env vars:\n${errorMsgs.join('\n')}\n`);
251
+ process.exit(1);
252
+ }
253
+ return graph.getResolvedEnvObject();
207
254
  });
208
- // Refuse to resolve a graph varlock never finished loading (a malformed
209
- // .env.schema / .env.local): resolving an unprocessed item whose key is
210
- // also in process.env reaches varlock's `expected dataType to be set`
211
- // invariant as a FLOATED, never-settling rejection — the CLI then exits
212
- // 0 with the command never run (HQ-CLI-W). Run this BEFORE prewarm so a
213
- // bad file can never trigger a secret fetch.
214
- assertEnvGraphLoaded(graph);
215
- await prewarmHqSecrets(graph, pluginOpts, state);
216
- // Defence in depth: convert a floated resolution rejection into a thrown
217
- // error instead of hanging on varlock's never-settling promise, in case
218
- // the shape-dependent guard above ever silently degrades.
219
- await resolveEnvValuesOrThrow(graph);
220
- // varlock's item.errors includes warning-severity entries (isWarning),
221
- // e.g. "Value is very short! Is it actually sensitive?" for a short
222
- // sensitive value. Print those and carry on; only real errors are fatal.
223
- const schemaItems = Object.entries(graph.configSchema);
224
- const itemMessages = (wantWarnings) => schemaItems.flatMap(([k, item]) => (item.errors ?? [])
225
- .filter((e) => Boolean(e?.isWarning) === wantWarnings)
226
- .filter((e) => {
227
- if (wantWarnings)
228
- return true;
229
- if (!itemIsOptional(item))
230
- return true;
231
- const msg = e?.message ?? '';
232
- return !/No read permission|does not exist in company|not returned by vault/.test(msg);
233
- })
234
- .map((e) => ` ${k}: ${e?.message ?? String(e)}`));
235
- const warningMsgs = itemMessages(true);
236
- if (warningMsgs.length > 0) {
237
- process.stderr.write(`Warning: env var checks reported warnings:\n${warningMsgs.join('\n')}\n`);
238
- }
239
- const errorMsgs = itemMessages(false);
240
- if (errorMsgs.length > 0) {
241
- process.stderr.write(`Error: failed to resolve env vars:\n${errorMsgs.join('\n')}\n`);
242
- process.exit(1);
243
- }
244
- resolvedEnv = graph.getResolvedEnvObject();
245
255
  }
246
256
  const varCount = Object.keys(resolvedEnv).length;
247
257
  process.stderr.write(`Loaded ${varCount} env vars from .env.schema (company: ${slug})\n`);
@@ -37,6 +37,7 @@ import { createSignalsAlertChannelPoster, raiseSignalsFailureAlerts } from "../l
37
37
  import { audienceKey } from "../lib/hot-channels/audience.js";
38
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
+ import { recordSignalsPassClaudeLogin } from "../lib/hot-channels/signals-claude-login.js";
40
41
  import { backlogRunResult, parseSince, queueSignalsRedo, selectSignalsRedo, SignalsRedoUsageError, } from "../lib/hot-channels/signals-redo.js";
41
42
  import { assertSafeSegment } from "../lib/hot-channels/landing.js";
42
43
  import { acquireSyncLock, SYNC_LOCK_BUSY_REASON } from "../lib/hot-channels/sync-lock.js";
@@ -607,7 +608,7 @@ export async function runSync(options, overrides = {}) {
607
608
  ...(overrides.registry ? { registry: overrides.registry } : {}),
608
609
  ...(overrides.now ? { now: overrides.now } : {}),
609
610
  ...(overrides.createSelections ? { createSelections: overrides.createSelections } : {}),
610
- signalsGenerated: overrides.signalsGenerated ?? createClaudeSignalsPass({ hqRoot: options.hqRoot, company, botRuntime: defaultResolveBotRuntime }),
611
+ signalsGenerated: overrides.signalsGenerated ?? createClaudeSignalsPass({ hqRoot: options.hqRoot, company, botRuntime: defaultResolveBotRuntime, onClaudeLogin: recordSignalsPassClaudeLogin }),
611
612
  // The CLI has no owner-DM sender: the terminal is the primary alert here.
612
613
  signalsAlert: {
613
614
  sendOwnerDm: async (text) => {
@@ -723,7 +724,7 @@ export async function runSignalsRedo(options, overrides = {}) {
723
724
  });
724
725
  const pass = overrides.createPass
725
726
  ? overrides.createPass(maxDocs)
726
- : createClaudeSignalsPass({ hqRoot: options.hqRoot, company, maxDocs, botRuntime: defaultResolveBotRuntime });
727
+ : createClaudeSignalsPass({ hqRoot: options.hqRoot, company, maxDocs, botRuntime: defaultResolveBotRuntime, onClaudeLogin: recordSignalsPassClaudeLogin });
727
728
  for (const channel of channels) {
728
729
  try {
729
730
  report.signalsWritten += await pass(backlogRunResult(channel), { beforeWrite: lock.assertHeld });
@@ -437,10 +437,13 @@ export function renderFleetHotSignalSyncScript(input) {
437
437
  ? ["sources", "sync", "--trigger", "scheduled", "--company", input.company, "--hq-root", input.hqRoot]
438
438
  : ["signals", "run", "--trigger", "job", "--company", input.company, "--hq-root", input.hqRoot, "--report-found"];
439
439
  const syncCommand = `hq sources sync --company ${input.company}`;
440
+ const claudeSignInFix = `open HQ, go to Settings → AI tools, and use the Claude Code button there (Connect Claude, or Install Claude if it is not installed yet). Or run \`${signInCommand("claude")}\` in a terminal on this computer.`;
440
441
  const fixes = {
441
442
  hq_signed_out: "run `hq login`.",
442
- claude_signed_out: `run \`${signInCommand("claude")}\`.`,
443
- codex_bot_needs_claude: `sign in to Claude Code here (\`${signInCommand("claude")}\`).`,
443
+ // The desktop app first (Settings → AI tools lists Claude Code with a
444
+ // "Connect Claude" or "Install Claude" button), the terminal as the fallback.
445
+ claude_signed_out: claudeSignInFix,
446
+ codex_bot_needs_claude: claudeSignInFix,
444
447
  claude_missing: `install Claude Code (\`npm install -g @anthropic-ai/claude-code\`), then run \`${signInCommand("claude")}\`.`,
445
448
  claude_timeout_key: `run \`hq sources signals --company ${input.company} --key KEY\` to retry that document.`,
446
449
  claude_timeout: "the next run retries the document.",
@@ -73,6 +73,15 @@ export interface InflightTurn {
73
73
  /** Older markers: the raw excerpt. Not reported anywhere since 5.345.76. */
74
74
  excerpt?: string;
75
75
  };
76
+ /**
77
+ * A signals "Try now" run (US-006 AC9): the company it ran for and the
78
+ * job's zone. A run cut off by a restart puts the Try now offer back, so
79
+ * the owner's next "Try now" runs.
80
+ */
81
+ tryNow?: {
82
+ company: string;
83
+ timeZone?: string;
84
+ };
76
85
  rootEventId?: string;
77
86
  /** DM message carrying the thinking reaction, so a restart can clear it. */
78
87
  reactionEventId?: string;
@@ -42,6 +42,8 @@ import { type FormattedReply } from "../../signals/reply.js";
42
42
  import { type BotConfig } from "../config.js";
43
43
  import { type LocalJob } from "../local-jobs.js";
44
44
  export declare const HOT_SIGNAL_SYNC_JOB_KIND = "hot-signal-sync";
45
+ /** The job name in a "Try now" run's reply (the scheduled job's is "Morning signals"). */
46
+ export declare const TRY_NOW_JOB_NAME = "Signals";
45
47
  /**
46
48
  * 06:30 every day, in the job's time zone (the stored six-field form of
47
49
  * "30 6 * * *"). Only the first registration uses it; after that the job's
@@ -64,6 +66,16 @@ export declare function forgetHotSignalSyncRegistrationsExcept(dir: string, keep
64
66
  export declare function hotSignalSyncJobContext(company: string): Record<string, unknown>;
65
67
  /** The company a job item syncs, when its context marks it as this built-in; else null. */
66
68
  export declare function hotSignalSyncJobCompany(context: unknown): string | null;
69
+ /**
70
+ * The companies this bot runs the hot-signal-sync job for. A legacy bot's job
71
+ * is in its own `jobs.json`; an HQ Fleet Runtime bot's job lives in the
72
+ * runtime's cron store, which only the runtime's python can list, so its
73
+ * registration marker (`hot-signal-sync:fleet:{company}`) stands in for it.
74
+ * Never throws: an unreadable file counts as no job.
75
+ */
76
+ export declare function hotSignalSyncJobCompanies(dir: string, opts?: {
77
+ fleet?: boolean;
78
+ }): string[];
67
79
  /**
68
80
  * The HQ's active company from `{hqRoot}/.hq/config.json` (`activeCompany`),
69
81
  * the same company `hq sources sync` falls back to. Undefined when the file is
@@ -215,7 +227,34 @@ export interface HotSignalSyncRunInput {
215
227
  * the failure reply say when it tries again. Unset = no automatic retry.
216
228
  */
217
229
  scheduleRetry?: (at: string) => boolean;
230
+ /**
231
+ * The member answered a reply's "Try now" (US-006 AC9): one run with
232
+ * `trigger: "chat"` and `force: true`, the same as `hq signals run --trigger
233
+ * chat --force`, with the engine's caps and company lock. Never a catch-up,
234
+ * never retried. Runs only through the engine: with no engine (the
235
+ * cli.bot-signals-engine-job flag off) nothing runs.
236
+ */
237
+ tryNow?: boolean;
238
+ /**
239
+ * The reply goes to the HQ desktop app (the local bot's owner DM), so it
240
+ * links today's brief with `hq-desktop://brief` (US-023). Unset keeps the
241
+ * "Create today's brief" decision and writes no hq-desktop:// link.
242
+ */
243
+ desktopLinks?: boolean;
244
+ /**
245
+ * This bot has a scheduled brief job (`hasScheduledBriefJob`). Only then
246
+ * does a desktop reply say the brief builds next.
247
+ */
248
+ briefJobScheduled?: boolean;
218
249
  }
250
+ /**
251
+ * True when the bot's own jobs.json has a scheduled job that runs
252
+ * /daily-brief. hq-cli never starts the brief itself, so a reply says the
253
+ * brief builds next only when one of these exists. Cloud-scheduled jobs are
254
+ * not read here; a bot with only those gets the "open it to create" wording.
255
+ * Never throws: an unreadable jobs.json counts as no brief job.
256
+ */
257
+ export declare function hasScheduledBriefJob(dir: string): boolean;
219
258
  /**
220
259
  * The engine options a fired job passes. `signalsAlert` is the owner-DM
221
260
  * sender for the signals-failure alert (US-018, hq-cli #2314). Until #2314
@@ -240,7 +279,19 @@ export interface HotSignalSyncRunOutcome {
240
279
  retryAt?: string;
241
280
  /** The signals-failure alert already told the owner, so the bot sends no second DM for this run. */
242
281
  ownerAlerted?: boolean;
282
+ /** The reply asks the member for "Try now" (a failed or finished-with-problems run). */
283
+ tryNowOffered?: boolean;
284
+ /** Another run held the company lock, so this one started nothing. */
285
+ running?: boolean;
286
+ /** A Try now with no engine (flag off): nothing ran and nothing should be sent. */
287
+ notRun?: true;
243
288
  }
289
+ /**
290
+ * True when a member's message is the "Try now" answer: the decision button
291
+ * (which sends its label, "Try now") or the exact text the reply asks for.
292
+ * Case, surrounding space and quotes are ignored; anything else is not it.
293
+ */
294
+ export declare function isTryNowReply(text: string): boolean;
244
295
  /** Run the scheduled sync once and describe it in plain words. Never throws. */
245
296
  export declare function runHotSignalSyncJob(input: HotSignalSyncRunInput): Promise<HotSignalSyncRunOutcome>;
246
297
  export declare function describeSyncReport(company: string, report: OnDemandSyncReport): string;
@@ -39,10 +39,12 @@ import * as path from "node:path";
39
39
  import { signalsAlertKey } from "../../hot-channels/alert.js";
40
40
  import { JOB_RUN_OPTIONS_CONTEXT_KEY } from "../job-run.js";
41
41
  import { localDate, raiseStoppedRunAlert, runRecordRel } from "../../signals/engine.js";
42
- import { formatJobErrorReply, formatLockedReply, formatRunReply, timeInWords } from "../../signals/reply.js";
42
+ import { TRY_NOW_LABEL, TRY_NOW_OPTION_ID, formatJobErrorReply, formatLockedReply, formatRunReply, replyOffersTryNow, timeInWords, } from "../../signals/reply.js";
43
43
  import { effectiveBotCompanies, effectiveBotKind, readBotConfig } from "../config.js";
44
44
  import { ensureLocalJob, readLocalJobs, removeLocalJobsWhere, withJobsLock } from "../local-jobs.js";
45
45
  export const HOT_SIGNAL_SYNC_JOB_KIND = "hot-signal-sync";
46
+ /** The job name in a "Try now" run's reply (the scheduled job's is "Morning signals"). */
47
+ export const TRY_NOW_JOB_NAME = "Signals";
46
48
  /**
47
49
  * 06:30 every day, in the job's time zone (the stored six-field form of
48
50
  * "30 6 * * *"). Only the first registration uses it; after that the job's
@@ -149,6 +151,36 @@ export function hotSignalSyncJobCompany(context) {
149
151
  return null;
150
152
  return typeof company === "string" && company.trim() ? company.trim() : null;
151
153
  }
154
+ /**
155
+ * The companies this bot runs the hot-signal-sync job for. A legacy bot's job
156
+ * is in its own `jobs.json`; an HQ Fleet Runtime bot's job lives in the
157
+ * runtime's cron store, which only the runtime's python can list, so its
158
+ * registration marker (`hot-signal-sync:fleet:{company}`) stands in for it.
159
+ * Never throws: an unreadable file counts as no job.
160
+ */
161
+ export function hotSignalSyncJobCompanies(dir, opts = {}) {
162
+ const out = new Set();
163
+ if (opts.fleet) {
164
+ const prefix = fleetMarkerKey("");
165
+ for (const key of Object.keys(readMarker(dir).registered)) {
166
+ if (key.startsWith(prefix) && key.length > prefix.length)
167
+ out.add(key.slice(prefix.length));
168
+ }
169
+ }
170
+ else {
171
+ try {
172
+ for (const job of readLocalJobs(dir)) {
173
+ const company = hotSignalSyncJobCompany(job.context);
174
+ if (company)
175
+ out.add(company);
176
+ }
177
+ }
178
+ catch {
179
+ // An unreadable jobs.json: no job this bot can run now.
180
+ }
181
+ }
182
+ return [...out].sort();
183
+ }
152
184
  const ACTIVE_COMPANY_RE = /^[a-z0-9][a-z0-9_-]*$/i;
153
185
  /**
154
186
  * The HQ's active company from `{hqRoot}/.hq/config.json` (`activeCompany`),
@@ -357,6 +389,36 @@ function errorMessage(err) {
357
389
  return err instanceof Error ? err.message : String(err);
358
390
  }
359
391
  export const noLocalSignalsPass = async () => 0;
392
+ /** A job prompt that runs the daily-brief skill. */
393
+ const BRIEF_JOB_PROMPT = /(^|\s)\/daily-brief\b/;
394
+ /**
395
+ * True when the bot's own jobs.json has a scheduled job that runs
396
+ * /daily-brief. hq-cli never starts the brief itself, so a reply says the
397
+ * brief builds next only when one of these exists. Cloud-scheduled jobs are
398
+ * not read here; a bot with only those gets the "open it to create" wording.
399
+ * Never throws: an unreadable jobs.json counts as no brief job.
400
+ */
401
+ export function hasScheduledBriefJob(dir) {
402
+ try {
403
+ return readLocalJobs(dir).some((job) => typeof job.cron === "string" && BRIEF_JOB_PROMPT.test(job.prompt ?? ""));
404
+ }
405
+ catch {
406
+ return false;
407
+ }
408
+ }
409
+ /**
410
+ * True when a member's message is the "Try now" answer: the decision button
411
+ * (which sends its label, "Try now") or the exact text the reply asks for.
412
+ * Case, surrounding space and quotes are ignored; anything else is not it.
413
+ */
414
+ export function isTryNowReply(text) {
415
+ const core = text
416
+ .trim()
417
+ .replace(/^["'“”‘’`]+|["'“”‘’`]+$/g, "")
418
+ .trim()
419
+ .toLowerCase();
420
+ return core === TRY_NOW_LABEL.toLowerCase() || core === TRY_NOW_OPTION_ID;
421
+ }
360
422
  /**
361
423
  * Today's run record for the company, or null. The automatic retry reads it
362
424
  * first: when another run (a "Try now", a brief run) already finished the day
@@ -372,8 +434,10 @@ function readTodaysRecord(hqRoot, company, now) {
372
434
  }
373
435
  }
374
436
  async function runSignalsEngineJob(input) {
437
+ // A member's "Try now" can come at any hour: its reply says "Signals".
438
+ const jobName = input.tryNow ? TRY_NOW_JOB_NAME : "Morning signals";
375
439
  if (!input.hqRoot) {
376
- const reply = formatJobErrorReply(`Morning signals for ${input.company} did not run.`, "The bot has no HQ folder set, so it cannot find the company's files.");
440
+ const reply = formatJobErrorReply(`${jobName} for ${input.company} did not run.`, "The bot has no HQ folder set, so it cannot find the company's files.");
377
441
  return { ok: false, text: reply.text, report: null, reply };
378
442
  }
379
443
  const timeZone = input.timeZone ?? "UTC";
@@ -388,7 +452,7 @@ async function runSignalsEngineJob(input) {
388
452
  await raiseStoppedRunAlert({ hqRoot: input.hqRoot, company: input.company, now: input.now, senders, daysAgo });
389
453
  }
390
454
  }
391
- if (input.retry) {
455
+ if (input.retry && !input.tryNow) {
392
456
  const today = readTodaysRecord(input.hqRoot, input.company, input.now());
393
457
  if (today && (today.status === "complete" || today.status === "partial")) {
394
458
  const at = timeInWords(today.finishedAt, timeZone);
@@ -402,8 +466,10 @@ async function runSignalsEngineJob(input) {
402
466
  // The run right after the job is registered is a setup run, not the day's
403
467
  // scheduled run: a non-job trigger leaves jobRanAt alone, so the morning
404
468
  // job still runs (a bot first started at 01:00 is not "already ran").
405
- trigger: input.firstRun ? "manual" : "job",
406
- catchUp: input.catchUp,
469
+ // A member's "Try now" is `hq signals run --trigger chat --force` (US-006 AC9).
470
+ trigger: input.tryNow ? "chat" : input.firstRun ? "manual" : "job",
471
+ ...(input.tryNow ? { force: true } : {}),
472
+ catchUp: input.tryNow ? false : input.catchUp,
407
473
  now: input.now,
408
474
  // The signals-failure alert (US-018): the owner DM, sent even when the job is quiet.
409
475
  ...(input.sendAlert
@@ -416,21 +482,24 @@ async function runSignalsEngineJob(input) {
416
482
  }
417
483
  catch (err) {
418
484
  const reason = err instanceof Error ? err.message : String(err);
419
- const reply = formatJobErrorReply(`Morning signals for ${input.company} failed.`, reason);
485
+ const reply = formatJobErrorReply(`${jobName} for ${input.company} failed.`, reason);
420
486
  return { ok: false, text: reply.text, report: null, reply };
421
487
  }
422
488
  const replyOptions = {
423
489
  timeZone,
490
+ jobName,
424
491
  ...(input.scheduledFor ? { scheduledFor: input.scheduledFor } : {}),
492
+ ...(input.desktopLinks ? { desktopLinks: true } : {}),
493
+ ...(input.briefJobScheduled ? { briefJobScheduled: true } : {}),
425
494
  };
426
495
  const record = result.records.find((r) => r.company === input.company) ?? result.records[0];
427
496
  if (!record) {
428
497
  const locked = (result.locked ?? []).find((l) => l.company === input.company);
429
498
  if (locked) {
430
499
  const reply = formatLockedReply(locked, replyOptions);
431
- return { ok: true, text: reply.text, report: null, signals: result, reply };
500
+ return { ok: true, text: reply.text, report: null, signals: result, reply, running: true };
432
501
  }
433
- const reply = formatJobErrorReply(`Morning signals for ${input.company} did not finish.`, "The run left no run record, so I cannot say what happened.");
502
+ const reply = formatJobErrorReply(`${jobName} for ${input.company} did not finish.`, "The run left no run record, so I cannot say what happened.");
434
503
  return { ok: false, text: reply.text, report: null, signals: result, reply };
435
504
  }
436
505
  // One automatic retry per failed scheduled run, only when the engine set a
@@ -440,6 +509,7 @@ async function runSignalsEngineJob(input) {
440
509
  !record.alreadyRanToday &&
441
510
  typeof record.nextRetryAt === "string" &&
442
511
  !input.retry &&
512
+ !input.tryNow &&
443
513
  input.scheduleRetry !== undefined &&
444
514
  input.scheduleRetry(record.nextRetryAt);
445
515
  const reply = formatRunReply(record, result.summary, {
@@ -448,12 +518,23 @@ async function runSignalsEngineJob(input) {
448
518
  ...(input.retry ? { wasRetry: true } : {}),
449
519
  });
450
520
  const ok = reply.variant !== "failed" && reply.variant !== "partial";
451
- return { ok, text: reply.text, report: null, signals: result, reply, ...(retryScheduled ? { retryAt: record.nextRetryAt } : {}) };
521
+ return {
522
+ ok,
523
+ text: reply.text,
524
+ report: null,
525
+ signals: result,
526
+ reply,
527
+ ...(retryScheduled ? { retryAt: record.nextRetryAt } : {}),
528
+ ...(replyOffersTryNow(reply) ? { tryNowOffered: true } : {}),
529
+ };
452
530
  }
453
531
  /** Run the scheduled sync once and describe it in plain words. Never throws. */
454
532
  export async function runHotSignalSyncJob(input) {
455
533
  if (input.signals)
456
534
  return runSignalsEngineJob({ ...input, signals: input.signals });
535
+ // "Try now" is a signals-engine run only; without the engine nothing runs.
536
+ if (input.tryNow)
537
+ return { ok: false, text: "", report: null, notRun: true };
457
538
  const signalsPass = input.signalsPass ?? noLocalSignalsPass;
458
539
  let report;
459
540
  try {