@indigoai-us/hq-cli 5.345.238 → 5.345.242

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 (206) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-grant.sh +170 -8
  3. package/assets/scaffold/core/scripts/hq-delegate-publish.sh +21 -1
  4. package/assets/scaffold/core/scripts/hq-delegate-repo.sh +7 -1
  5. package/assets/scaffold/core/scripts/hq-delegate-secrets.sh +95 -20
  6. package/assets/scaffold/core/scripts/hq-delegate-transfer.sh +57 -9
  7. package/assets/scaffold/core/scripts/lib/delegate-engine.sh +77 -0
  8. package/dist/command-catalog.generated.d.ts +212 -10
  9. package/dist/command-catalog.generated.js +260 -10
  10. package/dist/command-registration-plan.d.ts +6 -0
  11. package/dist/command-registration-plan.js +1 -0
  12. package/dist/commands/cloud-off-gate.d.ts +9 -8
  13. package/dist/commands/cloud-off-gate.js +41 -40
  14. package/dist/commands/cloud.d.ts +17 -2
  15. package/dist/commands/cloud.js +126 -24
  16. package/dist/commands/core-delegate-w1b.js +333 -27
  17. package/dist/commands/core-delegate.d.ts +2 -1
  18. package/dist/commands/core-delegate.js +209 -48
  19. package/dist/commands/core-handoff.js +1 -1
  20. package/dist/commands/core-job-model-auth.d.ts +95 -0
  21. package/dist/commands/core-job-model-auth.js +247 -0
  22. package/dist/commands/core-job-run-native.js +280 -12
  23. package/dist/commands/core.js +1 -0
  24. package/dist/commands/deploy-comments.js +8 -2
  25. package/dist/commands/deploy-events.d.ts +40 -0
  26. package/dist/commands/deploy-events.js +300 -0
  27. package/dist/commands/doctor.d.ts +4 -4
  28. package/dist/commands/doctor.js +2 -2
  29. package/dist/commands/feedback.js +2 -3
  30. package/dist/commands/files-browse.js +2 -0
  31. package/dist/commands/files.js +4 -0
  32. package/dist/commands/integrations-core.d.ts +11 -0
  33. package/dist/commands/integrations-core.js +15 -1
  34. package/dist/commands/keyed-sync-pull.d.ts +12 -0
  35. package/dist/commands/keyed-sync-pull.js +151 -0
  36. package/dist/commands/lanes-link.js +2 -2
  37. package/dist/commands/lanes-loop.d.ts +2 -2
  38. package/dist/commands/lanes-loop.js +5 -5
  39. package/dist/commands/lanes-questions.js +1 -1
  40. package/dist/commands/lanes-stories.js +1 -1
  41. package/dist/commands/lanes.js +80 -14
  42. package/dist/commands/library-add.d.ts +5 -2
  43. package/dist/commands/library-add.js +22 -9
  44. package/dist/commands/mcp-registration.d.ts +4 -18
  45. package/dist/commands/mcp-registration.js +9 -29
  46. package/dist/commands/mesh.d.ts +4 -0
  47. package/dist/commands/mesh.js +25 -5
  48. package/dist/commands/pack-install.d.ts +2 -3
  49. package/dist/commands/pack-install.js +6 -8
  50. package/dist/commands/rescue.d.ts +3 -2
  51. package/dist/commands/rescue.js +48 -34
  52. package/dist/commands/search.d.ts +6 -0
  53. package/dist/commands/search.js +24 -4
  54. package/dist/commands/secrets.d.ts +3 -4
  55. package/dist/commands/secrets.js +3 -20
  56. package/dist/commands/sources.js +6 -2
  57. package/dist/commands/sync-core.d.ts +8 -0
  58. package/dist/commands/sync-core.js +43 -0
  59. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +1830 -1468
  60. package/dist/hq-cloud-sync-runner/package.json +1 -1
  61. package/dist/lib/bot/api.d.ts +2 -1
  62. package/dist/lib/bot/api.js +2 -15
  63. package/dist/lib/capacity/accounts.d.ts +1 -1
  64. package/dist/lib/capacity/accounts.js +1 -1
  65. package/dist/lib/capacity/collectors/claude-oauth.d.ts +0 -2
  66. package/dist/lib/capacity/collectors/claude-oauth.js +0 -5
  67. package/dist/lib/capacity/freshness.d.ts +1 -1
  68. package/dist/lib/capacity/freshness.js +1 -1
  69. package/dist/lib/capacity/route.js +1 -1
  70. package/dist/lib/core-utils/delegate-helper-paths.d.ts +26 -0
  71. package/dist/lib/core-utils/delegate-helper-paths.js +33 -0
  72. package/dist/lib/daemon/catalog.d.ts +3 -0
  73. package/dist/lib/daemon/hook-requests.d.ts +1 -1
  74. package/dist/lib/daemon/hook-requests.js +4 -2
  75. package/dist/lib/daemon/jq-provision.d.ts +63 -0
  76. package/dist/lib/daemon/jq-provision.js +155 -0
  77. package/dist/lib/daemon/lanes-reconcile-guard.d.ts +4 -3
  78. package/dist/lib/daemon/lanes-reconcile-guard.js +4 -4
  79. package/dist/lib/daemon/mesh-owner.d.ts +4 -0
  80. package/dist/lib/daemon/mesh-owner.js +20 -0
  81. package/dist/lib/daemon/ops/policy.d.ts +3 -0
  82. package/dist/lib/daemon/ops/policy.js +32 -4
  83. package/dist/lib/daemon/run.js +17 -22
  84. package/dist/lib/daemon/server.d.ts +6 -0
  85. package/dist/lib/daemon/server.js +5 -0
  86. package/dist/lib/daemon/verified-jq.d.ts +96 -0
  87. package/dist/lib/daemon/verified-jq.js +337 -0
  88. package/dist/lib/doctor/checks/jq.js +16 -0
  89. package/dist/lib/doctor/deep/executor.d.ts +7 -0
  90. package/dist/lib/doctor/deep/executor.js +1 -1
  91. package/dist/lib/doctor/deep/parity.js +1 -27
  92. package/dist/lib/doctor/deep/sandbox.d.ts +2 -2
  93. package/dist/lib/doctor/deep/sandbox.js +3 -19
  94. package/dist/lib/doctor/fix/refresh-sync-handoff.js +52 -21
  95. package/dist/lib/doctor/fixtures/discover.d.ts +2 -0
  96. package/dist/lib/doctor/fixtures/discover.js +1 -1
  97. package/dist/lib/doctor/json-output.d.ts +1 -1
  98. package/dist/lib/doctor/registry.d.ts +6 -7
  99. package/dist/lib/doctor/registry.js +6 -7
  100. package/dist/lib/doctor/report.d.ts +9 -10
  101. package/dist/lib/doctor/report.js +4 -4
  102. package/dist/lib/environment/work-requirements.d.ts +1 -1
  103. package/dist/lib/environment/work-requirements.js +1 -1
  104. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  105. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  106. package/dist/lib/hook-engine/coverage.js +11 -3
  107. package/dist/lib/hook-engine/git-stop-config.json +510 -510
  108. package/dist/lib/hook-engine/native-precompact-compatibility.json +443 -443
  109. package/dist/lib/hook-engine/native-stop-compatibility.json +359 -359
  110. package/dist/lib/hot-channels/adapters/meetings.d.ts +1 -16
  111. package/dist/lib/hot-channels/adapters/meetings.js +3 -28
  112. package/dist/lib/hot-channels/adapters/slack.d.ts +3 -1
  113. package/dist/lib/hot-channels/adapters/slack.js +4 -1
  114. package/dist/lib/hot-channels/contract.d.ts +14 -0
  115. package/dist/lib/hot-channels/fleet-complete.d.ts +18 -2
  116. package/dist/lib/hot-channels/fleet-complete.js +29 -4
  117. package/dist/lib/hot-channels/meeting-source-ref.d.ts +17 -0
  118. package/dist/lib/hot-channels/meeting-source-ref.js +32 -0
  119. package/dist/lib/hot-channels/prompts/signals-pass.md +6 -1
  120. package/dist/lib/hot-channels/run.d.ts +10 -0
  121. package/dist/lib/hot-channels/run.js +34 -0
  122. package/dist/lib/hot-channels/signals-pass.d.ts +27 -0
  123. package/dist/lib/hot-channels/signals-pass.js +57 -2
  124. package/dist/lib/hot-channels/signals-runtime.js +3 -2
  125. package/dist/lib/jq/install.d.ts +27 -0
  126. package/dist/lib/jq/install.js +156 -0
  127. package/dist/lib/lanes/accounts.js +2 -2
  128. package/dist/lib/lanes/claude-balance.d.ts +6 -0
  129. package/dist/lib/lanes/claude-balance.js +124 -0
  130. package/dist/lib/lanes/grants.js +15 -2
  131. package/dist/lib/lanes/hq-root.d.ts +1 -1
  132. package/dist/lib/lanes/hq-root.js +1 -1
  133. package/dist/lib/lanes/links.d.ts +1 -1
  134. package/dist/lib/lanes/liveness.d.ts +3 -0
  135. package/dist/lib/lanes/liveness.js +61 -7
  136. package/dist/lib/lanes/models.d.ts +1 -1
  137. package/dist/lib/lanes/models.js +1 -1
  138. package/dist/lib/lanes/outpost-dispatch.d.ts +1 -1
  139. package/dist/lib/lanes/outpost-dispatch.js +13 -13
  140. package/dist/lib/lanes/outpost-pruner-install.js +1 -1
  141. package/dist/lib/lanes/questions.d.ts +1 -1
  142. package/dist/lib/lanes/questions.js +2 -2
  143. package/dist/lib/lanes/spawn.js +4 -6
  144. package/dist/lib/lanes/store.d.ts +13 -2
  145. package/dist/lib/lanes/store.js +13 -5
  146. package/dist/lib/lanes/types.d.ts +7 -7
  147. package/dist/lib/lanes/types.js +1 -1
  148. package/dist/lib/lanes/watcher-main.js +1 -1
  149. package/dist/lib/lanes/watcher.d.ts +1 -1
  150. package/dist/lib/lanes/watcher.js +1 -1
  151. package/dist/lib/mesh/live/daemon/doctor.js +7 -1
  152. package/dist/lib/mesh/live/daemon/install.d.ts +4 -0
  153. package/dist/lib/mesh/live/daemon/install.js +10 -0
  154. package/dist/lib/mesh/live/daemon/run.js +17 -0
  155. package/dist/lib/mesh/live/emit-retry.d.ts +20 -2
  156. package/dist/lib/mesh/live/emit-retry.js +57 -4
  157. package/dist/lib/mesh/live/emit.js +25 -4
  158. package/dist/lib/mesh/live/flush.d.ts +2 -0
  159. package/dist/lib/mesh/live/flush.js +21 -8
  160. package/dist/lib/mesh/live/spool.d.ts +9 -1
  161. package/dist/lib/mesh/live/spool.js +41 -29
  162. package/dist/lib/onboarding/cli/onboard.js +5 -0
  163. package/dist/lib/signals/sanitize.d.ts +19 -0
  164. package/dist/lib/signals/sanitize.js +103 -7
  165. package/dist/lib/signals/steps/upload.d.ts +40 -1
  166. package/dist/lib/signals/steps/upload.js +122 -6
  167. package/dist/lib/sync-core/access-refresh.d.ts +29 -0
  168. package/dist/lib/sync-core/access-refresh.js +97 -0
  169. package/dist/lib/sync-core/company-adoption.d.ts +33 -0
  170. package/dist/lib/sync-core/company-adoption.js +223 -0
  171. package/dist/lib/sync-core/engine-home.d.ts +1 -0
  172. package/dist/lib/sync-core/engine-owned.d.ts +13 -0
  173. package/dist/lib/sync-core/engine-owned.js +38 -0
  174. package/dist/lib/sync-core/hand-back.d.ts +17 -0
  175. package/dist/lib/sync-core/hand-back.js +23 -0
  176. package/dist/lib/sync-core/post-apply-reindex.d.ts +33 -0
  177. package/dist/lib/sync-core/post-apply-reindex.js +149 -0
  178. package/dist/lib/sync-core/reconcile.d.ts +10 -0
  179. package/dist/lib/sync-core/reconcile.js +117 -12
  180. package/dist/lib/sync-core/rollout-state.d.ts +11 -1
  181. package/dist/lib/sync-core/rollout-state.js +40 -4
  182. package/dist/lib/vault-sync-switches.d.ts +14 -0
  183. package/dist/lib/vault-sync-switches.js +22 -0
  184. package/dist/lib/windows/jq.d.ts +4 -0
  185. package/dist/lib/windows/jq.js +10 -39
  186. package/dist/lib/workers-registry/index.d.ts +1 -1
  187. package/dist/lib/workers-registry/index.js +8 -12
  188. package/dist/utils/callback-port-busy.d.ts +2 -2
  189. package/dist/utils/callback-port-busy.js +2 -2
  190. package/dist/utils/cli-network-lifecycle.js +1 -0
  191. package/dist/utils/client-health-contract.d.ts +2 -0
  192. package/dist/utils/client-health-contract.js +1 -1
  193. package/dist/utils/client-health.js +1 -9
  194. package/dist/utils/cognito-config.js +5 -0
  195. package/dist/utils/cognito-session.d.ts +4 -6
  196. package/dist/utils/cognito-session.js +4 -24
  197. package/dist/utils/github-tag-fallback.d.ts +16 -0
  198. package/dist/utils/github-tag-fallback.js +126 -0
  199. package/dist/utils/incomplete-install-error.js +1 -11
  200. package/dist/utils/install-tree-torn.d.ts +11 -0
  201. package/dist/utils/install-tree-torn.js +1 -1
  202. package/dist/utils/resident-package-preload.js +2 -1
  203. package/dist/utils/version-report.d.ts +2 -1
  204. package/dist/utils/version-report.js +40 -27
  205. package/docs/anywhere-runtime.md +8 -0
  206. package/package.json +9 -9
