@indigoai-us/hq-cli 5.345.218 → 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 (138) hide show
  1. package/CHANGELOG.md +130 -0
  2. package/dist/command-catalog.generated.d.ts +94 -1
  3. package/dist/command-catalog.generated.js +114 -1
  4. package/dist/commands/agents.d.ts +22 -0
  5. package/dist/commands/agents.js +92 -1
  6. package/dist/commands/bot.d.ts +48 -0
  7. package/dist/commands/bot.js +108 -8
  8. package/dist/commands/cloud.d.ts +16 -0
  9. package/dist/commands/cloud.js +112 -102
  10. package/dist/commands/core-checkpoint-native.d.ts +13 -0
  11. package/dist/commands/core-checkpoint-native.js +167 -52
  12. package/dist/commands/core-hook-registration-plan.d.ts +8 -0
  13. package/dist/commands/core-hook-registration-plan.js +22 -0
  14. package/dist/commands/core.js +9 -0
  15. package/dist/commands/daemon.js +21 -2
  16. package/dist/commands/doctor.js +4 -0
  17. package/dist/commands/integrations.js +84 -3
  18. package/dist/commands/lanes-shared.d.ts +2 -0
  19. package/dist/commands/lanes-watch.js +28 -1
  20. package/dist/commands/lanes.d.ts +2 -0
  21. package/dist/commands/lanes.js +99 -9
  22. package/dist/commands/packs.js +23 -0
  23. package/dist/commands/pkg-update.d.ts +6 -0
  24. package/dist/commands/pkg-update.js +15 -7
  25. package/dist/commands/reindex.js +6 -0
  26. package/dist/commands/run.js +55 -45
  27. package/dist/commands/sources.js +3 -2
  28. package/dist/index.js +8 -0
  29. package/dist/lib/anywhere-person-setting.d.ts +2 -2
  30. package/dist/lib/anywhere-person-setting.js +2 -2
  31. package/dist/lib/bot/fleet-cron.js +5 -2
  32. package/dist/lib/bot/inflight.d.ts +9 -0
  33. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +51 -0
  34. package/dist/lib/bot/jobs/hot-signal-sync.js +90 -9
  35. package/dist/lib/bot/run.d.ts +29 -5
  36. package/dist/lib/bot/run.js +203 -1
  37. package/dist/lib/bot/signals-try-now.d.ts +76 -0
  38. package/dist/lib/bot/signals-try-now.js +111 -0
  39. package/dist/lib/capacity/collectors/claude-oauth.d.ts +22 -3
  40. package/dist/lib/capacity/collectors/claude-oauth.js +78 -22
  41. package/dist/lib/capacity/scheduler.d.ts +8 -0
  42. package/dist/lib/capacity/scheduler.js +5 -2
  43. package/dist/lib/daemon/anywhere-listener.d.ts +33 -1
  44. package/dist/lib/daemon/anywhere-listener.js +86 -4
  45. package/dist/lib/daemon/machine-check-owner.d.ts +21 -0
  46. package/dist/lib/daemon/machine-check-owner.js +95 -0
  47. package/dist/lib/daemon/machine-check-registration.d.ts +4 -0
  48. package/dist/lib/daemon/machine-check-registration.js +64 -0
  49. package/dist/lib/daemon/machine-checks.d.ts +144 -0
  50. package/dist/lib/daemon/machine-checks.js +412 -0
  51. package/dist/lib/daemon/run.js +35 -4
  52. package/dist/lib/daemon/runtime-notifications.d.ts +7 -0
  53. package/dist/lib/daemon/runtime-notifications.js +50 -0
  54. package/dist/lib/daemon/server.d.ts +2 -0
  55. package/dist/lib/daemon/server.js +6 -0
  56. package/dist/lib/daemon/state-file.d.ts +12 -1
  57. package/dist/lib/daemon/state-file.js +23 -1
  58. package/dist/lib/doctor/checks/fleet-hook-core.d.ts +12 -0
  59. package/dist/lib/doctor/checks/fleet-hook-core.js +127 -0
  60. package/dist/lib/doctor/checks/host-core.js +3 -1
  61. package/dist/lib/doctor/checks/machine-checks.d.ts +16 -0
  62. package/dist/lib/doctor/checks/machine-checks.js +103 -0
  63. package/dist/lib/doctor/registry.js +4 -0
  64. package/dist/lib/doctor/types.d.ts +4 -0
  65. package/dist/lib/hook-engine/canary-gate.d.ts +64 -0
  66. package/dist/lib/hook-engine/canary-gate.js +147 -0
  67. package/dist/lib/hook-engine/coverage.d.ts +3 -1
  68. package/dist/lib/hook-engine/coverage.js +8 -2
  69. package/dist/lib/hook-engine/fleet-registration.d.ts +42 -0
  70. package/dist/lib/hook-engine/fleet-registration.js +168 -0
  71. package/dist/lib/hook-engine/reconcile.js +3 -2
  72. package/dist/lib/hook-engine/registration-identity.d.ts +33 -0
  73. package/dist/lib/hook-engine/registration-identity.js +97 -0
  74. package/dist/lib/hook-engine/registration.d.ts +1 -30
  75. package/dist/lib/hook-engine/registration.js +1 -88
  76. package/dist/lib/hook-engine/resolve.d.ts +2 -0
  77. package/dist/lib/hook-engine/resolve.js +7 -3
  78. package/dist/lib/hot-channels/alert.d.ts +10 -1
  79. package/dist/lib/hot-channels/alert.js +34 -7
  80. package/dist/lib/hot-channels/signals-claude-login.d.ts +53 -0
  81. package/dist/lib/hot-channels/signals-claude-login.js +96 -0
  82. package/dist/lib/hot-channels/signals-pass.d.ts +17 -0
  83. package/dist/lib/hot-channels/signals-pass.js +31 -3
  84. package/dist/lib/lanes/canonical-host.d.ts +8 -1
  85. package/dist/lib/lanes/canonical-host.js +9 -3
  86. package/dist/lib/lanes/machine-identity.d.ts +15 -0
  87. package/dist/lib/lanes/machine-identity.js +26 -0
  88. package/dist/lib/lanes/spawn.js +17 -3
  89. package/dist/lib/search-index/index.js +11 -1
  90. package/dist/lib/signals/engine.d.ts +1 -0
  91. package/dist/lib/signals/engine.js +7 -0
  92. package/dist/lib/signals/reply.d.ts +48 -0
  93. package/dist/lib/signals/reply.js +72 -11
  94. package/dist/lib/signals/steps/adapters.js +6 -0
  95. package/dist/lib/signals/steps/extract.d.ts +50 -3
  96. package/dist/lib/signals/steps/extract.js +100 -17
  97. package/dist/lib/signals/steps/types.d.ts +19 -0
  98. package/dist/lib/sync-core/engine-home.d.ts +6 -1
  99. package/dist/lib/sync-core/engine-home.js +13 -3
  100. package/dist/lib/sync-core/reconcile.js +1 -1
  101. package/dist/lib/sync-core/release-compare.d.ts +7 -0
  102. package/dist/lib/sync-core/release-compare.js +16 -0
  103. package/dist/lib/sync-core/release.d.ts +2 -1
  104. package/dist/lib/sync-core/release.js +2 -10
  105. package/dist/run/schema-env-overrides.d.ts +24 -0
  106. package/dist/run/schema-env-overrides.js +72 -0
  107. package/dist/utils/core-next-flag.d.ts +4 -0
  108. package/dist/utils/core-next-flag.js +22 -0
  109. package/dist/utils/core-next-kill.d.ts +16 -0
  110. package/dist/utils/core-next-kill.js +35 -0
  111. package/dist/utils/host-registration.d.ts +33 -23
  112. package/dist/utils/host-registration.js +90 -66
  113. package/package.json +14 -10
  114. package/scripts/check-function-manifest.mjs +5 -4
  115. package/dist/commands/__fixtures__/access-vault.d.ts +0 -95
  116. package/dist/commands/__fixtures__/access-vault.js +0 -166
  117. package/dist/commands/__fixtures__/make-tar.d.ts +0 -38
  118. package/dist/commands/__fixtures__/make-tar.js +0 -102
  119. package/dist/commands/secrets-public-types.test-d.d.ts +0 -2
  120. package/dist/commands/secrets-public-types.test-d.js +0 -18
  121. package/dist/lib/decisions/fixtures/us001.d.ts +0 -137
  122. package/dist/lib/decisions/fixtures/us001.js +0 -21
  123. package/dist/lib/doctor/__testing__/fake-hq-tree.d.ts +0 -226
  124. package/dist/lib/doctor/__testing__/fake-hq-tree.js +0 -408
  125. package/dist/lib/doctor/__testing__/run-doctor.d.ts +0 -8
  126. package/dist/lib/doctor/__testing__/run-doctor.js +0 -69
  127. package/dist/lib/fingerprint/fixtures.d.ts +0 -19
  128. package/dist/lib/fingerprint/fixtures.js +0 -61
  129. package/dist/lib/hot-channels/adapters/__fixtures__/dummy.d.ts +0 -33
  130. package/dist/lib/hot-channels/adapters/__fixtures__/dummy.js +0 -53
  131. package/dist/lib/hot-channels/adapters/__fixtures__/meeting-providers.d.ts +0 -38
  132. package/dist/lib/hot-channels/adapters/__fixtures__/meeting-providers.js +0 -64
  133. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.d.ts +0 -2
  134. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.js +0 -10
  135. package/dist/lib/test-utils/isolated-flag-company-context.d.ts +0 -3
  136. package/dist/lib/test-utils/isolated-flag-company-context.js +0 -18
  137. package/scripts/hook-engine-manifest.mjs +0 -22
  138. package/scripts/mesh-daemon-if-stale.mjs +0 -20
