@indigoai-us/hq-cli 5.345.236 → 5.345.238

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 (96) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/command-catalog.generated.d.ts +1 -1
  3. package/dist/command-catalog.generated.js +1 -1
  4. package/dist/commands/bot.d.ts +2 -0
  5. package/dist/commands/bot.js +32 -0
  6. package/dist/commands/daemon.d.ts +1 -0
  7. package/dist/commands/daemon.js +70 -6
  8. package/dist/commands/deploy-app-db.js +4 -19
  9. package/dist/commands/deploy-app-upload.js +66 -40
  10. package/dist/commands/deploy-mutations.js +24 -16
  11. package/dist/commands/deploy-runtime-bindings.js +7 -26
  12. package/dist/commands/deploy-ssr.js +5 -24
  13. package/dist/commands/mesh.js +6 -2
  14. package/dist/commands/signals-run.d.ts +43 -2
  15. package/dist/commands/signals-run.js +85 -7
  16. package/dist/commands/sync-core.d.ts +7 -0
  17. package/dist/commands/sync-core.js +52 -3
  18. package/dist/lib/agent-kit/inbox-state.d.ts +2 -1
  19. package/dist/lib/agent-kit/inbox-state.js +27 -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 +32 -3
  28. package/dist/lib/bot/promote.js +188 -16
  29. package/dist/lib/bot/promotion-hold-reconcile.d.ts +56 -0
  30. package/dist/lib/bot/promotion-hold-reconcile.js +155 -0
  31. package/dist/lib/daemon/catalog.d.ts +13 -0
  32. package/dist/lib/daemon/catalog.js +32 -6
  33. package/dist/lib/daemon/lanes-reconcile-status.d.ts +0 -4
  34. package/dist/lib/daemon/lanes-reconcile-status.js +2 -12
  35. package/dist/lib/daemon/lanes-reconcile-watcher.d.ts +1 -1
  36. package/dist/lib/daemon/lanes-reconcile-watcher.js +2 -1
  37. package/dist/lib/daemon/legacy-handover.d.ts +38 -0
  38. package/dist/lib/daemon/legacy-handover.js +117 -0
  39. package/dist/lib/daemon/mesh-owner.js +2 -1
  40. package/dist/lib/daemon/run.d.ts +35 -2
  41. package/dist/lib/daemon/run.js +108 -15
  42. package/dist/lib/daemon/selfcheck.d.ts +28 -0
  43. package/dist/lib/daemon/selfcheck.js +86 -15
  44. package/dist/lib/deploy-api.d.ts +1 -1
  45. package/dist/lib/deploy-api.js +2 -1
  46. package/dist/lib/deploy-identity.d.ts +18 -0
  47. package/dist/lib/deploy-identity.js +179 -0
  48. package/dist/lib/hot-channels/alert.js +13 -6
  49. package/dist/lib/hot-channels/fleet-complete.d.ts +89 -0
  50. package/dist/lib/hot-channels/fleet-complete.js +157 -0
  51. package/dist/lib/hot-channels/run.js +2 -1
  52. package/dist/lib/hot-channels/signals-claude-login.d.ts +3 -2
  53. package/dist/lib/hot-channels/signals-claude-login.js +6 -1
  54. package/dist/lib/hot-channels/signals-pass-failure.d.ts +29 -0
  55. package/dist/lib/hot-channels/signals-pass-failure.js +36 -0
  56. package/dist/lib/hot-channels/signals-pass.d.ts +49 -2
  57. package/dist/lib/hot-channels/signals-pass.js +188 -12
  58. package/dist/lib/hot-channels/signals-runtime.d.ts +6 -3
  59. package/dist/lib/hot-channels/signals-runtime.js +11 -2
  60. package/dist/lib/lanes/reconcile-result.d.ts +5 -0
  61. package/dist/lib/lanes/reconcile-result.js +20 -2
  62. package/dist/lib/lanes/reconcile.js +12 -3
  63. package/dist/lib/mesh/live/emit.js +25 -6
  64. package/dist/lib/mesh/live/flush.js +119 -15
  65. package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -0
  66. package/dist/lib/mesh/live/reporting-privacy.js +147 -1
  67. package/dist/lib/mesh/live/spool.d.ts +16 -0
  68. package/dist/lib/mesh/live/spool.js +45 -0
  69. package/dist/lib/signals/engine.d.ts +17 -3
  70. package/dist/lib/signals/engine.js +28 -9
  71. package/dist/lib/signals/failure-alert.d.ts +33 -1
  72. package/dist/lib/signals/failure-alert.js +72 -5
  73. package/dist/lib/signals/owner-notice.d.ts +94 -0
  74. package/dist/lib/signals/owner-notice.js +233 -0
  75. package/dist/lib/signals/reply.d.ts +7 -0
  76. package/dist/lib/signals/reply.js +23 -3
  77. package/dist/lib/signals/steps/adapters.d.ts +51 -2
  78. package/dist/lib/signals/steps/adapters.js +213 -7
  79. package/dist/lib/signals/steps/extract.js +18 -4
  80. package/dist/lib/signals/steps/types.d.ts +63 -1
  81. package/dist/lib/signals/steps/types.js +32 -0
  82. package/dist/lib/sync-core/engine-auth.d.ts +35 -0
  83. package/dist/lib/sync-core/engine-auth.js +96 -0
  84. package/dist/lib/sync-core/engine-home.d.ts +6 -0
  85. package/dist/lib/sync-core/engine-home.js +12 -0
  86. package/dist/lib/sync-core/rollout-state.d.ts +1 -0
  87. package/dist/lib/sync-core/rollout-state.js +3 -0
  88. package/dist/lib/vault-sync-switches.d.ts +7 -0
  89. package/dist/lib/vault-sync-switches.js +56 -0
  90. package/dist/lib/work-context/errors.d.ts +12 -0
  91. package/dist/lib/work-context/errors.js +15 -0
  92. package/dist/lib/work-context/organize.js +6 -1
  93. package/dist/lib/work-context/reconcile.js +20 -1
  94. package/dist/utils/resident-package-preload.js +34 -4
  95. package/docs/anywhere-runtime.md +6 -0
  96. package/package.json +7 -7
