@indigoai-us/hq-cli 5.345.232 → 5.345.233

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.
@@ -1 +1 @@
1
- {"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.112","bundleSha256":"8c9e1034d6fc5a89949c510ab5283c7e965e3c645e4c7e00695b10e299cb6837","formatVersion":1}
1
+ {"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.114","bundleSha256":"48442336bfcf5bf30f4bd9b6af8723cbc7cf72a6adc546aaebce2e1197917e15","formatVersion":1}
package/dist/index.js CHANGED
@@ -396,7 +396,12 @@ function dispatchCliCommand(versionRequest, helpRequest, parsedFastCore, monitor
396
396
  }
397
397
  else if (mcpRequest) {
398
398
  // Keep the minimal startup route; runMcpServe applies the hq-flags gate.
399
- void import("./commands/mcp-serve.js").then(({ runMcpServe }) => runMcpServe());
399
+ // Without a person token cache the server is denied before mcp-serve.js
400
+ // and its hqd protocol, lease and preload imports load; same message and
401
+ // exit code as runMcpServe gives.
402
+ void import("./commands/mcp-serve-gate.js").then(({ denyMcpServeWithoutTokenCache }) => denyMcpServeWithoutTokenCache()
403
+ ? undefined
404
+ : import("./commands/mcp-serve.js").then(({ runMcpServe }) => runMcpServe()));
400
405
  }
