@indigoai-us/hq-cli 5.345.234 → 5.345.235

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 (98) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/command-catalog.generated.d.ts +236 -7
  3. package/dist/command-catalog.generated.js +291 -7
  4. package/dist/command-registration-plan.d.ts +24 -0
  5. package/dist/command-registration-plan.js +4 -0
  6. package/dist/commands/bot-companies.d.ts +4 -1
  7. package/dist/commands/bot-companies.js +5 -1
  8. package/dist/commands/bot.d.ts +10 -0
  9. package/dist/commands/bot.js +165 -36
  10. package/dist/commands/capacity.js +1 -1
  11. package/dist/commands/core-handoff.js +2 -2
  12. package/dist/commands/core-ontology-native.js +5 -4
  13. package/dist/commands/core-pipeline-workflow-runner-native.js +4 -9
  14. package/dist/commands/deploy-app-db.d.ts +3 -0
  15. package/dist/commands/deploy-app-db.js +79 -0
  16. package/dist/commands/deploy-app-upload.d.ts +3 -0
  17. package/dist/commands/deploy-app-upload.js +120 -0
  18. package/dist/commands/deploy-comments.js +46 -1
  19. package/dist/commands/deploy-mutations.js +71 -5
  20. package/dist/commands/deploy-ssr.d.ts +3 -0
  21. package/dist/commands/deploy-ssr.js +74 -0
  22. package/dist/commands/dm.d.ts +7 -1
  23. package/dist/commands/dm.js +39 -9
  24. package/dist/commands/doctor.js +2 -10
  25. package/dist/commands/fingerprint.js +4 -9
  26. package/dist/commands/lanes-accounts.js +5 -5
  27. package/dist/commands/lanes-hold.js +1 -1
  28. package/dist/commands/lanes-message.js +3 -3
  29. package/dist/commands/lanes-move.js +1 -1
  30. package/dist/commands/lanes-resume.js +6 -6
  31. package/dist/commands/lanes-watch.js +2 -2
  32. package/dist/commands/lanes.js +21 -21
  33. package/dist/commands/work-env.d.ts +90 -0
  34. package/dist/commands/work-env.js +304 -0
  35. package/dist/lazy-commands.js +2 -10
  36. package/dist/lib/bot/api.d.ts +27 -0
  37. package/dist/lib/bot/api.js +28 -2
  38. package/dist/lib/bot/cloud-create.d.ts +46 -0
  39. package/dist/lib/bot/cloud-create.js +128 -0
  40. package/dist/lib/bot/fleet-daemon.js +4 -1
  41. package/dist/lib/bot/fleet-local.d.ts +7 -0
  42. package/dist/lib/bot/fleet-local.js +39 -3
  43. package/dist/lib/bot/fleet-owner-companies.js +2 -2
  44. package/dist/lib/bot/promote.d.ts +81 -2
  45. package/dist/lib/bot/promote.js +425 -51
  46. package/dist/lib/bot/promotion-hold.d.ts +9 -0
  47. package/dist/lib/bot/promotion-hold.js +29 -0
  48. package/dist/lib/bot/promotion-receipt.d.ts +10 -0
  49. package/dist/lib/bot/promotion-receipt.js +41 -1
  50. package/dist/lib/bot/promotion-upload.d.ts +6 -1
  51. package/dist/lib/bot/promotion-upload.js +3 -1
  52. package/dist/lib/bot/readiness.d.ts +9 -0
  53. package/dist/lib/bot/readiness.js +16 -0
  54. package/dist/lib/capacity/route.js +4 -4
  55. package/dist/lib/capacity/sign-in.js +1 -1
  56. package/dist/lib/checkpoint-ontology/entity-file.js +15 -17
  57. package/dist/lib/daemon/catalog.d.ts +2 -0
  58. package/dist/lib/daemon/catalog.js +2 -0
  59. package/dist/lib/daemon/hook-requests.js +23 -3
  60. package/dist/lib/daemon/run.d.ts +14 -0
  61. package/dist/lib/daemon/run.js +24 -14
  62. package/dist/lib/deploy-api.d.ts +2 -0
  63. package/dist/lib/deploy-api.js +9 -0
  64. package/dist/lib/environment/work-requirements.js +1 -1
  65. package/dist/lib/hot-channels/signals-pass.d.ts +0 -76
  66. package/dist/lib/hot-channels/signals-pass.js +81 -4
  67. package/dist/lib/lanes/account-company.js +1 -1
  68. package/dist/lib/lanes/account-ownership.js +1 -1
  69. package/dist/lib/lanes/accounts.js +1 -1
  70. package/dist/lib/lanes/delivery.js +7 -7
  71. package/dist/lib/lanes/dropbox.js +1 -1
  72. package/dist/lib/lanes/grants.js +3 -3
  73. package/dist/lib/lanes/hq-root.js +1 -1
  74. package/dist/lib/lanes/keep-alive-audit.js +2 -2
  75. package/dist/lib/lanes/links.js +4 -4
  76. package/dist/lib/lanes/monitor.js +3 -3
  77. package/dist/lib/lanes/quota-notice.js +1 -1
  78. package/dist/lib/lanes/reconcile.js +22 -12
  79. package/dist/lib/lanes/signal-brief-template.js +1 -1
  80. package/dist/lib/lanes/worker-continuity.js +1 -1
  81. package/dist/lib/mesh/live/direct-drain.d.ts +1 -0
  82. package/dist/lib/mesh/live/direct-drain.js +12 -1
  83. package/dist/lib/mesh/live/emit.d.ts +1 -1
  84. package/dist/lib/mesh/live/emit.js +10 -5
  85. package/dist/lib/mesh/live/flush.js +19 -4
  86. package/dist/lib/mesh/live/reporting-privacy.d.ts +9 -3
  87. package/dist/lib/mesh/live/reporting-privacy.js +27 -7
  88. package/dist/lib/mesh/live/spool.d.ts +2 -0
  89. package/dist/lib/mesh/live/spool.js +41 -0
  90. package/dist/lib/signals/sanitize.js +5 -4
  91. package/dist/lib/signals/steps/garden.js +5 -4
  92. package/dist/utils/frontmatter.d.ts +8 -0
  93. package/dist/utils/frontmatter.js +11 -2
  94. package/dist/utils/hq-roots-core.d.ts +5 -0
  95. package/dist/utils/hq-roots-core.js +18 -9
  96. package/dist/utils/owner-session.d.ts +13 -0
  97. package/dist/utils/owner-session.js +28 -0
  98. package/package.json +7 -7