@@ -20,6 +20,8 @@ export interface EngineUnitProblem {
20
20
  since: number;
21
21
  /** One line for the DM. */
22
22
  what: string;
23
+ /** Already past its own bound when it first shows (a stuck handover), so it is reported without the 30-minute wait. */
24
+ urgent?: boolean;
23
25
  }
24
26
  /** Engine units held, or failing without a heartbeat, for more than ATTENTION_AFTER_MS at `now`. */
25
27
  export declare function engineUnitsNeedingAttention(state: DaemonState | null, holds: PersistedHolds, now: number,
@@ -38,6 +40,8 @@ export interface WakeProblem {
38
40
  export interface WakeWatch {
39
41
  notLiveSince: number;
40
42
  checkedAt: number;
43
+ /** When the self-check last restarted or took over Work Mesh while the marker was not live. */
44
+ repairedAt?: number;
41
45
  }
42
46
  export declare const WAKE_WATCH_GAP_MS: number;
43
47
  export declare function readWakeWatch(file: string): WakeWatch | null;
@@ -92,6 +96,11 @@ vaultName?: (vaultUid: string) => string | undefined, wake?: WakeProblem | null)
92
96
  body: string;
93
97
  details: string;
94
98
  };
99
+ export interface EngineAuthRefusalProblem {
100
+ unitId: string;
101
+ since: number;
102
+ what: string;
103
+ }
95
104
  export interface SelfCheckDeps {
96
105
  statePath: string;
97
106
  holdsPath: string;
@@ -119,8 +128,27 @@ export interface SelfCheckDeps {
119
128
  markerPath: string;
120
129
  watchPath: string;
121
130
  meshWanted: () => boolean;
131
+ /** Restart Work Mesh or take it over from an older unit; resolves to what was done, or null when nothing could be. */
132
+ repairMesh?: () => Promise<string | null>;
133
+ /** Where the last repair time is kept, so repairs stay at most one per MESH_REPAIR_MIN_INTERVAL_MS. */
134
+ repairPath?: string;
122
135
  };
136
+ /** Vaults switched back to the current sync that the running old sync has skipped for over the bound. */
137
+ readRestoreStuck?: () => readonly {
138
+ what: string;
139
+ since: number;
140
+ reason: string;
141
+ }[];
142
+ /**
143
+ * Engine units whose cycles the sync service keeps refusing (HTTP 401). The
144
+ * unit runs and heartbeats, so the unit checks above see it as healthy.
145
+ */
146
+ readAuthRefusals?: () => readonly EngineAuthRefusalProblem[] | Promise<readonly EngineAuthRefusalProblem[]>;
123
147
  }
148
+ export declare const MESH_REPAIR_MIN_INTERVAL_MS: number;
149
+ export declare const MESH_HELD_BY_OLDER_UNIT = "already run by ";
150
+ /** What the self-check does about Work Mesh when change notifications are not live. */
151
+ export declare function meshRepairAction(state: DaemonState | null): "take-over" | "restart" | null;
124
152
  export type SelfCheckOutcome = "healthy" | "reported" | "already-reported" | "no-owner";
125
153
  export declare function runSelfCheck(deps: SelfCheckDeps): Promise<SelfCheckOutcome>;
126
154
  //# sourceMappingURL=selfcheck.d.ts.map
@@ -11,6 +11,7 @@
11
11
  import * as fs from "node:fs";
12
12
  import * as path from "node:path";
13
13
  import { syncCoreUnitId } from "../sync-core/engine-home.js";
14
+ import { LEGACY_HANDOVER_STUCK_PREFIX } from "./catalog.js";
14
15
  import { ensurePrivateDir, readStoreFile, writeStoreFile } from "./paths.js";
15
16
  /** An engine unit that has been held or failing this long needs a person. */
16
17
  export const ATTENTION_AFTER_MS = 30 * 60_000;
