@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
@@ -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
@@ -0,0 +1,111 @@
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
+ import * as fs from "node:fs";
24
+ import * as path from "node:path";
25
+ const TRY_NOW_STATE_FILE = "signals-try-now.json";
26
+ /** How long a Try now offer stays answerable: until the next morning's run. */
27
+ export const TRY_NOW_OFFER_TTL_MS = 24 * 60 * 60 * 1000;
28
+ /**
29
+ * A press with no server send time (`receivedAt`) picked up this soon after a
30
+ * Try now run ended is taken as sent during it: it gets the run's result,
31
+ * never a second run. hq-pro-agents always sets `receivedAt`; this covers a
32
+ * delivery path that does not.
33
+ */
34
+ export const TRY_NOW_UNTIMED_GRACE_MS = 2 * 60 * 1000;
35
+ const isIso = (value) => typeof value === "string" && Number.isFinite(Date.parse(value));
36
+ export function readTryNowState(dir) {
37
+ let raw;
38
+ try {
39
+ raw = fs.readFileSync(path.join(dir, TRY_NOW_STATE_FILE), "utf8");
40
+ }
41
+ catch {
42
+ // No file: no offer was ever made.
43
+ return { v: 1, offer: null, lastRun: null };
44
+ }
45
+ try {
46
+ const parsed = JSON.parse(raw);
47
+ if (parsed?.v !== 1)
48
+ return { v: 1, offer: null, lastRun: null };
49
+ const o = parsed.offer;
50
+ const offer = o && typeof o.company === "string" && o.company && isIso(o.offeredAt)
51
+ ? { company: o.company, offeredAt: o.offeredAt, ...(typeof o.timeZone === "string" && o.timeZone ? { timeZone: o.timeZone } : {}) }
52
+ : null;
53
+ const r = parsed.lastRun;
54
+ const lastRun = r && typeof r.company === "string" && r.company && isIso(r.startedAt) && isIso(r.finishedAt) && typeof r.prose === "string"
55
+ ? { company: r.company, startedAt: r.startedAt, finishedAt: r.finishedAt, prose: r.prose }
56
+ : null;
57
+ return { v: 1, offer, lastRun };
58
+ }
59
+ catch (err) {
60
+ console.warn(`hq bot: ignoring unreadable ${TRY_NOW_STATE_FILE}: ${err instanceof Error ? err.message : String(err)}`);
61
+ return { v: 1, offer: null, lastRun: null };
62
+ }
63
+ }
64
+ function writeTryNowState(dir, state) {
65
+ const file = path.join(dir, TRY_NOW_STATE_FILE);
66
+ if (!state.offer && !state.lastRun) {
67
+ fs.rmSync(file, { force: true });
68
+ return;
69
+ }
70
+ const tmp = `${file}.${process.pid}.tmp`;
71
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
72
+ fs.renameSync(tmp, file);
73
+ }
74
+ export function readTryNowOffer(dir) {
75
+ return readTryNowState(dir).offer;
76
+ }
77
+ /** Set (or clear, with null) the offer; the last run is kept. */
78
+ export function writeTryNowOffer(dir, offer) {
79
+ writeTryNowState(dir, { ...readTryNowState(dir), offer });
80
+ }
81
+ /** Record the Try now run that just finished; the offer is kept. */
82
+ export function writeTryNowLastRun(dir, lastRun) {
83
+ writeTryNowState(dir, { ...readTryNowState(dir), lastRun });
84
+ }
85
+ function fresh(iso, nowMs) {
86
+ const at = Date.parse(iso);
87
+ return Number.isFinite(at) && nowMs - at <= TRY_NOW_OFFER_TTL_MS && at - nowMs <= TRY_NOW_OFFER_TTL_MS;
88
+ }
89
+ /**
90
+ * What a "Try now" sent at `pressedAtMs` means, read at `nowMs`:
91
+ * - `duplicate`: sent before the latest Try now run finished (it waited
92
+ * behind that run), so it answers that run and starts nothing;
93
+ * - `run`: sent after the open offer was made;
94
+ * - `none`: no open offer (none made, taken, expired, or made after this
95
+ * press was sent), so the model answers as before.
96
+ */
97
+ export function classifyTryNowPress(dir, pressedAtMs, nowMs, opts = {}) {
98
+ const { offer, lastRun } = readTryNowState(dir);
99
+ // Without the server's send time only the pickup time is known, and a
100
+ // press may have waited unpolled while the run went on: anything picked up
101
+ // within the grace after a run ended counts as sent during it.
102
+ const grace = opts.exact === false ? TRY_NOW_UNTIMED_GRACE_MS : 0;
103
+ if (lastRun && fresh(lastRun.finishedAt, nowMs) && pressedAtMs < Date.parse(lastRun.finishedAt) + grace) {
104
+ return { kind: "duplicate", lastRun };
105
+ }
106
+ if (offer && fresh(offer.offeredAt, nowMs) && pressedAtMs >= Date.parse(offer.offeredAt)) {
107
+ return { kind: "run", offer };
108
+ }
109
+ return { kind: "none" };
110
+ }
111
+ //# sourceMappingURL=signals-try-now.js.map
@@ -61,7 +61,11 @@ export declare const CLAUDE_OAUTH_REFRESH_BACKOFF_MS: number;
61
61
  export declare const CLAUDE_OAUTH_REFRESH_REVOKED_BACKOFF_MS: number;
