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

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 (161) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/bin/hq-auth-refresh.js +2 -1
  3. package/dist/command-catalog.generated.d.ts +442 -50
  4. package/dist/command-catalog.generated.js +541 -50
  5. package/dist/commands/agent-inbox.d.ts +11 -1
  6. package/dist/commands/agent-inbox.js +128 -38
  7. package/dist/commands/agent-kit.js +2 -2
  8. package/dist/commands/agents.d.ts +51 -1
  9. package/dist/commands/agents.js +154 -2
  10. package/dist/commands/bot-jobs.d.ts +2 -15
  11. package/dist/commands/bot-jobs.js +2 -94
  12. package/dist/commands/bot-runtime.d.ts +46 -5
  13. package/dist/commands/bot-runtime.js +228 -18
  14. package/dist/commands/bot.d.ts +16 -9
  15. package/dist/commands/bot.js +169 -51
  16. package/dist/commands/cloud.d.ts +66 -13
  17. package/dist/commands/cloud.js +120 -39
  18. package/dist/commands/company-restore.d.ts +23 -0
  19. package/dist/commands/company-restore.js +128 -0
  20. package/dist/commands/company.js +2 -0
  21. package/dist/commands/core-handoff.js +1 -0
  22. package/dist/commands/core-hq-session-native.js +2 -2
  23. package/dist/commands/core-pin-native.js +1 -1
  24. package/dist/commands/core-policy.js +1 -1
  25. package/dist/commands/core-resolve-company-native.js +1 -1
  26. package/dist/commands/core-sentry-report-fast.d.ts +2 -0
  27. package/dist/commands/core-sentry-report-fast.js +3 -1
  28. package/dist/commands/daemon.js +11 -1
  29. package/dist/commands/integrations-connect.d.ts +17 -4
  30. package/dist/commands/integrations-connect.js +224 -26
  31. package/dist/commands/lanes-link.js +10 -5
  32. package/dist/commands/lanes.js +26 -9
  33. package/dist/commands/rescue.js +13 -0
  34. package/dist/commands/secrets.d.ts +11 -0
  35. package/dist/commands/secrets.js +41 -7
  36. package/dist/commands/sources.js +6 -0
  37. package/dist/commands/storage-offload.d.ts +12 -0
  38. package/dist/commands/storage-offload.js +41 -3
  39. package/dist/commands/sync-mode.js +5 -0
  40. package/dist/commands/whoami.js +4 -0
  41. package/dist/index.js +2 -0
  42. package/dist/lazy-commands.js +2 -0
  43. package/dist/lib/agent-kit/inbox-fetch.d.ts +122 -1
  44. package/dist/lib/agent-kit/inbox-fetch.js +215 -3
  45. package/dist/lib/agent-kit/inbox-redact.js +1 -1
  46. package/dist/lib/agent-kit/inbox-state.d.ts +98 -1
  47. package/dist/lib/agent-kit/inbox-state.js +261 -4
  48. package/dist/lib/agent-kit/mcp/tools.d.ts +3 -3
  49. package/dist/lib/agent-kit/mcp/tools.js +68 -25
  50. package/dist/lib/agent-kit/run/inbox.js +4 -2
  51. package/dist/lib/agent-kit/skills.js +4 -1
  52. package/dist/lib/agent-kit/wake.d.ts +9 -1
  53. package/dist/lib/agent-kit/wake.js +10 -3
  54. package/dist/lib/bot/config.d.ts +1 -0
  55. package/dist/lib/bot/config.js +10 -0
  56. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  57. package/dist/lib/bot/eventbridge-cron.js +104 -0
  58. package/dist/lib/bot/fleet-cron.js +193 -14
  59. package/dist/lib/bot/fleet-download.d.ts +2 -0
  60. package/dist/lib/bot/fleet-download.js +23 -0
  61. package/dist/lib/bot/fleet-local.d.ts +34 -1
  62. package/dist/lib/bot/fleet-local.js +254 -37
  63. package/dist/lib/bot/fleet-python.d.ts +3 -0
  64. package/dist/lib/bot/fleet-python.js +34 -4
  65. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  66. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  67. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  68. package/dist/lib/bot/legacy-provider-login.js +19 -2
  69. package/dist/lib/bot/prompt.js +1 -1
  70. package/dist/lib/bot/readiness.d.ts +8 -0
  71. package/dist/lib/bot/readiness.js +17 -3
  72. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  73. package/dist/lib/bot/runtime-auth.js +94 -3
  74. package/dist/lib/bot/status.d.ts +2 -0
  75. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  76. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  77. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  78. package/dist/lib/capacity/collectors/grok.js +56 -5
  79. package/dist/lib/core-utils/session-id.d.ts +1 -1
  80. package/dist/lib/core-utils/session-id.js +4 -0
  81. package/dist/lib/daemon/catalog.js +11 -1
  82. package/dist/lib/daemon/run.js +9 -1
  83. package/dist/lib/daemon/updater.d.ts +34 -2
  84. package/dist/lib/daemon/updater.js +51 -2
  85. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  86. package/dist/lib/db/sqlite-binding.js +1 -1
  87. package/dist/lib/delivery/artifacts.d.ts +99 -0
  88. package/dist/lib/delivery/artifacts.js +548 -0
  89. package/dist/lib/delivery/backup.d.ts +78 -0
  90. package/dist/lib/delivery/backup.js +343 -0
  91. package/dist/lib/delivery/cache.d.ts +29 -0
  92. package/dist/lib/delivery/cache.js +33 -0
  93. package/dist/lib/delivery/contracts.d.ts +142 -0
  94. package/dist/lib/delivery/contracts.js +289 -0
  95. package/dist/lib/delivery/credentials.d.ts +54 -0
  96. package/dist/lib/delivery/credentials.js +119 -0
  97. package/dist/lib/delivery/enrollment.d.ts +142 -0
  98. package/dist/lib/delivery/enrollment.js +382 -0
  99. package/dist/lib/delivery/identity.d.ts +25 -0
  100. package/dist/lib/delivery/identity.js +82 -0
  101. package/dist/lib/delivery/inbox.d.ts +116 -0
  102. package/dist/lib/delivery/inbox.js +260 -0
  103. package/dist/lib/delivery/migrations.d.ts +139 -0
  104. package/dist/lib/delivery/migrations.js +623 -0
  105. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  106. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  107. package/dist/lib/delivery/mqtt.d.ts +61 -0
  108. package/dist/lib/delivery/mqtt.js +112 -0
  109. package/dist/lib/delivery/outbox.d.ts +95 -0
  110. package/dist/lib/delivery/outbox.js +187 -0
  111. package/dist/lib/delivery/provenance.d.ts +129 -0
  112. package/dist/lib/delivery/provenance.js +93 -0
  113. package/dist/lib/delivery/reconciler.d.ts +151 -0
  114. package/dist/lib/delivery/reconciler.js +492 -0
  115. package/dist/lib/delivery/restore.d.ts +35 -0
  116. package/dist/lib/delivery/restore.js +134 -0
  117. package/dist/lib/delivery/store.d.ts +161 -0
  118. package/dist/lib/delivery/store.js +940 -0
  119. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  120. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  121. package/dist/lib/delivery/workers/macos.d.ts +176 -0
  122. package/dist/lib/delivery/workers/macos.js +901 -0
  123. package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
  124. package/dist/lib/delivery/workers/windows-boundary.js +693 -0
  125. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  126. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  127. package/dist/lib/delivery/workers/windows.d.ts +241 -0
  128. package/dist/lib/delivery/workers/windows.js +608 -0
  129. package/dist/lib/doctor/checks/release-links.d.ts +50 -8
  130. package/dist/lib/doctor/checks/release-links.js +260 -24
  131. package/dist/lib/doctor/fix/apply.js +24 -8
  132. package/dist/lib/doctor/fix/remediation.js +15 -5
  133. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  134. package/dist/lib/install/provider-wrappers.js +68 -3
  135. package/dist/lib/lanes/autopilot-registry.d.ts +14 -0
  136. package/dist/lib/lanes/autopilot-registry.js +59 -7
  137. package/dist/lib/lanes/links.d.ts +14 -0
  138. package/dist/lib/lanes/links.js +320 -25
  139. package/dist/lib/lanes/outpost-pruner-install.d.ts +10 -0
  140. package/dist/lib/lanes/outpost-pruner-install.js +4 -3
  141. package/dist/main.js +3 -1
  142. package/dist/sentry-init.d.ts +2 -0
  143. package/dist/sentry-init.js +13 -2
  144. package/dist/sentry.d.ts +2 -0
  145. package/dist/sentry.js +5 -1
  146. package/dist/utils/cli-network-lifecycle.d.ts +9 -0
  147. package/dist/utils/cli-network-lifecycle.js +52 -0
  148. package/dist/utils/cognito-callback-port.d.ts +14 -0
  149. package/dist/utils/cognito-callback-port.js +24 -0
  150. package/dist/utils/cognito-session.js +3 -3
  151. package/dist/utils/deleted-company-notice.d.ts +59 -0
  152. package/dist/utils/deleted-company-notice.js +156 -0
  153. package/dist/utils/login-browser.d.ts +1 -1
  154. package/dist/utils/login-browser.js +7 -5
  155. package/dist/utils/resident-package-preload.js +30 -15
  156. package/dist/utils/safe-link.d.ts +63 -0
  157. package/dist/utils/safe-link.js +246 -0
  158. package/dist/utils/sentry-keepalive-transport.d.ts +28 -0
  159. package/dist/utils/sentry-keepalive-transport.js +70 -0
  160. package/dist/utils/vault-api.js +7 -0
  161. package/package.json +7 -7