@@ -31,7 +32,7 @@ wanted = () => true) {
31
32
  continue;
32
33
  seen.add(unit.id);
33
34
  const problem = unitProblem(unit, holds[unit.id], state, now);
34
- if (problem && now - problem.since > ATTENTION_AFTER_MS)
35
+ if (problem && (problem.urgent === true || now - problem.since > ATTENTION_AFTER_MS))
35
36
  problems.push(problem);
36
37
  }
37
38
  // With no daemon state, the persisted holds are all there is to go on. With
@@ -59,7 +60,9 @@ function unitProblem(unit, hold, state, now) {
59
60
  const detail = unit.hold?.detail ?? hold?.detail ?? unit.reason ?? "held";
60
61
  return { unitId: unit.id, since, what: `held since ${iso(since)}: ${detail}` };
61
62
  }
62
- // Paused on purpose (sync paused, waiting for the legacy sync to hand over) is not failing.
63
+ if (unit.status === "waiting" && unit.reason?.startsWith(LEGACY_HANDOVER_STUCK_PREFIX)) {
64
+ return { unitId: unit.id, since: now, what: unit.reason, urgent: true };
65
+ }
63
66
  if (unit.status !== "backoff" && unit.status !== "exited" && unit.status !== "running")
64
67
  return null;
65
68
  const last = unit.lastHeartbeatAt ? Date.parse(unit.lastHeartbeatAt) : Number.NaN;
@@ -117,7 +120,7 @@ export function readWakeWatch(file) {
117
120
  const parsed = JSON.parse(text);
118
121
  const ok = (v) => typeof v === "number" && Number.isFinite(v);
119
122
  return ok(parsed?.notLiveSince) && ok(parsed.checkedAt)
120
- ? { notLiveSince: parsed.notLiveSince, checkedAt: parsed.checkedAt }
123
+ ? { notLiveSince: parsed.notLiveSince, checkedAt: parsed.checkedAt, ...(ok(parsed.repairedAt) ? { repairedAt: parsed.repairedAt } : {}) }
121
124
  : null;
122
125
  }