401
406
  else if (parsedFastCore) {
402
407
  // Hot relocated plumbing (`hq core hq-session`, `hq core checkpoint-stop-gate`)
@@ -62,6 +62,8 @@ export interface DaemonFlagRegistryRead {
62
62
  /** Every failure the request reported, first one first. Empty means the snapshot loaded. */
63
63
  errors: unknown[];
64
64
  client?: DaemonFlagClient;
65
+ /** The token the request was made with, so an observer can make the same caller's person-scoped request. Never logged. */
66
+ token?: string;
65
67
  }
66
68
  export interface DaemonFlagSnapshotSource {
67
69
  /** One refresh timer for every monitor on this source, so their reads land on the same tick. */
@@ -46,15 +46,17 @@ function closeQuietly(client) {
46
46
  async function loadDaemonFlagRegistry(env, options) {
47
47
  const errors = [];
48
48
  let client;
49
+ let token;
49
50
  try {
50
51
  const company = resolveProcessFlagCompanyContext(env);
51
52
  // Signed out reads as the flag fallback without reaching the registry.
52
- const token = await (options.getToken ?? (() => ensureCognitoIdToken({ interactive: false })))();
53
- if (typeof token !== "string" || token.trim() === "")
53
+ const idToken = await (options.getToken ?? (() => ensureCognitoIdToken({ interactive: false })))();
54
+ if (typeof idToken !== "string" || idToken.trim() === "")
54
55
  return { signedOut: true, errors };
56
+ token = idToken;
55
57
  client = (options.createClient ?? createFlagClient)({
56
58
  endpoint: resolveFlagRegistryEndpoint(undefined, env),
57
- getToken: () => token,
59
+ getToken: () => idToken,
58
60
  env: {},
59
61
  refreshIntervalMs: 0,
60
62
  requestTimeoutMs: READ_TIMEOUT_MS,
@@ -73,7 +75,7 @@ async function loadDaemonFlagRegistry(env, options) {
73
75
  if (errors.length === 0)
74
76
  errors.push(error);
75
77
  }
76
- return { signedOut: false, errors, ...(client ? { client } : {}) };
78
+ return { signedOut: false, errors, ...(client ? { client } : {}), ...(token ? { token } : {}) };
77
79
  }
78
80
  /**
79
81
  * Share registry requests between the daemon's timed flag reads.
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The daemon's one flag poller (hq-core-rust US-009 c1, US-036 c2).
3
+ *
4
+ * Every timed flag read in the daemon shares one DaemonFlagSnapshotSource
5
+ * (flag.ts): the four kill switches, the hqd HQ Anywhere runtime gate and the
6
+ * state file writer. The hqd listener's `isEnabled` used to make a second
7
+ * registry request of its own on every listener event and on its fallback
8
+ * timer, through the flag-registry worker, only so that the on-disk flag
9
+ * snapshot it reads afterwards was fresh.
10
+ *
11
+ * Here the shared request writes that snapshot itself, for the daemon's own
12
+ * scope, the way the worker does: a company uid writes that company's
13
+ * snapshot, no company context writes the person snapshot, and a slug that
14
+ * resolves to no uid writes nothing. The listener then reads the snapshot
15
+ * without any request of its own (hqdListenerFlagGate), so the daemon makes
16
+ * one registry request per refresh interval for every flag reader.
17
+ *
18
+ * As the worker did, an agent token with a company context also refreshes the
19
+ * agent's person snapshot from one more request without company selectors
20
+ * (the service maps that caller to personUid=agentUid), and a failed snapshot
21
+ * write is reported to Sentry with the worker's event tags
22
+ * (component flag-snapshot-cache-write).
23
+ *
24
+ * Nothing here can turn a flag on. A signed-out or failed read writes nothing,
25
+ * so the snapshot keeps the last answer the registry gave, exactly as it did
26
+ * when the worker's refresh failed.
27
+ */
28
+ import { type FlagClientOptions, type FlagSnapshot } from "@indigoai-us/hq-flags-client";
29
+ import { type DaemonFlagClient, type DaemonFlagRegistryRead, type DaemonFlagSnapshotSource, type DaemonFlagSnapshotSourceOptions } from "./flag.js";
30
+ export type SharedFlagSnapshotWrite = "company" | "person" | "skipped";
31
+ /** Receives a failed snapshot write with the flag-registry worker's Sentry tags. */
32
+ export type FlagSnapshotWriteReporter = (error: Error, tags: Record<string, string>) => void;
33
+ export interface WriteSharedFlagSnapshotOptions {
34
+ writeCompany?: (companyUid: string, flags: FlagSnapshot["flags"], options: {
35
+ env: NodeJS.ProcessEnv;
36
+ }) => unknown;
37
+ writePerson?: (flags: FlagSnapshot["flags"], options: {
38
+ env: NodeJS.ProcessEnv;
39
+ }) => unknown;
40
+ /** Defaults to the CLI's Sentry captureException, as flag-registry.ts reports the same failure. */
41
+ report?: FlagSnapshotWriteReporter;
42
+ /** The agent person request, for tests. Defaults to the registry client. */
43
+ createClient?: (options: FlagClientOptions) => DaemonFlagClient;
44
+ }
45
+ /** Write the on-disk flag snapshot from one shared registry read. Never throws. */
46
+ export declare function writeSharedFlagSnapshotFile(read: DaemonFlagRegistryRead, env: NodeJS.ProcessEnv, options?: WriteSharedFlagSnapshotOptions): SharedFlagSnapshotWrite;
47
+ /**
48
+ * The worker's agent person refresh: when a loaded shared read was made for a
49
+ * company context with an agent token, resolve again without company selectors
50
+ * and write the result as the person snapshot. Company-scoped answers are never
51
+ * relabelled as person answers. A failed person request writes nothing. Never
52
+ * rejects.
53
+ */
54
+ export declare function refreshAgentPersonFlagSnapshot(read: DaemonFlagRegistryRead, env: NodeJS.ProcessEnv, options?: WriteSharedFlagSnapshotOptions): Promise<"person" | "skipped">;
55
+ export interface DaemonSharedFlagReadsOptions extends Omit<DaemonFlagSnapshotSourceOptions, "onRead"> {
56
+ /** Told about every shared read after the snapshot file is written, in order. One that throws does not stop the rest. */
57
+ observers?: ReadonlyArray<(read: DaemonFlagRegistryRead, env: NodeJS.ProcessEnv) => void>;
58
+ snapshotFile?: WriteSharedFlagSnapshotOptions;
59
+ }
60
+ /** The daemon's one flag source: the shared read, which also keeps the on-disk flag snapshot fresh. */
61
+ export declare function createDaemonSharedFlagReads(options?: DaemonSharedFlagReadsOptions): DaemonFlagSnapshotSource;
62
+ /**
63
+ * The flag half of the hqd listener's `isEnabled`, for anywhereRuntimeAllowed:
64
+ * the HQ Anywhere flag as the shared read last wrote it to the snapshot. It
65
+ * has no `refreshFlag`, so a listener check makes no registry request.
66
+ */
67
+ export declare function hqdListenerFlagGate(): {
68
+ readFlag: (env: NodeJS.ProcessEnv) => boolean;
69
+ };
70
+ //# sourceMappingURL=shared-flag-reads.d.ts.map
@@ -0,0 +1,173 @@
1
+ /**
2
+ * The daemon's one flag poller (hq-core-rust US-009 c1, US-036 c2).
3
+ *
4
+ * Every timed flag read in the daemon shares one DaemonFlagSnapshotSource
5
+ * (flag.ts): the four kill switches, the hqd HQ Anywhere runtime gate and the
6
+ * state file writer. The hqd listener's `isEnabled` used to make a second
7
+ * registry request of its own on every listener event and on its fallback
8
+ * timer, through the flag-registry worker, only so that the on-disk flag
9
+ * snapshot it reads afterwards was fresh.
10
+ *
11
+ * Here the shared request writes that snapshot itself, for the daemon's own
12
+ * scope, the way the worker does: a company uid writes that company's
13
+ * snapshot, no company context writes the person snapshot, and a slug that
14
+ * resolves to no uid writes nothing. The listener then reads the snapshot
15
+ * without any request of its own (hqdListenerFlagGate), so the daemon makes
16
+ * one registry request per refresh interval for every flag reader.
17
+ *
18
+ * As the worker did, an agent token with a company context also refreshes the
19
+ * agent's person snapshot from one more request without company selectors
20
+ * (the service maps that caller to personUid=agentUid), and a failed snapshot
21
+ * write is reported to Sentry with the worker's event tags
22
+ * (component flag-snapshot-cache-write).
23
+ *
24
+ * Nothing here can turn a flag on. A signed-out or failed read writes nothing,
25
+ * so the snapshot keeps the last answer the registry gave, exactly as it did
26
+ * when the worker's refresh failed.
27
+ */
28
+ import { createFlagClient } from "@indigoai-us/hq-flags-client";
29
+ import { anywhereRuntimeEnabledFromSnapshot } from "../anywhere-runtime-fast-flag.js";
30
+ import { resolveFlagRegistryEndpoint } from "../flag-registry-endpoint.js";
31
+ import { flagSnapshotWriteFailureTags, writeFlagSnapshotFile, writePersonFlagSnapshotFile, } from "../flag-snapshot-file.js";
32
+ import { resolveProcessFlagCompanyContext } from "../process-flag-company-context.js";
33
+ import { createDaemonFlagSnapshotSource, } from "./flag.js";
34
+ import { decodeJwtClaims } from "./machine-token-identity.js";
35
+ const PERSON_READ_TIMEOUT_MS = 5_000;
36
+ const AGENT_UID_RE = /^agt_[A-Za-z0-9]+$/;
37
+ /** The flag-registry worker's Sentry event for a failed snapshot write. Loaded lazily, as run.ts loads Sentry. */
38
+ function reportToSentry(error, tags) {
39
+ void import("../../sentry.js").then(({ Sentry }) => { Sentry.captureException(error, { tags }); }, () => { });
40
+ }
41
+ function reportWriteFailure(error, companyUidPresent, report) {
42
+ try {
43
+ let tags;
44
+ try {
45
+ tags = flagSnapshotWriteFailureTags(error);
46
+ }
47
+ catch {
48
+ tags = {};
49
+ }
50
+ (report ?? reportToSentry)(error instanceof Error ? error : new Error(String(error)), {
51
+ component: "flag-snapshot-cache-write",
52
+ company_uid_present: companyUidPresent ? "true" : "false",
53
+ ...tags,
54
+ });
55
+ }
56
+ catch {
57
+ // a reporter cannot reach the flag read
58
+ }
59
+ }
60
+ function loadedSnapshot(read) {
61
+ if (read.signedOut || read.errors.length > 0 || !read.client)
62
+ return null;
63
+ return read.client.snapshot?.() ?? null;
64
+ }
65
+ /** Write the on-disk flag snapshot from one shared registry read. Never throws. */
66
+ export function writeSharedFlagSnapshotFile(read, env, options = {}) {
67
+ let companyUidPresent = false;
68
+ try {
69
+ const snapshot = loadedSnapshot(read);
70
+ if (!snapshot)
71
+ return "skipped";
72
+ const company = resolveProcessFlagCompanyContext(env);
73
+ if (company.companyUid) {
74
+ companyUidPresent = true;
75
+ (options.writeCompany ?? writeFlagSnapshotFile)(company.companyUid, snapshot.flags, { env });
76
+ return "company";
77
+ }
78
+ if (company.companySlug)
79
+ return "skipped";
80
+ (options.writePerson ?? writePersonFlagSnapshotFile)(snapshot.flags, { env });
81
+ return "person";
82
+ }
83
+ catch (error) {
84
+ reportWriteFailure(error, companyUidPresent, options.report);
85
+ return "skipped";
86
+ }
87
+ }
88
+ /**
89
+ * The worker's agent person refresh: when a loaded shared read was made for a
90
+ * company context with an agent token, resolve again without company selectors
91
+ * and write the result as the person snapshot. Company-scoped answers are never
92
+ * relabelled as person answers. A failed person request writes nothing. Never
93
+ * rejects.
94
+ */
95
+ export async function refreshAgentPersonFlagSnapshot(read, env, options = {}) {
96
+ let personClient;
97
+ try {
98
+ if (!loadedSnapshot(read))
99
+ return "skipped";
100
+ const token = read.token;
101
+ if (typeof token !== "string" || token.trim() === "")
102
+ return "skipped";
103
+ const company = resolveProcessFlagCompanyContext(env);
104
+ if (!company.companyUid && !company.companySlug)
105
+ return "skipped";
106
+ // The claims of the token the request was made with; the service authenticates it again.
107
+ const claims = decodeJwtClaims(token);
108
+ const agentUid = claims?.["custom:entityUid"];
109
+ if (claims?.["custom:entityType"] !== "agent" || typeof agentUid !== "string" || !AGENT_UID_RE.test(agentUid)) {
110
+ return "skipped";
111
+ }
112
+ personClient = (options.createClient ?? createFlagClient)({
113
+ endpoint: resolveFlagRegistryEndpoint(undefined, env),
114
+ getToken: () => token,
115
+ env: {},
116
+ refreshIntervalMs: 0,
117
+ requestTimeoutMs: PERSON_READ_TIMEOUT_MS,
118
+ onError: () => { },
119
+ });
120
+ await personClient.ready();
121
+ const personSnapshot = personClient.snapshot?.() ?? null;
122
+ if (!personSnapshot)
123
+ return "skipped";
124
+ try {
125
+ (options.writePerson ?? writePersonFlagSnapshotFile)(personSnapshot.flags, { env });
126
+ }
127
+ catch (error) {
128
+ reportWriteFailure(error, false, options.report);
129
+ return "skipped";
130
+ }
131
+ return "person";
132
+ }
133
+ catch {
134
+ // The company snapshot stands when person scope is offline, as in the worker.
135
+ return "skipped";
136
+ }
137
+ finally {
138
+ try {
139
+ personClient?.close();
140
+ }
141
+ catch {
142
+ // same isolated failure boundary
143
+ }
144
+ }
145
+ }
146
+ /** The daemon's one flag source: the shared read, which also keeps the on-disk flag snapshot fresh. */
147
+ export function createDaemonSharedFlagReads(options = {}) {
148
+ const { observers = [], snapshotFile, ...sourceOptions } = options;
149
+ return createDaemonFlagSnapshotSource({
150
+ ...sourceOptions,
151
+ onRead: (read, env) => {
152
+ writeSharedFlagSnapshotFile(read, env, snapshotFile);
153
+ void refreshAgentPersonFlagSnapshot(read, env, snapshotFile);
154
+ for (const observe of observers) {
155
+ try {
156
+ observe(read, env);
157
+ }
158
+ catch {
159
+ // one observer cannot stop the others
160
+ }
161
+ }
162
+ },
163
+ });
164
+ }
165
+ /**
166
+ * The flag half of the hqd listener's `isEnabled`, for anywhereRuntimeAllowed:
167
+ * the HQ Anywhere flag as the shared read last wrote it to the snapshot. It
168
+ * has no `refreshFlag`, so a listener check makes no registry request.
169
+ */
170
+ export function hqdListenerFlagGate() {
171
+ return { readFlag: anywhereRuntimeEnabledFromSnapshot };
172
+ }
173
+ //# sourceMappingURL=shared-flag-reads.js.map