@@ -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 {
@@ -80,6 +80,25 @@ export declare const UNDELIVERABLE_JOB_REPORT_TEXT = "This scheduled run finishe
80
80
  */
81
81
  export declare const MAX_PARALLEL_JOB_TURNS = 1;
82
82
  export type SleepFn = (ms: number, signal?: AbortSignal) => Promise<void>;
83
+ /** What the bot's signals job (hot-signal-sync) reports for one run. */
84
+ export interface SignalsJobResult {
85
+ ok: boolean;
86
+ text: string;
87
+ ownerAlerted?: boolean;
88
+ /** The reply asks the member for "Try now" (US-006 AC9). */
89
+ tryNowOffered?: boolean;
90
+ /** Another run held the company lock, so this one started nothing. */
91
+ running?: boolean;
92
+ }
93
+ /** One "Try now" run (US-006 AC9). */
94
+ export interface SignalsTryNowInput {
95
+ company: string;
96
+ now: () => Date;
97
+ /** The job's zone, for the times in the reply. */
98
+ timeZone: string;
99
+ /** The signals-failure alert to the owner (US-012). */
100
+ sendAlert: (text: string) => Promise<void>;
101
+ }
83
102
  export interface BotRunDeps {
84
103
  dir: string;
85
104
  config: BotConfig;
@@ -120,11 +139,16 @@ export interface BotRunDeps {
120
139
  * offered for a local job's scheduled run, never for a retry.
121
140
  */
122
141
  scheduleRetry?: (at: string) => boolean;
123
- }) => Promise<{
124
- ok: boolean;
125
- text: string;
126
- ownerAlerted?: boolean;
127
- }>;
142
+ }) => Promise<SignalsJobResult>;
143
+ /**
144
+ * US-006 AC9: the member's "Try now" answer to a signals job reply.
145
+ * Resolves cli.bot-signals-engine-job the same way a fired job does and
146
+ * returns null when it is off (the message then goes to the model as
147
+ * before); otherwise the runner for one `--trigger chat --force` run of the
148
+ * signals engine through the job's own entry point, with its caps and lock.
149
+ * Unset = "Try now" is never handled here.
150
+ */
151
+ signalsTryNow?: () => Promise<((input: SignalsTryNowInput) => Promise<SignalsJobResult>) | null>;
128
152
  heartbeatIntervalMs?: number;