@@ -136,8 +136,46 @@ async function readAction(appNameOrId, commentId, company) {
136
136
  throw new DeployCommentsError(`Comment '${displayText(commentId)}' was not found on that app.`);
137
137
  console.log(safeJson(comment));
138
138
  }
139
+ async function toggleAction(appId, mode, options) {
140
+ if (mode !== "on" && mode !== "off")
141
+ throw new DeployCommentsError("Choose on or off.");
142
+ if (!/^(?:[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}|app_[A-Za-z0-9_-]+)$/i.test(appId)) {
143
+ throw new DeployCommentsError("Use the app ID shown by hq deploy list.");
144
+ }
145
+ if (Boolean(options.company) === Boolean(options.personal)) {
146
+ throw new DeployCommentsError("Choose exactly one of --company <slug> or --personal.");
147
+ }
148
+ const orgHeaders = options.personal ? { "X-HQ-Deploy-Scope": "personal" } : callerOrgHeaders(options.company);
149
+ const token = await ensureCognitoToken().catch(() => {
150
+ throw new DeployCommentsError("Could not get an HQ sign-in. Run hq login and retry.");
151
+ });
152
+ const commentsEnabled = mode === "on";
153
+ let response;
154
+ try {
155
+ response = await deployApiRequest(token, `/api/apps/${encodeURIComponent(appId)}`, "PATCH", { commentsEnabled }, orgHeaders);
156
+ }
157
+ catch {
158
+ throw new DeployCommentsError("Could not confirm the comments setting. Check your connection and retry.");
159
+ }
160
+ if (!response.ok) {
161
+ const prefix = `Could not change the app's comments setting (HTTP ${response.status}).`;
162
+ switch (response.status) {
163
+ case 401:
164
+ throw new DeployCommentsError(`${prefix} Run hq login and retry.`);
165
+ case 403:
166
+ throw new DeployCommentsError(`${prefix} Check your scope or ask the app owner or an org admin to make the change.`);
167
+ case 404:
168
+ throw new DeployCommentsError(`${prefix} Run hq deploy list to check the app ID and scope.`);
169
+ case 429:
170
+ throw new DeployCommentsError(`${prefix} Wait a moment and try again.`);
171
+ default:
172
+ throw new DeployCommentsError(`${prefix} Try again in a moment.`);
173
+ }
174
+ }
175
+ console.log(options.json ? safeJson({ appId, commentsEnabled }) : `Comments turned ${mode} for ${appId}.`);
176
+ }
139
177
  export function registerDeployCommentsCommand(deploy) {
140
- const comments = deploy.command("comments").description("List and read comments on your deployed apps");
178
+ const comments = deploy.command("comments").description("Read and configure comments on your deployed apps");
141
179
  comments
142
180
  .command("list <app>")
143
181
  .description("List comments on an app in your org")
@@ -150,5 +188,12 @@ export function registerDeployCommentsCommand(deploy) {
150
188
  .description("Read a comment on an app in your org")
151
189
  .option("--company <slug>", "use this company instead of the active company")
152
190
  .action((app, commentId, options) => run(() => readAction(app, commentId, options.company)));
191
+ comments
192
+ .command("toggle <app-id> <mode>")
193
+ .description("Turn app comments on or off by app ID")
194
+ .option("--company <slug>", "company owning the app")
195
+ .option("--personal", "use personal scope")
196
+ .option("--json", "print the updated comments setting as JSON")
197
+ .action((appId, mode, options) => run(() => toggleAction(appId, mode, options)));
153
198
  }
154
199
  //# sourceMappingURL=deploy-comments.js.map
@@ -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 { findDeployApp } from "../lib/deploy-apps.js";
4
5
  import { ensureCognitoToken } from "../utils/cognito-session.js";
5
6
  import { displayText } from "./deploy-comments.js";
6
7
  class DeployMutationError extends Error {
@@ -17,6 +18,17 @@ function id(value) {
17
18
  throw new DeployMutationError("Invalid app or deployment identifier.");
18
19
  return encodeURIComponent(value);
19
20
  }
21
+ async function resolveAppId(token, app, context) {
22
+ // The service issues UUIDs. The deploy CLI also accepts legacy app_ IDs.
23
+ if (/^(?:[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}|app_[A-Za-z0-9_-]+)$/i.test(app))
24
+ return app;
25
+ const match = await findDeployApp(app, (route) => request(token, route, "GET", undefined, context));
26
+ if (match.kind === "none")
27
+ throw new DeployMutationError(`No deploy app '${displayText(app)}' in the selected scope.`);
28
+ if (match.kind === "many")
29
+ throw new DeployMutationError(`'${displayText(app)}' matches ${match.ids.length} apps. Use the app id.`);
30
+ return match.id;
31
+ }
20
32
  async function signIn() {
21
33
  try {
22
34
  return await ensureCognitoToken();
@@ -60,6 +72,16 @@ function requiredText(record, key) {
60
72
  throw new DeployMutationError(`hq-deploy response is missing ${key}.`);
61
73
  return record[key];
62
74
  }
75
+ function deploymentMetadata(row, idKey) {
76
+ if (typeof row !== "object" || row === null)
77
+ throw new DeployMutationError("hq-deploy returned an invalid deployment row.");
78
+ const record = row;
79
+ return {
80
+ [idKey]: requiredText(record, idKey),
81
+ status: requiredText(record, "status"),
82
+ createdAt: requiredText(record, "createdAt"),
83
+ };
84
+ }
63
85
  function output(value, options, text = "Deploy operation completed.") {
64
86
  console.log(options.json ? JSON.stringify(value) : text);
65
87
  }
@@ -78,11 +100,53 @@ function action(fn) {
78
100
  };
79
101
  }
80
102
  export function registerDeployMutationsCommand(deploy) {
81
- scope(deploy.command("inspect <app>").description("Read app access mode, password protection and private mode state"))
103
+ scope(deploy.command("inspect <app>").description("Read app access state by id, exact name or subdomain"))
104
+ .action(action(async (app, options) => {
105
+ const context = headers(options);
106
+ const token = await signIn();
107
+ const appId = await resolveAppId(token, app, context);
108
+ const record = await request(token, `/api/apps/${id(appId)}`, "GET", undefined, context);
109
+ output({ id: appId, accessMode: record.accessMode ?? null, passwordProtected: record.passwordProtected === true, privateMode: record.privateMode === true }, options);
110
+ }));
111
+ scope(deploy.command("app-info <app>").description("Read deploy app identity and access metadata"))
112
+ .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);
117
+ if (record.id !== appId)
118
+ throw new DeployMutationError("hq-deploy returned a different app id.");
119
+ const subdomain = requiredText(record, "subdomain");
120
+ const metadata = { id: appId, subdomain };
121
+ for (const key of ["name", "type", "url", "createdAt", "status", "accessMode", "title", "deployId"]) {
122
+ if (typeof record[key] === "string")
123
+ metadata[key] = record[key];
124
+ }
125
+ for (const key of ["active", "passwordProtected", "privateMode", "database"]) {
126
+ if (typeof record[key] === "boolean")
127
+ metadata[key] = record[key];
128
+ }
129
+ if (record.accessMode === null)
130
+ metadata.accessMode = null;
131
+ output(metadata, options, `App ${displayText(subdomain)} (${appId}).`);
132
+ }));
133
+ scope(deploy.command("history <app>").description("Read deployment history for one app"))
82
134
  .action(action(async (app, options) => {
83
135
  const context = headers(options);
84
- const record = await request(await signIn(), `/api/apps/${id(app)}`, "GET", undefined, context);
85
- output({ id: app, accessMode: record.accessMode ?? null, passwordProtected: record.passwordProtected === true, privateMode: record.privateMode === true }, 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);
139
+ if (record.appId !== appId)
140
+ throw new DeployMutationError("hq-deploy returned a different app id.");
141
+ if (Array.isArray(record.deploys)) {
142
+ const deploys = record.deploys.map((row) => deploymentMetadata(row, "id"));
143
+ output({ appId, deploys }, options, `App ${appId} has ${deploys.length} deployment(s).`);
144
+ return;
145
+ }
146
+ if (record.deploymentModel !== "single-live")
147
+ throw new DeployMutationError("hq-deploy returned invalid deployment history.");
148
+ const currentDeployment = deploymentMetadata(record.currentDeployment, "deploymentId");
149
+ output({ appId, deploymentModel: "single-live", currentDeployment }, options, `App ${appId} has one live deployment.`);
86
150
  }));