@@ -0,0 +1,40 @@
1
+ import type { Command } from "commander";
2
+ /**
3
+ * Owner side of the hq-deploy site-events loop (US-033). A deployed page records
4
+ * visitor actions with POST /site-events; the owner reads them, acts on them,
5
+ * and answers with a reply the page shows. Event `data` and `actor` are visitor
6
+ * input: they are printed as JSON data and never interpreted.
7
+ */
8
+ interface ScopeOptions {
9
+ company?: string;
10
+ personal?: boolean;
11
+ }
12
+ export interface WatchOptions extends ScopeOptions {
13
+ cursorFile?: string;
14
+ label?: string;
15
+ interval?: string;
16
+ status?: string;
17
+ once?: boolean;
18
+ }
19
+ export interface WatchDeps {
20
+ sleep: (ms: number) => Promise<void>;
21
+ now: () => number;
22
+ emit: (line: string) => void;
23
+ heartbeatMs: number;
24
+ }
25
+ /** One-line JSON with terminal control and bidi characters escaped. */
26
+ export declare function jsonLine(value: unknown): string;
27
+ /**
28
+ * Poll for new events and print one JSON line per result: armed, event,
29
+ * poll_failing (first failure, then every fifth), poll_recovered,
30
+ * cursor_write_failed, heartbeat. The cursor advances only once it is on disk,
31
+ * so after a successful write a restart does not replay those events. When the
32
+ * write fails the cursor stays where it was: the next poll reports the same
33
+ * events again (at least once) together with cursor_write_failed. Each poll opens a
34
+ * fresh sign-in, so a long-running watch survives token refresh. Returns the
35
+ * exit code for --once; otherwise it runs until stopped.
36
+ */
37
+ export declare function watchSiteEvents(appId: string, options: WatchOptions, deps: WatchDeps): Promise<number>;
38
+ export declare function registerDeployEventsCommand(deploy: Command): void;
39
+ export {};
40
+ //# sourceMappingURL=deploy-events.d.ts.map
@@ -0,0 +1,300 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { deployApiRequest } from "../lib/deploy-api.js";
4
+ import { DeployIdentityError, openDeployIdentity } from "../lib/deploy-identity.js";
5
+ class SiteEventsError extends Error {
6
+ }
7
+ const APP_ID = /^(?:[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}|app_[A-Za-z0-9_-]+)$/i;
8
+ const EVENT_ID = /^evt_[0-9a-z]{9}[0-9a-f]{16}$/;
9
+ const COMPANY = /^[a-z0-9][a-z0-9-]{0,62}$/;
10
+ const MIN_INTERVAL_SECONDS = 30;
11
+ const DEFAULT_HEARTBEAT_MS = 30 * 60_000;
12
+ /** One-line JSON with terminal control and bidi characters escaped. */
13
+ export function jsonLine(value) {
14
+ return JSON.stringify(value).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/gu, (character) => `\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, "0")}`);
15
+ }
16
+ function display(value) {
17
+ return [...String(value ?? "")].map((character) => {
18
+ const code = character.codePointAt(0) ?? 0;
19
+ const unsafe = code <= 0x1f || (code >= 0x7f && code <= 0x9f)
20
+ || (code >= 0x202a && code <= 0x202e) || (code >= 0x2066 && code <= 0x2069);
21
+ return unsafe ? `\\u${code.toString(16).padStart(4, "0")}` : character;
22
+ }).join("");
23
+ }
24
+ function checkApp(appId) {
25
+ if (!APP_ID.test(appId))
26
+ throw new SiteEventsError("Use the app ID shown by hq deploy list.");
27
+ }
28
+ function checkScope(options) {
29
+ if ((options.company !== undefined) === (options.personal === true)) {
30
+ throw new SiteEventsError("Choose exactly one of --company <slug> or --personal.");
31
+ }
32
+ if (options.company !== undefined && !COMPANY.test(options.company)) {
33
+ throw new SiteEventsError("Use a valid company slug.");
34
+ }
35
+ return options.personal ? { personal: true } : { company: options.company };
36
+ }
37
+ function checkStatus(status) {
38
+ if (status !== undefined && status !== "new" && status !== "handled") {
39
+ throw new SiteEventsError("--status must be new or handled.");
40
+ }
41
+ }
42
+ function responseError(status, what) {
43
+ switch (status) {
44
+ case 403:
45
+ return new SiteEventsError(`Could not ${what} (HTTP 403). Only the app owner or an org admin can do this; check the scope.`);
46
+ case 404:
47
+ return new SiteEventsError(`Could not ${what} (HTTP 404). Run hq deploy list to check the app ID and scope.`);
48
+ case 429:
49
+ return new SiteEventsError(`Could not ${what} (HTTP 429). Wait a moment and try again.`);
50
+ default:
51
+ return new SiteEventsError(`Could not ${what} (HTTP ${status}). Try again in a moment.`);
52
+ }
53
+ }
54
+ async function send(scope, route, method, body, what) {
55
+ const request = await openDeployIdentity(scope);
56
+ let response;
57
+ try {
58
+ response = await request((token, headers) => deployApiRequest(token, route, method, body, headers, { redirect: "error" }));
59
+ }
60
+ catch (error) {
61
+ if (error instanceof DeployIdentityError)
62
+ throw error;
63
+ throw new SiteEventsError(`Could not reach hq-deploy to ${what}.`);
64
+ }
65
+ if (response.status !== 200)
66
+ throw responseError(response.status, what);
67
+ const parsed = await response.json().catch(() => null);
68
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
69
+ throw new SiteEventsError(`hq-deploy returned an invalid response when asked to ${what}.`);
70
+ }
71
+ return parsed;
72
+ }
73
+ function eventsRoute(appId, query) {
74
+ const params = new URLSearchParams();
75
+ if (query.after)
76
+ params.set("after", query.after);
77
+ if (query.status)
78
+ params.set("status", query.status);
79
+ if (query.limit)
80
+ params.set("limit", query.limit);
81
+ const search = params.toString();
82
+ return `/api/apps/${encodeURIComponent(appId)}/manage/events${search ? `?${search}` : ""}`;
83
+ }
84
+ async function listOnce(appId, scope, query) {
85
+ const body = await send(scope, eventsRoute(appId, query), "GET", undefined, "read site events");
86
+ if (!Array.isArray(body.events))
87
+ throw new SiteEventsError("hq-deploy returned an invalid site events list.");
88
+ return body;
89
+ }
90
+ async function enableAction(appId, options) {
91
+ checkApp(appId);
92
+ const scope = checkScope(options);
93
+ const eventsEnabled = options.off !== true;
94
+ const receipt = await send(scope, `/api/apps/${encodeURIComponent(appId)}`, "PATCH", { eventsEnabled }, "change the site events setting");
95
+ if (receipt.eventsEnabled !== eventsEnabled) {
96
+ throw new SiteEventsError("hq-deploy did not confirm the site events setting. Check it before trying again.");
97
+ }
98
+ const id = typeof receipt.id === "string" ? receipt.id : appId;
99
+ console.log(options.json
100
+ ? jsonLine({ ok: true, appId: id, eventsEnabled })
101
+ : `Site events turned ${eventsEnabled ? "on" : "off"} for ${display(id)}.`);
102
+ }
103
+ async function listAction(appId, options) {
104
+ checkApp(appId);
105
+ const scope = checkScope(options);
106
+ checkStatus(options.status);
107
+ if (options.after !== undefined && !EVENT_ID.test(options.after))
108
+ throw new SiteEventsError("--after must be a site event id.");
109
+ if (options.limit !== undefined && !/^[0-9]+$/.test(options.limit))
110
+ throw new SiteEventsError("--limit must be a number.");
111
+ const body = await listOnce(appId, scope, options);
112
+ if (options.json) {
113
+ console.log(jsonLine(body));
114
+ return;
115
+ }
116
+ if (body.events.length === 0) {
117
+ console.log("No site events.");
118
+ return;
119
+ }
120
+ for (const event of body.events) {
121
+ const row = (typeof event === "object" && event !== null ? event : {});
122
+ console.log([row.id, row.status, row.name, row.createdAt].map((value) => display(value ?? "-")).join(" | "));
123
+ }
124
+ }
125
+ async function replyAction(appId, eventId, options) {
126
+ checkApp(appId);
127
+ const scope = checkScope(options);
128
+ if (!EVENT_ID.test(eventId))
129
+ throw new SiteEventsError("Use a site event id (evt_...).");
130
+ checkStatus(options.status);
131
+ if (options.text === undefined && options.status === undefined)
132
+ throw new SiteEventsError("Give --text, --status, or both.");
133
+ if (options.text !== undefined && options.text.trim() === "")
134
+ throw new SiteEventsError("--text must not be empty.");
135
+ const payload = {};
136
+ if (options.text !== undefined)
137
+ payload.reply = options.text;
138
+ if (options.status !== undefined)
139
+ payload.status = options.status;
140
+ const route = `/api/apps/${encodeURIComponent(appId)}/manage/events/${encodeURIComponent(eventId)}`;
141
+ const receipt = await send(scope, route, "PATCH", payload, "reply to the site event");
142
+ if (typeof receipt.id !== "string")
143
+ throw new SiteEventsError("hq-deploy returned an invalid reply receipt.");
144
+ const result = { ok: true, id: receipt.id, status: receipt.status ?? null, reply: receipt.reply ?? null };
145
+ console.log(options.json ? jsonLine(result) : `Replied to ${display(receipt.id)} (status ${display(result.status)}).`);
146
+ }
147
+ function readCursor(cursorFile) {
148
+ try {
149
+ const value = fs.readFileSync(cursorFile, "utf8").trim();
150
+ return EVENT_ID.test(value) ? value : "";
151
+ }
152
+ catch {
153
+ return "";
154
+ }
155
+ }
156
+ function writeCursor(cursorFile, value) {
157
+ const tmp = `${cursorFile}.tmp`;
158
+ try {
159
+ fs.writeFileSync(tmp, `${value}\n`, { mode: 0o600 });
160
+ fs.renameSync(tmp, cursorFile);
161
+ return true;
162
+ }
163
+ catch {
164
+ try {
165
+ fs.rmSync(tmp, { force: true });
166
+ }
167
+ catch { /* best effort */ }
168
+ return false;
169
+ }
170
+ }
171
+ /**
172
+ * Poll for new events and print one JSON line per result: armed, event,
173
+ * poll_failing (first failure, then every fifth), poll_recovered,
174
+ * cursor_write_failed, heartbeat. The cursor advances only once it is on disk,
175
+ * so after a successful write a restart does not replay those events. When the
176
+ * write fails the cursor stays where it was: the next poll reports the same
177
+ * events again (at least once) together with cursor_write_failed. Each poll opens a
178
+ * fresh sign-in, so a long-running watch survives token refresh. Returns the
179
+ * exit code for --once; otherwise it runs until stopped.
180
+ */
181
+ export async function watchSiteEvents(appId, options, deps) {
182
+ checkApp(appId);
183
+ const scope = checkScope(options);
184
+ if (!options.cursorFile)
185
+ throw new SiteEventsError("--cursor-file is required so a restart resumes where it stopped.");
186
+ const intervalText = options.interval ?? String(MIN_INTERVAL_SECONDS);
187
+ if (!/^[0-9]+$/.test(intervalText) || Number(intervalText) < MIN_INTERVAL_SECONDS) {
188
+ throw new SiteEventsError(`--interval must be a whole number of seconds, at least ${MIN_INTERVAL_SECONDS}.`);
189
+ }
190
+ // Handled events were already answered; replaying them could repeat a change.
191
+ const status = options.status ?? "new";
192
+ checkStatus(status);
193
+ const cursorFile = options.cursorFile;
194
+ try {
195
+ fs.mkdirSync(path.dirname(cursorFile), { recursive: true });
196
+ }
197
+ catch {
198
+ throw new SiteEventsError("Could not create the cursor file's directory.");
199
+ }
200
+ const label = options.label ?? appId;
201
+ let cursor = readCursor(cursorFile);
202
+ deps.emit(jsonLine({ type: "armed", app: label, cursor: cursor || null }));
203
+ let fails = 0;
204
+ let lastBeat = deps.now();
205
+ for (;;) {
206
+ // A failed poll (network, HTTP error, sign-in) is reported below and retried.
207
+ const body = await listOnce(appId, scope, { after: cursor || undefined, status }).catch(() => null);
208
+ if (body === null) {
209
+ fails += 1;
210
+ if (fails % 5 === 1)
211
+ deps.emit(jsonLine({ type: "poll_failing", app: label, count: fails }));
212
+ }
213
+ else {
214
+ if (fails > 0)
215
+ deps.emit(jsonLine({ type: "poll_recovered", app: label, after: fails }));
216
+ fails = 0;
217
+ for (const event of body.events) {
218
+ if (typeof event !== "object" || event === null || Array.isArray(event))
219
+ continue;
220
+ const row = event;
221
+ deps.emit(jsonLine({
222
+ type: "event",
223
+ app: label,
224
+ id: row.id ?? null,
225
+ name: row.name ?? null,
226
+ createdAt: row.createdAt ?? null,
227
+ status: row.status ?? null,
228
+ data: row.data ?? null,
229
+ actor: row.actor ?? null,
230
+ }));
231
+ }
232
+ const next = body.nextAfter;
233
+ if (typeof next === "string" && EVENT_ID.test(next) && next !== cursor) {
234
+ if (writeCursor(cursorFile, next)) {
235
+ cursor = next;
236
+ }
237
+ else {
238
+ deps.emit(jsonLine({ type: "cursor_write_failed", app: label, path: cursorFile }));
239
+ if (options.once)
240
+ return 1;
241
+ }
242
+ }
243
+ }
244
+ if (options.once)
245
+ return 0;
246
+ const now = deps.now();
247
+ if (now - lastBeat >= deps.heartbeatMs) {
248
+ deps.emit(jsonLine({ type: "heartbeat", app: label }));
249
+ lastBeat = now;
250
+ }
251
+ await deps.sleep(Number(intervalText) * 1000);
252
+ }
253
+ }
254
+ async function run(action) {
255
+ try {
256
+ const code = await action();
257
+ if (typeof code === "number" && code !== 0)
258
+ process.exitCode = code;
259
+ }
260
+ catch (error) {
261
+ console.error(error instanceof SiteEventsError || error instanceof DeployIdentityError
262
+ ? error.message
263
+ : "Site events command failed.");
264
+ process.exitCode = 1;
265
+ }
266
+ }
267
+ function scoped(command) {
268
+ return command.option("--company <slug>", "company owning the app").option("--personal", "use personal scope");
269
+ }
270
+ export function registerDeployEventsCommand(deploy) {
271
+ const events = deploy.command("events").description("Read and answer site events that visitors send from your deployed apps");
272
+ scoped(events.command("enable <app-id>").description("Turn site events on (or off with --off) for an app"))
273
+ .option("--off", "turn site events off; stored events are kept")
274
+ .option("--json", "print {ok, appId, eventsEnabled} as JSON")
275
+ .action((appId, options) => run(() => enableAction(appId, options)));
276
+ scoped(events.command("list <app-id>").description("List site events on an app"))
277
+ .option("--after <event-id>", "only events after this event id")
278
+ .option("--status <status>", "new or handled")
279
+ .option("--limit <n>", "maximum number of events")
280
+ .option("--json", "print the API response ({events, nextAfter}) as JSON")
281
+ .action((appId, options) => run(() => listAction(appId, options)));
282
+ scoped(events.command("reply <app-id> <event-id>").description("Reply to a site event and/or set its status"))
283
+ .option("--text <reply>", "reply text the page shows")
284
+ .option("--status <status>", "new or handled")
285
+ .option("--json", "print {ok, id, status, reply} as JSON")
286
+ .action((appId, eventId, options) => run(() => replyAction(appId, eventId, options)));
287
+ scoped(events.command("watch <app-id>").description("Poll for new site events and print one JSON line per event"))
288
+ .option("--cursor-file <path>", "file that stores the last reported event id")
289
+ .option("--label <name>", "name used in the output lines (default: the app id)")
290
+ .option("--interval <seconds>", `seconds between polls, at least ${MIN_INTERVAL_SECONDS}`, String(MIN_INTERVAL_SECONDS))
291
+ .option("--status <status>", "new or handled (default: new)")
292
+ .option("--once", "poll once and exit")
293
+ .action((appId, options) => run(() => watchSiteEvents(appId, options, {
294
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
295
+ now: () => Date.now(),
296
+ emit: (line) => console.log(line),
297
+ heartbeatMs: DEFAULT_HEARTBEAT_MS,
298
+ })));
299
+ }
300
+ //# sourceMappingURL=deploy-events.js.map
@@ -18,8 +18,8 @@
18
18
  * a TTY. The rendering and contract live in ../lib/doctor/report.ts and