129
153
  readyComponents?: () => HeartbeatReadyComponents;
130
154
  /** Override the rendered system prompt (tests). */
@@ -92,7 +92,9 @@ import { isAgentSender, isDmItem, isMetaNonReply, resolveReplyTarget } from "./r
92
92
  import { resolveRoomMentionsForBot, roomPostHasMentionTokens, } from "./room-mentions.js";
93
93
  import { buildJobTurnPrompt, isCatchUpRun, isJobItem, jobReportHeader, jobRunOutput, machineTimeZone, planJobRuns, stripJobHeader, SUPERSEDED_DISPOSITION } from "./job-run.js";
94
94
  import { botJobQuietOptionEnabled } from "./job-quiet-flag.js";
95
- import { currentHotSignalSyncCompany, hotSignalSyncJobCompany, readActiveCompanySlug, removeStaleHotSignalSyncJobs } from "./jobs/hot-signal-sync.js";
95
+ import { currentHotSignalSyncCompany, hotSignalSyncJobCompany, isTryNowReply, readActiveCompanySlug, removeStaleHotSignalSyncJobs, } from "./jobs/hot-signal-sync.js";
96
+ import { classifyTryNowPress, readTryNowOffer, writeTryNowLastRun, writeTryNowOffer } from "./signals-try-now.js";
97
+ import { BOT_SIGNALS_ENGINE_JOB_FLAG } from "./signals-engine-flag.js";
96
98
  import { isLocalJobMessage, isLocalJobRetryMessage, localJobRetryMessageId, readLocalJobs } from "./local-jobs.js";
