@indigoai-us/hq-cli 5.345.235 → 5.345.237

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 (94) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/command-catalog.generated.d.ts +76 -1
  3. package/dist/command-catalog.generated.js +93 -1
  4. package/dist/command-registration-plan.d.ts +6 -0
  5. package/dist/command-registration-plan.js +1 -0
  6. package/dist/commands/bot.js +9 -0
  7. package/dist/commands/daemon.d.ts +1 -0
  8. package/dist/commands/daemon.js +70 -6
  9. package/dist/commands/deploy-app-db.js +4 -19
  10. package/dist/commands/deploy-app-upload.js +66 -40
  11. package/dist/commands/deploy-mutations.js +24 -16
  12. package/dist/commands/deploy-runtime-bindings.d.ts +3 -0
  13. package/dist/commands/deploy-runtime-bindings.js +116 -0
  14. package/dist/commands/deploy-ssr.js +5 -24
  15. package/dist/commands/mesh.js +6 -2
  16. package/dist/commands/signals-run.d.ts +43 -2
  17. package/dist/commands/signals-run.js +85 -7
  18. package/dist/commands/sync-core.d.ts +7 -0
  19. package/dist/commands/sync-core.js +52 -3
  20. package/dist/lib/bot/continuity.d.ts +21 -2
  21. package/dist/lib/bot/continuity.js +48 -19
  22. package/dist/lib/bot/fleet-cron.js +6 -0
  23. package/dist/lib/bot/fleet-local.d.ts +11 -1
  24. package/dist/lib/bot/fleet-local.js +21 -1
  25. package/dist/lib/bot/fleet-state.d.ts +129 -0
  26. package/dist/lib/bot/fleet-state.js +669 -0
  27. package/dist/lib/bot/promote.d.ts +9 -3
  28. package/dist/lib/bot/promote.js +115 -16
  29. package/dist/lib/daemon/catalog.d.ts +13 -0
  30. package/dist/lib/daemon/catalog.js +32 -6
  31. package/dist/lib/daemon/lanes-reconcile-status.d.ts +0 -4
  32. package/dist/lib/daemon/lanes-reconcile-status.js +2 -12
  33. package/dist/lib/daemon/lanes-reconcile-watcher.d.ts +1 -1
  34. package/dist/lib/daemon/lanes-reconcile-watcher.js +2 -1
  35. package/dist/lib/daemon/legacy-handover.d.ts +38 -0
  36. package/dist/lib/daemon/legacy-handover.js +117 -0
  37. package/dist/lib/daemon/mesh-owner.js +2 -1
  38. package/dist/lib/daemon/run.d.ts +18 -1
  39. package/dist/lib/daemon/run.js +85 -12
  40. package/dist/lib/daemon/selfcheck.d.ts +28 -0
  41. package/dist/lib/daemon/selfcheck.js +86 -15
  42. package/dist/lib/deploy-api.d.ts +2 -2
  43. package/dist/lib/deploy-api.js +4 -2
  44. package/dist/lib/deploy-identity.d.ts +18 -0
  45. package/dist/lib/deploy-identity.js +179 -0
  46. package/dist/lib/hot-channels/alert.js +13 -6
  47. package/dist/lib/hot-channels/fleet-complete.d.ts +89 -0
  48. package/dist/lib/hot-channels/fleet-complete.js +157 -0
  49. package/dist/lib/hot-channels/run.js +2 -1
  50. package/dist/lib/hot-channels/signals-claude-login.d.ts +3 -2
  51. package/dist/lib/hot-channels/signals-claude-login.js +6 -1
  52. package/dist/lib/hot-channels/signals-pass-failure.d.ts +29 -0
  53. package/dist/lib/hot-channels/signals-pass-failure.js +36 -0
  54. package/dist/lib/hot-channels/signals-pass.d.ts +49 -2
  55. package/dist/lib/hot-channels/signals-pass.js +188 -12
  56. package/dist/lib/hot-channels/signals-runtime.d.ts +6 -3
  57. package/dist/lib/hot-channels/signals-runtime.js +11 -2
  58. package/dist/lib/lanes/reconcile-result.d.ts +5 -0
  59. package/dist/lib/lanes/reconcile-result.js +20 -2
  60. package/dist/lib/lanes/reconcile.js +12 -3
  61. package/dist/lib/mesh/live/emit.js +25 -6
  62. package/dist/lib/mesh/live/flush.js +119 -15
  63. package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -0
  64. package/dist/lib/mesh/live/reporting-privacy.js +147 -1
  65. package/dist/lib/mesh/live/spool.d.ts +16 -0
  66. package/dist/lib/mesh/live/spool.js +45 -0
  67. package/dist/lib/signals/engine.d.ts +17 -3
  68. package/dist/lib/signals/engine.js +28 -9
  69. package/dist/lib/signals/failure-alert.d.ts +33 -1
  70. package/dist/lib/signals/failure-alert.js +72 -5
  71. package/dist/lib/signals/owner-notice.d.ts +94 -0
  72. package/dist/lib/signals/owner-notice.js +233 -0
  73. package/dist/lib/signals/reply.d.ts +7 -0
  74. package/dist/lib/signals/reply.js +23 -3
  75. package/dist/lib/signals/steps/adapters.d.ts +51 -2
  76. package/dist/lib/signals/steps/adapters.js +213 -7
  77. package/dist/lib/signals/steps/extract.js +18 -4
  78. package/dist/lib/signals/steps/types.d.ts +63 -1
  79. package/dist/lib/signals/steps/types.js +32 -0
  80. package/dist/lib/sync-core/engine-auth.d.ts +35 -0
  81. package/dist/lib/sync-core/engine-auth.js +96 -0
  82. package/dist/lib/sync-core/engine-home.d.ts +6 -0
  83. package/dist/lib/sync-core/engine-home.js +12 -0
  84. package/dist/lib/sync-core/rollout-state.d.ts +1 -0
  85. package/dist/lib/sync-core/rollout-state.js +3 -0
  86. package/dist/lib/vault-sync-switches.d.ts +7 -0
  87. package/dist/lib/vault-sync-switches.js +56 -0
  88. package/dist/lib/work-context/errors.d.ts +12 -0
  89. package/dist/lib/work-context/errors.js +15 -0
  90. package/dist/lib/work-context/organize.js +6 -1
  91. package/dist/lib/work-context/reconcile.js +20 -1
  92. package/dist/utils/resident-package-preload.js +34 -4
  93. package/docs/anywhere-runtime.md +6 -0
  94. package/package.json +7 -7