87
151
  scope(deploy.command("create <name>").description("Create a deploy app").option("--type <type>", "static, app or ssr", "static"))
88
152
  .action(action(async (name, options) => {
@@ -94,10 +158,12 @@ export function registerDeployMutationsCommand(deploy) {
94
158
  const appUrl = typeof created.url === "string" && created.url ? created.url : "not returned";
95
159
  output(created, options, `Created app ${displayText(appId)}. URL: ${displayText(appUrl)}`);
96
160
  }));
97
- scope(deploy.command("takedown <app>").description("Deactivate a deploy app"))
161
+ scope(deploy.command("takedown <app>").description("Deactivate a deploy app by id, exact name or subdomain"))
98
162
  .action(action(async (app, options) => {
99
163
  const context = headers(options);
100
- await request(await signIn(), `/api/apps/${id(app)}`, "PATCH", { active: false }, context);
164
+ const token = await signIn();
165
+ const appId = await resolveAppId(token, app, context);
166
+ await request(token, `/api/apps/${id(appId)}`, "PATCH", { active: false }, context);
101
167
  output({ app, active: false }, options);
102
168
  }));
103
169
  scope(deploy.command("password-gate <app>").description("Set a password gate using a file").requiredOption("--password-file <path>", "file containing the password"))
@@ -0,0 +1,3 @@
1
+ import type { Command } from "commander";
2
+ export declare function registerDeploySsrCommand(deploy: Command): void;
3
+ //# sourceMappingURL=deploy-ssr.d.ts.map
@@ -0,0 +1,74 @@
1
+ import { deployApiRequest } from "../lib/deploy-api.js";
2
+ import { ensureCognitoToken } from "../utils/cognito-session.js";
3
+ class RegisterSsrError extends Error {
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
+ async function register(appId, imageTag, options) {
17
+ const headers = scopeHeaders(options);
18
+ if (!/^(?:[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}|app_[A-Za-z0-9_-]+)$/i.test(appId)) {
19
+ throw new RegisterSsrError("Use the app ID shown by hq deploy list.");
20
+ }
21
+ if (!/^(?:[a-z0-9][a-z0-9._-]*\/)*[a-z0-9][a-z0-9._-]*:[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(imageTag)) {
22
+ throw new RegisterSsrError("Give the existing ECR image in repository:tag form.");
23
+ }
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
+ });
32
+ if (response.status !== 202) {
33
+ const prefix = `hq-deploy did not confirm SSR registration (HTTP ${response.status}).`;
34
+ switch (response.status) {
35
+ case 401:
36
+ throw new RegisterSsrError(`${prefix} Run hq login and try again.`);
37
+ case 403:
38
+ throw new RegisterSsrError(`${prefix} Check your app scope or ask the app owner or an org admin.`);
39
+ case 404:
40
+ throw new RegisterSsrError(`${prefix} Check the app ID, scope, and ECR image reference.`);
41
+ default:
42
+ throw new RegisterSsrError(`${prefix} Check deployment history before trying again.`);
43
+ }
44
+ }
45
+ const receipt = await response.json().catch(() => null);
46
+ const { deployId, version, statusUrl } = receipt ?? {};
47
+ if (typeof deployId !== "string" || !/^[A-Za-z0-9_-]+$/.test(deployId)
48
+ || typeof version !== "number" || !Number.isSafeInteger(version) || version < 1
49
+ || statusUrl !== `${appRoute}/deploys/${deployId}`) {
50
+ throw new RegisterSsrError("hq-deploy returned an invalid acceptance receipt. Check deployment history before trying again.");
51
+ }
52
+ console.log(options.json
53
+ ? JSON.stringify({ deployId, version, statusUrl })
54
+ : `SSR deployment accepted for ${appId} (deployment ${deployId}, version ${version}).`);
55
+ }
56
+ export function registerDeploySsrCommand(deploy) {
57
+ deploy.command("register-ssr <app-id> <image-tag>")
58
+ .description("Register an existing ECR image for an SSR deployment")
59
+ .option("--company <slug>", "company owning the app")
60
+ .option("--personal", "use personal scope")
61
+ .option("--json", "print the acceptance receipt as JSON")
62
+ .action(async (appId, imageTag, options) => {
63
+ try {
64
+ await register(appId, imageTag, options);
65
+ }
66
+ catch (error) {
67
+ console.error(error instanceof RegisterSsrError
68
+ ? error.message
69
+ : "Could not confirm SSR registration. Check deployment history before trying again.");
70
+ process.exitCode = 1;
71
+ }
72
+ });
73
+ }
74
+ //# sourceMappingURL=deploy-ssr.js.map
@@ -208,6 +208,12 @@ export declare function buildDmBody(args: {
208
208
  * server holds without delivering files.
209
209
  */
210
210
  export declare function resolveDmPeerUid(token: string, recipient: string): Promise<string>;
211
+ /**
212
+ * Error text for an agent's `hq dm thread` read. The agent route has its own
213
+ * refusals (hq-pro-core 1.165.0): 403 when the server predates it or the route
214
+ * is closed, 400 for a bad peer or cursor. 404 keeps the shared text. Pure.
215
+ */
216
+ export declare function agentThreadError(status: number, code: string | undefined, fallback: string): string;
211
217
  /** A pending incoming connection request, as returned by the backend. */
212
218
  export interface ConnectionRequest {
213
219
  pairKey: string;
@@ -442,7 +448,7 @@ export declare function formatChannelTranscript(messages: ChannelMessageItem[],
442
448
  * GET /v1/agents/{uid}/inbox.
443
449
  */
444
450
  export declare function agentCallerUid(token: string, machine?: () => boolean): string | null;
445
- export declare const AGENT_THREAD_UNAVAILABLE: string;
451
+ export declare const AGENT_THREAD_NEEDS_UID: string;
446
452
  /**
447
453
  * Where to write each downloaded attachment. One file and an `--out` that is
448
454
  * not an existing directory: write exactly there. Otherwise `--out` (default
@@ -456,6 +456,23 @@ function friendlyDmError(status, code, fallback) {
456
456
  return `Server error: ${fallback}`;
457
457
  return fallback;
458
458
  }
459
+ /**
460
+ * Error text for an agent's `hq dm thread` read. The agent route has its own
461
+ * refusals (hq-pro-core 1.165.0): 403 when the server predates it or the route
462
+ * is closed, 400 for a bad peer or cursor. 404 keeps the shared text. Pure.
463
+ */
464
+ export function agentThreadError(status, code, fallback) {
465
+ if (status === 403) {
466
+ return "Your agent token cannot read this thread (needs hq-pro-core 1.165.0 or later on the server, and a peer in a company you share). Use `hq dm inbox` for new messages.";
467
+ }
468
+ if (status === 400 && code === "AGENT_THREAD_PEER_UID_REQUIRED") {
469
+ return AGENT_THREAD_NEEDS_UID;
470
+ }
471
+ if (status === 400 && code === "INVALID_CURSOR") {
472
+ return "The thread cursor was rejected as invalid. Re-run without a cursor.";
473
+ }
474
+ return friendlyDmError(status, code, fallback);
475
+ }
459
476
  function friendlyForwardError(code) {
460
477
  switch (code) {
461
478
  case "FORWARD_SOURCE_NOT_FOUND":
@@ -1542,8 +1559,8 @@ export function agentCallerUid(token, machine = isMachineIdentity) {
1542
1559
  return null;
1543
1560
  }
1544
1561
  }
1545
- export const AGENT_THREAD_UNAVAILABLE = "`hq dm thread` reads /v1/notify/thread, which is not available to agent identities. " +
1546
- "Use `hq dm inbox` — for agents it reads GET /v1/agents/{uid}/inbox.";
1562
+ export const AGENT_THREAD_NEEDS_UID = "An agent reads its 1:1 thread by uid: pass the peer's personUid or agentUid (prs_… / agt_…), " +
1563
+ "not an email. Resolve one with `hq people resolve`.";
1547
1564
  /** One-line summary of an agent inbox item (DM, email, … — shapes vary by channel). Pure. */
1548
1565
  function formatAgentInboxItem(item) {
1549
1566
  const str = (k) => (typeof item[k] === "string" ? item[k] : "");
@@ -1788,8 +1805,13 @@ async function runDmThread(identifier, opts) {
1788
1805
  if (opts.limit)
1789
1806
  query.limit = opts.limit;
1790
1807
  const token = await ensureCognitoToken();
1791
- if (agentCallerUid(token)) {
1792
- console.error(chalk.yellow(AGENT_THREAD_UNAVAILABLE));
1808
+ // An agent token may read GET /v1/notify/thread only for its own 1:1
1809
+ // conversation, and only when the peer is named by uid (the server returns
1810
+ // 400 for withEmail). It cannot call POST /v1/notify/thread/read, so it
1811
+ // never acks.
1812
+ const isAgent = agentCallerUid(token) !== null;
1813
+ if (isAgent && !query.withPersonUid) {
1814
+ console.error(chalk.yellow(AGENT_THREAD_NEEDS_UID));
1793
1815
  process.exit(1);
1794
1816
  }
1795
1817
  const res = await vaultApiFetch({
@@ -1799,15 +1821,20 @@ async function runDmThread(identifier, opts) {
1799
1821
  });
1800
1822
  if (!res.ok) {
1801
1823
  const err = (await res.json().catch(() => ({})));
1802
- console.error(chalk.red(friendlyDmError(res.status, err.code, err.error ?? err.message ?? res.statusText)));
1824
+ const detail = err.error ?? err.message ?? res.statusText;
1825
+ console.error(chalk.red(isAgent
1826
+ ? agentThreadError(res.status, err.code, detail)
1827
+ : friendlyDmError(res.status, err.code, detail)));
1803
1828
  process.exit(1);
1804
1829
  }
1805
1830
  const data = (await res.json());
1831
+ const truncated = data.scanTruncated === true;
1806
1832
  const messages = data.messages ?? [];
1807
1833
  // The server returns newest-first; read a conversation oldest-first.
1808
1834
  const ordered = [...messages].reverse();
1809
1835
  if (opts.json) {
1810
- console.log(JSON.stringify(ordered, null, 2));
1836
+ // A partial read keeps the flag in the output; a complete read stays a bare array.
1837
+ console.log(JSON.stringify(truncated ? { messages: ordered, scanTruncated: true } : ordered, null, 2));
1811
1838
  }
1812
1839
  else if (ordered.length === 0) {
1813
1840
  console.log(chalk.dim(`No messages with ${identifier} yet.`));
@@ -1818,10 +1845,13 @@ async function runDmThread(identifier, opts) {
1818
1845
  for (const m of ordered)
1819
1846
  console.log(`\n${formatThreadMessage(m, now)}`);
1820
1847
  }
1848
+ if (truncated && !opts.json) {
1849
+ console.log(chalk.dim("\nPartial thread: the server stopped scanning early, so older messages may be missing."));
1850
+ }
1821
1851
  // Mark the incoming messages read unless the caller opted out. Best-effort:
1822
1852
  // a read is a side effect, not the point of the command, so an ack failure
1823
1853
  // is surfaced but does not fail the read.
1824
- if (opts.ack !== false) {
1854
+ if (opts.ack !== false && !isAgent) {
1825
1855
  const inIds = messages
1826
1856
  .filter((m) => m.direction === "in")
1827
1857
  .map((m) => m.eventId)
@@ -2001,9 +2031,9 @@ export function registerDmCommand(program) {
2001
2031
  dm
2002
2032
  .command("thread <person>")
2003
2033
  .alias("read")
2004
- .description("Show your two-way conversation with a person (email, personUid, or agentUid). Reads oldest-first and marks their messages read unless --no-ack.")
2034
+ .description("Show your two-way conversation with a person (email, personUid, or agentUid). Reads oldest-first and marks their messages read unless --no-ack (agents never mark read).")
2005
2035
  .option("--limit <n>", "Max messages to fetch (server-capped)")
2006
- .option("--no-ack", "Do not mark the incoming messages as read")
2036
+ .option("--no-ack", "Do not mark the incoming messages as read (agents never mark read)")
2007
2037
  .option("--json", "Output raw JSON instead of a transcript")
2008
2038
  .action(async (person, opts) => {
2009
2039
  await runDmThread(person, opts);
@@ -21,6 +21,7 @@
21
21
  * The detected platform is a placeholder (UNKNOWN_PLATFORM) until host platform
22
22
  * detection (US-003) lands and injects the real value through `platform`.
23
23
  */
24
+ import { findHqRootAncestor } from "../utils/hq-roots-core.js";
24
25
  import * as fs from "node:fs";
25
26
  import * as path from "node:path";
26
27
  import { Option } from "commander";
@@ -64,16 +65,7 @@ export function resolveHqRoot(startDir = process.cwd()) {
64
65
  catch {
65
66
  dir = path.resolve(startDir);
66
67
  }
67
- // Walk to the filesystem root. `path.dirname("/") === "/"` is the loop's
68
- // terminal fixed point.
69
- for (;;) {
70
- if (isHqRoot(dir))
71
- return dir;
72
- const parent = path.dirname(dir);
73
- if (parent === dir)
74
- return null;
75
- dir = parent;
76
- }
68
+ return findHqRootAncestor(dir, isHqRoot);
77
69
  }
78
70
  function isHqRoot(dir) {
79
71
  return HQ_ROOT_MARKERS.every((marker) => {
@@ -17,6 +17,7 @@
17
17
  * plus core/core.yaml) `self` prints a fingerprint with machine `-`, writes
18
18
  * nothing, skips registration, and reports `reason: "no HQ root"` in --json.
19
19
  */
20
+ import { findHqRootAncestor } from "../utils/hq-roots-core.js";
20
21
  import * as fs from "node:fs";
21
22
  import * as path from "node:path";
22
23
  import { isFingerprint } from "../lib/fingerprint/format.js";
@@ -36,16 +37,10 @@ export function findSelfHqRoot(env = process.env, cwd = process.cwd(), existsSyn
36
37
  const fromEnv = env.HQ_ROOT?.trim();
37
38
  if (fromEnv)
38
39
  return fromEnv;
39
- let dir = path.resolve(cwd);
40
- while (true) {
40
+ return findHqRootAncestor(path.resolve(cwd), (dir) => {
41
41
  const marked = existsSync(path.join(dir, ".claude")) || existsSync(path.join(dir, "workers"));
42
- if (marked && existsSync(path.join(dir, "core", "core.yaml")))
43
- return dir;
44
- const parent = path.dirname(dir);
45
- if (parent === dir)
46
- return null;
47
- dir = parent;
48
- }
42
+ return marked && existsSync(path.join(dir, "core", "core.yaml"));
43
+ });
49
44
  }
50
45
  async function loadIdToken() {
51
46
  const { loadCachedTokens } = await import("../utils/cognito-session.js");
@@ -28,7 +28,7 @@ export function setOwnerWarnings(env, provider, id, holder, accounts) {
28
28
  if (usable.length === 0) {
29
29
  warnings.push({
30
30
  code: "no_usable_login",
31
- message: "No enabled " + provider + " login is usable by lanes now. If " + id + " is really your own login, record it with: hq lanes accounts set-owner " + provider + " " + id + " --holder owner",
31
+ message: "No enabled " + provider + " login is usable by lanes now. If " + id + " is really your own login, record it with: hq runners accounts set-owner " + provider + " " + id + " --holder owner",
32
32
  });
33
33
  }
34
34
  const localNames = [env.USER, env.LOGNAME, env.USERNAME]
@@ -175,7 +175,7 @@ export function createLaneAccountsHandlers(deps) {
175
175
  effective_home: status.home,
176
176
  ...(status.auth_state === "home_missing" ? {
177
177
  error: "home_missing",
178
- fix_command: `hq lanes accounts set-home ${provider} ${status.id} <host-home>`,
178
+ fix_command: `hq runners accounts set-home ${provider} ${status.id} <host-home>`,
179
179
  } : {}),
180
180
  ...(provider === "claude" && status.sign_in_state === "expired" ? {
181
181
  error: "sign_in_expired",
@@ -206,7 +206,7 @@ export function createLaneAccountsHandlers(deps) {
206
206
  if (ownershipWarnings.length > 0) {
207
207
  const names = ownershipWarnings.map((warning) => warning.provider + "/" + warning.account).join(", ");
208
208
  process.stderr.write("warning: " + ownershipWarnings.length + " enabled account(s) have no owning_company or holder recorded: " + names +
209
- ". Record them with: hq lanes accounts set-owner <provider> <account-id> --owning-company <slug|personal|unknown> --holder <owner|name>\n");
209
+ ". Record them with: hq runners accounts set-owner <provider> <account-id> --owning-company <slug|personal|unknown> --holder <owner|name>\n");
210
210
  }
211
211
  const providerDefaults = providers.map((provider) => ({
212
212
  provider,
@@ -362,7 +362,7 @@ export function createLaneAccountsHandlers(deps) {
362
362
  ...(load ? { recent_usage_at: load.recent_usage_at } : {}),
363
363
  ...(currentHomeMissing ? {
364
364
  error: "home_missing",
365
- fix_command: `hq lanes accounts set-home claude ${account} <host-home>`,
365
+ fix_command: `hq runners accounts set-home claude ${account} <host-home>`,
366
366
  } : {}),
367
367
  hosts: loaded.snapshots.map((host) => {
368
368
  const accountStatus = host.capacity.providers.claude.accounts[account];
@@ -374,7 +374,7 @@ export function createLaneAccountsHandlers(deps) {
374
374
  ...(accountStatus?.auth_state !== undefined ? { auth_state: accountStatus.auth_state } : {}),
375
375
  ...(accountStatus?.auth_state === "home_missing" ? {
376
376
  error: "home_missing",
377
- fix_command: `hq lanes accounts set-home claude ${account} <host-home>`,
377
+ fix_command: `hq runners accounts set-home claude ${account} <host-home>`,
378
378
  } : {}),
379
379
  live_lanes: accountLoad?.live_lanes ?? null,
380
380
  lane_counts: accountLoad?.lane_counts ?? { running: null, queued: null, awaiting_input: null },
@@ -407,7 +407,7 @@ export function registerLaneRepoMergeHoldCommand(lanes, deps, wrap) {
407
407
  writeHold(hqRoot, next);
408
408
  return next;
409
409
  });
410
- const notificationWarnings = notifyRunningLocalLanes(hqRoot, company, `Merge hold on ${repo} until ${hold.until}: ${reason}. \`hq lanes hold check\` can refuse merges when the \`${LANES_REPO_MERGE_HOLD_FLAG}\` gate is enabled.`);
410
+ const notificationWarnings = notifyRunningLocalLanes(hqRoot, company, `Merge hold on ${repo} until ${hold.until}: ${reason}. \`hq runners hold check\` can refuse merges when the \`${LANES_REPO_MERGE_HOLD_FLAG}\` gate is enabled.`);
411
411
  reportNotificationWarnings(notificationWarnings);
412
412
  printJson({ action: "lanes.hold.set", hold, ...(notificationWarnings.length ? { notification_warnings: notificationWarnings } : {}) });
413
413
  }));
@@ -506,13 +506,13 @@ export function createLaneMessageHandlers(deps) {
506
506
  : [];
507
507
  if (pendingQuestions.length > 0) {
508
508
  const companySlug = lane.company?.slug ?? lane.mesh_company ?? "<company-slug>";
509
- const instructions = pendingQuestions.map(({ question_id, audience }) => `question ${question_id} awaits ${audience.kind}:${audience.id}; answer it with hq lanes questions answer ${question_id} --company ${companySlug} --freeform <answer>`);
509
+ const instructions = pendingQuestions.map(({ question_id, audience }) => `question ${question_id} awaits ${audience.kind}:${audience.id}; answer it with hq runners questions answer ${question_id} --company ${companySlug} --freeform <answer>`);
510
510
  const message = `Lane ${laneId} is awaiting input. ${instructions.join("; ")}`;
511
511
  throw new LanesError("lane_not_accepting_messages", message, {
512
512
  lane_id: laneId,
513
513
  state: lane.state,
514
514
  pending_questions: pendingQuestions,
515
- answer_commands: pendingQuestions.map(({ question_id }) => `hq lanes questions answer ${question_id} --company ${companySlug} --freeform <answer>`),
515
+ answer_commands: pendingQuestions.map(({ question_id }) => `hq runners questions answer ${question_id} --company ${companySlug} --freeform <answer>`),
516
516
  provider: lane.provider,
517
517
  message,
518
518
  });
@@ -543,7 +543,7 @@ export function createLaneMessageHandlers(deps) {
543
543
  ? resolveResumeProfile(ctx, lane, refreshWorker, refreshProfileSettings)
544
544
  : undefined;
545
545
  if (opts.model !== undefined && opts.account === undefined) {
546
- throw new LanesError("model_requires_account", "--model on hq lanes message is only accepted together with --account", {});
546
+ throw new LanesError("model_requires_account", "--model on hq runners message is only accepted together with --account", {});
547
547
  }
548
548
  let quotaHoldDeferred;
549
549
  let automaticAccountSelection = undefined;
@@ -247,7 +247,7 @@ export function createLaneMoveHandlers(deps) {
247
247
  const knownNoPersistence = (isLanesError(err) && err.error === "outpost_self_target") ||
248
248
  (dispatchDetails.done === true && dispatchDetails.pickup_persisted === false);
249
249
  if (!definitelyNotSubmitted && !knownNoPersistence) {
250
- const checkCommand = `hq lanes show ${laneId}`;
250
+ const checkCommand = `hq runners show ${laneId}`;
251
251
  const message = `Failed to dispatch lane ${laneId} to Outpost ${target.id}; outcome is unknown and the lane remains assigned to Outpost ${target.id}. ` +
252
252
  `Check the target copy by running \`${checkCommand}\` on Outpost ${target.id}. ` +
253
253
  dispatchErrorMessage(err);
@@ -105,7 +105,7 @@ export function createLaneResumeHandlers(deps) {
105
105
  }
106
106
  const failedResumeReason = opts.reason?.trim();
107
107
  if (opts.reason !== undefined && opts.fromFailed !== true) {
108
- throw new LanesError("failed_resume_reason_requires_flag", "--reason on hq lanes resume requires --from-failed", { lane_id: laneId });
108
+ throw new LanesError("failed_resume_reason_requires_flag", "--reason on hq runners resume requires --from-failed", { lane_id: laneId });
109
109
  }
110
110
  if (opts.fromFailed === true && !failedResumeReason) {
111
111
  throw new LanesError("failed_resume_reason_required", "--from-failed requires a non-empty --reason", { lane_id: laneId });
@@ -173,7 +173,7 @@ export function createLaneResumeHandlers(deps) {
173
173
  lane = casUpdateLane(hqRoot, laneId, (current) => ({ ...current, provider_session_id: opts.loopSessionId }));
174
174
  }
175
175
  if (opts.model !== undefined && opts.account === undefined) {
176
- throw new LanesError("model_requires_account", "--model on hq lanes resume is only accepted together with --account", {});
176
+ throw new LanesError("model_requires_account", "--model on hq runners resume is only accepted together with --account", {});
177
177
  }
178
178
  if (opts.account !== undefined && lane.state === "running") {
179
179
  throw new LanesError("lane_running", `Lane ${laneId} is running; stop it or wait for it to exit before moving its session`, {
@@ -186,7 +186,7 @@ export function createLaneResumeHandlers(deps) {
186
186
  }
187
187
  if (lane.state === "queued" &&
188
188
  (lane.queued_reason !== "worker_profile_changed" || opts.worker === undefined)) {
189
- throw new LanesError("lane_not_resumable", `Lane ${laneId} is queued; use hq lanes admit ${laneId} to request admission`, { lane_id: laneId, state: lane.state, admission_command: `hq lanes admit ${laneId}` });
189
+ throw new LanesError("lane_not_resumable", `Lane ${laneId} is queued; use hq runners admit ${laneId} to request admission`, { lane_id: laneId, state: lane.state, admission_command: `hq runners admit ${laneId}` });
190
190
  }
191
191
  const queuedProfileRecovery = lane.state === "queued" &&
192
192
  lane.queued_reason === "worker_profile_changed" &&
@@ -200,20 +200,20 @@ export function createLaneResumeHandlers(deps) {
200
200
  opts.keepAlive !== undefined ||
201
201
  opts.meshCompany !== undefined ||
202
202
  opts.compact === false)) {
203
- throw new LanesError("worker_profile_recovery_options_invalid", "Queued worker-profile recovery accepts only --worker; rerun hq lanes resume after reconcile admits the lane", { lane_id: laneId });
203
+ throw new LanesError("worker_profile_recovery_options_invalid", "Queued worker-profile recovery accepts only --worker; rerun hq runners resume after reconcile admits the lane", { lane_id: laneId });
204
204
  }
205
205
  const pendingQuestions = lane.state === "awaiting_input"
206
206
  ? await deps.pendingQuestionsForLane(ctx, lane)
207
207
  : [];
208
208
  if (pendingQuestions.length > 0 && !loopHandoffRepair) {
209
209
  const companySlug = lane.company?.slug ?? lane.mesh_company ?? "<company-slug>";
210
- const instructions = pendingQuestions.map(({ question_id, audience }) => `question ${question_id} awaits ${audience.kind}:${audience.id}; answer it with hq lanes questions answer ${question_id} --company ${companySlug} --freeform <answer>`);
210
+ const instructions = pendingQuestions.map(({ question_id, audience }) => `question ${question_id} awaits ${audience.kind}:${audience.id}; answer it with hq runners questions answer ${question_id} --company ${companySlug} --freeform <answer>`);
211
211
  const message = `Lane ${laneId} is awaiting input. ${instructions.join("; ")}`;
212
212
  throw new LanesError("lane_pending_questions", message, {
213
213
  lane_id: laneId,
214
214
  state: lane.state,
215
215
  pending_questions: pendingQuestions,
216
- answer_commands: pendingQuestions.map(({ question_id }) => `hq lanes questions answer ${question_id} --company ${companySlug} --freeform <answer>`),
216
+ answer_commands: pendingQuestions.map(({ question_id }) => `hq runners questions answer ${question_id} --company ${companySlug} --freeform <answer>`),
217
217
  });
218
218
  }
219
219
  const projectId = opts.project?.trim() || lane.project_id;
@@ -27,7 +27,7 @@ function monitorCallsForLaneIds(laneIds) {
27
27
  for (let offset = 0; offset < laneIds.length; offset += MAX_WATCHED_LANES) {
28
28
  const chunk = laneIds.slice(offset, offset + MAX_WATCHED_LANES);
29
29
  calls.push({
30
- command: `hq lanes watch ${chunk.join(" ")}`,
30
+ command: `hq runners watch ${chunk.join(" ")}`,
31
31
  timeout_ms: MONITOR_MAX_TIMEOUT_MS,
32
32
  persistent: false,
33
33
  });
@@ -151,7 +151,7 @@ export function createLaneWatchHandlers(deps) {
151
151
  }
152
152
  const sessionId = opts.session?.trim();
153
153
  if (!sessionId) {
154
- throw new LanesError("monitor_session_required", "hq lanes monitor-check requires --session <id> unless --reminder is used");
154
+ throw new LanesError("monitor_session_required", "hq runners monitor-check requires --session <id> unless --reminder is used");
155
155
  }
156
156
  const engine = resolveMonitorEngine(opts.engine, ctx.env);
157
157
  const activeLanes = loadAllLanes(ctx.hqRoot()).filter((lane) => lane.senior.kind === "session" &&