@indigoai-us/hq-cli 5.345.206 → 5.345.208
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.
- package/CHANGELOG.md +31 -0
- package/assets/scaffold/core/scripts/checkpoint-stop-gate.sh +111 -15
- package/dist/command-catalog.generated.d.ts +14 -2
- package/dist/command-catalog.generated.js +17 -2
- package/dist/commands/bot.d.ts +6 -0
- package/dist/commands/bot.js +88 -12
- package/dist/commands/core-checkpoint-stop-gate-native.js +130 -25
- package/dist/commands/files.d.ts +36 -0
- package/dist/commands/files.js +80 -1
- package/dist/commands/lanes-shared.d.ts +13 -0
- package/dist/commands/lanes.d.ts +2 -0
- package/dist/commands/lanes.js +44 -4
- package/dist/commands/sources.js +1 -1
- package/dist/commands/storage-offload.d.ts +11 -3
- package/dist/commands/storage-offload.js +32 -13
- package/dist/commands/storage.js +6 -1
- package/dist/hq-cloud-sync-runner/bin/sync-runner.js +260 -250
- package/dist/hq-cloud-sync-runner/package.json +1 -1
- package/dist/lib/bot/fleet-cron.js +4 -1
- package/dist/lib/bot/fleet-owner-companies.d.ts +7 -0
- package/dist/lib/bot/fleet-owner-companies.js +16 -4
- package/dist/lib/bot/jobs/hot-signal-sync.d.ts +2 -0
- package/dist/lib/bot/jobs/hot-signal-sync.js +18 -1
- package/dist/lib/bot/jobs/meeting-detect.d.ts +41 -2
- package/dist/lib/bot/jobs/meeting-detect.js +280 -16
- package/dist/lib/bot/run.d.ts +1 -0
- package/dist/lib/bot/run.js +4 -2
- package/dist/lib/bot/runtime-failure.js +4 -2
- package/dist/lib/capacity/collect.d.ts +7 -0
- package/dist/lib/capacity/collect.js +22 -16
- package/dist/lib/capacity/route.d.ts +23 -0
- package/dist/lib/capacity/route.js +41 -2
- package/dist/lib/company-skill-wrapper.js +33 -4
- package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
- package/dist/lib/flag-registry-worker-source.generated.js +1 -1
- package/dist/lib/hot-channels/alert.d.ts +4 -1
- package/dist/lib/hot-channels/alert.js +10 -4
- package/dist/lib/hot-channels/ledger.d.ts +4 -4
- package/dist/lib/hot-channels/ledger.js +2 -0
- package/dist/lib/hot-channels/run.d.ts +6 -0
- package/dist/lib/hot-channels/run.js +7 -2
- package/dist/lib/hot-channels/signals-pass.d.ts +11 -2
- package/dist/lib/hot-channels/signals-pass.js +129 -15
- package/dist/lib/live-meetings.js +1 -1
- package/dist/lib/sync-core/release.d.ts +1 -1
- package/dist/lib/sync-core/release.js +1 -1
- package/dist/utils/redact-error-text.js +1 -0
- package/dist/utils/resident-package-preload.js +32 -4
- package/package.json +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.
|
|
1
|
+
{"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.109","bundleSha256":"f48413f1a1488c5970274fd1dfa973fa6ebd25ba05cc9b486ce9b040fd217a0b","formatVersion":1}
|
|
@@ -223,13 +223,16 @@ export function renderFleetHotSignalSyncScript(input) {
|
|
|
223
223
|
// The engine prints only when it finds new signals (--report-found), so its
|
|
224
224
|
// stdout goes to the owner's DM as is. The plain sync prints a report every
|
|
225
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
|
|
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.
|
|
227
229
|
const deliver = input.signalsEngine === false
|
|
228
230
|
? [
|
|
229
231
|
" with open(LOG, 'a', encoding='utf-8') as log:",
|
|
230
232
|
" log.write(result.stdout)",
|
|
231
233
|
" if result.returncode != 0:",
|
|
232
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)",
|
|
233
236
|
]
|
|
234
237
|
: [" sys.stdout.write(result.stdout)"];
|
|
235
238
|
return [
|
|
@@ -7,6 +7,13 @@ export interface FleetOwnerCompaniesDependencies {
|
|
|
7
7
|
/** The signed-in owner's memberships; never prompts for sign-in. */
|
|
8
8
|
memberships?: () => Promise<OwnerMembership[]>;
|
|
9
9
|
}
|
|
10
|
+
export interface OwnerCompanyRow {
|
|
11
|
+
companyUid: string;
|
|
12
|
+
/** Undefined when the row has no slug: hq-pro answers 200 without one when its metadata read fails. */
|
|
13
|
+
slug: string | undefined;
|
|
14
|
+
}
|
|
15
|
+
/** The owner's active company rows, including rows that came back with no slug. */
|
|
16
|
+
export declare function fleetOwnerCompanyRows(dependencies?: FleetOwnerCompaniesDependencies): Promise<OwnerCompanyRow[]>;
|
|
10
17
|
/** Every active company the signed-in owner can access, independent of rollout flags or local folders. */
|
|
11
18
|
export declare function fleetOwnerCompanies(dependencies?: FleetOwnerCompaniesDependencies): Promise<string[]>;
|
|
12
19
|
//# sourceMappingURL=fleet-owner-companies.d.ts.map
|
|
@@ -13,18 +13,30 @@ async function signedInMemberships() {
|
|
|
13
13
|
throw new Error("membership lookup returned no list");
|
|
14
14
|
return data.memberships;
|
|
15
15
|
}
|
|
16
|
-
/**
|
|
17
|
-
export async function
|
|
16
|
+
/** The owner's active company rows, including rows that came back with no slug. */
|
|
17
|
+
export async function fleetOwnerCompanyRows(dependencies = {}) {
|
|
18
18
|
const memberships = await (dependencies.memberships ?? signedInMemberships)();
|
|
19
|
-
const
|
|
19
|
+
const rows = [];
|
|
20
20
|
for (const membership of memberships) {
|
|
21
21
|
const slug = membership.companySlug?.trim() ?? "";
|
|
22
22
|
if (membership.status !== "active" || !COMPANY_UID_RE.test(membership.companyUid))
|
|
23
23
|
continue;
|
|
24
|
+
if (!slug) {
|
|
25
|
+
rows.push({ companyUid: membership.companyUid, slug: undefined });
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
24
28
|
if (!COMPANY_SLUG_RE.test(slug) || slug === "personal")
|
|
25
29
|
continue;
|
|
26
|
-
|
|
30
|
+
rows.push({ companyUid: membership.companyUid, slug });
|
|
27
31
|
}
|
|
32
|
+
return rows;
|
|
33
|
+
}
|
|
34
|
+
/** Every active company the signed-in owner can access, independent of rollout flags or local folders. */
|
|
35
|
+
export async function fleetOwnerCompanies(dependencies = {}) {
|
|
36
|
+
const companies = new Set();
|
|
37
|
+
for (const { slug } of await fleetOwnerCompanyRows(dependencies))
|
|
38
|
+
if (slug)
|
|
39
|
+
companies.add(slug);
|
|
28
40
|
return [...companies].sort((a, b) => a.localeCompare(b));
|
|
29
41
|
}
|
|
30
42
|
//# sourceMappingURL=fleet-owner-companies.js.map
|
|
@@ -234,6 +234,8 @@ export interface HotSignalSyncRunOutcome {
|
|
|
234
234
|
reply?: FormattedReply;
|
|
235
235
|
/** When the bot runs the automatic retry (the record's nextRetryAt), if one was scheduled. */
|
|
236
236
|
retryAt?: string;
|
|
237
|
+
/** The signals-failure alert already told the owner, so the bot sends no second DM for this run. */
|
|
238
|
+
ownerAlerted?: boolean;
|
|
237
239
|
}
|
|
238
240
|
/** Run the scheduled sync once and describe it in plain words. Never throws. */
|
|
239
241
|
export declare function runHotSignalSyncJob(input: HotSignalSyncRunInput): Promise<HotSignalSyncRunOutcome>;
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
*/
|
|
37
37
|
import * as fs from "node:fs";
|
|
38
38
|
import * as path from "node:path";
|
|
39
|
+
import { signalsAlertKey } from "../../hot-channels/alert.js";
|
|
39
40
|
import { JOB_RUN_OPTIONS_CONTEXT_KEY } from "../job-run.js";
|
|
40
41
|
import { localDate, runRecordRel } from "../../signals/engine.js";
|
|
41
42
|
import { formatJobErrorReply, formatLockedReply, formatRunReply, timeInWords } from "../../signals/reply.js";
|
|
@@ -454,7 +455,23 @@ export async function runHotSignalSyncJob(input) {
|
|
|
454
455
|
const reason = err instanceof Error ? err.message : String(err);
|
|
455
456
|
return { ok: false, text: `The hot-channel sync for ${input.company} failed: ${reason}`, report: null };
|
|
456
457
|
}
|
|
457
|
-
|
|
458
|
+
const ok = report.exitCode === 0 && !report.signInRequired;
|
|
459
|
+
return {
|
|
460
|
+
ok,
|
|
461
|
+
text: describeSyncReport(input.company, report),
|
|
462
|
+
report,
|
|
463
|
+
...(!ok && ownerAlreadyAlerted(report) ? { ownerAlerted: true } : {}),
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* True when the signals-failure alert already covers every failed outcome: sent
|
|
468
|
+
* now, or sent within its dedupe hour. A failure with a reconnect step still
|
|
469
|
+
* needs the report, which carries that step.
|
|
470
|
+
*/
|
|
471
|
+
function ownerAlreadyAlerted(report) {
|
|
472
|
+
const covered = new Set([...(report.signalsAlert?.sent ?? []), ...(report.signalsAlert?.suppressed ?? [])]);
|
|
473
|
+
const failed = report.outcomes.filter((o) => o.status === "failed");
|
|
474
|
+
return failed.length > 0 && failed.every((o) => !o.reconnect && covered.has(signalsAlertKey(o)));
|
|
458
475
|
}
|
|
459
476
|
export function describeSyncReport(company, report) {
|
|
460
477
|
if (report.signInRequired) {
|
|
@@ -1,5 +1,40 @@
|
|
|
1
1
|
import { type LiveMeetingBot } from "../../live-meetings.js";
|
|
2
|
-
import type
|
|
2
|
+
import { type BotConfig } from "../config.js";
|
|
3
|
+
import { type FleetOwnerCompaniesDependencies } from "../fleet-owner-companies.js";
|
|
4
|
+
/**
|
|
5
|
+
* Log backoff only: polling stays on the normal cadence so a recovered company is
|
|
6
|
+
* detected on the next poll. The first repeat of a failure stays quiet for five
|
|
7
|
+
* minutes; the quiet period doubles up to an hour.
|
|
8
|
+
*/
|
|
9
|
+
export declare const MEETING_DETECT_FAILURE_BACKOFF_START_MS: number;
|
|
10
|
+
export declare const MEETING_DETECT_FAILURE_BACKOFF_MAX_MS: number;
|
|
11
|
+
export declare const MEETING_DETECT_STEPS: readonly ["token", "company-uid", "meetings list", "ledger", "memberships", "validation", "event", "detector"];
|
|
12
|
+
export type MeetingDetectStep = (typeof MEETING_DETECT_STEPS)[number];
|
|
13
|
+
/** A detection failure that names the step and, when the caller set one, the HTTP status. */
|
|
14
|
+
export declare class MeetingDetectError extends Error {
|
|
15
|
+
readonly step: MeetingDetectStep;
|
|
16
|
+
readonly status: number | undefined;
|
|
17
|
+
constructor(step: MeetingDetectStep, cause: unknown);
|
|
18
|
+
}
|
|
19
|
+
/** Company, step, error name, and HTTP status or error class. Secrets are stripped. */
|
|
20
|
+
export declare function meetingDetectFailureLine(company: string, err: unknown, fallback: MeetingDetectStep): string;
|
|
21
|
+
/**
|
|
22
|
+
* Companies this bot may poll: an explicit bind, otherwise a company bot's
|
|
23
|
+
* memberships, otherwise the signed-in owner's active memberships.
|
|
24
|
+
* Manifest fixtures and cmp_ ids are not a poll list. A bind to a company UID
|
|
25
|
+
* polls the manifest slug with that cloud_uid.
|
|
26
|
+
*/
|
|
27
|
+
export declare function resolveDetectionCompanies(config: Pick<BotConfig, "hqRoot" | "companySlug" | "kind" | "companies" | "workerId">, memberships?: () => Promise<readonly string[]>): Promise<string[]>;
|
|
28
|
+
/**
|
|
29
|
+
* Owner companies for one detector. A row with no slug keeps the slug last seen
|
|
30
|
+
* for that company UID and is reported once. A row that is absent or no longer
|
|
31
|
+
* active is forgotten, so a real membership removal still takes effect.
|
|
32
|
+
*/
|
|
33
|
+
export declare function createDetectionMemberships(log: (message: string) => void, dependencies?: FleetOwnerCompaniesDependencies & {
|
|
34
|
+
now?: () => number;
|
|
35
|
+
}): () => Promise<string[]>;
|
|
36
|
+
/** Why the poll list came back empty, for the one line logged when detection has nothing to poll. */
|
|
37
|
+
export declare function noDetectionCompaniesReason(config: Pick<BotConfig, "companySlug" | "kind" | "companies" | "workerId">): string;
|
|
3
38
|
export declare function detectIntervalSeconds(hqRoot: string): number;
|
|
4
39
|
/** Desktop events carry company UIDs; local rider files use manifest slugs. */
|
|
5
40
|
export declare function normalizeDetectedCompany(hqRoot: string, payload: unknown): unknown;
|
|
@@ -7,12 +42,16 @@ export interface MeetingDetectDeps {
|
|
|
7
42
|
hqRoot: string;
|
|
8
43
|
dir: string;
|
|
9
44
|
enabled: () => boolean;
|
|
10
|
-
companies: () => string[]
|
|
45
|
+
companies: () => readonly string[] | Promise<readonly string[]>;
|
|
11
46
|
list: (company: string, signal: AbortSignal) => Promise<{
|
|
12
47
|
companyId: string;
|
|
13
48
|
bots: LiveMeetingBot[];
|
|
14
49
|
}>;
|
|
15
50
|
intervalSeconds?: () => number;
|
|
51
|
+
/** Named in the line logged once when the poll list is empty. */
|
|
52
|
+
emptyReason?: () => string;
|
|
53
|
+
/** Deadline for an asynchronous companies() lookup. */
|
|
54
|
+
companiesTimeoutMs?: number;
|
|
16
55
|
now?: () => Date;
|
|
17
56
|
log: (message: string) => void;
|
|
18
57
|
}
|
|
@@ -7,11 +7,178 @@ import { fetchAttendedLiveBots } from "../../live-meetings.js";
|
|
|
7
7
|
import { ensureCognitoToken } from "../../../utils/cognito-session.js";
|
|
8
8
|
import { getCompanyUid } from "../../../utils/vault-api.js";
|
|
9
9
|
import { assertSafeSegment } from "../../hot-channels/landing.js";
|
|
10
|
-
import {
|
|
10
|
+
import { effectiveBotCompanies, effectiveBotKind } from "../config.js";
|
|
11
11
|
import { emitBotEvent } from "../events.js";
|
|
12
12
|
import { executiveEnabled, isExecutiveBot } from "../executive-settings.js";
|
|
13
|
+
import { fleetOwnerCompanies, fleetOwnerCompanyRows } from "../fleet-owner-companies.js";
|
|
14
|
+
import { redactForLog } from "../log.js";
|
|
13
15
|
const RETENTION_MS = 24 * 60 * 60 * 1000;
|
|
14
16
|
const ACTIVE = new Set(["joining", "recording", "in_call"]);
|
|
17
|
+
/**
|
|
18
|
+
* Log backoff only: polling stays on the normal cadence so a recovered company is
|
|
19
|
+
* detected on the next poll. The first repeat of a failure stays quiet for five
|
|
20
|
+
* minutes; the quiet period doubles up to an hour.
|
|
21
|
+
*/
|
|
22
|
+
export const MEETING_DETECT_FAILURE_BACKOFF_START_MS = 5 * 60 * 1000;
|
|
23
|
+
export const MEETING_DETECT_FAILURE_BACKOFF_MAX_MS = 60 * 60 * 1000;
|
|
24
|
+
/** Failures remembered per company, so two alternating failures still back off. */
|
|
25
|
+
const MAX_FAILURE_SIGNATURES = 4;
|
|
26
|
+
const COMPANIES_TIMEOUT_MS = 15_000;
|
|
27
|
+
const ENTITLED_KEY = "\0entitled";
|
|
28
|
+
const POLL_KEY = "\0poll";
|
|
29
|
+
export const MEETING_DETECT_STEPS = ["token", "company-uid", "meetings list", "ledger", "memberships", "validation", "event", "detector"];
|
|
30
|
+
/** A detection failure that names the step and, when the caller set one, the HTTP status. */
|
|
31
|
+
export class MeetingDetectError extends Error {
|
|
32
|
+
step;
|
|
33
|
+
status;
|
|
34
|
+
constructor(step, cause) {
|
|
35
|
+
const base = cause instanceof Error ? cause : new Error(cause == null ? "unknown error" : String(cause));
|
|
36
|
+
super(base.message);
|
|
37
|
+
this.name = base.name || "Error";
|
|
38
|
+
this.step = step;
|
|
39
|
+
this.status = httpStatusOf(cause);
|
|
40
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function httpStatusOf(err) {
|
|
44
|
+
if (!err || typeof err !== "object")
|
|
45
|
+
return undefined;
|
|
46
|
+
const record = err;
|
|
47
|
+
for (const value of [record.status, record.statusCode, record.httpStatus]) {
|
|
48
|
+
if (typeof value === "number" && value >= 100 && value <= 599)
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
if (typeof record.message !== "string")
|
|
52
|
+
return undefined;
|
|
53
|
+
const match = /\bHTTP\s+(\d{3})\b/.exec(record.message) ?? /\breturned\s+(\d{3})\b/.exec(record.message);
|
|
54
|
+
return match ? Number(match[1]) : undefined;
|
|
55
|
+
}
|
|
56
|
+
const SECRET_KEY = "[a-z0-9_-]*(?:token|secret|password|passwd|pwd|api[_-]?key|signature|credential|authorization|cookie)[a-z0-9_-]*";
|
|
57
|
+
const SECRET_JSON_FIELD = new RegExp(`\\\\?"(${SECRET_KEY})\\\\?"\\s*:\\s*\\\\?"(?:[^"\\\\]|\\\\[^"])*\\\\?"`, "gi");
|
|
58
|
+
const SECRET_PARAM = new RegExp(`\\b(${SECRET_KEY})=[^\\s&"',;]+`, "gi");
|
|
59
|
+
const SECRET_HEADER = new RegExp(`\\b(${SECRET_KEY})\\s*:\\s*(?:(?:Basic|Bearer|Token|Digest|Negotiate)\\s+)?[^\\s"',;]+`, "gi");
|
|
60
|
+
function safeErrorMessage(err) {
|
|
61
|
+
const raw = err instanceof Error ? err.message : String(err ?? "unknown error");
|
|
62
|
+
return redactForLog(raw)
|
|
63
|
+
.replace(/\s*[\r\n]+\s*/g, " ")
|
|
64
|
+
.replace(/\/\/[^\s/@]+@/g, "//[REDACTED]@")
|
|
65
|
+
.replace(SECRET_JSON_FIELD, '"$1":"[REDACTED]"')
|
|
66
|
+
.replace(SECRET_PARAM, "$1=[REDACTED]")
|
|
67
|
+
.replace(SECRET_HEADER, "$1: [REDACTED]")
|
|
68
|
+
.replace(/\bhqk_[A-Za-z0-9._-]+/gi, "hqk_[REDACTED]")
|
|
69
|
+
.replace(/\bsk-[a-z]+-[A-Za-z0-9_-]+/gi, "[REDACTED]")
|
|
70
|
+
.replace(/\b(?:sk|pk|api|token)[_-][A-Za-z0-9]{8,}/gi, "[REDACTED]")
|
|
71
|
+
.replace(/(?<![A-Za-z0-9_+=-])[A-Za-z0-9_+=-]{24,}/g, "[REDACTED]");
|
|
72
|
+
}
|
|
73
|
+
/** Failures differing only in a number or generated id count as the same failure. HTTP status still differs. */
|
|
74
|
+
function failureSignature(line) {
|
|
75
|
+
return line.replace(/\b[0-9a-f]{8,}\b/gi, "#").replace(/(?<!HTTP )\b\d+\b/g, "#");
|
|
76
|
+
}
|
|
77
|
+
/** Company, step, error name, and HTTP status or error class. Secrets are stripped. */
|
|
78
|
+
export function meetingDetectFailureLine(company, err, fallback) {
|
|
79
|
+
const step = err instanceof MeetingDetectError ? err.step : fallback;
|
|
80
|
+
const status = err instanceof MeetingDetectError ? err.status : httpStatusOf(err);
|
|
81
|
+
const name = err instanceof Error && err.name ? err.name : "Error";
|
|
82
|
+
const statusText = status !== undefined ? `HTTP ${status} ` : "";
|
|
83
|
+
return `meeting detection failed for ${company} at ${step}: ${statusText}${name}: ${safeErrorMessage(err)}`;
|
|
84
|
+
}
|
|
85
|
+
function fixtureSlugs(hqRoot) {
|
|
86
|
+
const skipped = new Set();
|
|
87
|
+
try {
|
|
88
|
+
const text = fs.readFileSync(path.join(hqRoot, "companies/manifest.yaml"), "utf8").replace(/^\uFEFF/, "");
|
|
89
|
+
const parsed = yaml.load(text);
|
|
90
|
+
const companies = parsed?.companies;
|
|
91
|
+
if (!companies || typeof companies !== "object")
|
|
92
|
+
return skipped;
|
|
93
|
+
for (const [slug, value] of Object.entries(companies)) {
|
|
94
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
95
|
+
continue;
|
|
96
|
+
const entry = value;
|
|
97
|
+
const marked = [entry.kind, entry.type, entry.purpose].some((mark) => typeof mark === "string" && ["fixture", "test"].includes(mark.trim().toLowerCase()));
|
|
98
|
+
if (entry.fixture === true || entry.test === true || marked)
|
|
99
|
+
skipped.add(slug);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
catch { /* An unreadable manifest does not widen the poll to every directory. */ }
|
|
103
|
+
return skipped;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Companies this bot may poll: an explicit bind, otherwise a company bot's
|
|
107
|
+
* memberships, otherwise the signed-in owner's active memberships.
|
|
108
|
+
* Manifest fixtures and cmp_ ids are not a poll list. A bind to a company UID
|
|
109
|
+
* polls the manifest slug with that cloud_uid.
|
|
110
|
+
*/
|
|
111
|
+
export async function resolveDetectionCompanies(config, memberships = fleetOwnerCompanies) {
|
|
112
|
+
const explicit = typeof config.companySlug === "string" ? config.companySlug.trim() : "";
|
|
113
|
+
const bound = explicit ? [explicit.startsWith("cmp_") ? slugForCompanyUid(config.hqRoot, explicit) : explicit] : effectiveBotCompanies(config);
|
|
114
|
+
// Only a personal bot acts as its owner. A company bot with no companies polls nothing.
|
|
115
|
+
const source = bound.length > 0 || effectiveBotKind(config) === "company" ? bound : await memberships();
|
|
116
|
+
const fixtures = fixtureSlugs(config.hqRoot);
|
|
117
|
+
const out = [];
|
|
118
|
+
for (const slug of source) {
|
|
119
|
+
if (!slug || slug === "personal" || slug.startsWith("cmp_") || fixtures.has(slug) || out.includes(slug))
|
|
120
|
+
continue;
|
|
121
|
+
out.push(slug);
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Owner companies for one detector. A row with no slug keeps the slug last seen
|
|
127
|
+
* for that company UID and is reported once. A row that is absent or no longer
|
|
128
|
+
* active is forgotten, so a real membership removal still takes effect.
|
|
129
|
+
*/
|
|
130
|
+
export function createDetectionMemberships(log, dependencies = {}) {
|
|
131
|
+
const now = dependencies.now ?? Date.now;
|
|
132
|
+
let known = new Map();
|
|
133
|
+
let reported = 0;
|
|
134
|
+
let quietUntil = 0;
|
|
135
|
+
return async () => {
|
|
136
|
+
const rows = await fleetOwnerCompanyRows(dependencies);
|
|
137
|
+
const next = new Map();
|
|
138
|
+
let missing = 0;
|
|
139
|
+
let kept = 0;
|
|
140
|
+
for (const { companyUid, slug } of rows) {
|
|
141
|
+
const resolved = slug ?? known.get(companyUid);
|
|
142
|
+
if (!slug) {
|
|
143
|
+
missing += 1;
|
|
144
|
+
if (resolved)
|
|
145
|
+
kept += 1;
|
|
146
|
+
}
|
|
147
|
+
if (resolved)
|
|
148
|
+
next.set(companyUid, resolved);
|
|
149
|
+
}
|
|
150
|
+
known = next;
|
|
151
|
+
if (missing > reported) {
|
|
152
|
+
log(`meeting detection: membership lookup returned ${missing} active row(s) with no company slug: ${kept} kept from the last good list, ${missing - kept} dropped and not polled`);
|
|
153
|
+
reported = missing;
|
|
154
|
+
quietUntil = now() + MEETING_DETECT_FAILURE_BACKOFF_START_MS;
|
|
155
|
+
}
|
|
156
|
+
else if (missing === 0 && now() >= quietUntil) {
|
|
157
|
+
reported = 0;
|
|
158
|
+
}
|
|
159
|
+
return [...new Set(next.values())].sort((a, b) => a.localeCompare(b));
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/** Why the poll list came back empty, for the one line logged when detection has nothing to poll. */
|
|
163
|
+
export function noDetectionCompaniesReason(config) {
|
|
164
|
+
const explicit = typeof config.companySlug === "string" ? config.companySlug.trim() : "";
|
|
165
|
+
if (explicit)
|
|
166
|
+
return `bind ${explicit} is personal, a fixture, or a company UID with no manifest slug`;
|
|
167
|
+
if (effectiveBotCompanies(config).length > 0)
|
|
168
|
+
return "every configured company is a fixture";
|
|
169
|
+
if (effectiveBotKind(config) === "company")
|
|
170
|
+
return "this company bot has no configured companies";
|
|
171
|
+
return "no active membership has a usable company slug";
|
|
172
|
+
}
|
|
173
|
+
function slugForCompanyUid(hqRoot, uid) {
|
|
174
|
+
try {
|
|
175
|
+
const { company } = normalizeDetectedCompany(hqRoot, { company: uid });
|
|
176
|
+
return company.startsWith("cmp_") ? "" : company;
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
return "";
|
|
180
|
+
}
|
|
181
|
+
}
|
|
15
182
|
export function detectIntervalSeconds(hqRoot) {
|
|
16
183
|
try {
|
|
17
184
|
const settings = yaml.load(fs.readFileSync(path.join(hqRoot, "core/settings/signals.yaml"), "utf8"));
|
|
@@ -57,13 +224,86 @@ export function createMeetingDetect(deps) {
|
|
|
57
224
|
let next = 0;
|
|
58
225
|
let disabledLogged = false;
|
|
59
226
|
let pending;
|
|
227
|
+
let emptyLogged = false;
|
|
228
|
+
let lastCompanies;
|
|
229
|
+
const failures = new Map();
|
|
230
|
+
const label = (key) => key === ENTITLED_KEY ? "entitled companies" : key === POLL_KEY ? "detector" : key;
|
|
231
|
+
const remember = (key, err, fallback) => {
|
|
232
|
+
if (controller.signal.aborted)
|
|
233
|
+
return;
|
|
234
|
+
const line = meetingDetectFailureLine(label(key), err, fallback);
|
|
235
|
+
const signature = failureSignature(line);
|
|
236
|
+
const seen = failures.get(key) ?? new Map();
|
|
237
|
+
failures.set(key, seen);
|
|
238
|
+
const prev = seen.get(signature);
|
|
239
|
+
const at = now().getTime();
|
|
240
|
+
if (prev && at < prev.nextAt)
|
|
241
|
+
return;
|
|
242
|
+
const backoffMs = prev ? Math.min(prev.backoffMs * 2, MEETING_DETECT_FAILURE_BACKOFF_MAX_MS) : MEETING_DETECT_FAILURE_BACKOFF_START_MS;
|
|
243
|
+
seen.delete(signature);
|
|
244
|
+
seen.set(signature, { nextAt: at + backoffMs, backoffMs });
|
|
245
|
+
if (seen.size > MAX_FAILURE_SIGNATURES)
|
|
246
|
+
seen.delete(seen.keys().next().value);
|
|
247
|
+
deps.log(line);
|
|
248
|
+
};
|
|
249
|
+
/** A success ends the backoff, but a company flapping between success and failure still logs at most every few minutes. */
|
|
250
|
+
const recovered = (key) => {
|
|
251
|
+
const seen = failures.get(key);
|
|
252
|
+
if (!seen)
|
|
253
|
+
return;
|
|
254
|
+
const at = now().getTime();
|
|
255
|
+
for (const [signature, state] of seen) {
|
|
256
|
+
if (at >= state.nextAt)
|
|
257
|
+
seen.delete(signature);
|
|
258
|
+
else
|
|
259
|
+
seen.set(signature, { nextAt: Math.min(state.nextAt, at + MEETING_DETECT_FAILURE_BACKOFF_START_MS), backoffMs: MEETING_DETECT_FAILURE_BACKOFF_START_MS });
|
|
260
|
+
}
|
|
261
|
+
if (seen.size === 0)
|
|
262
|
+
failures.delete(key);
|
|
263
|
+
};
|
|
264
|
+
/** Assign a thrown error to the step it came from. */
|
|
265
|
+
const atStep = (step, work) => {
|
|
266
|
+
try {
|
|
267
|
+
return work();
|
|
268
|
+
}
|
|
269
|
+
catch (err) {
|
|
270
|
+
throw err instanceof MeetingDetectError ? err : new MeetingDetectError(step, err);
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
const safeSegment = (value, name) => atStep("validation", () => assertSafeSegment(value, name));
|
|
60
274
|
const poll = async () => {
|
|
275
|
+
let companies;
|
|
276
|
+
try {
|
|
277
|
+
const listed = deps.companies();
|
|
278
|
+
const bounded = AbortSignal.any([controller.signal, AbortSignal.timeout(deps.companiesTimeoutMs ?? COMPANIES_TIMEOUT_MS)]);
|
|
279
|
+
companies = [...new Set(listed instanceof Promise ? await untilAborted(bounded, () => listed) : listed)];
|
|
280
|
+
if (controller.signal.aborted)
|
|
281
|
+
return;
|
|
282
|
+
recovered(ENTITLED_KEY);
|
|
283
|
+
lastCompanies = companies;
|
|
284
|
+
}
|
|
285
|
+
catch (err) {
|
|
286
|
+
if (controller.signal.aborted)
|
|
287
|
+
return;
|
|
288
|
+
remember(ENTITLED_KEY, err, "memberships");
|
|
289
|
+
// A failed lookup says nothing about who is entitled: keep polling the last good list.
|
|
290
|
+
if (!lastCompanies)
|
|
291
|
+
return;
|
|
292
|
+
companies = lastCompanies;
|
|
293
|
+
}
|
|
294
|
+
if (companies.length === 0) {
|
|
295
|
+
if (!emptyLogged)
|
|
296
|
+
deps.log(`meeting detection has no companies to poll: ${deps.emptyReason?.() ?? "the company list is empty"}`);
|
|
297
|
+
emptyLogged = true;
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
emptyLogged = false;
|
|
61
301
|
// One slow or denied company must not delay detection in another company.
|
|
62
|
-
await Promise.all(
|
|
302
|
+
await Promise.all(companies.map(async (company) => {
|
|
63
303
|
if (controller.signal.aborted || !deps.enabled())
|
|
64
304
|
return;
|
|
65
305
|
try {
|
|
66
|
-
|
|
306
|
+
safeSegment(company, "company");
|
|
67
307
|
const root = path.join(deps.hqRoot, "workspace/executive/meetings", company);
|
|
68
308
|
const file = path.join(root, ".detected.json");
|
|
69
309
|
let stored = {};
|
|
@@ -78,7 +318,16 @@ export function createMeetingDetect(deps) {
|
|
|
78
318
|
throw new Error("Invalid detected ledger");
|
|
79
319
|
const time = now();
|
|
80
320
|
const seen = Object.fromEntries(Object.entries(stored).filter((entry) => typeof entry[1] === "string" && Date.parse(entry[1]) > time.getTime() - RETENTION_MS));
|
|
81
|
-
|
|
321
|
+
let companyId;
|
|
322
|
+
let bots;
|
|
323
|
+
try {
|
|
324
|
+
({ companyId, bots } = await deps.list(company, controller.signal));
|
|
325
|
+
}
|
|
326
|
+
catch (err) {
|
|
327
|
+
if (controller.signal.aborted)
|
|
328
|
+
return;
|
|
329
|
+
throw err instanceof MeetingDetectError ? err : new MeetingDetectError("meetings list", err);
|
|
330
|
+
}
|
|
82
331
|
if (controller.signal.aborted || !deps.enabled())
|
|
83
332
|
return;
|
|
84
333
|
fs.mkdirSync(root, { recursive: true });
|
|
@@ -88,22 +337,22 @@ export function createMeetingDetect(deps) {
|
|
|
88
337
|
const id = bot.recallBotId || bot.botId || bot.meetingId;
|
|
89
338
|
if (typeof id !== "string" || !id)
|
|
90
339
|
continue;
|
|
91
|
-
|
|
340
|
+
safeSegment(id, "meeting id");
|
|
92
341
|
if (Object.hasOwn(seen, id))
|
|
93
342
|
continue;
|
|
94
343
|
// Check aliases too: an older rider may have started with a Recall ID.
|
|
95
344
|
const ids = [id, bot.recallBotId, bot.botId, bot.meetingId].filter((value) => typeof value === "string" && value.length > 0);
|
|
96
345
|
for (const alias of ids)
|
|
97
|
-
|
|
346
|
+
safeSegment(alias, "meeting id");
|
|
98
347
|
if (ids.some((alias) => [company, companyId].some((co) => {
|
|
99
|
-
|
|
348
|
+
safeSegment(co, "company");
|
|
100
349
|
const base = path.join(deps.hqRoot, "workspace/executive/meetings", co, alias);
|
|
101
350
|
return fs.existsSync(`${base}.rider.lock`) || fs.existsSync(`${base}.rider.json`);
|
|
102
351
|
}))) {
|
|
103
352
|
seen[id] = time.toISOString();
|
|
104
353
|
continue;
|
|
105
354
|
}
|
|
106
|
-
const event = emitBotEvent(deps.dir, "meeting.detected", { meeting_id: id, company, source: "poll" }, time, (prior) => prior.event === "meeting.detected" && [company, companyId].includes(String(prior.payload.company)) && ids.includes(String(prior.payload.meeting_id)));
|
|
355
|
+
const event = atStep("event", () => emitBotEvent(deps.dir, "meeting.detected", { meeting_id: id, company, source: "poll" }, time, (prior) => prior.event === "meeting.detected" && [company, companyId].includes(String(prior.payload.company)) && ids.includes(String(prior.payload.meeting_id))));
|
|
107
356
|
seen[id] = event.at;
|
|
108
357
|
}
|
|
109
358
|
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
@@ -114,10 +363,12 @@ export function createMeetingDetect(deps) {
|
|
|
114
363
|
finally {
|
|
115
364
|
fs.rmSync(tmp, { force: true });
|
|
116
365
|
}
|
|
366
|
+
recovered(company);
|
|
117
367
|
}
|
|
118
|
-
catch {
|
|
119
|
-
if (
|
|
120
|
-
|
|
368
|
+
catch (err) {
|
|
369
|
+
if (controller.signal.aborted)
|
|
370
|
+
return;
|
|
371
|
+
remember(company, err, "ledger");
|
|
121
372
|
}
|
|
122
373
|
}));
|
|
123
374
|
};
|
|
@@ -137,7 +388,8 @@ export function createMeetingDetect(deps) {
|
|
|
137
388
|
return;
|
|
138
389
|
const seconds = deps.intervalSeconds?.() ?? 60;
|
|
139
390
|
next = now().getTime() + (Number.isFinite(seconds) ? Math.max(5, seconds) : 60) * 1000;
|
|
140
|
-
pending = poll().catch(() =>
|
|
391
|
+
pending = poll().catch((err) => { if (!controller.signal.aborted)
|
|
392
|
+
remember(POLL_KEY, err, "detector"); }).finally(() => { pending = undefined; });
|
|
141
393
|
},
|
|
142
394
|
async settled() { await pending; },
|
|
143
395
|
async stop() { controller.abort(); await pending; },
|
|
@@ -159,16 +411,28 @@ async function untilAborted(signal, work) {
|
|
|
159
411
|
}
|
|
160
412
|
}
|
|
161
413
|
export function defaultMeetingDetectDeps(config, dir, log) {
|
|
414
|
+
const ownerCompanies = createDetectionMemberships(log);
|
|
162
415
|
return {
|
|
163
416
|
hqRoot: config.hqRoot, dir, log,
|
|
164
417
|
enabled: () => isExecutiveBot(config) && executiveEnabled(),
|
|
165
|
-
companies: () => config
|
|
418
|
+
companies: () => resolveDetectionCompanies(config, ownerCompanies),
|
|
419
|
+
emptyReason: () => noDetectionCompaniesReason(config),
|
|
166
420
|
intervalSeconds: () => detectIntervalSeconds(config.hqRoot),
|
|
167
421
|
list: async (company, signal) => {
|
|
168
422
|
const bounded = AbortSignal.any([signal, AbortSignal.timeout(15_000)]);
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
423
|
+
const step = async (name, work) => {
|
|
424
|
+
try {
|
|
425
|
+
return await untilAborted(bounded, work);
|
|
426
|
+
}
|
|
427
|
+
catch (err) {
|
|
428
|
+
if (signal.aborted)
|
|
429
|
+
throw err;
|
|
430
|
+
throw new MeetingDetectError(name, err);
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
const token = await step("token", () => ensureCognitoToken({ interactive: false, signal: bounded }));
|
|
434
|
+
const companyId = company.startsWith("cmp_") ? company : await step("company-uid", () => getCompanyUid(token, company));
|
|
435
|
+
const bots = await step("meetings list", () => fetchAttendedLiveBots(token, companyId, true, bounded));
|
|
172
436
|
return { companyId, bots };
|
|
173
437
|
},
|
|
174
438
|
};
|
package/dist/lib/bot/run.d.ts
CHANGED
package/dist/lib/bot/run.js
CHANGED
|
@@ -2263,7 +2263,9 @@ export async function runBot(deps) {
|
|
|
2263
2263
|
: { ok: false, text: `This bot cannot run the hot-channel sync for ${syncCompany}.` };
|
|
2264
2264
|
markProcessed(dir, id, now().toISOString());
|
|
2265
2265
|
const status = result.ok ? "succeeded" : "failed";
|
|
2266
|
-
|
|
2266
|
+
// The signals-failure alert is the one DM for a failure it already covers.
|
|
2267
|
+
const sendReport = !(quietJob && result.ok) && !("ownerAlerted" in result && result.ownerAlerted === true);
|
|
2268
|
+
if (sendReport) {
|
|
2267
2269
|
try {
|
|
2268
2270
|
await sendToPerson(result.text);
|
|
2269
2271
|
}
|
|
@@ -2277,7 +2279,7 @@ export async function runBot(deps) {
|
|
|
2277
2279
|
clearInflight(dir, id);
|
|
2278
2280
|
attempts.delete(id);
|
|
2279
2281
|
setStatus({
|
|
2280
|
-
...(
|
|
2282
|
+
...(sendReport ? { repliesSent: (readStatus()?.repliesSent ?? 0) + 1 } : {}),
|
|
2281
2283
|
lastActivityAt: now().toISOString(),
|
|
2282
2284
|
});
|
|
2283
2285
|
log("info", `hot-signal-sync job ${jobId} run ${id} ${status} for ${syncCompany}${catchUp ? " (catch-up)" : ""}`);
|
|
@@ -47,9 +47,11 @@ const MODEL_UNSUPPORTED = /there'?s an issue with the selected model|\bnot_found
|
|
|
47
47
|
/**
|
|
48
48
|
* The account's plan ran out of usage. Claude Code: "You've hit your weekly
|
|
49
49
|
* limit · resets 9pm (Asia/Dhaka)", "You've hit your session limit". Codex:
|
|
50
|
-
* "You've hit your usage limit".
|
|
50
|
+
* "You've hit your usage limit". Also "You've hit your org's monthly usage
|
|
51
|
+
* limit", "You're out of extra usage" and "Spending cap reached"; those three
|
|
52
|
+
* wordings are remembered, not captured from a live account.
|
|
51
53
|
*/
|
|
52
|
-
const USAGE_LIMIT = /\byou['’]?ve (?:hit|reached) your (?:[\w
|
|
54
|
+
const USAGE_LIMIT = /\byou(?:['’]?ve| have) (?:hit|reached) your (?:[\w'’-]+ ){0,3}limit\b|\b(?:usage|session|weekly|daily|monthly|5-hour) limit (?:reached|exceeded)\b|\byou['’]?re out of (?:[\w-]+ )?usage\b|\bspending cap reached\b/i;
|
|
53
55
|
/**
|
|
54
56
|
* Limits that a "You've hit your … limit" sentence can name but that are not
|
|
55
57
|
* the plan running out: a short rate limit ("You've hit your rate limit. Try
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* ~/.hq/capacity unless that root is requested.
|
|
7
7
|
*/
|
|
8
8
|
import { type CapacityAccount } from "./accounts.js";
|
|
9
|
+
import type { LaneProvider } from "../lanes/types.js";
|
|
9
10
|
import { type CodexAppServerSpawn } from "./collectors/codex.js";
|
|
10
11
|
import { type CollectClaudeOAuthOptions } from "./collectors/claude-oauth.js";
|
|
11
12
|
import { type CollectGrokOptions } from "./collectors/grok.js";
|
|
@@ -28,6 +29,12 @@ export interface CollectCapacityOnceOptions {
|
|
|
28
29
|
};
|
|
29
30
|
/** Login passes false so a partial account list cannot label the whole spool. */
|
|
30
31
|
includeSpool?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Run only these providers' readers. Omit to read every provider. The
|
|
34
|
+
* `lanes create --account auto` refresh passes the providers it skipped as
|
|
35
|
+
* stale, so it never reads a provider outside `--provider`.
|
|
36
|
+
*/
|
|
37
|
+
providers?: readonly LaneProvider[];
|
|
31
38
|
}
|
|
32
39
|
export declare function collectCapacityOnce(options?: CollectCapacityOnceOptions): Promise<NowView>;
|
|
33
40
|
//# sourceMappingURL=collect.d.ts.map
|