19
19
  * ../lib/doctor/json-output.ts; this command wires them to the CLI.
20
20
  *
21
- * The detected platform is a placeholder (UNKNOWN_PLATFORM) until host platform
22
- * detection (US-003) lands and injects the real value through `platform`.
21
+ * The command detects the host platform once (`detectPlatform`) and passes it
22
+ * through `platform`; UNKNOWN_PLATFORM is the fallback when none is given.
23
23
  */
24
24
  import { Command } from "commander";
25
25
  import { type DoctorRegistry } from "../lib/doctor/registry.js";
@@ -70,8 +70,8 @@ export interface RunDoctorOptions {
70
70
  /** In text mode, emit ANSI colour. Default: false (no escape sequences). */
71
71
  color?: boolean;
72
72
  /**
73
- * The detected platform. Defaults to {@link UNKNOWN_PLATFORM}; host platform
74
- * detection (US-003) injects the real value here. It is exposed to every check
73
+ * The detected platform. Defaults to {@link UNKNOWN_PLATFORM}; the CLI action
74
+ * passes the result of host platform detection here. It is exposed to every check
75
75
  * so host-specific checks (the US-006 runtime probe) can key off it.
76
76
  */
77
77
  platform?: DoctorPlatform;
@@ -18,8 +18,8 @@
18
18
  * a TTY. The rendering and contract live in ../lib/doctor/report.ts and
19
19
  * ../lib/doctor/json-output.ts; this command wires them to the CLI.
20
20
  *
21
- * The detected platform is a placeholder (UNKNOWN_PLATFORM) until host platform
22
- * detection (US-003) lands and injects the real value through `platform`.
21
+ * The command detects the host platform once (`detectPlatform`) and passes it
22
+ * through `platform`; UNKNOWN_PLATFORM is the fallback when none is given.
23
23
  */
24
24
  import { findHqRootAncestor } from "../utils/hq-roots-core.js";
25
25
  import * as fs from "node:fs";
@@ -430,7 +430,6 @@ function describeRowState(row) {
430
430
  async function currentStateNote(id, token) {
431
431
  return describeRowState(await fetchFeedbackRow({ id, token }));
432
432
  }
433
- const OLD_SERVER_HINT = "The server may not support work links yet.";
434
433
  /** Delays between read-back attempts: 3 reads over about 1s. */
435
434
  export const LINK_READBACK_DELAYS_MS = [300, 700];
436
435
  /** Overridable in tests so retries do not wait on real timers. */
@@ -456,7 +455,7 @@ export async function storeFeedbackWorkLink(opts) {
456
455
  });
457
456
  if (!res.ok) {
458
457
  const message = await readFeedbackError(res);
459
- throw new Error(`The server rejected the work link for ${opts.id}: ${message}. ${OLD_SERVER_HINT} ${await currentStateNote(opts.id, opts.token)}`);
458
+ throw new Error(`The server rejected the work link for ${opts.id}: ${message}. ${await currentStateNote(opts.id, opts.token)}`);
460
459
  }
461
460
  // The GET resolves through an eventually consistent index, so a read right
462
461
  // after the PATCH can return the old row. Retry briefly before deciding.
@@ -474,7 +473,7 @@ export async function storeFeedbackWorkLink(opts) {
474
473
  if (!readOk) {
475
474
  throw new Error(`Could not read ${opts.id} back to confirm the work link; the link may have been saved. The state was not posted; rerun the same command to retry.`);
476
475
  }
477
- throw new Error(`The server did not store the work link for ${opts.id}. ${OLD_SERVER_HINT} ${describeRowState(row)}`);
476
+ throw new Error(`The server did not store the work link for ${opts.id}. ${describeRowState(row)}`);
478
477
  }
479
478
  /** Post a customer-visible update; the server also mirrors it into #hq-feedback. */
480
479
  export async function postFeedbackUpdate(opts) {
@@ -39,6 +39,7 @@ import * as fs from "node:fs";
39
39
  import * as path from "node:path";
40
40
  import { Readable } from "node:stream";
41
41
  import { pipeline } from "node:stream/promises";
42
+ import { raiseAccessRefresh } from "../lib/sync-core/access-refresh.js";
42
43
  import { S3Client, ListObjectsV2Command, GetObjectCommand, } from "@aws-sdk/client-s3";
43
44
  import { VaultClient, } from "@indigoai-us/hq-cloud";
44
45
  import { isPrivateFolderPattern } from "./_patterns.js";
@@ -694,6 +695,7 @@ export async function runGet(input) {
694
695
  if (input.into === undefined) {
695
696
  addPin(hqRoot, slug, bucketPrefix);
696
697
  pinned = { companySlug: slug, prefix: bucketPrefix };
698
+ raiseAccessRefresh({ companyUid: entity.uid, companySlug: slug });
697
699
  }
698
700
  return { filesWritten: keys.length, bytesWritten, destinations, pinned };
699
701
  }
@@ -15,6 +15,7 @@ import { resolveCompanySlug, resolvePersonWithRosterFallback, } from "./people.j
15
15
  import { findHqRoot } from "../utils/manifest.js";
16
16
  import { maxLength } from "../utils/table-width.js";
17
17
  import { resolveCompanyFlagGate } from "../lib/flag-registry.js";
18
+ import { raiseAccessRefresh } from "../lib/sync-core/access-refresh.js";
18
19
  const PERSON_UID_PATTERN = /^(prs|agt)_[A-Za-z0-9_-]+$/;
19
20
  const AGENT_UID_PATTERN = /^agt_[A-Za-z0-9_-]+$/;
20
21
  export const FILES_SHARE_EMPTY_PREFIX_WARNING_FLAG = "files.share-empty-prefix-warning";
@@ -400,6 +401,7 @@ export function registerFilesCommand(program) {
400
401
  }
401
402
  process.exit(1);
402
403
  }
404
+ raiseAccessRefresh({ companyUid });
403
405
  const removedCount = body.removedEntries;
404
406
  const cleanupMessage = typeof removedCount === "number" && removedCount > 0
405
407
  ? `Removed ${removedCount} empty ${removedCount === 1 ? "entry" : "entries"} from '${canonicalPrefix}'. `
@@ -431,6 +433,7 @@ export function registerFilesCommand(program) {
431
433
  body: { prefix: candidate, granteeType, granteeId },
432
434
  });