@@ -1,24 +1,18 @@
1
1
  import { openAsBlob } from "node:fs";
2
2
  import { stat } from "node:fs/promises";
3
3
  import { deployApiFormRequest } from "../lib/deploy-api.js";
4
- import { ensureCognitoToken, resolveCognitoTokenSource } from "../utils/cognito-session.js";
4
+ import { DeployIdentityError, openDeployIdentity } from "../lib/deploy-identity.js";
5
5
  const MAX_ARCHIVE_BYTES = 100 * 1024 * 1024;
6
+ const DATABASE_PROVISIONING_WAIT_MS = 600_000;
6
7
  class AppUploadError extends Error {
7
8
  }
8
- function scopeHeaders(options) {
9
- if (Boolean(options.company) === Boolean(options.personal)) {
9
+ function validateScope(options) {
10
+ if ((options.company !== undefined) === (options.personal === true)) {
10
11
  throw new AppUploadError("Choose exactly one of --company <slug> or --personal.");
11
12
  }
12
- if (options.company) {
13
- if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(options.company)) {
14
- throw new AppUploadError("Use a valid company slug.");
15
- }
16
- return { "X-Org-Slug": options.company };
17
- }
18
- if (resolveCognitoTokenSource() === "machine") {
19
- throw new AppUploadError("A machine identity needs an explicit company scope. Choose an authorized company.");
13
+ if (options.company !== undefined && !/^[a-z0-9][a-z0-9-]{0,62}$/.test(options.company)) {
14
+ throw new AppUploadError("Use a valid company slug.");
20
15
  }
21
- return { "X-HQ-Deploy-Scope": "personal" };
22
16
  }
23
17
  async function loadArchive(path) {
24
18
  try {
@@ -42,37 +36,72 @@ async function loadArchive(path) {
42
36
  throw new AppUploadError("Could not read the archive. Check the file path and permissions.");
43
37
  }
44
38
  }
45
- async function failureMessage(response) {
46
- if (response.status === 401)
47
- return "Your deploy sign-in expired. Run hq login and try again.";
48
- if (response.status === 403 || response.status === 404) {
39
+ function failureMessage(status, code) {
40
+ if (status === 403 || status === 404) {
49
41
  return "Could not access this app. To continue, check your scope and app ID or ask the app owner.";
50
42
  }
51
- if (response.status === 413 || response.status === 415 || response.status === 422) {
43
+ if (status === 413 || status === 415 || status === 422) {
52
44
  return "The deploy service refused the archive. Rebuild it as gzip within 100 MiB and try again.";
53
45
  }
54
- if (response.status === 409 || response.status === 503) {
55
- const body = await response.json().catch(() => null);
56
- const code = body?.code ?? body?.error?.code;
57
- if (response.status === 409 && code === "DATABASE_BILLING_ACK_REQUIRED") {
58
- return "This deployment needs database billing approval. Obtain approval before acknowledging billing.";
59
- }
60
- if (response.status === 409 && code === "PUBLIC_SECRET_BACKED_DEPLOY_BLOCKED") {
61
- return "This public app has bound secrets. Add an access gate or obtain explicit approval before acknowledging the risk.";
62
- }
63
- if (response.status === 503 && code === "DATABASE_PROVISIONING") {
46
+ if (status === 409 && code === "DATABASE_BILLING_ACK_REQUIRED") {
47
+ return "This deployment needs database billing approval. Obtain approval before acknowledging billing.";
48
+ }
49
+ if (status === 409 && code === "PUBLIC_SECRET_BACKED_DEPLOY_BLOCKED") {
50
+ return "This public app has bound secrets. Add an access gate or obtain explicit approval before acknowledging the risk.";
51
+ }
52
+ return "Could not confirm the app upload. Check deployment history before trying again.";
53
+ }
54
+ async function submitArchive(send) {
55
+ let retry;
56
+ try {
57
+ while (true) {
58
+ const signal = retry?.controller.signal;
59
+ const response = await send(signal);
60
+ if (response.status === 200) {
61
+ const receipt = await response.json().catch(() => null);
62
+ signal?.throwIfAborted();
63
+ return receipt;
64
+ }
65
+ const body = (response.status === 409 || response.status === 503
66
+ ? await response.json().catch(() => null)
67
+ : null);
68
+ signal?.throwIfAborted();
69
+ const code = body?.code ?? body?.error?.code;
70
+ if (response.status !== 503 || code !== "DATABASE_PROVISIONING") {
71
+ throw new AppUploadError(failureMessage(response.status, code));
72
+ }
73
+ // The deploy service stops this attempt before activation and reuses the app's pending cluster.
74
+ if (!retry) {
75
+ const controller = new AbortController();
76
+ retry = {
77
+ controller,
78
+ deadline: performance.now() + DATABASE_PROVISIONING_WAIT_MS,
79
+ timer: setTimeout(() => controller.abort(), DATABASE_PROVISIONING_WAIT_MS),
80
+ };
81
+ }
64
82
  const hint = body?.retryAfterSeconds;
65
- const delay = typeof hint === "number" && Number.isFinite(hint) ? Math.max(2, Math.min(30, Math.floor(hint))) : 5;
66
- return `DATABASE_PROVISIONING: the app database is being created. Wait and retry in ${delay} seconds.`;
83
+ const delaySeconds = typeof hint === "number" && Number.isFinite(hint) ? Math.max(2, Math.min(30, Math.floor(hint))) : 5;
84
+ const delayMs = delaySeconds * 1000;
85
+ if (performance.now() + delayMs >= retry.deadline) {
86
+ throw new AppUploadError("The app database is still being created. Check deployment history before trying again.");
87
+ }
88
+ console.error(`The app database is being created. Retrying the same upload in ${delaySeconds} seconds.`);
89
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
90
+ if (performance.now() >= retry.deadline)
91
+ retry.controller.abort();
92
+ retry.controller.signal.throwIfAborted();
67
93
  }
68
94
  }
69
- return "Could not confirm the app upload. Check deployment history before trying again.";
95
+ finally {
96
+ if (retry)
97
+ clearTimeout(retry.timer);
98
+ }
70
99
  }
71
100
  async function uploadApp(appId, archive, options) {
72
101
  if (!/^(?:[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}|app_[A-Za-z0-9_-]+)$/i.test(appId)) {
73
102
  throw new AppUploadError("Use the app ID shown by hq deploy list.");
74
103
  }
75
- const headers = scopeHeaders(options);
104
+ validateScope(options);
76
105
  const form = new FormData();
77
106
  form.set("type", "app");
78
107
  form.set("file", await loadArchive(archive), "upload.tar.gz");
@@ -80,14 +109,11 @@ async function uploadApp(appId, archive, options) {
80
109
  form.set("database_billing_acknowledged", "true");
81
110
  if (options.acknowledgePublicSecretRisk)
82
111
  form.set("acknowledge_public_secret_risk", "true");
83
- const token = await ensureCognitoToken({ interactive: false, ...(options.personal ? { tokenSource: "person" } : {}) })
84
- .catch(() => { throw new AppUploadError("Could not get an HQ sign-in. Run hq login or check the configured machine identity."); });
85
- const appRoute = `/api/apps/${encodeURIComponent(appId)}`;
86
- const response = await deployApiFormRequest(token, `${appRoute}/deploy`, form, headers)
87
- .catch(() => { throw new AppUploadError("Could not confirm the app upload. Check deployment history before trying again."); });
88
- if (response.status !== 200)
89
- throw new AppUploadError(await failureMessage(response));
90
- const receipt = await response.json().catch(() => null);
112
+ const request = await openDeployIdentity(options);
113
+ const appRoute = "/api/apps/" + encodeURIComponent(appId);
114
+ const receipt = await submitArchive((signal) => request((token, headers) => deployApiFormRequest(token, appRoute + "/deploy", form, headers, signal),
115
+ // Provisioning retries already have a deadline and must reuse the accepted identity.
116
+ { recoverUnauthorized: signal === undefined }));
91
117
  const { appId: returnedApp, deployId, version, status, statusUrl } = receipt ?? {};
92
118
  if (returnedApp !== appId || typeof deployId !== "string" || !/^[A-Za-z0-9_-]+$/.test(deployId)
93
119
  || typeof version !== "number" || !Number.isSafeInteger(version) || version < 1
@@ -112,7 +138,7 @@ export function registerDeployAppUploadCommand(deploy) {
112
138
  await uploadApp(appId, archive, options);
113
139
  }
114
140
  catch (error) {
115
- console.error(error instanceof AppUploadError ? error.message : "Could not confirm the app upload. Check deployment history before trying again.");
141
+ console.error(error instanceof AppUploadError || error instanceof DeployIdentityError ? error.message : "Could not confirm the app upload. Check deployment history before trying again.");
116
142
  process.exitCode = 1;
117
143
  }
118
144
  });
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { deployApiRequest } from "../lib/deploy-api.js";
4
+ import { DeployIdentityError, openDeployIdentity } from "../lib/deploy-identity.js";
4
5
  import { findDeployApp } from "../lib/deploy-apps.js";
5
6
  import { ensureCognitoToken } from "../utils/cognito-session.js";
6
7
  import { displayText } from "./deploy-comments.js";
@@ -18,11 +19,11 @@ function id(value) {
18
19
  throw new DeployMutationError("Invalid app or deployment identifier.");
19
20
  return encodeURIComponent(value);
20
21
  }
21
- async function resolveAppId(token, app, context) {
22
+ async function resolveAppId(app, lookup) {
22
23
  // The service issues UUIDs. The deploy CLI also accepts legacy app_ IDs.
23
24
  if (/^(?:[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}|app_[A-Za-z0-9_-]+)$/i.test(app))
24
25
  return app;
25
- const match = await findDeployApp(app, (route) => request(token, route, "GET", undefined, context));
26
+ const match = await findDeployApp(app, lookup);
26
27
  if (match.kind === "none")
27
28
  throw new DeployMutationError(`No deploy app '${displayText(app)}' in the selected scope.`);
28
29
  if (match.kind === "many")
@@ -45,12 +46,17 @@ async function readLocal(path, what) {
45
46
  throw new DeployMutationError(`Could not read the ${what} at ${path}. Nothing was sent.`);
46
47
  }
47
48
  }
48
- async function request(token, route, method, body, scope) {
49
+ function request(token, route, method, body, scope) {
50
+ return readResponse(deployApiRequest(token, route, method, body, scope));
51
+ }
52
+ async function readResponse(pending) {
49
53
  let response;
50
54
  try {
51
- response = await deployApiRequest(token, route, method, body, scope);
55
+ response = await pending;
52
56
  }
53
- catch {
57
+ catch (error) {
58
+ if (error instanceof DeployIdentityError)
59
+ throw error;
54
60
  throw new DeployMutationError("Could not reach hq-deploy. Retry the operation.");
55
61
  }
56
62
  if (!response.ok) {
@@ -67,6 +73,10 @@ async function request(token, route, method, body, scope) {
67
73
  throw new DeployMutationError("hq-deploy returned an invalid response.");
68
74
  }
69
75
  }
76
+ async function openMetadataRead(options) {
77
+ const scopedRequest = await openDeployIdentity(options);
78
+ return (route) => readResponse(scopedRequest((token, headers) => deployApiRequest(token, route, "GET", undefined, headers, { redirect: "error" })));
79
+ }
70
80
  function requiredText(record, key) {
71
81
  if (typeof record[key] !== "string" || !record[key])
72
82
  throw new DeployMutationError(`hq-deploy response is missing ${key}.`);
@@ -94,7 +104,7 @@ function action(fn) {
94
104
  await fn(...args);
95
105
  }
96
106
  catch (error) {
97
- console.error(error instanceof DeployMutationError ? error.message : "Deploy operation failed.");
107
+ console.error(error instanceof DeployMutationError || error instanceof DeployIdentityError ? error.message : "Deploy operation failed.");
98
108
  process.exitCode = 1;
99
109
  }
100
110
  };
@@ -104,16 +114,15 @@ export function registerDeployMutationsCommand(deploy) {
104
114
  .action(action(async (app, options) => {
105
115
  const context = headers(options);
106
116
  const token = await signIn();
107
- const appId = await resolveAppId(token, app, context);
117
+ const appId = await resolveAppId(app, (route) => request(token, route, "GET", undefined, context));
108
118
  const record = await request(token, `/api/apps/${id(appId)}`, "GET", undefined, context);
109
119
  output({ id: appId, accessMode: record.accessMode ?? null, passwordProtected: record.passwordProtected === true, privateMode: record.privateMode === true }, options);
110
120
  }));
111
121
  scope(deploy.command("app-info <app>").description("Read deploy app identity and access metadata"))
112
122
  .action(action(async (app, options) => {
113
- const context = headers(options);
114
- const token = await signIn();
115
- const appId = await resolveAppId(token, app, context);
116
- const record = await request(token, `/api/apps/${id(appId)}`, "GET", undefined, context);
123
+ const read = await openMetadataRead(options);
124
+ const appId = await resolveAppId(app, read);
125
+ const record = await read("/api/apps/" + id(appId));
117
126
  if (record.id !== appId)
118
127
  throw new DeployMutationError("hq-deploy returned a different app id.");
119
128
  const subdomain = requiredText(record, "subdomain");
@@ -132,10 +141,9 @@ export function registerDeployMutationsCommand(deploy) {
132
141
  }));
133
142
  scope(deploy.command("history <app>").description("Read deployment history for one app"))
134
143
  .action(action(async (app, options) => {
135
- const context = headers(options);
136
- const token = await signIn();
137
- const appId = await resolveAppId(token, app, context);
138
- const record = await request(token, `/api/apps/${id(appId)}/deploys`, "GET", undefined, context);
144
+ const read = await openMetadataRead(options);
145
+ const appId = await resolveAppId(app, read);
146
+ const record = await read("/api/apps/" + id(appId) + "/deploys");
139
147
  if (record.appId !== appId)
140
148
  throw new DeployMutationError("hq-deploy returned a different app id.");
141
149
  if (Array.isArray(record.deploys)) {
@@ -162,7 +170,7 @@ export function registerDeployMutationsCommand(deploy) {
162
170
  .action(action(async (app, options) => {
163
171
  const context = headers(options);
164
172
  const token = await signIn();
165
- const appId = await resolveAppId(token, app, context);
173
+ const appId = await resolveAppId(app, (route) => request(token, route, "GET", undefined, context));
166
174
  await request(token, `/api/apps/${id(appId)}`, "PATCH", { active: false }, context);
167
175
  output({ app, active: false }, options);
168
176
  }));
@@ -0,0 +1,3 @@
1
+ import type { Command } from "commander";
2
+ export declare function registerDeployRuntimeBindingsCommand(deploy: Command): void;
3
+ //# sourceMappingURL=deploy-runtime-bindings.d.ts.map
@@ -0,0 +1,116 @@
1
+ import { deployApiRequest } from "../lib/deploy-api.js";
2
+ import { DeployIdentityError, openDeployIdentity } from "../lib/deploy-identity.js";
3
+ class BindingError extends Error {
4
+ }
5
+ const REFERENCE_PATH = /^[A-Z][A-Z0-9_]*(\/[A-Z][A-Z0-9_]+)*$/;
6
+ const ALIAS = /^[A-Za-z_][A-Za-z0-9_]*$/;
7
+ const CONFIRM_STATE = "List the current bindings before trying again.";
8
+ function projectReference(entry) {
9
+ if (typeof entry !== "object" || entry === null)
10
+ return undefined;
11
+ const { name, envVar } = entry;
12
+ if (typeof name !== "string" || !REFERENCE_PATH.test(name))
13
+ return undefined;
14
+ if (envVar === undefined)
15
+ return { name };
16
+ return typeof envVar === "string" && ALIAS.test(envVar) ? { name, envVar } : undefined;
17
+ }
18
+ function replacement(options) {
19
+ if (options.confirmReplace !== true) {
20
+ throw new BindingError("Review the full reference set before passing --confirm-replace.");
21
+ }
22
+ const { companyUid, ref } = options;
23
+ if (!companyUid || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(companyUid)) {
24
+ throw new BindingError("Provide a valid --company-uid for the selected company.");
25
+ }
26
+ if (ref.length === 0)
27
+ throw new BindingError("Provide at least one --ref for the full replacement.");
28
+ const secrets = ref.map((argument) => {
29
+ const [name, envVar, extra] = argument.split(":");
30
+ const projected = projectReference({ name, envVar });
31
+ if (!projected || extra !== undefined) {
32
+ throw new BindingError("Use a vault reference path or a path followed by :ALIAS.");
33
+ }
34
+ return projected;
35
+ });
36
+ const names = new Set(secrets.map((reference) => reference.name));
37
+ const aliases = new Set(secrets.map((reference) => reference.envVar ?? reference.name));
38
+ if (names.size !== secrets.length || aliases.size !== secrets.length) {
39
+ throw new BindingError("Use unique vault reference paths and runtime aliases.");
40
+ }
41
+ return { companyUid, secrets };
42
+ }
43
+ async function scopedRequest(appId, company, update) {
44
+ if (!/^(?:[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}|app_[A-Za-z0-9_-]+)$/i.test(appId)) {
45
+ throw new BindingError("Use the app ID shown by hq deploy list.");
46
+ }
47
+ if (!company || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(company)) {
48
+ throw new BindingError("Provide an explicit --company slug.");
49
+ }
50
+ const request = await openDeployIdentity({ company }, { personOnly: true, companion: update !== undefined });
51
+ const response = await request((token, headers) => deployApiRequest(token, "/api/apps/" + encodeURIComponent(appId) + "/secret-bindings", update ? "PUT" : "GET", update, headers, { redirect: "error" })).catch((error) => {
52
+ if (error instanceof DeployIdentityError)
53
+ throw error;
54
+ throw new BindingError(update
55
+ ? "Could not confirm the binding replacement. " + CONFIRM_STATE
56
+ : "Could not read runtime bindings. Check your connection and try again.");
57
+ });
58
+ if (response.status === 200)
59
+ return response;
60
+ if (response.status === 403 || response.status === 404) {
61
+ throw new BindingError("Could not access runtime bindings. Check the app ID, company and your permissions.");
62
+ }
63
+ if (response.status === 400 && update) {
64
+ throw new BindingError("The deploy service rejected the binding request. Check the app runtime, company UID and reference paths.");
65
+ }
66
+ throw new BindingError(update
67
+ ? `Could not confirm the binding replacement (HTTP ${response.status}). ${CONFIRM_STATE}`
68
+ : `Could not read runtime bindings (HTTP ${response.status}). Try again in a moment.`);
69
+ }
70
+ function canonicalReferences(refs) {
71
+ return JSON.stringify(refs.map(({ name, envVar }) => [name, envVar ?? ""]).sort());
72
+ }
73
+ async function run(appId, options, update) {
74
+ const response = await scopedRequest(appId, options.company, update);
75
+ const receipt = await response.json().catch(() => null);
76
+ const bindingVersion = receipt?.bindingVersion;
77
+ const secrets = Array.isArray(receipt?.secrets) ? receipt.secrets.map(projectReference) : null;
78
+ if (receipt?.appId !== appId || receipt.orgSlug !== options.company || typeof bindingVersion !== "number"
79
+ || !Number.isSafeInteger(bindingVersion) || bindingVersion < (update ? 1 : 0)
80
+ || !secrets || !secrets.every((reference) => reference !== undefined)
81
+ || (update && (receipt.companyUid !== update.companyUid
82
+ || canonicalReferences(secrets) !== canonicalReferences(update.secrets)))) {
83
+ throw new BindingError(update
84
+ ? `The deploy service returned an invalid binding receipt. ${CONFIRM_STATE}`
85
+ : "The deploy service returned invalid runtime binding metadata.");
86
+ }
87
+ console.log(options.json
88
+ ? JSON.stringify({ appId, bindingVersion, secrets })
89
+ : `Runtime bindings for ${appId}: ${secrets.length} references (version ${bindingVersion}).`);
90
+ }
91
+ async function report(action) {
92
+ try {
93
+ await action();
94
+ }
95
+ catch (error) {
96
+ console.error(error instanceof BindingError || error instanceof DeployIdentityError ? error.message : "Could not confirm the runtime binding operation.");
97
+ process.exitCode = 1;
98
+ }
99
+ }
100
+ export function registerDeployRuntimeBindingsCommand(deploy) {
101
+ const bindings = deploy.command("runtime-bindings").description("Manage app runtime references to company vault secrets");
102
+ bindings.command("list <app-id>")
103
+ .description("List an app's runtime binding references")
104
+ .option("--company <slug>", "company owning the app")
105
+ .option("--json", "print the binding reference metadata as JSON")
106
+ .action((appId, options) => report(() => run(appId, options)));
107
+ bindings.command("replace <app-id>")
108
+ .description("Replace the complete set of app runtime binding references")
109
+ .option("--company <slug>", "company owning the app")
110
+ .option("--company-uid <uid>", "vault company UID for the same company")
111
+ .option("--ref <reference>", "repeat with a vault reference path or PATH:ALIAS", (value, refs) => [...refs, value], [])
112
+ .option("--confirm-replace", "confirm replacement of the entire binding set")
113
+ .option("--json", "print the binding reference metadata as JSON")
114
+ .action((appId, options) => report(() => run(appId, options, replacement(options))));
115
+ }
116
+ //# sourceMappingURL=deploy-runtime-bindings.js.map
@@ -1,39 +1,20 @@
1
1
  import { deployApiRequest } from "../lib/deploy-api.js";
2
- import { ensureCognitoToken } from "../utils/cognito-session.js";
2
+ import { DeployIdentityError, openDeployIdentity } from "../lib/deploy-identity.js";
3
3
  class RegisterSsrError extends Error {
4
4
  }
5
- function scopeHeaders(options) {
6
- if (Boolean(options.company) === Boolean(options.personal)) {
7
- throw new RegisterSsrError("Choose exactly one of --company <slug> or --personal.");
8
- }
9
- if (!options.company)
10
- return { "X-HQ-Deploy-Scope": "personal" };
11
- if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(options.company)) {
12
- throw new RegisterSsrError("Invalid company slug.");
13
- }
14
- return { "X-Org-Slug": options.company };
15
- }
16
5
  async function register(appId, imageTag, options) {
17
- const headers = scopeHeaders(options);
18
6
  if (!/^(?:[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}|app_[A-Za-z0-9_-]+)$/i.test(appId)) {
19
7
  throw new RegisterSsrError("Use the app ID shown by hq deploy list.");
20
8
  }
21
9
  if (!/^(?:[a-z0-9][a-z0-9._-]*\/)*[a-z0-9][a-z0-9._-]*:[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(imageTag)) {
22
10
  throw new RegisterSsrError("Give the existing ECR image in repository:tag form.");
23
11
  }
24
- const token = await ensureCognitoToken().catch(() => {
25
- throw new RegisterSsrError("Could not get an HQ sign-in for hq-deploy. Run hq login and try again.");
26
- });
27
- const appRoute = `/api/apps/${encodeURIComponent(appId)}`;
28
- const response = await deployApiRequest(token, `${appRoute}/deploy`, "POST", { type: "ssr", image_tag: imageTag }, headers)
29
- .catch(() => {
30
- throw new RegisterSsrError("Could not confirm SSR registration. Check deployment history before trying again.");
31
- });
12
+ const request = await openDeployIdentity(options);
13
+ const appRoute = "/api/apps/" + encodeURIComponent(appId);
14
+ const response = await request((token, headers) => deployApiRequest(token, appRoute + "/deploy", "POST", { type: "ssr", image_tag: imageTag }, headers, { redirect: "error" }));
32
15
  if (response.status !== 202) {
33
16
  const prefix = `hq-deploy did not confirm SSR registration (HTTP ${response.status}).`;
34
17
  switch (response.status) {
35
- case 401:
36
- throw new RegisterSsrError(`${prefix} Run hq login and try again.`);
37
18
  case 403:
38
19
  throw new RegisterSsrError(`${prefix} Check your app scope or ask the app owner or an org admin.`);
39
20
  case 404:
@@ -64,7 +45,7 @@ export function registerDeploySsrCommand(deploy) {
64
45
  await register(appId, imageTag, options);
65
46
  }
66
47
  catch (error) {
67
- console.error(error instanceof RegisterSsrError
48
+ console.error(error instanceof RegisterSsrError || error instanceof DeployIdentityError
68
49
  ? error.message
69
50
  : "Could not confirm SSR registration. Check deployment history before trying again.");
70
51
  process.exitCode = 1;
@@ -1150,8 +1150,12 @@ async function runPrdSync(opts) {
1150
1150
  evidence: { ...evidenceBase, task: event.taskId },
1151
1151
  }));
1152
1152
  const poster = createEmitPoster({ token, baseUrl: resolveVaultApiBase(process.env) });
1153
+ // Asked once. With HQ Anywhere off the events of a session with a verified
1154
+ // company binding are still sent (emitEvents); the story claim below is a
1155
+ // Board write on the person's behalf and stays off.
1156
+ const reportingOn = await reportingRuntimeAllowed(isMachineIdentity());
1153
1157
  const emitted = await emitEvents({
1154
- reportingAllowed: () => reportingRuntimeAllowed(isMachineIdentity()),
1158
+ reportingAllowed: async () => reportingOn,
1155
1159
  workMeshRoot: meshRoot,
1156
1160
  poster,
1157
1161
  newEvents: events,
@@ -1169,7 +1173,7 @@ async function runPrdSync(opts) {
1169
1173
  }
1170
1174
  const advanced = events.flatMap((event) => (event.eventId && event.taskId && !blocked.has(event.eventId) ? [event.taskId] : []));
1171
1175
  plan.commit([...alreadyOnBoard, ...advanced]);
1172
- const claimed = bound?.companyUid && bound.projectId
1176
+ const claimed = reportingOn && bound?.companyUid && bound.projectId
1173
1177
  ? await claimUnassignedInProgress({
1174
1178
  token,
1175
1179
  companyUid: bound.companyUid,
@@ -9,7 +9,8 @@
9
9
  */
10
10
  import { Command } from "commander";
11
11
  import { type RunSignalsResult, type SignalsStepChoice, type SignalsTrigger } from "../lib/signals/engine.js";
12
- import type { SignalsRunAlertSenders } from "../lib/signals/failure-alert.js";
12
+ import { type SignalsRunAlertSenders } from "../lib/signals/failure-alert.js";
13
+ import { type SignalsNoticeBot } from "../lib/signals/owner-notice.js";
13
14
  interface RunCliOptions {
14
15
  source?: string;
15
16
  incremental?: boolean;
@@ -27,7 +28,47 @@ interface RunCliOptions {
27
28
  hqRoot: string;
28
29
  }
29
30
  export declare function formatRunResult(result: RunSignalsResult, dryRun: boolean): string;
30
- export declare function foundSignalsReply(result: RunSignalsResult, company: string | undefined, timeZone: string): string | null;
31
+ /**
32
+ * The owner's reply for `--report-found`, or null when there is nothing to
33
+ * say. The HQ Fleet Runtime job sends this command's stdout to the owner and
34
+ * its stderr to a log, so this is the only line the owner gets from that job.
35
+ * It is printed when the run found signals, from the extract step or from the
36
+ * hot-channel signals pass the adapters step runs, and when that pass did not
37
+ * finish in a way the signals-failure alert counts (`signalsPassRunFailure`:
38
+ * the tool signed out, a failure after a landing, the document cap spent
39
+ * before a landing was read). The alert itself goes to stderr here.
40
+ */
41
+ export declare function foundSignalsReply(result: RunSignalsResult, company: string | undefined, timeZone: string, bot?: SignalsNoticeBot): string | null;
42
+ /**
43
+ * The Executive bot whose Fleet job runs `--report-found` (fleet-cron.ts is its
44
+ * only caller), so a signed-out notice names that bot's own sign-in. Never
45
+ * throws: an unreadable bot list gives the "your bot" wording.
46
+ */
47
+ export declare function reportFoundBot(): SignalsNoticeBot;
48
+ /**
49
+ * Everything `--report-found` prints, which HQ Fleet sends to the owner as an
50
+ * HQ DM. A run that could not do its work (`signalsNoticeProblem`: the tool
51
+ * the signals pass runs on is signed out, the pass failed, the document cap
52
+ * left landed documents unread, or the run failed) prints the owner's plain
53
+ * notice with its fix, once per company per day per cause, in place of the run
54
+ * reply. A clean run after a told problem prints the "running again" notice
55
+ * once, before the found-signals reply. Otherwise the found-signals reply, as
56
+ * before. The notice state is saved only after `write` returned.
57
+ */
58
+ export declare function reportFoundOutput(result: RunSignalsResult, opts: {
59
+ company: string | undefined;
60
+ timeZone: string;
61
+ hqRoot: string;
62
+ now: Date;
63
+ write: (text: string) => void;
64
+ log?: (message: string) => void;
65
+ /**
66
+ * The bot whose job this is. `--report-found` is printed only by the Fleet
67
+ * Executive bot's job, so a signed-out notice always names the bot's own
68
+ * sign-in, never a Claude Code sign-in. Default: "your bot".
69
+ */
70
+ bot?: SignalsNoticeBot;
71
+ }): Promise<void>;
31
72
  /**
32
73
  * The terminal alert sender for `hq signals run` (US-018). The CLI has no
33
74
  * owner-DM sender, so the terminal is the primary alert, as in
@@ -12,6 +12,9 @@ import chalk from "chalk";
12
12
  import { DEFAULT_HQ_ROOT } from "../utils/cognito-session.js";
13
13
  import { Sentry } from "../sentry.js";
14
14
  import { runSignals, signalsExitCode, SignalsUsageError, SIGNALS_STEP_CHOICES, SIGNALS_TRIGGERS, } from "../lib/signals/engine.js";
15
+ import { signalsPassRunFailure } from "../lib/signals/failure-alert.js";
16
+ import { deliverSignalsNotice, signalsNoticeProblem, UNKNOWN_SIGNALS_NOTICE_BOT } from "../lib/signals/owner-notice.js";
17
+ import { resolveExecutiveBot } from "../lib/bot/executive.js";
15
18
  import { formatRunReply } from "../lib/signals/reply.js";
16
19
  function parsePositiveInt(v) {
17
20
  const n = Number(v);
@@ -67,14 +70,83 @@ export function formatRunResult(result, dryRun) {
67
70
  }
68
71
  return `${lines.join("\n")}\n`;
69
72
  }
70
- export function foundSignalsReply(result, company, timeZone) {
73
+ /**
74
+ * The owner's reply for `--report-found`, or null when there is nothing to
75
+ * say. The HQ Fleet Runtime job sends this command's stdout to the owner and
76
+ * its stderr to a log, so this is the only line the owner gets from that job.
77
+ * It is printed when the run found signals, from the extract step or from the
78
+ * hot-channel signals pass the adapters step runs, and when that pass did not
79
+ * finish in a way the signals-failure alert counts (`signalsPassRunFailure`:
80
+ * the tool signed out, a failure after a landing, the document cap spent
81
+ * before a landing was read). The alert itself goes to stderr here.
82
+ */
83
+ export function foundSignalsReply(result, company, timeZone, bot = UNKNOWN_SIGNALS_NOTICE_BOT) {
71
84
  const record = result.records.find((r) => !company || r.company === company);
72
85
  if (!record || record.alreadyRanToday || (record.status !== "complete" && record.status !== "partial"))
73
86
  return null;
74
87
  const extract = record.steps.find((s) => s.name === "extract" && s.status !== "skipped");
75
- if (!extract || extract.itemsOut <= 0)
88
+ const passSignals = record.steps.filter((s) => s.name === "adapters").reduce((n, s) => n + (s.signalsOut ?? 0), 0);
89
+ const found = (extract?.itemsOut ?? 0) + passSignals;
90
+ if (found <= 0 && signalsPassRunFailure(record) === null)
76
91
  return null;
77
- return formatRunReply(record, result.summary, { timeZone }).text;
92
+ return formatRunReply(record, result.summary, { timeZone, bot }).text;
93
+ }
94
+ /**
95
+ * The Executive bot whose Fleet job runs `--report-found` (fleet-cron.ts is its
96
+ * only caller), so a signed-out notice names that bot's own sign-in. Never
97
+ * throws: an unreadable bot list gives the "your bot" wording.
98
+ */
99
+ export function reportFoundBot() {
100
+ try {
101
+ const bot = resolveExecutiveBot();
102
+ return bot ? { name: bot.name, runtime: typeof bot.config.runtime === "string" ? bot.config.runtime : null } : UNKNOWN_SIGNALS_NOTICE_BOT;
103
+ }
104
+ catch {
105
+ return UNKNOWN_SIGNALS_NOTICE_BOT;
106
+ }
107
+ }
108
+ /**
109
+ * Everything `--report-found` prints, which HQ Fleet sends to the owner as an
110
+ * HQ DM. A run that could not do its work (`signalsNoticeProblem`: the tool
111
+ * the signals pass runs on is signed out, the pass failed, the document cap
112
+ * left landed documents unread, or the run failed) prints the owner's plain
113
+ * notice with its fix, once per company per day per cause, in place of the run
114
+ * reply. A clean run after a told problem prints the "running again" notice
115
+ * once, before the found-signals reply. Otherwise the found-signals reply, as
116
+ * before. The notice state is saved only after `write` returned.
117
+ */
118
+ export async function reportFoundOutput(result, opts) {
119
+ const bot = opts.bot ?? UNKNOWN_SIGNALS_NOTICE_BOT;
120
+ const record = result.records.find((r) => !opts.company || r.company === opts.company);
121
+ if (!record)
122
+ return;
123
+ const problem = signalsNoticeProblem(record);
124
+ const reply = foundSignalsReply(result, opts.company, opts.timeZone, bot);
125
+ // Signals the run did find are news even on a day with a problem: the run
126
+ // reply then carries them and the notice's words and link together.
127
+ const withFound = problem !== null && signalsFoundIn(record) > 0 && reply !== null ? reply : null;
128
+ const told = await deliverSignalsNotice({
129
+ hqRoot: opts.hqRoot,
130
+ record,
131
+ now: opts.now,
132
+ send: (text) => opts.write(`${withFound ?? text}\n`),
133
+ bot,
134
+ ...(opts.log ? { log: opts.log } : {}),
135
+ });
136
+ if (problem === null) {
137
+ if (reply)
138
+ opts.write(`${reply}\n`);
139
+ }
140
+ else if (withFound && told.kind === null) {
141
+ // The cause was already told today; the signals found this run still go out.
142
+ opts.write(`${withFound}\n`);
143
+ }
144
+ }
145
+ /** Signals this run wrote: the extract step's plus the adapters step's signals pass. */
146
+ function signalsFoundIn(record) {
147
+ const extract = record.steps.find((s) => s.name === "extract" && s.status !== "skipped");
148
+ const passSignals = record.steps.filter((s) => s.name === "adapters").reduce((n, s) => n + (s.signalsOut ?? 0), 0);
149
+ return (extract?.itemsOut ?? 0) + passSignals;
78
150
  }
79
151
  function localTimeZone() {
80
152
  try {
@@ -123,9 +195,15 @@ export async function runSignalsCli(options, overrides = {}) {
123
195
  });
124
196
  const code = signalsExitCode(result);
125
197
  if (options.reportFound) {
126
- const reply = foundSignalsReply(result, options.company, localTimeZone());
127
- if (reply)
128
- process.stdout.write(`${reply}\n`);
198
+ await reportFoundOutput(result, {
199
+ company: options.company,
200
+ timeZone: localTimeZone(),
201
+ hqRoot: options.hqRoot,
202
+ now: new Date(),
203
+ write: (text) => void process.stdout.write(text),
204
+ bot: reportFoundBot(),
205
+ log: (message) => void process.stderr.write(chalk.yellow(`${message}\n`)),
206
+ });
129
207
  if (code !== 0)
130
208
  process.exitCode = code;
131
209
  return;
@@ -163,7 +241,7 @@ export function registerSignalsRunSubcommand(signals) {
163
241
  .option("--max-turns <n>", "Model turn cap for the extract step (default from core/settings/signals.yaml, else 40)", parsePositiveInt)
164
242
  .option("--max-budget-usd <x>", "Spend cap in USD for the extract step (default from core/settings/signals.yaml, else 2.00)", parseNonNegative)
165
243
  .option("--json", "Print the run record as JSON")
166
- .option("--report-found", "Print the owner's run reply only when the run found new signals; print nothing otherwise")
244
+ .option("--report-found", "Print the owner's run reply only when the run found new signals or its hot-channel signals pass did not finish; print nothing otherwise")
167
245
  .option("--redo <file>", "Process a source item again (sources/<channel>/<file>.md; repeatable; needs --company): the extract step re-queues it in the ontology worklist before listing", collectRedo)
168
246
  .option("--hq-root <path>", `HQ root (default: ${DEFAULT_HQ_ROOT})`, DEFAULT_HQ_ROOT)
169
247
  .action(async (options) => {