@indigoai-us/hq-cli 5.345.179 → 5.345.181
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 +23 -0
- package/dist/command-catalog.generated.d.ts +126 -0
- package/dist/command-catalog.generated.js +155 -0
- package/dist/commands/bot.d.ts +29 -1
- package/dist/commands/bot.js +282 -22
- package/dist/commands/channels.d.ts +18 -1
- package/dist/commands/channels.js +185 -1
- package/dist/commands/lanes.d.ts +1 -1
- package/dist/commands/lanes.js +6 -2
- package/dist/commands/mesh.js +19 -0
- package/dist/hq-cloud-sync-runner/bin/sync-runner.js +2285 -1743
- package/dist/hq-cloud-sync-runner/package.json +1 -1
- package/dist/lib/bot/config.d.ts +8 -0
- package/dist/lib/bot/fleet-local.d.ts +7 -3
- package/dist/lib/bot/fleet-local.js +234 -64
- package/dist/lib/bot/run.js +39 -2
- package/dist/lib/bot/runtime-auth.d.ts +119 -0
- package/dist/lib/bot/runtime-auth.js +251 -0
- package/dist/lib/daemon/catalog.d.ts +1 -0
- package/dist/lib/daemon/catalog.js +1 -1
- package/dist/lib/daemon/run.d.ts +2 -0
- package/dist/lib/daemon/run.js +64 -16
- 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/adapters/meetings.js +3 -1
- package/dist/lib/hot-channels/contract.d.ts +6 -0
- package/dist/lib/hot-channels/ledger.js +17 -0
- package/dist/lib/hot-channels/loop.js +2 -0
- package/dist/lib/lanes/accounts.d.ts +1 -17
- package/dist/lib/lanes/accounts.js +5 -45
- package/dist/lib/lanes/provider-home.d.ts +24 -0
- package/dist/lib/lanes/provider-home.js +52 -0
- package/dist/lib/lanes/spawn.d.ts +12 -0
- package/dist/lib/lanes/spawn.js +27 -0
- package/dist/lib/mesh/live/daemon/doctor.d.ts +3 -0
- package/dist/lib/mesh/live/daemon/doctor.js +13 -0
- package/dist/lib/mesh/live/daemon/owner-inbox-push.d.ts +94 -0
- package/dist/lib/mesh/live/daemon/owner-inbox-push.js +273 -0
- package/dist/lib/mesh/live/daemon/run.js +31 -0
- package/dist/lib/mesh/live/daemon/work-subscribe.d.ts +14 -0
- package/dist/lib/mesh/live/daemon/work-subscribe.js +210 -3
- package/dist/lib/mesh/live/paths.d.ts +2 -0
- package/dist/lib/mesh/live/paths.js +2 -0
- package/dist/lib/sync-core/flag.d.ts +1 -1
- package/dist/lib/sync-core/flag.js +1 -1
- package/dist/lib/sync-core/reconcile.d.ts +1 -1
- package/dist/lib/sync-core/reconcile.js +9 -7
- package/dist/lib/sync-core/release.d.ts +3 -3
- package/dist/lib/sync-core/release.js +4 -4
- package/dist/lib/sync-core/rollout-state.d.ts +1 -0
- package/dist/lib/sync-core/rollout-state.js +1 -0
- package/package.json +8 -8
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Owner (prs_) DM doorbell state for the mesh daemon.
|
|
3
|
+
*
|
|
4
|
+
* The server publishes a wake to `hq/{prs}/dm` for each DM, thread reply and
|
|
5
|
+
* channel post the owner should see. The daemon reads only `type`,
|
|
6
|
+
* `channelId` and `eventId` from that payload, keeps a channel event only when
|
|
7
|
+
* the channel belongs to an allowed company, and bumps a content-free counter
|
|
8
|
+
* in `owner-inbox-push.json`. Message text, poster name and email are never
|
|
9
|
+
* stored, logged or forwarded.
|
|
10
|
+
*/
|
|
11
|
+
import * as fs from "node:fs";
|
|
12
|
+
import * as path from "node:path";
|
|
13
|
+
import { OWNER_INBOX_PUSH_STATE_BASENAME } from "../paths.js";
|
|
14
|
+
export { OWNER_INBOX_PUSH_STATE_BASENAME } from "../paths.js";
|
|
15
|
+
/** Heartbeat cadence while the owner DM topic is subscribed. */
|
|
16
|
+
export const OWNER_PUSH_HEARTBEAT_MS = 5_000;
|
|
17
|
+
/** A heartbeat older than this means the push signal is stale. */
|
|
18
|
+
export const OWNER_PUSH_STALE_MS = 15_000;
|
|
19
|
+
/** Channel list refreshes at most this often when an unknown channel arrives. */
|
|
20
|
+
export const OWNER_CHANNEL_REFRESH_MIN_MS = 60_000;
|
|
21
|
+
/** A channel-list fetch that runs longer than this is abandoned. */
|
|
22
|
+
export const OWNER_CHANNEL_REFRESH_TIMEOUT_MS = 10_000;
|
|
23
|
+
/** Every key the state file may contain. Nothing else is ever written. */
|
|
24
|
+
export const OWNER_INBOX_PUSH_STATE_KEYS = [
|
|
25
|
+
"connected",
|
|
26
|
+
"heartbeatAtMs",
|
|
27
|
+
"count",
|
|
28
|
+
"lastAt",
|
|
29
|
+
"lastType",
|
|
30
|
+
"principalUid",
|
|
31
|
+
];
|
|
32
|
+
const CHANNEL_ID_RE = /^chn_[A-Za-z0-9]+$/;
|
|
33
|
+
const EVENT_ID_RE = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
34
|
+
/**
|
|
35
|
+
* Read only `type`, `channelId` and `eventId`. Returns null for anything that
|
|
36
|
+
* is not a dm, thread or channel wake. Other payload fields are discarded.
|
|
37
|
+
*/
|
|
38
|
+
export function parseOwnerDoorbell(payload) {
|
|
39
|
+
let raw;
|
|
40
|
+
try {
|
|
41
|
+
raw = JSON.parse(typeof payload === "string" ? payload : payload.toString("utf8"));
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
47
|
+
return null;
|
|
48
|
+
const record = raw;
|
|
49
|
+
const type = record.type;
|
|
50
|
+
if (type !== "dm" && type !== "thread" && type !== "channel")
|
|
51
|
+
return null;
|
|
52
|
+
const out = { type };
|
|
53
|
+
if (typeof record.channelId === "string" && CHANNEL_ID_RE.test(record.channelId)) {
|
|
54
|
+
out.channelId = record.channelId;
|
|
55
|
+
}
|
|
56
|
+
if (typeof record.eventId === "string" && EVENT_ID_RE.test(record.eventId)) {
|
|
57
|
+
out.eventId = record.eventId;
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
function ownerStatePath(meshRoot) {
|
|
62
|
+
return path.join(meshRoot, OWNER_INBOX_PUSH_STATE_BASENAME);
|
|
63
|
+
}
|
|
64
|
+
/** Read the state file. Missing, non-regular or malformed files return null. */
|
|
65
|
+
export function readOwnerInboxPushState(meshRoot, onInfo) {
|
|
66
|
+
const target = ownerStatePath(meshRoot);
|
|
67
|
+
try {
|
|
68
|
+
const info = fs.lstatSync(target);
|
|
69
|
+
if (!info.isFile() || info.isSymbolicLink()) {
|
|
70
|
+
onInfo?.("owner inbox push state read ignored (not a regular file)");
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
const parsed = JSON.parse(fs.readFileSync(target, "utf8"));
|
|
74
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
75
|
+
return null;
|
|
76
|
+
const count = Number.isSafeInteger(parsed.count) && Number(parsed.count) >= 0
|
|
77
|
+
? Number(parsed.count)
|
|
78
|
+
: 0;
|
|
79
|
+
const heartbeatAtMs = Number.isFinite(parsed.heartbeatAtMs)
|
|
80
|
+
? Number(parsed.heartbeatAtMs)
|
|
81
|
+
: 0;
|
|
82
|
+
const state = {
|
|
83
|
+
connected: parsed.connected === true,
|
|
84
|
+
heartbeatAtMs,
|
|
85
|
+
count,
|
|
86
|
+
};
|
|
87
|
+
if (typeof parsed.lastAt === "string" && Number.isFinite(Date.parse(parsed.lastAt))) {
|
|
88
|
+
state.lastAt = parsed.lastAt;
|
|
89
|
+
}
|
|
90
|
+
if (parsed.lastType === "dm" || parsed.lastType === "thread" || parsed.lastType === "channel") {
|
|
91
|
+
state.lastType = parsed.lastType;
|
|
92
|
+
}
|
|
93
|
+
if (typeof parsed.principalUid === "string" && parsed.principalUid.startsWith("prs_")) {
|
|
94
|
+
state.principalUid = parsed.principalUid;
|
|
95
|
+
}
|
|
96
|
+
return state;
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
if (error.code !== "ENOENT") {
|
|
100
|
+
const name = error instanceof Error ? error.name : "UnknownError";
|
|
101
|
+
onInfo?.(`owner inbox push state read failed (${name})`);
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** Atomic write (temp file plus rename), mode 0600, allowed keys only. */
|
|
107
|
+
export function writeOwnerInboxPushState(meshRoot, state) {
|
|
108
|
+
fs.mkdirSync(meshRoot, { recursive: true, mode: 0o700 });
|
|
109
|
+
const target = ownerStatePath(meshRoot);
|
|
110
|
+
const temporary = `${target}.${process.pid}.tmp`;
|
|
111
|
+
const body = {
|
|
112
|
+
connected: state.connected,
|
|
113
|
+
heartbeatAtMs: state.heartbeatAtMs,
|
|
114
|
+
count: state.count,
|
|
115
|
+
};
|
|
116
|
+
if (state.lastAt)
|
|
117
|
+
body.lastAt = state.lastAt;
|
|
118
|
+
if (state.lastType)
|
|
119
|
+
body.lastType = state.lastType;
|
|
120
|
+
if (state.principalUid)
|
|
121
|
+
body.principalUid = state.principalUid;
|
|
122
|
+
try {
|
|
123
|
+
fs.writeFileSync(temporary, `${JSON.stringify(body)}\n`, { mode: 0o600 });
|
|
124
|
+
fs.chmodSync(temporary, 0o600);
|
|
125
|
+
fs.renameSync(temporary, target);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
try {
|
|
129
|
+
fs.unlinkSync(temporary);
|
|
130
|
+
}
|
|
131
|
+
catch (cleanupError) {
|
|
132
|
+
if (cleanupError.code !== "ENOENT")
|
|
133
|
+
throw cleanupError;
|
|
134
|
+
}
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Remove the state file. Used when the account is not a person account, so a
|
|
140
|
+
* file left by an earlier person login cannot report the push as stale.
|
|
141
|
+
*/
|
|
142
|
+
export function clearOwnerInboxPushState(meshRoot) {
|
|
143
|
+
try {
|
|
144
|
+
fs.unlinkSync(ownerStatePath(meshRoot));
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
if (error.code !== "ENOENT")
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* live: connected with a fresh heartbeat. stale: the file exists but the
|
|
153
|
+
* subscriber is disconnected or its heartbeat is older than the stale window.
|
|
154
|
+
* off: no state file (the daemon never subscribed on this machine).
|
|
155
|
+
*/
|
|
156
|
+
export function ownerPushStatus(state, nowMs, staleMs = OWNER_PUSH_STALE_MS) {
|
|
157
|
+
if (!state) {
|
|
158
|
+
return {
|
|
159
|
+
status: "off",
|
|
160
|
+
connected: false,
|
|
161
|
+
count: 0,
|
|
162
|
+
lastAt: null,
|
|
163
|
+
lastType: null,
|
|
164
|
+
heartbeatAt: null,
|
|
165
|
+
heartbeatAgeMs: null,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
const heartbeatAgeMs = state.heartbeatAtMs > 0 ? Math.max(0, nowMs - state.heartbeatAtMs) : null;
|
|
169
|
+
const fresh = heartbeatAgeMs !== null && heartbeatAgeMs <= staleMs;
|
|
170
|
+
return {
|
|
171
|
+
status: state.connected && fresh ? "live" : "stale",
|
|
172
|
+
connected: state.connected,
|
|
173
|
+
count: state.count,
|
|
174
|
+
lastAt: state.lastAt ?? null,
|
|
175
|
+
lastType: state.lastType ?? null,
|
|
176
|
+
heartbeatAt: state.heartbeatAtMs > 0 ? new Date(state.heartbeatAtMs).toISOString() : null,
|
|
177
|
+
heartbeatAgeMs,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Status for the signed-in account. Only a person account has an owner DM
|
|
182
|
+
* topic, so any other account kind (agent, outpost, or no login) reports off.
|
|
183
|
+
*/
|
|
184
|
+
export function ownerPushStatusForAccount(state, nowMs, actorKind) {
|
|
185
|
+
return ownerPushStatus(actorKind === "human" ? state : null, nowMs);
|
|
186
|
+
}
|
|
187
|
+
export function formatOwnerPushStatus(status) {
|
|
188
|
+
const last = status.lastAt ? `last event ${status.lastAt} (${status.lastType ?? "unknown"})` : "no events yet";
|
|
189
|
+
if (status.status === "off")
|
|
190
|
+
return "owner push: off (daemon has not subscribed on this machine)";
|
|
191
|
+
const beat = status.heartbeatAgeMs === null
|
|
192
|
+
? "no heartbeat"
|
|
193
|
+
: `heartbeat ${Math.round(status.heartbeatAgeMs / 1000)}s ago`;
|
|
194
|
+
return `owner push: ${status.status}; ${last}; count=${status.count}; ${beat}`;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Channel filter backed by the owner's channel list. A channel with no
|
|
198
|
+
* company, an unknown channel, or a company outside the allowed set is
|
|
199
|
+
* dropped. The allowed set is read on every check so a session lock change
|
|
200
|
+
* applies at once. The list refreshes at most once per refresh window.
|
|
201
|
+
*/
|
|
202
|
+
export function createOwnerChannelScope(opts) {
|
|
203
|
+
const now = opts.now ?? Date.now;
|
|
204
|
+
const refreshMinMs = opts.refreshMinMs ?? OWNER_CHANNEL_REFRESH_MIN_MS;
|
|
205
|
+
const refreshTimeoutMs = opts.refreshTimeoutMs ?? OWNER_CHANNEL_REFRESH_TIMEOUT_MS;
|
|
206
|
+
let companyByChannel = new Map();
|
|
207
|
+
let lastRefreshMs = null;
|
|
208
|
+
let inflight = null;
|
|
209
|
+
const refresh = async () => {
|
|
210
|
+
if (inflight)
|
|
211
|
+
return inflight;
|
|
212
|
+
lastRefreshMs = now();
|
|
213
|
+
inflight = (async () => {
|
|
214
|
+
try {
|
|
215
|
+
let timer;
|
|
216
|
+
const timeout = new Promise((_, reject) => {
|
|
217
|
+
timer = setTimeout(() => {
|
|
218
|
+
const err = new Error("owner channel list timed out");
|
|
219
|
+
err.name = "TimeoutError";
|
|
220
|
+
reject(err);
|
|
221
|
+
}, refreshTimeoutMs);
|
|
222
|
+
timer.unref?.();
|
|
223
|
+
});
|
|
224
|
+
let rows;
|
|
225
|
+
try {
|
|
226
|
+
rows = await Promise.race([opts.listChannels(), timeout]);
|
|
227
|
+
}
|
|
228
|
+
finally {
|
|
229
|
+
if (timer)
|
|
230
|
+
clearTimeout(timer);
|
|
231
|
+
}
|
|
232
|
+
const next = new Map();
|
|
233
|
+
for (const row of rows) {
|
|
234
|
+
if (typeof row.channelId !== "string")
|
|
235
|
+
continue;
|
|
236
|
+
next.set(row.channelId, typeof row.companyUid === "string" && row.companyUid ? row.companyUid : undefined);
|
|
237
|
+
}
|
|
238
|
+
companyByChannel = next;
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
// Keep the previous map; an unknown channel stays out of scope.
|
|
242
|
+
const name = error instanceof Error ? error.name : "UnknownError";
|
|
243
|
+
opts.onInfo?.(`owner channel list refresh failed (${name})`);
|
|
244
|
+
}
|
|
245
|
+
finally {
|
|
246
|
+
inflight = null;
|
|
247
|
+
}
|
|
248
|
+
})();
|
|
249
|
+
return inflight;
|
|
250
|
+
};
|
|
251
|
+
return {
|
|
252
|
+
async isInScope(channelId) {
|
|
253
|
+
let allowed;
|
|
254
|
+
try {
|
|
255
|
+
allowed = opts.allowedCompanyUids();
|
|
256
|
+
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
const name = error instanceof Error ? error.name : "UnknownError";
|
|
259
|
+
opts.onInfo?.(`owner allowed company read failed (${name})`);
|
|
260
|
+
allowed = undefined;
|
|
261
|
+
}
|
|
262
|
+
if (!allowed || allowed.length === 0)
|
|
263
|
+
return false;
|
|
264
|
+
if (!companyByChannel.has(channelId) &&
|
|
265
|
+
(lastRefreshMs === null || now() - lastRefreshMs >= refreshMinMs || inflight)) {
|
|
266
|
+
await refresh();
|
|
267
|
+
}
|
|
268
|
+
const companyUid = companyByChannel.get(channelId);
|
|
269
|
+
return companyUid !== undefined && allowed.includes(companyUid);
|
|
270
|
+
},
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
//# sourceMappingURL=owner-inbox-push.js.map
|
|
@@ -40,6 +40,8 @@ import { resolveRunningCliEntry } from "./install.js";
|
|
|
40
40
|
import { readDaemonConfig } from "./config.js";
|
|
41
41
|
import { retireLegacyListen } from "./legacy-listen.js";
|
|
42
42
|
import { startWorkCacheSubscriber } from "./work-subscribe.js";
|
|
43
|
+
import { createOwnerChannelScope } from "./owner-inbox-push.js";
|
|
44
|
+
import { vaultApiFetch } from "../../../../utils/vault-api.js";
|
|
43
45
|
import { capacityRoot } from "../../../capacity/ledger.js";
|
|
44
46
|
import { startCapacityScheduler, } from "../../../capacity/scheduler.js";
|
|
45
47
|
export const SPOOL_DEBOUNCE_MS = 2_000;
|
|
@@ -616,6 +618,35 @@ export async function runMeshDaemon(deps = {}) {
|
|
|
616
618
|
now,
|
|
617
619
|
onInfo: (message) => log(dir, message.slice(0, 200)),
|
|
618
620
|
random: deps.random,
|
|
621
|
+
// Channel events count only when the channel's company is in the
|
|
622
|
+
// device default or recent session company set. Unknown means drop.
|
|
623
|
+
ownerChannelScope: createOwnerChannelScope({
|
|
624
|
+
listChannels: async () => {
|
|
625
|
+
const res = await vaultApiFetch({
|
|
626
|
+
token: await getToken(),
|
|
627
|
+
path: "/v1/notify/channels",
|
|
628
|
+
baseUrl: resolveVaultApiBase(env),
|
|
629
|
+
});
|
|
630
|
+
if (!res.ok)
|
|
631
|
+
throw new Error(`channel list failed (${res.status})`);
|
|
632
|
+
const body = (await res.json());
|
|
633
|
+
if (!Array.isArray(body.channels))
|
|
634
|
+
return [];
|
|
635
|
+
return body.channels.flatMap((row) => {
|
|
636
|
+
if (!row || typeof row !== "object")
|
|
637
|
+
return [];
|
|
638
|
+
const record = row;
|
|
639
|
+
if (typeof record.channelId !== "string")
|
|
640
|
+
return [];
|
|
641
|
+
return [{
|
|
642
|
+
channelId: record.channelId,
|
|
643
|
+
...(typeof record.companyUid === "string" ? { companyUid: record.companyUid } : {}),
|
|
644
|
+
}];
|
|
645
|
+
});
|
|
646
|
+
},
|
|
647
|
+
allowedCompanyUids: () => readPreferredCompanyUids({ workContextRoot: ctxRoot }),
|
|
648
|
+
onInfo: (message) => log(dir, message.slice(0, 200)),
|
|
649
|
+
}),
|
|
619
650
|
});
|
|
620
651
|
}
|
|
621
652
|
catch (err) {
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Contract-2 subscriber for the personal work topic.
|
|
3
3
|
* Owns live-cache.json writes. Presence publish stays on PresenceClient.
|
|
4
|
+
* On a person (prs_) account it also subscribes to the owner DM topic and
|
|
5
|
+
* keeps the content-free owner-inbox-push.json counter.
|
|
4
6
|
*/
|
|
5
7
|
import type { IClientOptions } from "mqtt";
|
|
6
8
|
import type { MeshMqttEventClient } from "./mqtt-events.js";
|
|
7
9
|
import { type PersonalCredentialsFetcher } from "./credentials.js";
|
|
10
|
+
import { type OwnerChannelScope } from "./owner-inbox-push.js";
|
|
8
11
|
export interface WorkCacheMqtt extends MeshMqttEventClient {
|
|
9
12
|
subscribe(topic: string, opts: {
|
|
10
13
|
qos: 0 | 1;
|
|
@@ -19,6 +22,12 @@ export type SyncWakeVaults = Record<string, {
|
|
|
19
22
|
wakeSequence: number;
|
|
20
23
|
head?: number;
|
|
21
24
|
}>;
|
|
25
|
+
/**
|
|
26
|
+
* Owner DM subscribe retries per connection. The owner signal is best-effort:
|
|
27
|
+
* after this many failures it stays off until the next broker reconnect, and
|
|
28
|
+
* the work topic keeps running.
|
|
29
|
+
*/
|
|
30
|
+
export declare const OWNER_SUBSCRIBE_MAX_RETRIES = 6;
|
|
22
31
|
export declare function startWorkCacheSubscriber(opts: {
|
|
23
32
|
meshRoot: string;
|
|
24
33
|
fetchCredentials?: PersonalCredentialsFetcher;
|
|
@@ -32,5 +41,10 @@ export declare function startWorkCacheSubscriber(opts: {
|
|
|
32
41
|
};
|
|
33
42
|
onInfo?: (message: string) => void;
|
|
34
43
|
random?: () => number;
|
|
44
|
+
/**
|
|
45
|
+
* Company filter for channel events on the owner DM topic. Without it every
|
|
46
|
+
* event that names a channel is dropped.
|
|
47
|
+
*/
|
|
48
|
+
ownerChannelScope?: OwnerChannelScope;
|
|
35
49
|
}): Promise<WorkCacheSubscriber>;
|
|
36
50
|
//# sourceMappingURL=work-subscribe.d.ts.map
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Contract-2 subscriber for the personal work topic.
|
|
3
3
|
* Owns live-cache.json writes. Presence publish stays on PresenceClient.
|
|
4
|
+
* On a person (prs_) account it also subscribes to the owner DM topic and
|
|
5
|
+
* keeps the content-free owner-inbox-push.json counter.
|
|
4
6
|
*/
|
|
5
7
|
import * as fs from "node:fs";
|
|
6
8
|
import * as path from "node:path";
|
|
@@ -10,6 +12,7 @@ import { presignIotWssUrl } from "./presign.js";
|
|
|
10
12
|
import { applyProjectViewPush, parseProjectViewPush } from "./live-cache.js";
|
|
11
13
|
import { backoffDelayMs, RECONNECT_MIN_DELAY_MS } from "./presence.js";
|
|
12
14
|
import { AGENT_INBOX_PUSH_STATE_BASENAME, SYNC_WAKE_STATE_BASENAME } from "../paths.js";
|
|
15
|
+
import { clearOwnerInboxPushState, parseOwnerDoorbell, readOwnerInboxPushState, writeOwnerInboxPushState, } from "./owner-inbox-push.js";
|
|
13
16
|
export { AGENT_INBOX_PUSH_STATE_BASENAME, SYNC_WAKE_STATE_BASENAME } from "../paths.js";
|
|
14
17
|
const INBOX_PUSH_HEARTBEAT_MS = 5_000;
|
|
15
18
|
const SYNC_WAKE_KEYS = new Set(["v", "type", "vault", "head", "rootId"]);
|
|
@@ -57,6 +60,13 @@ function readVaultSequences(raw) {
|
|
|
57
60
|
}
|
|
58
61
|
return vaults;
|
|
59
62
|
}
|
|
63
|
+
const OWNER_SEEN_EVENT_LIMIT = 500;
|
|
64
|
+
/**
|
|
65
|
+
* Owner DM subscribe retries per connection. The owner signal is best-effort:
|
|
66
|
+
* after this many failures it stays off until the next broker reconnect, and
|
|
67
|
+
* the work topic keeps running.
|
|
68
|
+
*/
|
|
69
|
+
export const OWNER_SUBSCRIBE_MAX_RETRIES = 6;
|
|
60
70
|
function readWakeSequence(meshRoot, basename, label, onInfo) {
|
|
61
71
|
const target = path.join(meshRoot, basename);
|
|
62
72
|
try {
|
|
@@ -163,6 +173,39 @@ export async function startWorkCacheSubscriber(opts) {
|
|
|
163
173
|
let syncWakeSequence = syncWakeState.sequence;
|
|
164
174
|
const syncWakeVaults = { ...syncWakeState.vaults };
|
|
165
175
|
const syncStateWritable = syncWakeState.writable;
|
|
176
|
+
let ownerSubscribed = false;
|
|
177
|
+
let ownerUid;
|
|
178
|
+
// Carry the owner counter forward across restarts. The file holds counts
|
|
179
|
+
// and timestamps only.
|
|
180
|
+
const priorOwnerState = readOwnerInboxPushState(opts.meshRoot, opts.onInfo);
|
|
181
|
+
let ownerKnown = priorOwnerState !== null;
|
|
182
|
+
let ownerState = {
|
|
183
|
+
connected: false,
|
|
184
|
+
heartbeatAtMs: priorOwnerState?.heartbeatAtMs ?? 0,
|
|
185
|
+
count: priorOwnerState?.count ?? 0,
|
|
186
|
+
...(priorOwnerState?.lastAt ? { lastAt: priorOwnerState.lastAt } : {}),
|
|
187
|
+
...(priorOwnerState?.lastType ? { lastType: priorOwnerState.lastType } : {}),
|
|
188
|
+
};
|
|
189
|
+
const seenOwnerEventIds = new Set();
|
|
190
|
+
let ownerRetryTimer = null;
|
|
191
|
+
let ownerRetryAttempt = 0;
|
|
192
|
+
// Each distinct owner subscribe failure is logged once per daemon lifetime.
|
|
193
|
+
const ownerFailuresLogged = new Set();
|
|
194
|
+
let ownerGiveUpLogged = false;
|
|
195
|
+
const clearOwnerRetry = () => {
|
|
196
|
+
if (ownerRetryTimer !== null)
|
|
197
|
+
timers.clearTimeout(ownerRetryTimer);
|
|
198
|
+
ownerRetryTimer = null;
|
|
199
|
+
};
|
|
200
|
+
const reportOwnerSubscribeFailure = (err) => {
|
|
201
|
+
// Log the error name only; the message can carry the topic and its uid.
|
|
202
|
+
const key = `${err.name}:${err.message}`;
|
|
203
|
+
if (ownerFailuresLogged.has(key))
|
|
204
|
+
return;
|
|
205
|
+
ownerFailuresLogged.add(key);
|
|
206
|
+
opts.onInfo?.(`owner inbox push subscribe failed (${err.name}); retrying with backoff, ` +
|
|
207
|
+
`up to ${OWNER_SUBSCRIBE_MAX_RETRIES} times per connection`);
|
|
208
|
+
};
|
|
166
209
|
const clearInboxHeartbeat = () => {
|
|
167
210
|
if (heartbeatTimer !== null)
|
|
168
211
|
timers.clearTimeout(heartbeatTimer);
|
|
@@ -199,30 +242,79 @@ export async function startWorkCacheSubscriber(opts) {
|
|
|
199
242
|
const persistSyncState = (connected, durable = true) => syncStateWritable
|
|
200
243
|
? persistState(SYNC_WAKE_STATE_BASENAME, "sync wake", connected, syncWakeSequence, undefined, durable, syncWakeVaults)
|
|
201
244
|
: undefined;
|
|
245
|
+
const persistOwnerState = (connected) => {
|
|
246
|
+
if (!ownerKnown)
|
|
247
|
+
return;
|
|
248
|
+
ownerState = {
|
|
249
|
+
...ownerState,
|
|
250
|
+
connected,
|
|
251
|
+
heartbeatAtMs: now().getTime(),
|
|
252
|
+
};
|
|
253
|
+
if (connected && ownerUid)
|
|
254
|
+
ownerState.principalUid = ownerUid;
|
|
255
|
+
else
|
|
256
|
+
delete ownerState.principalUid;
|
|
257
|
+
try {
|
|
258
|
+
writeOwnerInboxPushState(opts.meshRoot, ownerState);
|
|
259
|
+
}
|
|
260
|
+
catch (error) {
|
|
261
|
+
const name = error instanceof Error ? error.name : "UnknownError";
|
|
262
|
+
opts.onInfo?.(`owner inbox push state write failed (${name})`);
|
|
263
|
+
}
|
|
264
|
+
};
|
|
202
265
|
const scheduleInboxHeartbeat = () => {
|
|
203
|
-
if (stopped || (!inboxSubscribed && !syncSubscribed))
|
|
266
|
+
if (stopped || (!inboxSubscribed && !syncSubscribed && !ownerSubscribed))
|
|
204
267
|
return;
|
|
205
268
|
clearInboxHeartbeat();
|
|
206
269
|
heartbeatTimer = timers.setTimeout(() => {
|
|
207
270
|
heartbeatTimer = null;
|
|
208
|
-
if (!stopped && (inboxSubscribed || syncSubscribed)) {
|
|
271
|
+
if (!stopped && (inboxSubscribed || syncSubscribed || ownerSubscribed)) {
|
|
209
272
|
if (inboxSubscribed)
|
|
210
273
|
persistInboxState(true, false);
|
|
211
274
|
if (syncSubscribed)
|
|
212
275
|
persistSyncState(true, false);
|
|
276
|
+
if (ownerSubscribed)
|
|
277
|
+
persistOwnerState(true);
|
|
213
278
|
scheduleInboxHeartbeat();
|
|
214
279
|
}
|
|
215
280
|
}, INBOX_PUSH_HEARTBEAT_MS);
|
|
216
281
|
};
|
|
282
|
+
const bumpOwnerCount = (type) => {
|
|
283
|
+
ownerState = {
|
|
284
|
+
...ownerState,
|
|
285
|
+
count: ownerState.count + 1,
|
|
286
|
+
lastAt: now().toISOString(),
|
|
287
|
+
lastType: type,
|
|
288
|
+
};
|
|
289
|
+
persistOwnerState(true);
|
|
290
|
+
};
|
|
291
|
+
const rememberOwnerEvent = (eventId) => {
|
|
292
|
+
if (!eventId)
|
|
293
|
+
return true;
|
|
294
|
+
if (seenOwnerEventIds.has(eventId))
|
|
295
|
+
return false;
|
|
296
|
+
seenOwnerEventIds.add(eventId);
|
|
297
|
+
if (seenOwnerEventIds.size > OWNER_SEEN_EVENT_LIMIT) {
|
|
298
|
+
const oldest = seenOwnerEventIds.values().next().value;
|
|
299
|
+
if (oldest !== undefined)
|
|
300
|
+
seenOwnerEventIds.delete(oldest);
|
|
301
|
+
}
|
|
302
|
+
return true;
|
|
303
|
+
};
|
|
217
304
|
const connect = async () => {
|
|
218
305
|
if (stopped)
|
|
219
306
|
return;
|
|
220
307
|
inboxSubscribed = false;
|
|
221
308
|
syncSubscribed = false;
|
|
222
309
|
actorUid = undefined;
|
|
310
|
+
ownerSubscribed = false;
|
|
311
|
+
ownerUid = undefined;
|
|
312
|
+
ownerRetryAttempt = 0;
|
|
313
|
+
clearOwnerRetry();
|
|
223
314
|
clearInboxHeartbeat();
|
|
224
315
|
persistInboxState(false);
|
|
225
316
|
persistSyncState(false);
|
|
317
|
+
persistOwnerState(false);
|
|
226
318
|
const gen = ++generation;
|
|
227
319
|
let bundle;
|
|
228
320
|
try {
|
|
@@ -241,7 +333,25 @@ export async function startWorkCacheSubscriber(opts) {
|
|
|
241
333
|
: undefined;
|
|
242
334
|
const syncTopic = syncStateWritable ? `hq/${bundle.actorUid}/sync` : undefined;
|
|
243
335
|
actorUid = inboxTopic || syncTopic ? bundle.actorUid : undefined;
|
|
244
|
-
|
|
336
|
+
const ownerTopic = bundle.actorUid.startsWith("prs_") &&
|
|
337
|
+
bundle.topics.dm === `hq/${bundle.actorUid}/dm`
|
|
338
|
+
? bundle.topics.dm
|
|
339
|
+
: undefined;
|
|
340
|
+
const ownerActorUid = ownerTopic ? bundle.actorUid : undefined;
|
|
341
|
+
ownerUid = ownerActorUid;
|
|
342
|
+
if (!ownerTopic && ownerKnown) {
|
|
343
|
+
// Not a person account (or no owner DM topic): drop a file left by an
|
|
344
|
+
// earlier person login so push-status reports off rather than stale.
|
|
345
|
+
try {
|
|
346
|
+
clearOwnerInboxPushState(opts.meshRoot);
|
|
347
|
+
ownerKnown = false;
|
|
348
|
+
}
|
|
349
|
+
catch (error) {
|
|
350
|
+
const name = error instanceof Error ? error.name : "UnknownError";
|
|
351
|
+
opts.onInfo?.(`owner inbox push state clear failed (${name})`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
if (!topic && !inboxTopic && !syncTopic && !ownerTopic) {
|
|
245
355
|
opts.onInfo?.("work cache subscribe skipped: credentials have no supported topic");
|
|
246
356
|
return;
|
|
247
357
|
}
|
|
@@ -257,6 +367,8 @@ export async function startWorkCacheSubscriber(opts) {
|
|
|
257
367
|
if (stopped || gen !== generation)
|
|
258
368
|
return;
|
|
259
369
|
reconnectLogged = false;
|
|
370
|
+
// The owner DM topic is best-effort and is not counted here: its failure
|
|
371
|
+
// retries on its own and never ends the connection.
|
|
260
372
|
let pendingSubscriptions = Number(Boolean(topic)) + Number(Boolean(inboxTopic)) +
|
|
261
373
|
Number(Boolean(syncTopic));
|
|
262
374
|
let subscriptionFailed = false;
|
|
@@ -282,6 +394,46 @@ export async function startWorkCacheSubscriber(opts) {
|
|
|
282
394
|
if (pendingSubscriptions === 0)
|
|
283
395
|
attempt = 0;
|
|
284
396
|
};
|
|
397
|
+
if (pendingSubscriptions === 0)
|
|
398
|
+
attempt = 0;
|
|
399
|
+
const subscribeOwner = () => {
|
|
400
|
+
if (!ownerTopic)
|
|
401
|
+
return;
|
|
402
|
+
next.subscribe(ownerTopic, { qos: 1 }, (err) => {
|
|
403
|
+
if (stopped || gen !== generation)
|
|
404
|
+
return;
|
|
405
|
+
if (err) {
|
|
406
|
+
ownerSubscribed = false;
|
|
407
|
+
ownerUid = undefined;
|
|
408
|
+
persistOwnerState(false);
|
|
409
|
+
reportOwnerSubscribeFailure(err);
|
|
410
|
+
if (ownerRetryAttempt >= OWNER_SUBSCRIBE_MAX_RETRIES) {
|
|
411
|
+
if (!ownerGiveUpLogged) {
|
|
412
|
+
ownerGiveUpLogged = true;
|
|
413
|
+
opts.onInfo?.(`owner inbox push subscribe gave up after ${OWNER_SUBSCRIBE_MAX_RETRIES} retries; ` +
|
|
414
|
+
"owner push stays off until the next reconnect");
|
|
415
|
+
}
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
const delay = backoffDelayMs(ownerRetryAttempt, 1000, 60_000, random, 0, RECONNECT_MIN_DELAY_MS);
|
|
419
|
+
ownerRetryAttempt += 1;
|
|
420
|
+
clearOwnerRetry();
|
|
421
|
+
ownerRetryTimer = timers.setTimeout(() => {
|
|
422
|
+
ownerRetryTimer = null;
|
|
423
|
+
if (stopped || gen !== generation)
|
|
424
|
+
return;
|
|
425
|
+
subscribeOwner();
|
|
426
|
+
}, delay);
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
ownerRetryAttempt = 0;
|
|
430
|
+
ownerSubscribed = true;
|
|
431
|
+
ownerKnown = true;
|
|
432
|
+
ownerUid = ownerActorUid;
|
|
433
|
+
persistOwnerState(true);
|
|
434
|
+
scheduleInboxHeartbeat();
|
|
435
|
+
});
|
|
436
|
+
};
|
|
285
437
|
if (topic) {
|
|
286
438
|
next.subscribe(topic, { qos: 1 }, (err) => finishSubscription(err));
|
|
287
439
|
}
|
|
@@ -320,6 +472,7 @@ export async function startWorkCacheSubscriber(opts) {
|
|
|
320
472
|
finishSubscription();
|
|
321
473
|
});
|
|
322
474
|
}
|
|
475
|
+
subscribeOwner();
|
|
323
476
|
});
|
|
324
477
|
next.on("message", (_topic, payload) => {
|
|
325
478
|
if (stopped || gen !== generation)
|
|
@@ -344,6 +497,48 @@ export async function startWorkCacheSubscriber(opts) {
|
|
|
344
497
|
persistSyncState(true);
|
|
345
498
|
return;
|
|
346
499
|
}
|
|
500
|
+
if (ownerTopic && _topic === ownerTopic) {
|
|
501
|
+
if (!ownerSubscribed)
|
|
502
|
+
return;
|
|
503
|
+
// Read only type, channelId and eventId. Message text, poster name
|
|
504
|
+
// and email are never stored, logged or forwarded.
|
|
505
|
+
const doorbell = parseOwnerDoorbell(payload);
|
|
506
|
+
if (!doorbell)
|
|
507
|
+
return;
|
|
508
|
+
if (doorbell.channelId) {
|
|
509
|
+
const scope = opts.ownerChannelScope;
|
|
510
|
+
if (!scope)
|
|
511
|
+
return;
|
|
512
|
+
if (doorbell.eventId && seenOwnerEventIds.has(doorbell.eventId))
|
|
513
|
+
return;
|
|
514
|
+
const channelId = doorbell.channelId;
|
|
515
|
+
void scope
|
|
516
|
+
.isInScope(channelId)
|
|
517
|
+
.catch((error) => {
|
|
518
|
+
const name = error instanceof Error ? error.name : "UnknownError";
|
|
519
|
+
opts.onInfo?.(`owner channel scope check failed (${name})`);
|
|
520
|
+
return false;
|
|
521
|
+
})
|
|
522
|
+
.then((inScope) => {
|
|
523
|
+
if (!inScope || stopped || gen !== generation || !ownerSubscribed)
|
|
524
|
+
return;
|
|
525
|
+
// Record the event only once it counts, so a redelivery after a
|
|
526
|
+
// failed or out-of-scope check is evaluated again.
|
|
527
|
+
if (!rememberOwnerEvent(doorbell.eventId))
|
|
528
|
+
return;
|
|
529
|
+
bumpOwnerCount(doorbell.type);
|
|
530
|
+
});
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
// A channel event must name its channel; without one its company is
|
|
534
|
+
// unknown, so it is dropped.
|
|
535
|
+
if (doorbell.type === "channel")
|
|
536
|
+
return;
|
|
537
|
+
if (!rememberOwnerEvent(doorbell.eventId))
|
|
538
|
+
return;
|
|
539
|
+
bumpOwnerCount(doorbell.type);
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
347
542
|
if (_topic !== topic)
|
|
348
543
|
return;
|
|
349
544
|
const push = parseProjectViewPush(payload);
|
|
@@ -360,9 +555,13 @@ export async function startWorkCacheSubscriber(opts) {
|
|
|
360
555
|
inboxSubscribed = false;
|
|
361
556
|
syncSubscribed = false;
|
|
362
557
|
actorUid = undefined;
|
|
558
|
+
ownerSubscribed = false;
|
|
559
|
+
ownerUid = undefined;
|
|
560
|
+
clearOwnerRetry();
|
|
363
561
|
clearInboxHeartbeat();
|
|
364
562
|
persistInboxState(false);
|
|
365
563
|
persistSyncState(false);
|
|
564
|
+
persistOwnerState(false);
|
|
366
565
|
opts.onInfo?.("work cache mqtt error");
|
|
367
566
|
schedule();
|
|
368
567
|
try {
|
|
@@ -378,9 +577,13 @@ export async function startWorkCacheSubscriber(opts) {
|
|
|
378
577
|
inboxSubscribed = false;
|
|
379
578
|
syncSubscribed = false;
|
|
380
579
|
actorUid = undefined;
|
|
580
|
+
ownerSubscribed = false;
|
|
581
|
+
ownerUid = undefined;
|
|
582
|
+
clearOwnerRetry();
|
|
381
583
|
clearInboxHeartbeat();
|
|
382
584
|
persistInboxState(false);
|
|
383
585
|
persistSyncState(false);
|
|
586
|
+
persistOwnerState(false);
|
|
384
587
|
schedule();
|
|
385
588
|
});
|
|
386
589
|
};
|
|
@@ -408,12 +611,16 @@ export async function startWorkCacheSubscriber(opts) {
|
|
|
408
611
|
generation += 1;
|
|
409
612
|
if (timer !== null)
|
|
410
613
|
timers.clearTimeout(timer);
|
|
614
|
+
clearOwnerRetry();
|
|
411
615
|
clearInboxHeartbeat();
|
|
412
616
|
inboxSubscribed = false;
|
|
413
617
|
syncSubscribed = false;
|
|
414
618
|
actorUid = undefined;
|
|
619
|
+
ownerSubscribed = false;
|
|
620
|
+
ownerUid = undefined;
|
|
415
621
|
persistInboxState(false);
|
|
416
622
|
persistSyncState(false);
|
|
623
|
+
persistOwnerState(false);
|
|
417
624
|
const current = client;
|
|
418
625
|
client = null;
|
|
419
626
|
if (!current)
|