@@ -45,10 +45,18 @@ export interface WakeNotice {
45
45
  reason: "new" | "retry" | "test";
46
46
  pending: number;
47
47
  messageIds: string[];
48
+ /**
49
+ * Ids in messageIds that the bot already handled but whose server ack is
50
+ * not confirmed yet (ack-pending.json). Do not reply to these again; run
51
+ * `hq agent inbox done <id>` to retry the ack. Absent when there are none.
52
+ */
53
+ ackPending?: string[];
48
54
  at: string;
49
55
  instructions: string;
50
56
  }
51
57
  export declare const WAKE_INSTRUCTIONS: string;
58
+ /** Added when the notice lists ids whose server ack is not confirmed yet. */
59
+ export declare const WAKE_ACK_PENDING_INSTRUCTIONS: string;
52
60
  export declare function wakePath(paths: Pick<AgentKitPaths, "agentDir">): string;
53
61
  export declare function validateWakeUrl(raw: string): string;
54
62
  /** Origin plus a masked path: enough to recognise, not enough to call. */
@@ -67,7 +75,7 @@ export interface WakeDeps {
67
75
  spawnImpl?: typeof spawn;
68
76
  pidAlive?: (pid: number | undefined) => boolean;
69
77
  }
70
- export declare function buildWakeNotice(agentUid: string, reason: WakeNotice["reason"], ids: string[], now: Date): WakeNotice;
78
+ export declare function buildWakeNotice(agentUid: string, reason: WakeNotice["reason"], ids: string[], now: Date, ackPendingIds?: readonly string[]): WakeNotice;
71
79
  /**
72
80
  * Decide whether to wake now: always on new mail, otherwise only when items
73
81
  * are still pending and the last wake is older than retryMs.
@@ -59,6 +59,9 @@ export const WAKE_INSTRUCTIONS = "New HQ messages are waiting. Run `hq agent inb
59
59
  "arrived: if it has a channelId, post in that channel with `hq dm <channelId> \"…\"`; otherwise reply to the " +
60
60
  "sender with `hq dm <sender-uid> \"…\"` (or hq_dm_send). Do not reply to another bot's greeting, thanks or " +
61
61
  "sign-off that asks for nothing. Then mark each handled with `hq agent inbox done <id>` (or hq_inbox_done).";
62
+ /** Added when the notice lists ids whose server ack is not confirmed yet. */
63
+ export const WAKE_ACK_PENDING_INSTRUCTIONS = "Ids in ackPending were already answered; their server ack is not confirmed. Do not reply to them again: " +
64
+ "run `hq agent inbox done <id>` (or hq_inbox_done) to retry the ack.";
62
65
  export function wakePath(paths) {
63
66
  return path.join(paths.agentDir, WAKE_FILE_NAME);
64
67
  }