62
62
  /** Try a refresh when the token is this close to expiry, so one tick does not land on a stale token. */
63
63
  export declare const CLAUDE_OAUTH_REFRESH_PREFLIGHT_MS: number;
64
- export declare const CLAUDE_OAUTH_REFRESH_TIMEOUT_MS = 10000;
64
+ /**
65
+ * Claude refresh tokens are single use. A refresh the server completed but whose
66
+ * response we abandoned leaves the stored token dead, so this limit is generous.
67
+ */
68
+ export declare const CLAUDE_OAUTH_REFRESH_TIMEOUT_MS = 30000;
65
69
  export declare const CLAUDE_OAUTH_REFRESH_LAST_FILE = "claude-oauth-refresh-last.json";
66
70
  export interface ClaudeOAuthFetchInit {
67
71
  method: "GET";
@@ -137,14 +141,24 @@ export interface WriteClaudeCredentialsResult {
137
141
  error?: string;
138
142
  }
139
143
  export type WriteClaudeCredentials = (request: WriteClaudeCredentialsRequest) => Promise<WriteClaudeCredentialsResult>;
144
+ /**
145
+ * Reads the refresh token currently stored for a home. `null` = stored item has no
146
+ * refresh token; `undefined` = the item could not be read. Never logged.
147
+ */
148
+ export type ReadStoredClaudeRefreshToken = (request: {
149
+ home: string;
150
+ service: string;
151
+ platform: NodeJS.Platform;
152
+ }) => string | null | undefined;
140
153
  /**
141
154
  * One row per lane the gate must consider.
142
155
  * - `isLive` is true for state ∈ {queued, running, awaiting_input}: a running
143
156
  * Claude Code may hold the home; a refresh would race and get invalid_grant.
144
157
  * - `isAuthFailed` is true when the lane terminated with reason
145
158
  * `provider_auth_failed` (src/lib/lanes/watcher.ts classifies 401/403 that
146
- * way). The gate treats this as proof the account is already signed out and
147
- * records revoked without hitting the token endpoint.
159
+ * way). The refresh gate no longer treats this as proof of revocation: the
160
+ * lane may have failed on an older token. Only invalid_grant from the token
161
+ * endpoint marks a refresh token revoked.
148
162
  * - `home` is the resolved per-host provider home for the account; the gate
149
163
  * compares it to the home being refreshed with `canonicalHomePath` (realpath,
150
164
  * lower case on darwin) so symlinks and case differences do not slip through;
@@ -225,6 +239,11 @@ export interface CollectClaudeOAuthOptions {
225
239
  * preserving all sibling fields (including `mcpOAuth`).
226
240
  */
227
241
  writeCredentials?: WriteClaudeCredentials;
242
+ /**
243
+ * Re-reads the stored refresh token before an invalid_grant is recorded as revoked,
244
+ * so a token another process rotated in the meantime is not marked dead.
245
+ */
246
+ readStoredRefreshToken?: ReadStoredClaudeRefreshToken;
228
247
  /** Returns homes that live lanes are using. Default implementation reads `hq runners list --json`. */
229
248
  listLiveLanes?: ListLiveLanes;
230
249
  /** Returns processes whose `CLAUDE_CONFIG_DIR` identifies a home. Default reads `ps -ewwo pid,command`. */