433
435
  if (res.ok) {
436
+ raiseAccessRefresh({ companyUid });
434
437
  console.log(chalk.green(`Removed grant for ${principalLabel} on '${displayAclPattern(candidate)}'`));
435
438
  if (bare && candidate === canonicalPrefix) {
436
439
  console.log(chalk.dim(`This removed the exact '${candidate}' grant. A grant for ${principalLabel} on ` +
@@ -1230,6 +1233,7 @@ async function runDirectGrant(params) {
1230
1233
  }
1231
1234
  process.exit(1);
1232
1235
  }
1236
+ raiseAccessRefresh({ companyUid });
1233
1237
  const data = (await res.json());
1234
1238
  const printedPrefix = data.acl?.path ?? data.acl?.prefix ?? canonicalPrefix;
1235
1239
  await warnIfEmptySharePrefix({
@@ -327,6 +327,17 @@ export declare function isBuiltInGatewayProvider(provider: string): boolean;
327
327
  * for it. Fails closed: a row without `viewerAccess` is not listed.
328
328
  */
329
329
  export declare function fetchUsableApps(token: string, companyUid: string): Promise<UsableAppsResult>;
330
+ /**
331
+ * `fetchUsableApps` plus every connection that is not revoked, usable by the
332
+ * caller or not (`knownConnections`), from the same single summary read. The
333
+ * hot-channel sync uses the known ones only to find saved channel picks.
334
+ */
335
+ export declare function fetchIntegrationsSummary(token: string, companyUid: string): Promise<UsableAppsResult & {
336
+ knownConnections: Array<{
337
+ connectionId: string;
338
+ provider: string;
339
+ }>;
340
+ }>;
330
341
  /**
331
342
  * Resolve one connection by `--connection acct_…` or `--provider linear`
332
343
  * (matches `factory:<slug>`, bare provider ids, and an installation's human
@@ -504,6 +504,15 @@ function gatewayHasProvider(row) {
504
504
  * for it. Fails closed: a row without `viewerAccess` is not listed.
505
505
  */
506
506
  export async function fetchUsableApps(token, companyUid) {
507
+ const { knownConnections: _known, ...usable } = await fetchIntegrationsSummary(token, companyUid);
508
+ return usable;
509
+ }
510
+ /**
511
+ * `fetchUsableApps` plus every connection that is not revoked, usable by the
512
+ * caller or not (`knownConnections`), from the same single summary read. The
513
+ * hot-channel sync uses the known ones only to find saved channel picks.
514
+ */
515
+ export async function fetchIntegrationsSummary(token, companyUid) {
507
516
  const res = await vaultApiFetch({
508
517
  token,
509
518
  path: "/v1/integrations/admin",
@@ -544,7 +553,12 @@ export async function fetchUsableApps(token, companyUid) {
544
553
  })
545
554
  .sort((a, b) => compareNames(a.name, b.name))
546
555
  : [];
547
- return { companyUid: data.companyUid ?? companyUid, viewerAccessKnown, apps };
556
+ // Revoked rows count: a pick the person saved on a connection that was
557
+ // later revoked still says which channels they want.
558
+ const knownConnections = rows
559
+ .filter((row) => typeof row.id === "string" && typeof row.provider === "string")
560
+ .map((row) => ({ connectionId: row.id, provider: row.provider }));
561
+ return { companyUid: data.companyUid ?? companyUid, viewerAccessKnown, apps, knownConnections };
548
562
  }
549
563
  /**
550
564
  * Resolve one connection by `--connection acct_…` or `--provider linear`
@@ -0,0 +1,12 @@
1
+ export interface KeyedPullOptions {
2
+ hqRoot: string;
3
+ company?: string;
4
+ companySlug?: string;
5
+ token: string;
6
+ }
7
+ /** No session discovery, journal, deletes or tombstones: absence from an
8
+ * ACL-filtered inventory never proves deletion. */
9
+ export declare function keyedSyncPull(options: KeyedPullOptions): Promise<{
10
+ filesDownloaded: number;
11
+ }>;
12
+ //# sourceMappingURL=keyed-sync-pull.d.ts.map
@@ -0,0 +1,151 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { Transform } from "node:stream";
4
+ import { pipeline } from "node:stream/promises";
5
+ import { GetObjectCommand } from "@aws-sdk/client-s3";
6
+ import { vaultApiFetch } from "../utils/vault-api.js";
7
+ const fail = (message) => Object.assign(new Error(message), { expected: true });
8
+ function safeKey(value) {
9
+ return typeof value === "string" && value.length > 0 &&
10
+ !/[\\:]/.test(value) && ![...value].some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) &&
11
+ value.split("/").every(part => part.length > 0 && ![".", "..", ".git", ".hq"].includes(part.toLowerCase()) && !/[. ]$/.test(part));
12
+ }
13
+ /** Require a real directory chain. Hydration runs before workload execution,
14
+ * in a launcher-owned tree without concurrent writers. */
15
+ async function directories(dir, create) {
16
+ const parent = path.dirname(dir);
17
+ if (parent !== dir)
18
+ await directories(parent, create);
19
+ let stat;
20
+ try {
21
+ stat = await fs.lstat(dir);
22
+ }
23
+ catch (err) {
24
+ if (err.code !== "ENOENT")
25
+ throw err;
26
+ if (!create)
27
+ return;
28
+ await fs.mkdir(dir, { mode: 0o700 });
29
+ stat = await fs.lstat(dir);
30
+ }
31
+ if (!stat.isDirectory() || stat.isSymbolicLink())
32
+ throw fail("Keyed pull refuses linked or non-directory parents");
33
+ }
34
+ async function destination(file) {
35
+ await directories(path.dirname(file), false);
36
+ try {
37
+ const stat = await fs.lstat(file);
38
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink > 1)
39
+ throw fail("Keyed pull refuses linked or non-file destinations");
40
+ }
41
+ catch (err) {
42
+ if (err.code !== "ENOENT")
43
+ throw err;
44
+ }
45
+ }
46
+ /** No session discovery, journal, deletes or tombstones: absence from an
47
+ * ACL-filtered inventory never proves deletion. */
48
+ export async function keyedSyncPull(options) {
49
+ const { token, company, companySlug } = options;
50
+ if (!token.startsWith("hqk_") || token.trim() !== token)
51
+ throw fail("Keyed pull requires a valid HQ_API_KEY");
52
+ if (!company || !/^cmp_[A-Za-z0-9]+$/.test(company))
53
+ throw fail("Keyed pull requires --company cmp_…; no session discovery is allowed");
54
+ if (!companySlug || !/^[a-z0-9][a-z0-9_-]*$/.test(companySlug))
55
+ throw fail("Keyed pull requires a safe --company-slug from the trusted launcher");
56
+ const root = path.resolve(options.hqRoot, "companies", companySlug);
57
+ const files = [];
58
+ const names = new Set();
59
+ const cursors = new Set();
60
+ let cursor;
61
+ for (let page = 0;; page++) {
62
+ if (page >= 10_000)
63
+ throw fail("Keyed pull inventory exceeded the page limit");
64
+ let response;
65
+ try {
66
+ response = await vaultApiFetch({ token, path: "/v1/files/list", query: { company, ...(cursor ? { cursor } : {}) } });
67
+ }
68
+ catch {
69
+ throw fail("Keyed pull inventory request failed");
70
+ }
71
+ if (!response.ok)
72
+ throw fail(`Keyed pull inventory refused (HTTP ${response.status})`);
73
+ let body;
74
+ try {
75
+ body = await response.json();
76
+ }
77
+ catch {
78
+ throw fail("Keyed pull inventory was not JSON");
79
+ }
80
+ if (!body || !Array.isArray(body.objects) || typeof body.truncated !== "boolean")
81
+ throw fail("Keyed pull inventory is incomplete or malformed");
82
+ for (const value of body.objects) {
83
+ const row = value;
84
+ if (!row || !safeKey(row.key) || !Number.isSafeInteger(row.size) || row.size < 0)
85
+ throw fail("Keyed pull inventory contains an unsafe file");
86
+ const name = row.key.normalize("NFC").toLowerCase();
87
+ if (names.has(name))
88
+ throw fail("Keyed pull inventory contains colliding files");
89
+ names.add(name);
90
+ files.push({ key: row.key, size: row.size });
91
+ }
92
+ if (!body.truncated) {
93
+ if (body.cursor !== undefined && body.cursor !== null && body.cursor !== "")
94
+ throw fail("Keyed pull inventory has an inconsistent cursor");
95
+ break;
96
+ }
97
+ if (typeof body.cursor !== "string" || !body.cursor || cursors.has(body.cursor))
98
+ throw fail("Keyed pull inventory has no advancing cursor");
99
+ cursor = body.cursor;
100
+ cursors.add(cursor);
101
+ }
102
+ for (const name of names) {
103
+ const parts = name.split("/");
104
+ for (let i = 1; i < parts.length; i++) {
105
+ if (names.has(parts.slice(0, i).join("/")))
106
+ throw fail("Keyed pull inventory has a file/directory collision");
107
+ }
108
+ }
109
+ for (const file of files)
110
+ await destination(path.join(root, file.key));
111
+ if (files.length === 0)
112
+ return { filesDownloaded: 0 };
113
+ await directories(root, true);
114
+ const stage = await fs.mkdtemp(path.join(root, ".keyed-pull-"));
115
+ try {
116
+ // This existing resident-preloaded module imports cloud.ts for personal
117
+ // identity resolution; defer it here to avoid a static command cycle.
118
+ const { createCompanyPresignClient } = await import("./files-browse.js");
119
+ const client = createCompanyPresignClient({ token, companyUid: company, companySlug });
120
+ for (const [index, file] of files.entries()) {
121
+ try {
122
+ const result = await client.send(new GetObjectCommand({ Bucket: "resolved-server-side", Key: file.key }));
123
+ if (!result.Body)
124
+ throw fail("Missing body");
125
+ let size = 0;
126
+ const counter = new Transform({ transform(chunk, _encoding, callback) {
127
+ size += chunk.length;
128
+ callback(size > file.size ? fail("Download exceeded listed size") : null, chunk);
129
+ } });
130
+ const handle = await fs.open(path.join(stage, String(index)), "wx", 0o600);
131
+ await pipeline(result.Body, counter, handle.createWriteStream());
132
+ if (size !== file.size)
133
+ throw fail("Download did not match listed size");
134
+ }
135
+ catch {
136
+ throw fail("Keyed pull download failed; no staged files were applied");
137
+ }
138
+ }
139
+ for (const [index, file] of files.entries()) {
140
+ const target = path.join(root, file.key);
141
+ await destination(target);
142
+ await directories(path.dirname(target), true);
143
+ await fs.rename(path.join(stage, String(index)), target);
144
+ }
145
+ return { filesDownloaded: files.length };
146
+ }
147
+ finally {
148
+ await fs.rm(stage, { recursive: true, force: true });
149
+ }
150
+ }
151
+ //# sourceMappingURL=keyed-sync-pull.js.map