97
99
  import { drainBotEvents } from "./events.js";
98
100
  import { clearPendingJobCompletion, isCompletionDue, isCompletionExpired, isCompletionForOtherAgent, readPendingJobCompletions, recordPendingJobCompletion } from "./job-completions.js";
@@ -521,6 +523,26 @@ export async function runBot(deps) {
521
523
  log("warn", `setup intro state not updated: ${err instanceof Error ? err.message : String(err)}`);
522
524
  }
523
525
  };
526
+ /**
527
+ * US-006 AC9: remember whether the signals job's latest reply for `company`
528
+ * asked the member for "Try now" (signals-try-now.ts). A "Running" reply
529
+ * leaves the offer as it is. Never lets a bookkeeping error touch the run.
530
+ */
531
+ const noteTryNowOffer = (company, result, zone) => {
532
+ try {
533
+ if (result.tryNowOffered) {
534
+ writeTryNowOffer(dir, { company, offeredAt: now().toISOString(), timeZone: zone });
535
+ return;
536
+ }
537
+ const current = readTryNowOffer(dir);
538
+ // An offer for another company (the bot switched) never comes back.
539
+ if (current && (!result.running || current.company !== company))
540
+ writeTryNowOffer(dir, null);
541
+ }
542
+ catch (err) {
543
+ log("warn", `signals Try now offer not updated: ${err instanceof Error ? err.message : String(err)}`);
544
+ }
545
+ };
524
546
  /** The tool the pending "continue setup there?" offer named, while the kickoff waits on it. */