123
126
  catch (error) {
@@ -223,48 +226,116 @@ export function selfCheckMessage(problems, machine,
223
226
  /** A name for a vault (company slug, "personal"), when known. */
224
227
  vaultName = () => undefined, wake = null) {
225
228
  const named = (p) => {
229
+ if (!p.unitId.startsWith(ENGINE_UNIT_PREFIX))
230
+ return "the old sync";
226
231
  const uid = p.unitId.slice(ENGINE_UNIT_PREFIX.length);
227
232
  const name = vaultName(uid);
228
233
  return name ? `${name} (${uid})` : uid;
229
234
  };
230
- const names = problems.map(named).join(", ");
231
- const body = problems.length > 0
235
+ const engineProblems = problems.filter((p) => p.unitId.startsWith(ENGINE_UNIT_PREFIX));
236
+ const names = engineProblems.map(named).join(", ");
237
+ const body = engineProblems.length > 0
232
238
  ? `HQ sync on ${machine}: the sync engine for ${names} has not synced for over ${ATTENTION_AFTER_MS / 60_000} minutes. ` +
233
239
  "Run `hq daemon status` on that machine."
234
- : `HQ sync on ${machine}: the sync engine is running without change notifications, so it only polls and other machines' changes can arrive up to 30 minutes late. ` +
235
- "Run `hq daemon status` and `hq daemon doctor` on that machine.";
236
- const lines = problems.map((p) => `- ${named(p)}: ${p.what}. Retry with: hq daemon restart ${p.unitId}`);
240
+ : problems.length > 0
241
+ ? `HQ sync on ${machine}: a vault switched back to the current sync is not syncing, because the running sync started before the switch. ` +
242
+ "Run `hq sync-core status` on that machine."
243
+ : `HQ sync on ${machine}: the sync engine is running without change notifications, so it only polls and other machines' changes can arrive up to 30 minutes late. ` +
244
+ "Run `hq daemon status` and `hq daemon doctor` on that machine.";
245
+ const lines = problems.map((p) => p.urgent
246
+ ? `- ${named(p)}: ${p.what}.`
247
+ : `- ${named(p)}: ${p.what}. Retry with: hq daemon restart ${p.unitId}`);
237
248
  if (wake)
238
249
  lines.push(`- change notifications: ${wake.what}. Check with: hq daemon status and hq daemon doctor`);
239
250
  lines.push("", "Logs: hq daemon logs <unit>. This check runs in hq daemon and sends at most one DM a day from this machine.");
240
251
  return { body, details: lines.join("\n") };
241
252
  }
242
- function checkWake(deps, state, now) {
253
+ export const MESH_REPAIR_MIN_INTERVAL_MS = 3 * 60 * 60_000;
254
+ function readLastRepair(file) {
255
+ if (!file)
256
+ return undefined;
257
+ try {
258
+ const at = JSON.parse(fs.readFileSync(file, "utf8")).at;
259
+ return typeof at === "number" && Number.isFinite(at) ? at : undefined;
260
+ }
261
+ catch {
262
+ return undefined;
263
+ }
264
+ }
265
+ async function checkWake(deps, state, now) {
243
266
  if (!deps.wake)
244
267
  return null;
245
268
  try {
269
+ const watch = readWakeWatch(deps.wake.watchPath);
246
270
  const assessment = assessWake({
247
271
  engineRunning: deps.wake.meshWanted() && engineIsRunning(state, deps.wanted),
248
272
  marker: readWakeMarker(deps.wake.markerPath),
249
- watch: readWakeWatch(deps.wake.watchPath),
273
+ watch,
250
274
  now,
251
275
  });
252
- if (assessment.live)
276
+ if (assessment.live) {
253
277
  fs.rmSync(deps.wake.watchPath, { force: true });
254
- else
255
- writeSelfCheckRecordFile(deps.wake.watchPath, { notLiveSince: assessment.notLiveSince ?? now, checkedAt: now });
256
- return assessment.problem;
278
+ return null;
279
+ }
280
+ const earlierRepair = watch?.repairedAt;
281
+ let repaired = null;
282
+ const lastRepair = readLastRepair(deps.wake.repairPath);
283
+ const repairDue = lastRepair === undefined || now - lastRepair >= MESH_REPAIR_MIN_INTERVAL_MS;
284
+ if (deps.wake.repairMesh && repairDue) {
285
+ try {
286
+ repaired = await deps.wake.repairMesh();
287
+ }
288
+ catch (error) {
289
+ deps.log(`sync engine self-check: could not repair Work Mesh (${error.message})`);
290
+ }
291
+ if (repaired && deps.wake.repairPath)
292
+ writeSelfCheckRecordFile(deps.wake.repairPath, { at: now });
293
+ }
294
+ else if (deps.wake.repairMesh) {
295
+ deps.log(`sync engine self-check: Work Mesh was last repaired at ${iso(lastRepair)}; not repairing again before ${iso(lastRepair + MESH_REPAIR_MIN_INTERVAL_MS)}`);
296
+ }
297
+ if (repaired)
298
+ deps.log(`sync engine self-check: change notifications are not live; ${repaired}`);
299
+ const repairedAt = repaired ? now : earlierRepair;
300
+ writeSelfCheckRecordFile(deps.wake.watchPath, {
301
+ notLiveSince: assessment.notLiveSince ?? now,
302
+ checkedAt: now,
303
+ ...(repairedAt !== undefined ? { repairedAt } : {}),
304
+ });
305
+ // The first repair gets one check to work before the owner hears about it.
306
+ return repaired && earlierRepair === undefined ? null : assessment.problem;
257
307
  }
258
308
  catch (error) {
259
309
  deps.log(`sync engine self-check: could not check change notifications (${error.code ?? error.message})`);
260
310
  return null;
261
311
  }
262
312
  }
313
+ export const MESH_HELD_BY_OLDER_UNIT = "already run by ";
314
+ /** What the self-check does about Work Mesh when change notifications are not live. */
315
+ export function meshRepairAction(state) {
316
+ const mesh = state?.units.find((unit) => unit.id === "mesh");
317
+ if (!mesh)
318
+ return null;
319
+ if (mesh.status === "waiting" && mesh.reason?.startsWith(MESH_HELD_BY_OLDER_UNIT))
320
+ return "take-over";
321
+ if (mesh.status === "running" || mesh.status === "backoff" || mesh.status === "exited")
322
+ return "restart";
323
+ return null;
324
+ }
263
325
  export async function runSelfCheck(deps) {
264
326
  const now = deps.now();
265
327
  const state = deps.readState();
266
328
  const problems = engineUnitsNeedingAttention(state, deps.readHolds(), now, deps.wanted);
267
- const wake = checkWake(deps, state, now);
329
+ const flagged = new Set(problems.map((p) => p.unitId));
330
+ for (const refused of (await deps.readAuthRefusals?.()) ?? []) {
331
+ if (flagged.has(refused.unitId))
332
+ continue;
333
+ problems.push({ unitId: refused.unitId, since: refused.since, what: refused.what, urgent: true });
334
+ }
335
+ for (const stuck of deps.readRestoreStuck?.() ?? []) {
336
+ problems.push({ unitId: "sync", since: stuck.since, what: stuck.reason, urgent: true });
337
+ }
338
+ const wake = await checkWake(deps, state, now);
268
339
  if (deps.resultPath) {
269
340
  try {
270
341
  writeSelfCheckResult(deps.resultPath, { checkedAt: now, problems: problems.length });
@@ -3,5 +3,5 @@ export declare const DEPLOY_API_URL: string;
3
3
  export declare function deployHeaders(token: string, json?: boolean, extra?: Record<string, string>): Record<string, string>;
4
4
  export declare function deployApiRequest(token: string, route: string, method: string, body?: unknown, extraHeaders?: Record<string, string>, options?: Pick<RequestInit, "redirect">): Promise<Response>;
5
5
  /** Submit an app archive on the authenticated multipart route. Fetch owns the boundary. */
6
- export declare function deployApiFormRequest(token: string, route: string, body: FormData, extraHeaders: Record<string, string>): Promise<Response>;
6
+ export declare function deployApiFormRequest(token: string, route: string, body: FormData, extraHeaders: Record<string, string>, signal?: AbortSignal): Promise<Response>;
7
7
  //# sourceMappingURL=deploy-api.d.ts.map
@@ -22,12 +22,13 @@ export async function deployApiRequest(token, route, method, body, extraHeaders
22
22
  });
23
23
  }
24
24
  /** Submit an app archive on the authenticated multipart route. Fetch owns the boundary. */
25
- export function deployApiFormRequest(token, route, body, extraHeaders) {
25
+ export function deployApiFormRequest(token, route, body, extraHeaders, signal) {
26
26
  return fetch(deployApiUrl(route), {
27
27
  method: "POST",
28
28
  headers: deployHeaders(token, false, extraHeaders),
29
29
  body,
30
30
  redirect: "error",
31
+ ...(signal ? { signal } : {}),
31
32
  });
32
33
  }
33
34
  //# sourceMappingURL=deploy-api.js.map
@@ -0,0 +1,18 @@
1
+ export declare class DeployIdentityError extends Error {
2
+ }
3
+ interface DeployScope {
4
+ company?: string;
5
+ personal?: boolean;
6
+ }
7
+ interface IdentityOptions {
8
+ personOnly?: boolean;
9
+ companion?: boolean;
10
+ }
11
+ type SendDeployRequest = (bearer: string, headers: Record<string, string>) => Promise<Response>;
12
+ type ScopedRequest = (send: SendDeployRequest, options?: {
13
+ recoverUnauthorized?: boolean;
14
+ }) => Promise<Response>;
15
+ /** Pin the selected principal and scope for the lifetime of a deploy command. */
16
+ export declare function openDeployIdentity(scope: DeployScope, options?: IdentityOptions): Promise<ScopedRequest>;
17
+ export {};
18
+ //# sourceMappingURL=deploy-identity.d.ts.map
@@ -0,0 +1,179 @@
1
+ import { delegatedMachineSessionFilePath, loadDelegatedMachineSession, loadMachineCreds, mintMachineTokens, } from "@indigoai-us/hq-cloud";
2
+ import { DEFAULT_COGNITO, cognitoSubjectFromToken, ensureCognitoIdToken, ensureCognitoToken, ensureMachineSessionTokens, isMachineCredsFileEnvSet, loadCachedTokens, refreshActivePersonTokens, resolveCognitoTokenSource, withMachineTokenStateDir, } from "../utils/cognito-session.js";
3
+ import { decodeJwtPayload } from "../utils/person-token-cache.js";
4
+ export class DeployIdentityError extends Error {
5
+ }
6
+ const PERSON = { tokenSource: "person", interactive: false };
7
+ const PERSON_REJECTED = "The deploy service rejected your sign-in. Run hq login and try again.";
8
+ const MACHINE_REJECTED = "The deploy service rejected the configured machine identity. Check its enrollment and company scope.";
9
+ const DELEGATED_REJECTED = "The deploy service rejected the delegated identity. Restart the Outpost job with a fresh session.";
10
+ function sameSubject(first, second, companion = false) {
11
+ const original = cognitoSubjectFromToken(first);
12
+ const next = cognitoSubjectFromToken(second);
13
+ const originalClaims = decodeJwtPayload(first);
14
+ const nextClaims = decodeJwtPayload(second);
15
+ const issuer = originalClaims?.iss;
16
+ if (original.sub === null || original.sub !== next.sub
17
+ || typeof issuer !== "string" || !issuer || issuer !== nextClaims?.iss) {
18
+ return false;
19
+ }
20
+ // The deploy producer uses the delegated operator when authorizing an Outpost.
21
+ if (originalClaims?.["custom:delegatedSub"] !== nextClaims?.["custom:delegatedSub"])
22
+ return false;
23
+ if (companion) {
24
+ return original.entityUid === next.entityUid || !original.entityUid || !next.entityUid;
25
+ }
26
+ return original.entityUid === next.entityUid
27
+ && originalClaims?.["custom:entityType"] === nextClaims?.["custom:entityType"];
28
+ }
29
+ function validateCredentials(credentials, companion) {
30
+ const issuer = decodeJwtPayload(credentials.bearer)?.iss;
31
+ if (!cognitoSubjectFromToken(credentials.bearer).sub || typeof issuer !== "string" || !issuer) {
32
+ throw new DeployIdentityError("Could not identify the HQ deploy session.");
33
+ }
34
+ if (companion && (!credentials.companion || !sameSubject(credentials.bearer, credentials.companion, true))) {
35
+ throw new DeployIdentityError("Deploy and HQ Pro sign-ins must belong to the same person. Run hq login and try again.");
36
+ }
37
+ return credentials;
38
+ }
39
+ function scopeHeaders(scope) {
40
+ if ((scope.company !== undefined) === (scope.personal === true)) {
41
+ throw new DeployIdentityError("Choose exactly one of --company <slug> or --personal.");
42
+ }
43
+ if (scope.company === undefined)
44
+ return { "X-HQ-Deploy-Scope": "personal" };
45
+ if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(scope.company)) {
46
+ throw new DeployIdentityError("Invalid company slug.");
47
+ }
48
+ return { "X-Org-Slug": scope.company };
49
+ }
50
+ function machineIdentityRequired() {
51
+ return [process.env.HQ_REQUIRE_MACHINE_IDENTITY, process.env.HQ_MACHINE_AUTH_REQUIRED]
52
+ .some((value) => ["1", "true", "yes"].includes(value?.trim().toLowerCase() ?? ""));
53
+ }
54
+ function personSource(includeCompanion) {
55
+ return {
56
+ rejected: PERSON_REJECTED,
57
+ async load() {
58
+ try {
59
+ const bearer = await ensureCognitoToken(PERSON);
60
+ return includeCompanion ? { bearer, companion: await ensureCognitoIdToken(PERSON) } : { bearer };
61
+ }
62
+ catch {
63
+ throw new DeployIdentityError("Could not get an HQ sign-in for hq-deploy. Run hq login and try again.");
64
+ }
65
+ },
66
+ async recover(current) {
67
+ if (delegatedMachineSessionFilePath() !== null || machineIdentityRequired() || isMachineCredsFileEnvSet()) {
68
+ throw new DeployIdentityError(PERSON_REJECTED);
69
+ }
70
+ const cached = loadCachedTokens();
71
+ if (!cached || !sameSubject(current.bearer, cached.accessToken))
72
+ throw new DeployIdentityError(PERSON_REJECTED);
73
+ const refreshed = await refreshActivePersonTokens(cached);
74
+ return {
75
+ bearer: refreshed.accessToken,
76
+ ...(includeCompanion ? { companion: refreshed.idToken } : {}),
77
+ };
78
+ },
79
+ };
80
+ }
81
+ function machineKey(creds) {
82
+ return JSON.stringify([
83
+ creds.username, creds.entityType, creds.entityUid, creds.clientId, creds.region,
84
+ creds.runtime, creds.hostKeyPath, creds.apiBaseUrl,
85
+ ]);
86
+ }
87
+ function machineSource() {
88
+ const creds = loadMachineCreds();
89
+ if (!creds || creds.delegated)
90
+ throw new DeployIdentityError(MACHINE_REJECTED);
91
+ const pinned = machineKey(creds);
92
+ function selectedMachine() {
93
+ const current = loadMachineCreds();
94
+ if (!current || current.delegated || machineKey(current) !== pinned) {
95
+ throw new DeployIdentityError(MACHINE_REJECTED);
96
+ }
97
+ return current;
98
+ }
99
+ return {
100
+ rejected: MACHINE_REJECTED,
101
+ async load() {
102
+ try {
103
+ const { idToken } = await ensureMachineSessionTokens();
104
+ selectedMachine();
105
+ if (creds.entityUid && cognitoSubjectFromToken(idToken).entityUid !== creds.entityUid) {
106
+ throw new DeployIdentityError(MACHINE_REJECTED);
107
+ }
108
+ return { bearer: idToken };
109
+ }
110
+ catch {
111
+ throw new DeployIdentityError(MACHINE_REJECTED);
112
+ }
113
+ },
114
+ async recover() {
115
+ const refreshed = await withMachineTokenStateDir(() => mintMachineTokens(DEFAULT_COGNITO, selectedMachine()));
116
+ selectedMachine();
117
+ return { bearer: refreshed.idToken };
118
+ },
119
+ };
120
+ }
121
+ function delegatedSource(path) {
122
+ async function load() {
123
+ const session = delegatedMachineSessionFilePath() === path ? loadDelegatedMachineSession() : null;
124
+ if (!session || session.expiresAt <= Date.now()
125
+ || cognitoSubjectFromToken(session.idToken).entityUid !== session.entityUid) {
126
+ throw new DeployIdentityError("The delegated Outpost session is missing, invalid, or expired. Restart the Outpost job.");
127
+ }
128
+ return { bearer: session.idToken };
129
+ }
130
+ return { load, recover: load, rejected: DELEGATED_REJECTED };
131
+ }
132
+ /** Pin the selected principal and scope for the lifetime of a deploy command. */
133
+ export async function openDeployIdentity(scope, options = {}) {
134
+ const headers = scopeHeaders(scope);
135
+ const delegation = delegatedMachineSessionFilePath();
136
+ const machine = delegation !== null || machineIdentityRequired() || isMachineCredsFileEnvSet()
137
+ || resolveCognitoTokenSource() === "machine";
138
+ if (machine && (options.personOnly || options.companion)) {
139
+ throw new DeployIdentityError("This deploy operation requires a person identity. Sign in as the authorized operator.");
140
+ }
141
+ if (machine && scope.personal) {
142
+ throw new DeployIdentityError("Personal deploy scope requires a person identity. Choose an authorized company scope for a machine deploy.");
143
+ }
144
+ const companion = options.companion === true;
145
+ const source = delegation !== null ? delegatedSource(delegation)
146
+ : machine ? machineSource() : personSource(companion);
147
+ let credentials = validateCredentials(await source.load(), companion);
148
+ let recovered = false;
149
+ return async (send, { recoverUnauthorized = true } = {}) => {
150
+ const request = (auth) => send(auth.bearer, {
151
+ ...headers,
152
+ ...(auth.companion ? { "X-HQ-Pro-Authorization": "Bearer " + auth.companion } : {}),
153
+ });
154
+ const prior = credentials;
155
+ const rejected = await request(prior);
156
+ if (rejected.status !== 401)
157
+ return rejected;
158
+ void rejected.body?.cancel().catch(() => undefined);
159
+ if (!recoverUnauthorized || recovered)
160
+ throw new DeployIdentityError(source.rejected);
161
+ recovered = true;
162
+ try {
163
+ const refreshed = validateCredentials(await source.recover(prior), companion);
164
+ if (refreshed.bearer === prior.bearer || !sameSubject(prior.bearer, refreshed.bearer)) {
165
+ throw new DeployIdentityError(source.rejected);
166
+ }
167
+ credentials = refreshed;
168
+ }
169
+ catch {
170
+ throw new DeployIdentityError(source.rejected);
171
+ }
172
+ const response = await request(credentials);
173
+ if (response.status !== 401)
174
+ return response;
175
+ void response.body?.cancel().catch(() => undefined);
176
+ throw new DeployIdentityError(source.rejected);
177
+ };
178
+ }
179
+ //# sourceMappingURL=deploy-identity.js.map
@@ -17,12 +17,15 @@ import * as fs from "node:fs";
17
17
  import * as path from "node:path";
18
18
  import { assertNotIntegrationSecretsPath, personDirName } from "./cursors.js";
19
19
  import { writeFileAtomic } from "./landing.js";
20
- import { CLAUDE_SIGNED_OUT_TEXT, CODEX_BOT_NEEDS_CLAUDE_TEXT, CODEX_SIGNED_OUT_TEXT } from "./signals-pass.js";
21
- const CODEX_BOT_NEEDS_CLAUDE_CODE = "claude-logged-out-codex-bot";
22
- const CLAUDE_SIGNED_OUT_CODE = "claude-logged-out";
23
- const CODEX_SIGNED_OUT_CODE = "codex-logged-out";
20
+ import { BOT_SIGNED_OUT_TEXT, BOT_API_KEY_TEXT, CLAUDE_SIGNED_OUT_TEXT, CODEX_BOT_NEEDS_CLAUDE_TEXT, CODEX_SIGNED_OUT_TEXT } from "./signals-pass.js";
21
+ import * as passFailure from "./signals-pass-failure.js";
22
+ // The codes live in a module with no imports, so the signals engine's adapters
23
+ // step can read them without loading this one. Typed here as pass codes.
24
+ const CODEX_BOT_NEEDS_CLAUDE_CODE = passFailure.CODEX_BOT_NEEDS_CLAUDE_CODE;
25
+ const CLAUDE_SIGNED_OUT_CODE = passFailure.CLAUDE_SIGNED_OUT_CODE;
26
+ const CODEX_SIGNED_OUT_CODE = passFailure.CODEX_SIGNED_OUT_CODE;
24
27
  /** Pass failures that mean the tool signals run on (Claude Code, or a Codex bot's Codex) is signed out or missing on this computer. */
25
- export const SIGNED_OUT_SIGNALS_CODES = new Set([CLAUDE_SIGNED_OUT_CODE, CODEX_BOT_NEEDS_CLAUDE_CODE, CODEX_SIGNED_OUT_CODE]);
28
+ export const SIGNED_OUT_SIGNALS_CODES = passFailure.SIGNED_OUT_SIGNALS_CODES;
26
29
  /** A failed ledger line whose pass found its tool signed out. */
27
30
  export function isSignedOutSignalsFailure(entry) {
28
31
  return entry.status === "failed" && entry.error !== null && SIGNED_OUT_SIGNALS_CODES.has(entry.error);
@@ -67,7 +70,11 @@ export function formatSignalsFailureAlert(entry, options = {}) {
67
70
  if (entry.error)
68
71
  lines.push(`Error: ${entry.error}`);
69
72
  // Name the tool the pass ran on, and how to fix it on this computer.
70
- if (entry.error === CODEX_BOT_NEEDS_CLAUDE_CODE)
73
+ if (entry.error === "bot-logged-out")
74
+ lines.push(BOT_SIGNED_OUT_TEXT);
75
+ else if (entry.error === "bot-api-key-login")
76
+ lines.push(BOT_API_KEY_TEXT);
77
+ else if (entry.error === CODEX_BOT_NEEDS_CLAUDE_CODE)
71
78
  lines.push(CODEX_BOT_NEEDS_CLAUDE_TEXT);
72
79
  else if (entry.error === CLAUDE_SIGNED_OUT_CODE)
73
80
  lines.push(CLAUDE_SIGNED_OUT_TEXT);
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The signals pass on an HQ Fleet Executive bot's own login.
3
+ *
4
+ * An HQ Fleet bot answers chat with the login its runtime resolves for it: its
5
+ * own sign-in, or the person's Claude or ChatGPT subscription sign-in when its
6
+ * login is "default". `hq-fleet-local complete` (hq-fleet-local,
7
+ * single-turn completion) makes one locked-down model turn with exactly that
8
+ * login: prompt on stdin, no tools, memory, context files or session, one
9
+ * request, one JSON object out. It never uses an API key (`api_key_login`).
10
+ *
11
+ * So the pass needs no `claude auth login` of its own: if the bot can chat,
12
+ * signals can run. This is the default for a Claude or Codex Fleet Executive
13
+ * bot. The pass falls back to the `claude` CLI only when the helper is
14
+ * missing: the bot is not a Claude or Codex Fleet bot, its helper is not
15
+ * installed, or the installed helper release has no `complete` command yet.
16
+ *
17
+ * Policy: hq-signals-pass-codex-exec-narrow-exception point 3 (owner decision
18
+ * 2026-11-15, widened to this Fleet turn; owner instruction 2026-11-18 that the
19
+ * turn uses the bot's own login). The turn's lockdown lives in the helper; this
20
+ * module only names the bot and its profile, sends the prompt on stdin, and
21
+ * reads the one JSON line back. The reply text is model output built from the
22
+ * document, so it is parsed and never logged.
23
+ */
24
+ import { type BotConfig } from "../bot/config.js";
25
+ import type { BoundedRun, SignalsFailureClass, SignalsRuntimeId } from "./signals-pass.js";
26
+ /** The bot, profile and helper one Fleet signals turn runs with. */
27
+ export interface FleetCompleteTarget {
28
+ /** `<runtime>/bin/hq-fleet-local` of the bot's installed HQ Fleet runtime. */
29
+ helper: string;
30
+ /** The bot's HQ Fleet profile folder. */
31
+ profileDir: string;
32
+ /** The bot's agent id, as its profile.json names it. */
33
+ botId: string;
34
+ /** Ledger family for failure codes: `codex-*` for a Codex bot, `claude-*` otherwise. */
35
+ runtime: SignalsRuntimeId;
36
+ /** The bot's name, for messages. */
37
+ botName: string;
38
+ }
39
+ /** Largest prompt the helper accepts (its hard limit, 1 MiB). */
40
+ export declare const FLEET_COMPLETE_MAX_PROMPT_BYTES: number;
41
+ /** The error codes `hq-fleet-local complete` prints, each with a fixed message. */
42
+ export type FleetCompleteErrorCode = "invalid_request" | "too_large" | "invalid_profile" | "signed_out" | "api_key_login" | "rate_limited" | "out_of_usage" | "provider_error" | "empty_response" | "timeout" | "runtime_unavailable" | "internal_error";
43
+ export type FleetCompleteResult = {
44
+ kind: "text";
45
+ text: string;
46
+ } | {
47
+ kind: "error";
48
+ code: FleetCompleteErrorCode | "unknown";
49
+ timedOut?: boolean;
50
+ }
51
+ /** The helper cannot run a completion at all: fall back to the `claude` CLI. */
52
+ | {
53
+ kind: "missing";
54
+ reason: string;
55
+ };
56
+ /**
57
+ * The Fleet target for the bot in `dir`, or null when the pass should keep
58
+ * today's `claude` CLI path: no readable bot.json, not an HQ Fleet bot, or its
59
+ * profile, runtime or helper is not installed on this computer.
60
+ */
61
+ export declare function fleetCompleteTargetFor(config: Pick<BotConfig, "name" | "agentUid" | "runtime" | "engine"> | null, deps?: {
62
+ fleetHome?: string;
63
+ platform?: NodeJS.Platform;
64
+ }): FleetCompleteTarget | null;
65
+ /** fleetCompleteTargetFor for the bot folder `dir`, read when the pass asks. */
66
+ export declare function fleetCompleteTarget(dir: string): FleetCompleteTarget | null;
67
+ export type BoundedRunner = (command: string, args: readonly string[], options: {
68
+ timeoutMs: number;
69
+ input?: string;
70
+ cwd?: string;
71
+ env?: NodeJS.ProcessEnv;
72
+ }) => Promise<BoundedRun>;
73
+ /** argv for one completion. The prompt never goes on argv. */
74
+ export declare function fleetCompleteArgs(target: FleetCompleteTarget, timeoutMs: number): string[];
75
+ /**
76
+ * Run one completion. Reads only the helper's single JSON line; stderr is used
77
+ * only to tell an older helper (no `complete` command) from a failure.
78
+ */
79
+ export declare function runFleetComplete(target: FleetCompleteTarget, prompt: string, options: {
80
+ timeoutMs: number;
81
+ env: NodeJS.ProcessEnv;
82
+ cwd: string;
83
+ run: BoundedRunner;
84
+ }): Promise<FleetCompleteResult>;
85
+ /** The pass's failure class for a helper error code. */
86
+ export declare function fleetFailureClass(code: FleetCompleteErrorCode | "unknown"): SignalsFailureClass;
87
+ /** A log-safe message for a helper error: the code and the fix, never provider text. */
88
+ export declare function fleetFailureMessage(target: FleetCompleteTarget, code: FleetCompleteErrorCode | "unknown", detail: string): string;
89
+ //# sourceMappingURL=fleet-complete.d.ts.map