@@ -160,15 +163,19 @@ function pidAlive(pid) {
160
163
  return false;
161
164
  }
162
165
  }
163
- export function buildWakeNotice(agentUid, reason, ids, now) {
166
+ export function buildWakeNotice(agentUid, reason, ids, now, ackPendingIds = []) {
167
+ const messageIds = ids.slice(0, 50);
168
+ const ackPendingSet = new Set(ackPendingIds);
169
+ const ackPending = messageIds.filter((id) => ackPendingSet.has(id));
164
170
  return {
165
171
  event: "hq.inbox.pending",
166
172
  agentUid,
167
173
  reason,
168
174
  pending: ids.length,
169
- messageIds: ids.slice(0, 50),
175
+ messageIds,
176
+ ...(ackPending.length ? { ackPending } : {}),
170
177
  at: now.toISOString(),
171
- instructions: WAKE_INSTRUCTIONS,
178
+ instructions: ackPending.length ? `${WAKE_INSTRUCTIONS} ${WAKE_ACK_PENDING_INSTRUCTIONS}` : WAKE_INSTRUCTIONS,
172
179
  };
173
180
  }
174
181
  /**
@@ -14,6 +14,7 @@ export interface BotEngineMetadata {
14
14
  }
15
15
  export declare function isBotEngineMetadata(value: unknown): value is BotEngineMetadata;
16
16
  export declare function isBotRuntimeId(value: unknown): value is BotRuntimeId;
17
+ export declare function botRuntimeFromBrainName(value: string | undefined | null): BotRuntimeId | null;
17
18
  /**
18
19
  * What a bot is (owner decisions, 2026-09-15):
19
20
  * - "personal": acts as its owner. Every turn (DMs, kickoff, rooms) runs with
@@ -23,6 +23,16 @@ export function isBotEngineMetadata(value) {
23
23
  export function isBotRuntimeId(value) {
24
24
  return typeof value === "string" && BOT_RUNTIMES.includes(value);
25
25
  }
26
+ export function botRuntimeFromBrainName(value) {
27
+ const name = (value ?? "").trim().toLowerCase();
28
+ if (name === "claude")
29
+ return "claude";
30
+ if (name === "codex" || name === "chatgpt")
31
+ return "codex";
32
+ if (name === "grok")
33
+ return "grok";
34
+ return null;
35
+ }
26
36
  /**
27
37
  * What a bot is (owner decisions, 2026-09-15):
28
38
  * - "personal": acts as its owner. Every turn (DMs, kickoff, rooms) runs with
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Standard five-field cron to the stored six-field `cron(...)` form shared by
3
+ * local bot jobs and hosted agent jobs. Pure and dependency-free so commands on
4
+ * resident paths (`hq agents jobs update`) can use it without loading the bot
5
+ * jobs command graph.
6
+ */
7
+ export declare class BotJobsError extends Error {
8
+ readonly expected: true;
9
+ }
10
+ /**
11
+ * Standard 5-field cron → the six-field `cron(...)` string a job is stored as.
12
+ *
13
+ * The stored form (the six-field cron syntax hosted agent jobs also use, so
14
+ * local and hosted jobs share one format; the function keeps its historical
15
+ * name) has SIX fields (a trailing year), numbers its days of week
16
+ * 1–7 with SUNDAY = 1 (standard cron uses 0–6 with SUNDAY = 0), and refuses
17
+ * `*` in BOTH the day-of-month and day-of-week fields — exactly one must be
18
+ * `?`. An expression that is already `cron(...)` or `rate(...)` is passed
19
+ * through untouched.
20
+ */
21
+ export declare function toEventBridgeCron(expr: string): string;
22
+ //# sourceMappingURL=eventbridge-cron.d.ts.map
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Standard five-field cron to the stored six-field `cron(...)` form shared by
3
+ * local bot jobs and hosted agent jobs. Pure and dependency-free so commands on
4
+ * resident paths (`hq agents jobs update`) can use it without loading the bot
5
+ * jobs command graph.
6
+ */
7
+ export class BotJobsError extends Error {
8
+ expected = true;
9
+ }
10
+ function refuse(message) {
11
+ throw new BotJobsError(message);
12
+ }
13
+ /**
14
+ * Standard 5-field cron → the six-field `cron(...)` string a job is stored as.
15
+ *
16
+ * The stored form (the six-field cron syntax hosted agent jobs also use, so
17
+ * local and hosted jobs share one format; the function keeps its historical
18
+ * name) has SIX fields (a trailing year), numbers its days of week
19
+ * 1–7 with SUNDAY = 1 (standard cron uses 0–6 with SUNDAY = 0), and refuses
20
+ * `*` in BOTH the day-of-month and day-of-week fields — exactly one must be
21
+ * `?`. An expression that is already `cron(...)` or `rate(...)` is passed
22
+ * through untouched.
23
+ */
24
+ export function toEventBridgeCron(expr) {
25
+ const trimmed = expr.trim();
26
+ // An explicit cron(...) / rate(...) is the caller saying "this is already the
27
+ // stored syntax" — passed through untranslated, on purpose.
28
+ if (/^(cron|rate)\s*\(/i.test(trimmed))
29
+ return trimmed;
30
+ const fields = trimmed.split(/\s+/).filter(Boolean);
31
+ if (fields.length === 6) {
32
+ // Six BARE fields are ambiguous: the stored form's sixth field is a
33
+ // trailing year, Quartz's first is leading seconds. Guessing wrong
34
+ // silently moves every run. Make the caller say which they mean.
35
+ refuse(`"${trimmed}" has six fields, and I can't tell whether the last one is a year ` +
36
+ `(minute hour day-of-month month day-of-week year, the form bot jobs are stored in) or the ` +
37
+ `first one is seconds (a Quartz expression) — reading it the wrong way would schedule the job ` +
38
+ `at the wrong time. Pass five fields ("0 9 * * 1-5"), or wrap it yourself as cron(...) if it ` +
39
+ `already ends with a year field.`);
40
+ }
41
+ if (fields.length !== 5) {
42
+ refuse(`"${trimmed}" is not a cron expression. A cron expression has five fields: ` +
43
+ `minute hour day-of-month month day-of-week (for example "0 9 * * 1-5").`);
44
+ }
45
+ const [minute, hour, month] = [fields[0], fields[1], fields[3]];
46
+ let dayOfMonth = fields[2];
47
+ let dayOfWeek = fields[4];
48
+ if (dayOfWeek === "*" || dayOfWeek === "?") {
49
+ dayOfWeek = "?";
50
+ if (dayOfMonth === "?")
51
+ dayOfMonth = "*";
52
+ }
53
+ else {
54
+ dayOfWeek = shiftDayOfWeek(dayOfWeek);
55
+ if (dayOfMonth === "*")
56
+ dayOfMonth = "?";
57
+ }
58
+ return `cron(${minute} ${hour} ${dayOfMonth} ${month} ${dayOfWeek} *)`;
59
+ }
60
+ /**
61
+ * Standard 0–6 (SUN=0, and 7 also SUN) → the stored form's 1–7 (SUN=1).
62
+ *
63
+ * Mapped per TERM, not per digit. Shifting digits individually turned a range
64
+ * that wraps past Sunday — "6-0" (Sat–Sun), "5-1" (Fri–Mon) — into "7-1" /
65
+ * "6-2": reversed or plain wrong, and silently so. Such a range is refused with
66
+ * the list form that does work.
67
+ */
68
+ function shiftDayOfWeek(field) {
69
+ return field
70
+ .split(",")
71
+ .map((term) => shiftDayOfWeekTerm(term.trim()))
72
+ .join(",");
73
+ }
74
+ function shiftDay(n) {
75
+ return (n % 7) + 1;
76
+ }
77
+ function shiftDayOfWeekTerm(term) {
78
+ const step = term.match(/^(.+)\/(\d+)$/);
79
+ if (step)
80
+ return `${shiftDayOfWeekTerm(step[1])}/${step[2]}`;
81
+ const range = term.match(/^(\d+)-(\d+)$/);
82
+ if (range) {
83
+ const from = shiftDay(Number(range[1]));
84
+ const to = shiftDay(Number(range[2]));
85
+ if (from > to) {
86
+ const days = [];
87
+ for (let d = Number(range[1]);; d = (d + 1) % 7) {
88
+ days.push(d);
89
+ if (d === Number(range[2]) % 7)
90
+ break;
91
+ if (days.length > 7)
92
+ break;
93
+ }
94
+ refuse(`"${term}" is a day-of-week range that wraps past Sunday, which the schedule cannot express. ` +
95
+ `List the days instead, for example "${days.join(",")}".`);
96
+ }
97
+ return `${from}-${to}`;
98
+ }
99
+ if (/^\d+$/.test(term))
100
+ return String(shiftDay(Number(term)));
101
+ // Day NAMES (MON, MON-FRI) mean the same thing in both syntaxes.
102
+ return term;
103
+ }
104
+ //# sourceMappingURL=eventbridge-cron.js.map
@@ -4,6 +4,7 @@ import * as path from "node:path";
4
4
  import { effectiveBotCompanies, effectiveBotKind } from "./config.js";
5
5
  import { fleetLocalRuntimePython, stderrTail } from "./fleet-local.js";
6
6
  import { readLocalJobs, withJobsLock, writeLocalJobs } from "./local-jobs.js";
7
+ import { signInCommand } from "./runtime-sign-in.js";
7
8
  import { currentHotSignalSyncCompany, forgetHotSignalSyncRegistrationsExcept, hotSignalSyncJobCompany, fleetHotSignalSyncRegistered, markFleetHotSignalSyncRegistered, otherBotWithHotSignalSync, } from "./jobs/hot-signal-sync.js";
8
9
  const RESULT_MARKER = "@@HQ_FLEET_CRON@@";
9
10
  export const FLEET_CRON_BRIDGE = [
@@ -216,35 +217,213 @@ export function companyOfHotSignalSyncJob(job) {
216
217
  const match = /^hot-signal-sync-([a-z0-9][a-z0-9_-]*)\.py$/i.exec(path.basename(job.script));
217
218
  return match ? match[1] : null;
218
219
  }
220
+ /**
221
+ * Python helpers for the flag-off script's failure alert. No backticks and no
222
+ * `${` here: the text is a raw template. Fix steps come in through FIXES.
223
+ *
224
+ * - scheduled_time(): the job's own daily time from the Fleet cron store next
225
+ * to the script (<profile>/scripts/<script>.py, <profile>/cron/jobs.json),
226
+ * so a time moved with `hq sources schedule --at` or `hq bot jobs
227
+ * --reschedule` shows. Disabled entries are skipped. When the store or a
228
+ * daily schedule cannot be read, the time this run started.
229
+ * - redact(): the credential patterns of utils/redact-error-text.ts (and the
230
+ * secret query and fragment values and opaque path segments of
231
+ * utils/redact-url.ts), applied to any line of hq's
232
+ * output before it goes into the owner's DM.
233
+ * - classify(): one short reason and one fix step from what hq printed.
234
+ */
235
+ const HOT_SIGNAL_SYNC_ALERT_HELPERS = String.raw `ANSI = re.compile(r'\x1b\[[0-9;]*m')
236
+ REASON_MAX = 200
237
+
238
+ def scheduled_time():
239
+ try:
240
+ here = os.path.abspath(__file__)
241
+ store = os.path.join(os.path.dirname(os.path.dirname(here)), 'cron', 'jobs.json')
242
+ with open(store, encoding='utf-8') as f:
243
+ data = json.load(f)
244
+ jobs = data.get('jobs', []) if isinstance(data, dict) else data
245
+ if isinstance(jobs, dict):
246
+ jobs = list(jobs.values())
247
+ for job in jobs:
248
+ if not isinstance(job, dict) or os.path.basename(str(job.get('script') or '')) != os.path.basename(here):
249
+ continue
250
+ if job.get('enabled') is False or str(job.get('state') or '').lower() in ('disabled', 'paused'):
251
+ continue
252
+ schedule = job.get('schedule')
253
+ expr = schedule.get('expr') if isinstance(schedule, dict) else schedule
254
+ m = re.match(r'^(\d{1,2})\s+(\d{1,2})\s+\*\s+\*\s+\*$', str(expr or '').strip())
255
+ if m and int(m.group(2)) < 24 and int(m.group(1)) < 60:
256
+ return '%02d:%02d' % (int(m.group(2)), int(m.group(1)))
257
+ except Exception:
258
+ pass
259
+ return time.strftime('%H:%M', STARTED)
260
+
261
+ SECRET_LABEL = re.compile(r'''\b(password|secret|client[_-]?secret|api[_-]?key|(?:id|access|refresh)[_-]?token|token|authorization)\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s&"'<>;,}]+)''', re.I)
262
+ SECRET_QUERY = re.compile(r'''([?&;#](?:[A-Za-z0-9_.-]*(?:key|token|secret|password|signature|credentials?)|pass|pwd|sig|auth|authorization|session|code|[A-Za-z0-9_.-]*[_-]code)=)[^&#\s"'<>]+''', re.I)
263
+
264
+ URL_IN_TEXT = re.compile(r'''\b[a-z][a-z0-9+.-]*://[^\s<>"'\x60]+''', re.I)
265
+ URL_PARTS = re.compile(r'^([a-z][a-z0-9+.-]*://[^/?#]*)([^?#]*)(.*)$', re.I | re.S)
266
+ SECRET_PATH_LABEL = re.compile(r'^(?:access[_-]?token|refresh[_-]?token|id[_-]?token|api[_-]?key|x?mcpkey|client[_-]?secret|token|key|secret|password|pass|pwd|auth|authorization|sig|signature|credential|credentials|session)[=_-].+$', re.I | re.S)
267
+
268
+ def opaque_segment(segment):
269
+ # isOpaqueCapabilitySegment in utils/redact-url.ts, for a webhook or
270
+ # capability URL whose secret is a path segment.
271
+ if SECRET_PATH_LABEL.match(segment):
272
+ return True
273
+ n = len(segment)
274
+ letter = re.search(r'[A-Za-z]', segment) is not None
275
+ digit = re.search(r'[0-9]', segment) is not None
276
+ long_hex = n >= 24 and re.match(r'^[A-Fa-f0-9]+$', segment) is not None
277
+ long_b64 = n >= 32 and re.match(r'^[A-Za-z0-9_-]+$', segment) is not None and letter and (digit or re.search(r'[A-Z_-]', segment) is not None)
278
+ return (n >= 20 and letter and digit) or long_hex or long_b64
279
+
280
+ def redact_url_path(match):
281
+ url = match.group(0)
282
+ tail = re.search(r'[),.;!?]+$', url)
283
+ punct = tail.group(0) if tail else ''
284
+ url = url[:len(url) - len(punct)]
285
+ head, route, rest = URL_PARTS.match(url).groups()
286
+ route = '/'.join('[REDACTED]' if opaque_segment(urllib.parse.unquote(s)) else s for s in route.split('/'))
287
+ return head + route + rest + punct
288
+
289
+ def redact(text):
290
+ # User info runs to the last @ before the host, so a raw @ in a password
291
+ # does not leave the rest of it visible.
292
+ text = re.sub(r'(\b[a-z][a-z0-9+.-]*://)[^/\s?#]*@', r'\1[REDACTED]@', text, flags=re.I)
293
+ text = URL_IN_TEXT.sub(redact_url_path, text)
294
+ text = SECRET_QUERY.sub(lambda m: m.group(1) + '[REDACTED]', text)
295
+ # The output is split into lines before redact() runs, so a private key
296
+ # arrives one line at a time: mask its BEGIN/END lines, and a body line that
297
+ # starts with a DER key header (MII, MIG, MHc) or the OpenSSH key magic.
298
+ text = re.sub(r'-----(?:BEGIN|END)[A-Z0-9 ]*PRIVATE KEY-----', '[REDACTED]', text)
299
+ text = re.sub(r'\b(?:MII|MIG|MHc|b3BlbnNzaC1rZXktdjE)[A-Za-z0-9+/]{20,}={0,2}', '[REDACTED]', text)
300
+ text = re.sub(r'[\x00-\x1f\x7f-\x9f]', ' ', text)
301
+ text = re.sub(r'\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+', '[REDACTED]', text, flags=re.I)
302
+ text = SECRET_LABEL.sub(lambda m: m.group(1) + '=[REDACTED]', text)
303
+ text = re.sub(r'\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b', '[REDACTED]', text)
304
+ text = re.sub(r'\b(?:hqk_|xox[abprs]-|github_pat_|gh[pousr]_)[A-Za-z0-9_-]+\b', '[REDACTED]', text, flags=re.I)
305
+ text = re.sub(r'\bsk-ant-[A-Za-z0-9_-]+', '[REDACTED]', text)
306
+ text = re.sub(r'\bAKIA[0-9A-Z]{16}\b', '[REDACTED]', text)
307
+ return re.sub(r'\s+', ' ', text).strip()
308
+
309
+ ERRORISH = re.compile(r'\b(?:fail(?:ed|ure|s)?|errors?|stopped|could not|cannot|denied|unauthori[sz]ed|forbidden|refused|invalid|expired|timed out|not found)\b', re.I)
310
+
311
+ def output_lines(source):
312
+ return [l.strip() for l in ANSI.sub('', source or '').splitlines() if l.strip()]
313
+
314
+ def last_error_line(out, err):
315
+ # A recognised error (a line hq marks with its error cross, or one that says
316
+ # it failed) wins over a stdout failure line, which wins over a plain stderr
317
+ # warning such as a skipped event.
318
+ errs, outs = output_lines(err), output_lines(out)
319
+ for lines in (
320
+ [l for l in errs if l.startswith('✗') or ERRORISH.search(l)],
321
+ [l for l in outs if ERRORISH.search(l)],
322
+ errs,
323
+ ):
324
+ for line in reversed(lines):
325
+ clean = redact(line.lstrip('✗').strip())[:REASON_MAX].rstrip('. ')
326
+ if clean:
327
+ return clean
328
+ return ''
329
+
330
+ def signal_name(number):
331
+ try:
332
+ return signal.Signals(number).name
333
+ except Exception:
334
+ return ''
335
+
336
+ def classify(out, err, code):
337
+ if code < 0:
338
+ name = signal_name(-code)
339
+ return 'hq was stopped by signal %d%s' % (-code, ' (' + name + ')' if name else ''), FIXES['signal']
340
+ text = ANSI.sub('', (err or '') + '\n' + (out or ''))
341
+ if re.search(r"HQ session has expired|not signed in to HQ|Sign in to HQ first|run .hq login", text, re.I):
342
+ return 'you are signed out of HQ', FIXES['hq_signed_out']
343
+ if re.search(r'claude could not start:.*\bENOENT\b|spawn claude ENOENT', text, re.I):
344
+ return 'Claude Code is not installed on this computer', FIXES['claude_missing']
345
+ if re.search(r'claude-logged-out|claude (reported it )?is not logged in|claude could not start', text, re.I):
346
+ return 'Claude is signed out on this computer', FIXES['claude_signed_out']
347
+ timed_out = re.search(r'claude timed out after \d+ ?ms on (\S+)', text, re.I)
348
+ if timed_out or re.search(r'claude-timeout', text, re.I):
349
+ key = timed_out.group(1).rstrip('.,;:)\'"') if timed_out else ''
350
+ if re.match(r'^sources/[A-Za-z0-9._/-]+\.md$', key) and '..' not in key:
351
+ return 'Claude ran out of time on one document', FIXES['claude_timeout_key'].replace('KEY', key)
352
+ return 'Claude ran out of time on one document', FIXES['claude_timeout']
353
+ if re.search(r'fetch failed|ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH|socket hang up', text, re.I):
354
+ return 'HQ could not reach the network', FIXES['network']
355
+ line = last_error_line(out, err)
356
+ if line:
357
+ return line, FIXES['other']
358
+ return 'hq stopped with exit code %d and gave no reason' % code, FIXES['unknown']
359
+ `;
360
+ /** How a run ended, for the log line after it: `exit 1` or `signal 9`. */
361
+ const HOT_SIGNAL_SYNC_RUN_END = String.raw `def run_end(code):
362
+ return 'signal %d' % -code if code < 0 else 'exit %d' % code
363
+ `;
219
364
  export function renderFleetHotSignalSyncScript(input) {
220
- const args = input.signalsEngine === false
365
+ const plainSync = input.signalsEngine === false;
366
+ const args = plainSync
221
367
  ? ["sources", "sync", "--company", input.company, "--hq-root", input.hqRoot]
222
368
  : ["signals", "run", "--trigger", "job", "--company", input.company, "--hq-root", input.hqRoot, "--report-found"];
369
+ const syncCommand = `hq sources sync --company ${input.company}`;
370
+ const fixes = {
371
+ hq_signed_out: "run `hq login`.",
372
+ claude_signed_out: `run \`${signInCommand("claude")}\`.`,
373
+ claude_missing: `install Claude Code (\`npm install -g @anthropic-ai/claude-code\`), then run \`${signInCommand("claude")}\`.`,
374
+ claude_timeout_key: `run \`hq sources signals --company ${input.company} --key KEY\` to retry that document.`,
375
+ claude_timeout: "the next run retries the document.",
376
+ network: `check this computer's connection. The next run retries, or run \`${syncCommand}\` now.`,
377
+ signal: `run \`${syncCommand}\` to see whether it happens again.`,
378
+ other: `run \`${syncCommand}\` to see the full error.`,
379
+ unknown: `run \`${syncCommand}\` to see what goes wrong.`,
380
+ };
381
+ // One header per run, so an alert's start time finds its entry in the log,
382
+ // and one line after it with how the run ended.
383
+ const header = ` log.write('=== ' + time.strftime('%Y-%m-%d %H:%M:%S %z', STARTED) + ${JSON.stringify(` hot-signal-sync for ${input.company} ===`)} + '\\n')`;
384
+ const footer = " log.write('=== ' + run_end(result.returncode) + ' ===\\n')";
223
385
  // The engine prints only when it finds new signals (--report-found), so its
224
- // stdout goes to the owner's DM as is. The plain sync prints a report every
225
- // run, so with the flag off its stdout goes to the log and the owner hears
226
- // only about a run that failed (for example, nobody signed in or the signals
227
- // pass failed). The script exits with hq's code, so the job's status is not
228
- // `ok` after a failed run: Fleet records a no-agent job from its exit code.
229
- const deliver = input.signalsEngine === false
386
+ // stdout goes to the owner's DM as is, and its stderr streams to the log
387
+ // while it runs. The plain sync prints a report every run, so with the flag
388
+ // off both streams go to the log and the owner hears only about a run that
389
+ // failed, with the job's time, the reason, one fix step and the log. The
390
+ // plain script exits non-zero after a failed run (128 + N after signal N, as
391
+ // a shell does), so the job's status is not `ok`: Fleet records a no-agent
392
+ // job from its exit code.
393
+ const run = plainSync
230
394
  ? [
395
+ " result = subprocess.run([NODE, HQ, *ARGS], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
231
396
  " with open(LOG, 'a', encoding='utf-8') as log:",
397
+ header,
398
+ " log.write(result.stderr)",
232
399
  " log.write(result.stdout)",
400
+ footer,
233
401
  " if result.returncode != 0:",
234
- ` sys.stdout.write(${JSON.stringify(`The 06:30 hot-channel sync for ${input.company} did not finish. Details are in `)} + LOG + '\\n')`,
235
- " sys.exit(result.returncode)",
402
+ " reason, fix = classify(result.stdout, result.stderr, result.returncode)",
403
+ ` sys.stdout.write('The ' + scheduled_time() + ${JSON.stringify(` hot-channel sync for ${input.company} did not finish: `)} + reason + '.\\n')`,
404
+ " sys.stdout.write('Fix: ' + fix + '\\n')",
405
+ " sys.stdout.write('Log: ' + LOG + ' (run started ' + time.strftime('%Y-%m-%d %H:%M', STARTED) + ')\\n')",
406
+ " sys.exit(128 - result.returncode if result.returncode < 0 else result.returncode)",
236
407
  ]
237
- : [" sys.stdout.write(result.stdout)"];
408
+ : [
409
+ " with open(LOG, 'a', encoding='utf-8') as log:",
410
+ header,
411
+ " log.flush()",
412
+ " result = subprocess.run([NODE, HQ, *ARGS], stdout=subprocess.PIPE, stderr=log, encoding='utf-8', errors='replace')",
413
+ footer,
414
+ " sys.stdout.write(result.stdout)",
415
+ ];
238
416
  return [
239
- "import subprocess, sys",
417
+ plainSync ? "import json, os, re, signal, subprocess, sys, time, urllib.parse" : "import subprocess, sys, time",
240
418
  `NODE = ${JSON.stringify(input.nodeBinary)}`,
241
419
  `HQ = ${JSON.stringify(input.hqBinary)}`,
242
420
  `ARGS = ${JSON.stringify(args)}`,
243
421
  `LOG = ${JSON.stringify(input.logFile)}`,
422
+ "STARTED = time.localtime()",
423
+ HOT_SIGNAL_SYNC_RUN_END,
424
+ ...(plainSync ? [`FIXES = ${JSON.stringify(fixes)}`, HOT_SIGNAL_SYNC_ALERT_HELPERS] : []),
244
425
  "try:",
245
- " with open(LOG, 'a', encoding='utf-8') as log:",
246
- " result = subprocess.run([NODE, HQ, *ARGS], stdout=subprocess.PIPE, stderr=log, text=True)",
247
- ...deliver,
426
+ ...run,
248
427
  "except OSError as exc:",
249
428
  " with open(LOG, 'a', encoding='utf-8') as log:",
250
429
  " log.write('hot-signal-sync could not run hq: ' + str(exc) + '\\n')",
@@ -28,6 +28,8 @@ export interface FleetDownloadOptions {
28
28
  * the server told us its size, the sizes match.
29
29
  */
30
30
  export declare function downloadFleetFile(url: string, destination: string, options?: FleetDownloadOptions): Promise<string>;
31
+ export declare const FLEET_DOWNLOAD_PREFERRED_MAX_RESUMES = 1;
32
+ export declare function downloadFleetFileFromSources(urls: readonly string[], destination: string, options?: FleetDownloadOptions, accept?: (file: string) => boolean): Promise<string>;
31
33
  /** sha256 of a file on disk, streamed. */
32
34
  export declare function fileSha256(file: string): string;
33
35
  //# sourceMappingURL=fleet-download.d.ts.map
@@ -266,6 +266,29 @@ export async function downloadFleetFile(url, destination, options = {}) {
266
266
  const cause = lastFailure instanceof Error ? lastFailure.message : String(lastFailure ?? "unknown error");
267
267
  throw expectedError(`Could not download ${name} after ${maxResumes + 1} attempts (${cause}). Check your internet connection and retry; the download continues where it stopped.`);
268
268
  }
269
+ export const FLEET_DOWNLOAD_PREFERRED_MAX_RESUMES = 1;
270
+ export async function downloadFleetFileFromSources(urls, destination, options = {}, accept) {
271
+ if (urls.length === 0)
272
+ throw expectedError(`Could not download ${path.basename(destination)}: no download source.`);
273
+ let failure = null;
274
+ for (const [index, url] of urls.entries()) {
275
+ const last = index === urls.length - 1;
276
+ const maxResumes = last
277
+ ? options.maxResumes
278
+ : Math.min(options.maxResumes ?? FLEET_DOWNLOAD_MAX_RESUMES, FLEET_DOWNLOAD_PREFERRED_MAX_RESUMES);
279
+ try {
280
+ const file = await downloadFleetFile(url, destination, { ...options, ...(maxResumes !== undefined ? { maxResumes } : {}) });
281
+ if (last || !accept || accept(file))
282
+ return file;
283
+ fs.rmSync(file, { force: true });
284
+ failure = expectedError(`Could not download ${path.basename(destination)}: a download source returned the wrong file.`);
285
+ }
286
+ catch (error) {
287
+ failure = error;
288
+ }
289
+ }
290
+ throw failure;
291
+ }
269
292
  /** sha256 of a file on disk, streamed. */
270
293
  export function fileSha256(file) {
271
294
  const hash = crypto.createHash("sha256");
@@ -1,8 +1,13 @@
1
- import { type BotEngineMetadata } from "./config.js";
1
+ import { type BotEngineMetadata, type BotRuntimeId } from "./config.js";
2
2
  import type { BotMachineCreds } from "./creds.js";
3
3
  import { type FleetPython } from "./fleet-python.js";
4
4
  import { vaultApiFetch } from "../../utils/vault-api.js";
5
5
  import type { LocalBotPromotionRuntime } from "./promote.js";
6
+ export interface FleetLocalEnvironmentArtifact {
7
+ name: string;
8
+ sha256: string;
9
+ size: number;
10
+ }
6
11
  export interface FleetLocalReleasePin {
7
12
  repository: string;
8
13
  tag: string;
@@ -14,12 +19,14 @@ export interface FleetLocalReleasePin {
14
19
  manifestSha256: string;
15
20
  signatureSha256: string;
16
21
  runtimeCommit: string;
22
+ environmentArtifacts?: Record<string, FleetLocalEnvironmentArtifact>;
17
23
  }
18
24
  export interface FleetLocalReleaseFiles {
19
25
  archive: Buffer;
20
26
  runtimeArchive: Buffer;
21
27
  manifest: Buffer;
22
28
  signature: Buffer;
29
+ wheelhouse?: string;
23
30
  }
24
31
  export interface FleetLocalInstallation {
25
32
  release: FleetLocalReleasePin;
@@ -29,6 +36,8 @@ export interface FleetLocalInstallation {
29
36
  manifest: string;
30
37
  signature: string;
31
38
  engine: BotEngineMetadata;
39
+ wheelhouse?: string;
40
+ environmentPlatform?: string;
32
41
  }
33
42
  export interface FleetLocalProfile {
34
43
  schemaVersion: 1;
@@ -69,6 +78,8 @@ export interface FleetLocalInstallDeps {
69
78
  /** How long a download may go without bytes before it is resumed (tests). */
70
79
  downloadStallMs?: number;
71
80
  allowFileLinks?: boolean;
81
+ platform?: NodeJS.Platform;
82
+ arch?: string;
72
83
  }
73
84
  export interface FleetLocalProfileInput {
74
85
  agentUid: string;
@@ -244,6 +255,9 @@ export declare const FLEET_RELEASE_POINTER_FILE_ENV = "HQ_FLEET_RELEASE_POINTER_
244
255
  export declare function fleetReleasePointerFileOverride(env?: NodeJS.ProcessEnv): string | null;
245
256
  export declare function readLocalFleetReleasePointer(file: string, now?: number): FleetLocalReleasePointer;
246
257
  export declare function parseFleetLocalReleasePin(value: unknown): FleetLocalReleasePin | null;
258
+ export declare function fleetEnvironmentPlatform(platform?: NodeJS.Platform, arch?: string): string;
259
+ export declare function releaseWheelhouse(release: FleetLocalReleasePin, platform: string): FleetLocalEnvironmentArtifact | null;
260
+ export declare function verifyFleetLocalWheelhouse(file: string, artifact: FleetLocalEnvironmentArtifact, manifest: Buffer, platform: string, release: FleetLocalReleasePin): void;
247
261
  export declare function parseFleetLocalReleasePointer(body: unknown, now?: number): FleetLocalReleasePointer | null;
248
262
  export declare function chooseFleetLocalTargetRelease(pointer: FleetLocalReleasePointer | null, compiled?: FleetLocalReleasePin, cliVersion?: string): FleetLocalTargetRelease;
249
263
  export declare function fetchFleetLocalReleasePointer(deps?: {
@@ -273,6 +287,7 @@ export declare function installTargetFleetLocalDistribution(deps?: Omit<FleetLoc
273
287
  target?: FleetLocalTargetRelease;
274
288
  now?: () => number;
275
289
  }): Promise<FleetLocalInstallation>;
290
+ export declare function fleetReleaseCdnLinkName(name: string): string;
276
291
  /** What an install is doing right now, for a progress bar or a log line. */
277
292
  export type FleetInstallProgress = {
278
293
  phase: "download-start";
@@ -372,6 +387,14 @@ export declare function writeFleetLocalFirstStart(profileDir: string, firstStart
372
387
  intro?: string;
373
388
  kickoff?: string;
374
389
  }): string;
390
+ export interface FleetLocalSignInNeeded {
391
+ runtime: BotRuntimeId;
392
+ login: "claude-code" | "codex-cli" | "grok-cli" | "bot" | null;
393
+ since: string | null;
394
+ }
395
+ export declare function fleetLocalSignInNeededPath(agentUid: string, deps?: Pick<FleetLocalControlDeps, "fleetHome">): string;
396
+ export declare function readFleetLocalSignInNeeded(agentUid: string, deps?: Pick<FleetLocalControlDeps, "fleetHome">): FleetLocalSignInNeeded | null;
397
+ export declare function readFleetLocalIntroSentAt(agentUid: string, deps?: Pick<FleetLocalControlDeps, "fleetHome">): string | null;
375
398
  export declare function writeFleetLocalSoul(agentUid: string, systemPrompt: string, deps?: Pick<FleetLocalControlDeps, "fleetHome">): string;
376
399
  /**
377
400
  * The pinned runtime refuses a persona file that trips its context-file
@@ -411,6 +434,12 @@ export declare function fleetLocalBusyReason(agentUid: string, deps?: Pick<Fleet
411
434
  export declare function refreshFleetLocalInstructions(agentUid: string, systemPrompt: string, deps?: FleetLocalControlDeps): string;
412
435
  /** Last few non-empty stderr lines of a failed child process, trimmed for an error message. */
413
436
  export declare function stderrTail(error: unknown): string;
437
+ export declare const FLEET_WHEELHOUSE_EXIT: {
438
+ readonly installed: 0;
439
+ readonly verificationFailed: 2;
440
+ readonly unavailable: 3;
441
+ readonly installFailed: 4;
442
+ };
414
443
  /** A FleetLocalSpawn backed by an execFileSync-shaped runner (stderr is only known on failure). */
415
444
  export declare function spawnFromRun(run: FleetLocalExec): FleetLocalSpawn;
416
445
  /**
@@ -448,6 +477,10 @@ export interface FleetLocalProviderAuthStatus {
448
477
  * not installed, or the helper failed.
449
478
  */
450
479
  export declare function fleetLocalProviderAuthStatus(agentUid: string, provider: string, deps?: FleetLocalControlDeps): FleetLocalProviderAuthStatus | null;
480
+ export type FleetLocalAsyncRun = (executable: string, args: string[], options: Record<string, unknown>) => Promise<string>;
481
+ export declare function fleetLocalProviderAuthStatusAsync(agentUid: string, provider: string, deps?: FleetLocalControlDeps & {
482
+ runAsync?: FleetLocalAsyncRun;
483
+ }): Promise<FleetLocalProviderAuthStatus | null>;
451
484
  /**
452
485
  * Sign a bot in from a login already on this computer, without a browser:
453
486
  * the helper imports the Codex CLI login (CODEX_HOME, else ~/.codex) or