525
547
  const pendingToolOffer = () => {
526
548
  try {
@@ -1853,6 +1875,26 @@ export async function runBot(deps) {
1853
1875
  await completeJobRun(marker.jobId, marker.messageId, completion);
1854
1876
  patchInflight(dir, marker.messageId, { jobCompleted: completion.status });
1855
1877
  };
1878
+ /**
1879
+ * A signals "Try now" run cut off by a restart (no saved reply): the run
1880
+ * took the offer when it started, so put it back as of now, and the owner's
1881
+ * next "Try now" runs. A run that finished (saved reply) already set the
1882
+ * offer from its result. Never lets a bookkeeping error touch recovery.
1883
+ */
1884
+ const restoreTryNowOffer = (marker) => {
1885
+ if (!marker.tryNow || marker.reply !== undefined)
1886
+ return;
1887
+ try {
1888
+ writeTryNowOffer(dir, {
1889
+ company: marker.tryNow.company,
1890
+ offeredAt: now().toISOString(),
1891
+ ...(marker.tryNow.timeZone ? { timeZone: marker.tryNow.timeZone } : {}),
1892
+ });
1893
+ }
1894
+ catch (err) {
1895
+ log("warn", `signals Try now offer not restored after a restart: ${err instanceof Error ? err.message : String(err)}`);
1896
+ }
1897
+ };
1856
1898
  /**
1857
1899
  * The body a recovery posts. A scheduled run's FIRST message carries its
1858
1900
  * header, so a report delivered by this path still reads as a scheduled run
@@ -1932,6 +1974,7 @@ export async function runBot(deps) {
1932
1974
  else {
1933
1975
  await postOne(marker.target, UNDELIVERABLE_REPLY_TEXT, marker.rootEventId, undefined, marker.omitFromHistory).catch(() => undefined);
1934
1976
  }
1977
+ restoreTryNowOffer(marker);
1935
1978
  await closeMarker(marker, isKickoff);
1936
1979
  return true;
1937
1980
  }
@@ -1941,6 +1984,7 @@ export async function runBot(deps) {
1941
1984
  return false;
1942
1985
  }
1943
1986
  await reportRecoveredJobRun(marker);
1987
+ restoreTryNowOffer(marker);
1944
1988
  await closeMarker(marker, isKickoff);
1945
1989
  log("info", marker.reply
1946
1990
  ? `posted the saved reply for ${marker.messageId}`
@@ -2264,6 +2308,15 @@ export async function runBot(deps) {
2264
2308
  const currentCompany = currentHotSignalSyncCompany(freshConfig, readActiveCompanySlug(freshConfig.hqRoot) ?? null);
2265
2309
  if (currentCompany !== syncCompany) {
2266
2310
  let removedNote = "";
2311
+ // A Try now offer for a company the bot left goes; the current company's stays.
2312
+ try {
2313
+ const offer = readTryNowOffer(dir);
2314
+ if (offer && offer.company !== currentCompany)
2315
+ writeTryNowOffer(dir, null);
2316
+ }
2317
+ catch (err) {
2318
+ log("warn", `signals Try now offer not checked: ${err instanceof Error ? err.message : String(err)}`);
2319
+ }
2267
2320
  try {
2268
2321
  removeStaleHotSignalSyncJobs(dir, currentCompany);
2269
2322
  removedNote = ` Removed job ${jobId}.`;
@@ -2307,6 +2360,7 @@ export async function runBot(deps) {
2307
2360
  })
2308
2361
  : { ok: false, text: `This bot cannot run the hot-channel sync for ${syncCompany}.` };
2309
2362
  markProcessed(dir, id, now().toISOString());
2363
+ noteTryNowOffer(syncCompany, result, jobZone);
2310
2364
  const status = result.ok ? "succeeded" : "failed";
2311
2365
  // The signals-failure alert is the one DM for a failure it already covers.
2312
2366
  const sendReport = !(quietJob && result.ok) && !("ownerAlerted" in result && result.ownerAlerted === true);
@@ -2433,6 +2487,146 @@ export async function runBot(deps) {
2433
2487
  await holdAfterFailures(outcome.excerpt, sendToPerson, false, failureClass(outcome));
2434
2488
  }
2435
2489
  };
2490
+ /** When each pending inbox item was picked up (ms), for "Try now" ordering. */
2491
+ const enqueuedAt = new Map();
2492
+ /**
2493
+ * US-006 AC9: the owner's "Try now" answer to a signals job reply that
2494
+ * offered it. Runs the signals engine once for that company through the
2495
+ * job's own entry point (`--trigger chat --force`, the engine's caps and
2496
+ * company lock) and replies in the job's reply format, with no model turn.
2497
+ * The run takes the offer as it starts. A press sent before the last Try
2498
+ * now run finished (it waited behind that run in the owner's DM lane)
2499
+ * starts nothing and gets that run's result. A press while another run
2500
+ * holds the company lock starts nothing, gets the "already running" reply,
2501
+ * and leaves the offer as it was. Returns false (the normal model turn
2502
+ * answers) when the text is not "Try now", no offer is open, the company
2503
+ * is no longer this bot's, or cli.bot-signals-engine-job is off.
2504
+ */
2505
+ const runSignalsTryNow = async (item, text) => {
2506
+ const id = item.messageId;
2507
+ if (!deps.signalsTryNow || !isTryNowReply(text))
2508
+ return false;
2509
+ // When the press was sent: the server's receivedAt (always set by
2510
+ // hq-pro-agents), or when this loop picked it up, whichever is earlier.
2511
+ // A press queued behind a run that just ended is older than that run's end.
2512
+ const received = Date.parse(item.receivedAt ?? "");
2513
+ const exact = Number.isFinite(received);
2514
+ const picked = enqueuedAt.get(id);
2515
+ const pressedAtMs = Math.min(exact ? received : Infinity, picked ?? Infinity, now().getTime());
2516
+ let press;
2517
+ try {
2518
+ press = classifyTryNowPress(dir, pressedAtMs, now().getTime(), { exact });
2519
+ }
2520
+ catch (err) {
2521
+ log("warn", `"Try now" check failed (${err instanceof Error ? err.message : String(err)}); answering ${id} with a model turn`);
2522
+ return false;
2523
+ }
2524
+ if (press.kind === "none")
2525
+ return false;
2526
+ if (press.kind === "duplicate") {
2527
+ // Sent while the last Try now run was going: answer with its result, run nothing.
2528
+ const reply = `That "Try now" came in while a signals run was going. That run just finished: ${press.lastRun.prose}`;
2529
+ // Processed first: however the send goes, this press never starts a run later.
2530
+ markProcessed(dir, id, now().toISOString());
2531
+ let sent = true;
2532
+ try {
2533
+ await sendToTarget({ kind: "dm", peerUid: config.ownerUid }, reply, item.rootEventId, "human");
2534
+ }
2535
+ catch (err) {
2536
+ sent = false;
2537
+ log("warn", `"Try now" duplicate reply for ${id} was not delivered: ${err instanceof Error ? err.message : String(err)}`);
2538
+ }
2539
+ await api.ackInbox(config.agentUid, id);
2540
+ setStatus({ ...(sent ? { repliesSent: (readStatus()?.repliesSent ?? 0) + 1 } : {}), lastActivityAt: now().toISOString() });
2541
+ log("info", `answered ${id} ("Try now" sent during the last run) with that run's result; nothing started, no model turn`);
2542
+ return true;
2543
+ }
2544
+ const company = press.offer.company;
2545
+ const zone = press.offer.timeZone ?? timeZone;
2546
+ let run;
2547
+ try {
2548
+ const fresh = readBotConfig(dir);
2549
+ if (!fresh || currentHotSignalSyncCompany(fresh, readActiveCompanySlug(fresh.hqRoot) ?? null) !== company) {
2550
+ // The bot moved off that company: the offer goes, and the model answers.
2551
+ writeTryNowOffer(dir, null);
2552
+ log("info", `"Try now" ${id}: the offer for ${company} is not this bot's company any more; cleared it, answering with a model turn`);
2553
+ return false;
2554
+ }
2555
+ run = await deps.signalsTryNow();
2556
+ }
2557
+ catch (err) {
2558
+ log("warn", `"Try now" check failed (${err instanceof Error ? err.message : String(err)}); answering ${id} with a model turn`);
2559
+ return false;
2560
+ }
2561
+ if (!run) {
2562
+ log("info", `"Try now" ${id}: ${BOT_SIGNALS_ENGINE_JOB_FLAG} is off; answering with a model turn`);
2563
+ return false;
2564
+ }
2565
+ const target = { kind: "dm", peerUid: config.ownerUid };
2566
+ // In flight before the run starts, like a model turn: a crash mid-run is
2567
+ // reported to the owner on restart and never runs again.
2568
+ const startedAt = now().toISOString();
2569
+ writeInflight(dir, {
2570
+ v: 1,
2571
+ messageId: id,
2572
+ target,
2573
+ ...(item.rootEventId ? { rootEventId: item.rootEventId } : {}),
2574
+ startedAt,
2575
+ tryNow: { company, timeZone: zone },
2576
+ });
2577
+ // The run takes the offer: no other press can start a run off it.
2578
+ try {
2579
+ writeTryNowOffer(dir, null);
2580
+ }
2581
+ catch (err) {
2582
+ log("warn", `signals Try now offer not cleared: ${err instanceof Error ? err.message : String(err)}`);
2583
+ }
2584
+ const sendToOwner = (body) => sendToTarget(target, body, item.rootEventId, "human");
2585
+ let result;
2586
+ try {
2587
+ result = await run({ company, now, timeZone: zone, sendAlert: sendToOwner });
2588
+ }
2589
+ catch (err) {
2590
+ // The job's entry point never throws; this guards a broken wiring only.
2591
+ log("warn", `"Try now" run for ${company} threw: ${err instanceof Error ? err.message : String(err)}`);
2592
+ result = { ok: false, text: `Signals for ${company} did not run. I could not start the run, so nothing changed.` };
2593
+ }
2594
+ try {
2595
+ if (!result.running) {
2596
+ writeTryNowLastRun(dir, { company, startedAt, finishedAt: now().toISOString(), prose: result.text.split("\n\n")[0].trim() });
2597
+ }
2598
+ }
2599
+ catch (err) {
2600
+ log("warn", `signals Try now run not recorded: ${err instanceof Error ? err.message : String(err)}`);
2601
+ }
2602
+ if (result.running) {
2603
+ // Another run held the lock and this one started nothing: the offer stays.
2604
+ try {
2605
+ writeTryNowOffer(dir, press.offer);
2606
+ }
2607
+ catch (err) {
2608
+ log("warn", `signals Try now offer not restored: ${err instanceof Error ? err.message : String(err)}`);
2609
+ }
2610
+ }
2611
+ else {
2612
+ noteTryNowOffer(company, result, zone);
2613
+ }
2614
+ // The reply is saved first, so a send that fails is resent on the next poll.
2615
+ patchInflight(dir, id, { reply: result.text });
2616
+ try {
2617
+ await sendToOwner(result.text);
2618
+ }
2619
+ catch (err) {
2620
+ log("warn", `"Try now" reply for ${id} was not delivered (${err instanceof Error ? err.message : String(err)}); it is resent on the next poll`);
2621
+ return true;
2622
+ }
2623
+ markProcessed(dir, id, now().toISOString());
2624
+ await api.ackInbox(config.agentUid, id);
2625
+ clearInflight(dir, id);
2626
+ setStatus({ repliesSent: (readStatus()?.repliesSent ?? 0) + 1, lastActivityAt: now().toISOString() });
2627
+ log("info", `answered ${id} ("Try now") for ${company}: ${result.running ? "another run holds the lock, nothing started" : `one signals run, ${result.ok ? "ok" : "not ok"}`}; no model turn`);
2628
+ return true;
2629
+ };
2436
2630
  /**
2437
2631
  * The instant answer to "Explain HQ first" (setup-explain.ts). Returns true
2438
2632
  * when it answered the message (sent, marked processed, acked); false sends
@@ -2642,9 +2836,15 @@ export async function runBot(deps) {
2642
2836
  const ownerDm = target.kind === "dm" && target.peerUid === config.ownerUid;
2643
2837
  if (isSetupBot && ownerDm && (await sendSetupExplanation(item, messageText, attachmentRefs.length)))
2644
2838
  return;
2839
+ // Decisions first: a decision option labelled "Try now", or a decision
2840
+ // reply waiting to be resent, is never taken for the signals answer.
2645
2841
  const decisionTurn = ownerDm && messageText ? await runDecisionDm(item, messageText) : { done: false };
2646
2842
  if (decisionTurn.done)
2647
2843
  return;
2844
+ // Signals job: "Try now" after a reply that offered it runs one signals
2845
+ // run in code (US-006 AC9); anything else goes on as before.
2846
+ if (ownerDm && attachmentRefs.length === 0 && (await runSignalsTryNow(item, messageText)))
2847
+ return;
2648
2848
  const attempt = (attempts.get(id) ?? 0) + 1;
2649
2849
  attempts.set(id, attempt);
2650
2850
  const reactionId = item.eventId ?? id;
@@ -3035,6 +3235,7 @@ export async function runBot(deps) {
3035
3235
  resetInboxBackoff();
3036
3236
  busyLanes.delete(lane);
3037
3237
  pending.delete(item.messageId);
3238
+ enqueuedAt.delete(item.messageId);
3038
3239
  running.delete(task);
3039
3240
  pump();
3040
3241
  });
@@ -3045,6 +3246,7 @@ export async function runBot(deps) {
3045
3246
  if (pending.has(item.messageId))
3046
3247
  return;
3047
3248
  pending.add(item.messageId);
3249
+ enqueuedAt.set(item.messageId, now().getTime());
3048
3250
  const lane = inboxLaneKey(item, config);
3049
3251
  const queue = lanes.get(lane);
3050
3252
  if (queue)
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The "Try now" offer from the bot's signals job (hot-signal-sync US-006 AC9).
3
+ *
4
+ * When the built-in signals job replies that a run failed or finished with
5
+ * problems, the reply asks the member for "Try now" (a decision button whose
6
+ * click sends the text "Try now", or the line `Say "Try now" to run signals
7
+ * again.`). The runner remembers that offer here, in the bot's own folder, so
8
+ * the member's answer is handled by code: one signals run for that company
9
+ * through the job's own entry point, not a model turn.
10
+ *
11
+ * One offer per bot (the latest reply wins). A Try now run takes the offer as
12
+ * it starts, so a second press can never start a second run off the same
13
+ * offer. A job reply that offers no Try now clears it; a "Running" reply
14
+ * (another run held the lock) leaves it. An offer older than
15
+ * `TRY_NOW_OFFER_TTL_MS` is ignored, so a "Try now" typed days later goes to
16
+ * the model as before.
17
+ *
18
+ * `lastRun` is the latest Try now run. Owner DMs are handled one at a time,
19
+ * so a second press sent while a run was going is only read after it ends; a
20
+ * press sent before `lastRun.finishedAt` is that kind of duplicate and gets a
21
+ * short reply with the run's result instead of another run.
22
+ */
23
+ /** How long a Try now offer stays answerable: until the next morning's run. */
24
+ export declare const TRY_NOW_OFFER_TTL_MS: number;
25
+ /**
26
+ * A press with no server send time (`receivedAt`) picked up this soon after a
27
+ * Try now run ended is taken as sent during it: it gets the run's result,
28
+ * never a second run. hq-pro-agents always sets `receivedAt`; this covers a
29
+ * delivery path that does not.
30
+ */
31
+ export declare const TRY_NOW_UNTIMED_GRACE_MS: number;
32
+ export interface TryNowOffer {
33
+ company: string;
34
+ offeredAt: string;
35
+ /** The job's zone, for the times in the reply. */
36
+ timeZone?: string;
37
+ }
38
+ export interface TryNowLastRun {
39
+ company: string;
40
+ startedAt: string;
41
+ finishedAt: string;
42
+ /** The first line of the run's reply, for a duplicate press. */
43
+ prose: string;
44
+ }
45
+ export interface TryNowState {
46
+ v: 1;
47
+ offer: TryNowOffer | null;
48
+ lastRun?: TryNowLastRun | null;
49
+ }
50
+ export declare function readTryNowState(dir: string): TryNowState;
51
+ export declare function readTryNowOffer(dir: string): TryNowOffer | null;
52
+ /** Set (or clear, with null) the offer; the last run is kept. */
53
+ export declare function writeTryNowOffer(dir: string, offer: TryNowOffer | null): void;
54
+ /** Record the Try now run that just finished; the offer is kept. */
55
+ export declare function writeTryNowLastRun(dir: string, lastRun: TryNowLastRun): void;
56
+ export type TryNowPress = {
57
+ kind: "run";
58
+ offer: TryNowOffer;
59
+ } | {
60
+ kind: "duplicate";
61
+ lastRun: TryNowLastRun;
62
+ } | {
63
+ kind: "none";
64
+ };
65
+ /**
66
+ * What a "Try now" sent at `pressedAtMs` means, read at `nowMs`:
67
+ * - `duplicate`: sent before the latest Try now run finished (it waited
68
+ * behind that run), so it answers that run and starts nothing;
69
+ * - `run`: sent after the open offer was made;
70
+ * - `none`: no open offer (none made, taken, expired, or made after this
71
+ * press was sent), so the model answers as before.
72
+ */
73
+ export declare function classifyTryNowPress(dir: string, pressedAtMs: number, nowMs: number, opts?: {
74
+ exact?: boolean;
75
+ }): TryNowPress;
76
+ //# sourceMappingURL=signals-try-now.d.ts.map