@indigoai-us/hq-cli 5.345.156 → 5.345.159

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 (144) hide show
  1. package/CHANGELOG.md +231 -0
  2. package/assets/scaffold/core/scripts/rebuild-company-knowledge-index.sh +110 -2
  3. package/assets/scaffold/core/scripts/rebuild-projects-index.sh +101 -5
  4. package/assets/scaffold/core/scripts/worktree.sh +4 -0
  5. package/dist/command-catalog.generated.d.ts +531 -6
  6. package/dist/command-catalog.generated.js +674 -27
  7. package/dist/command-registration-plan.d.ts +18 -0
  8. package/dist/command-registration-plan.js +4 -0
  9. package/dist/commands/_patterns.d.ts +17 -0
  10. package/dist/commands/_patterns.js +22 -0
  11. package/dist/commands/agent-kit.js +8 -6
  12. package/dist/commands/bot.js +7 -4
  13. package/dist/commands/channel-suggest.d.ts +56 -0
  14. package/dist/commands/channel-suggest.js +170 -0
  15. package/dist/commands/channels.js +7 -1
  16. package/dist/commands/cloud.d.ts +45 -0
  17. package/dist/commands/cloud.js +150 -10
  18. package/dist/commands/company.js +4 -3
  19. package/dist/commands/core-checkpoint-native.d.ts +18 -0
  20. package/dist/commands/core-checkpoint-native.js +67 -2
  21. package/dist/commands/core-pipeline-driver-native.d.ts +12 -1
  22. package/dist/commands/core-pipeline-driver-native.js +131 -5
  23. package/dist/commands/core.js +12 -0
  24. package/dist/commands/crm.js +83 -6
  25. package/dist/commands/deploy-access.d.ts +33 -0
  26. package/dist/commands/deploy-access.js +322 -0
  27. package/dist/commands/dm-attach.d.ts +106 -0
  28. package/dist/commands/dm-attach.js +184 -0
  29. package/dist/commands/dm.d.ts +37 -0
  30. package/dist/commands/dm.js +172 -10
  31. package/dist/commands/feedback-show.d.ts +40 -0
  32. package/dist/commands/feedback-show.js +261 -0
  33. package/dist/commands/feedback.d.ts +21 -0
  34. package/dist/commands/feedback.js +152 -2
  35. package/dist/commands/files.d.ts +24 -0
  36. package/dist/commands/files.js +52 -1
  37. package/dist/commands/integrations-connect.js +7 -3
  38. package/dist/commands/lanes-accounts.js +16 -1
  39. package/dist/commands/lanes-loop.js +14 -4
  40. package/dist/commands/lanes-message.js +6 -4
  41. package/dist/commands/lanes-resume.js +36 -13
  42. package/dist/commands/lanes-shared.d.ts +5 -0
  43. package/dist/commands/lanes-shared.js +13 -3
  44. package/dist/commands/lanes-watch.js +1 -0
  45. package/dist/commands/lanes.d.ts +20 -1
  46. package/dist/commands/lanes.js +201 -51
  47. package/dist/commands/mesh.js +149 -1
  48. package/dist/commands/monitor.d.ts +1 -0
  49. package/dist/commands/monitor.js +4 -1
  50. package/dist/commands/repo.d.ts +41 -0
  51. package/dist/commands/repo.js +331 -0
  52. package/dist/commands/scan.d.ts +3 -1
  53. package/dist/commands/scan.js +7 -3
  54. package/dist/commands/secrets.d.ts +21 -0
  55. package/dist/commands/secrets.js +114 -14
  56. package/dist/commands/signals.js +17 -5
  57. package/dist/commands/staff/listings.d.ts +41 -0
  58. package/dist/commands/staff/listings.js +160 -0
  59. package/dist/commands/staff/reset-test-account.d.ts +3 -2
  60. package/dist/commands/staff/reset-test-account.js +4 -3
  61. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +2629 -1036
  62. package/dist/hq-cloud-sync-runner/package.json +1 -1
  63. package/dist/lib/agent-kit/run/inbox.js +2 -1
  64. package/dist/lib/agent-kit/wake-secrets.d.ts +7 -0
  65. package/dist/lib/agent-kit/wake-secrets.js +32 -0
  66. package/dist/lib/agent-kit/wake.d.ts +4 -0
  67. package/dist/lib/agent-kit/wake.js +49 -3
  68. package/dist/lib/bot/inflight.d.ts +7 -1
  69. package/dist/lib/bot/inflight.js +10 -2
  70. package/dist/lib/bot/prompt.js +3 -0
  71. package/dist/lib/bot/run.js +72 -20
  72. package/dist/lib/bot/session.d.ts +14 -0
  73. package/dist/lib/bot/session.js +70 -0
  74. package/dist/lib/capacity/collectors/claude-oauth.d.ts +6 -0
  75. package/dist/lib/capacity/collectors/claude-oauth.js +12 -0
  76. package/dist/lib/capacity/lane-login.d.ts +6 -0
  77. package/dist/lib/capacity/lane-login.js +5 -0
  78. package/dist/lib/core-utils/worktree.js +2 -0
  79. package/dist/lib/daemon/exit-cause.d.ts +43 -0
  80. package/dist/lib/daemon/exit-cause.js +88 -0
  81. package/dist/lib/daemon/handoff.d.ts +2 -0
  82. package/dist/lib/daemon/handoff.js +6 -1
  83. package/dist/lib/daemon/hq-child-bootstrap.mjs +20 -3
  84. package/dist/lib/daemon/paths.d.ts +2 -0
  85. package/dist/lib/daemon/paths.js +1 -0
  86. package/dist/lib/daemon/run.js +13 -0
  87. package/dist/lib/daemon/supervisor.d.ts +54 -1
  88. package/dist/lib/daemon/supervisor.js +297 -21
  89. package/dist/lib/daemon/unit-holds.d.ts +22 -0
  90. package/dist/lib/daemon/unit-holds.js +86 -0
  91. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  92. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  93. package/dist/lib/index-render/company-knowledge.js +1 -3
  94. package/dist/lib/index-render/projects.js +1 -3
  95. package/dist/lib/lanes/account-company.d.ts +28 -0
  96. package/dist/lib/lanes/account-company.js +53 -0
  97. package/dist/lib/lanes/accounts.d.ts +22 -3
  98. package/dist/lib/lanes/accounts.js +38 -2
  99. package/dist/lib/lanes/claude-balance.d.ts +6 -1
  100. package/dist/lib/lanes/claude-balance.js +6 -1
  101. package/dist/lib/lanes/claude-credential.d.ts +78 -0
  102. package/dist/lib/lanes/claude-credential.js +163 -0
  103. package/dist/lib/lanes/compaction.d.ts +2 -0
  104. package/dist/lib/lanes/compaction.js +9 -0
  105. package/dist/lib/lanes/config.js +6 -0
  106. package/dist/lib/lanes/envelope-repair-dispatch.js +2 -1
  107. package/dist/lib/lanes/hooks-install.js +2 -1
  108. package/dist/lib/lanes/host-capacity.d.ts +2 -0
  109. package/dist/lib/lanes/host-capacity.js +1 -0
  110. package/dist/lib/lanes/keep-alive.d.ts +1 -1
  111. package/dist/lib/lanes/keep-alive.js +3 -1
  112. package/dist/lib/lanes/links.js +10 -4
  113. package/dist/lib/lanes/loop.js +16 -1
  114. package/dist/lib/lanes/node-binary.d.ts +17 -0
  115. package/dist/lib/lanes/node-binary.js +30 -0
  116. package/dist/lib/lanes/outpost-dispatch.d.ts +2 -1
  117. package/dist/lib/lanes/outpost-dispatch.js +1 -0
  118. package/dist/lib/lanes/reconcile.js +4 -0
  119. package/dist/lib/lanes/remote-control-lane.js +2 -0
  120. package/dist/lib/lanes/spawn.d.ts +3 -0
  121. package/dist/lib/lanes/spawn.js +119 -9
  122. package/dist/lib/lanes/store.d.ts +6 -0
  123. package/dist/lib/lanes/store.js +107 -18
  124. package/dist/lib/lanes/types.d.ts +2 -0
  125. package/dist/lib/lanes/watch.js +28 -5
  126. package/dist/lib/lanes/watcher-main.js +4 -3
  127. package/dist/lib/lanes/watcher.d.ts +4 -0
  128. package/dist/lib/lanes/watcher.js +110 -21
  129. package/dist/lib/mesh/api.d.ts +32 -0
  130. package/dist/lib/mesh/api.js +75 -0
  131. package/dist/lib/secret-scan/detect.js +9 -0
  132. package/dist/lib/secret-scan/repo-config.d.ts +41 -0
  133. package/dist/lib/secret-scan/repo-config.js +237 -0
  134. package/dist/lib/secret-scan/rules.d.ts +7 -1
  135. package/dist/lib/secret-scan/rules.js +3 -1
  136. package/dist/lib/secret-scan/staged.d.ts +5 -0
  137. package/dist/lib/secret-scan/staged.js +19 -2
  138. package/dist/lib/secret-scan/types.d.ts +2 -0
  139. package/dist/lib/sync/server-owned-local-only.d.ts +29 -0
  140. package/dist/lib/sync/server-owned-local-only.js +75 -0
  141. package/dist/utils/package-use-lease.js +27 -9
  142. package/dist/utils/version-gate.d.ts +7 -0
  143. package/dist/utils/version-gate.js +66 -0
  144. package/package.json +8 -8
@@ -1,5 +1,5 @@
1
1
  import * as fs from "fs";
2
- import { at, basename, date, extractKeepFences, generatedFingerprint, generatedStamp, hasUnclosedKeepMarker, heading, immediateEntries, isHidden, log, looksAutoGenerated, readJson, readText, sanitize, stampGenerated, titleize, truncate, write, } from "./shared.js";
2
+ import { at, basename, date, extractKeepFences, generatedFingerprint, generatedStamp, hasUnclosedKeepMarker, heading, immediateEntries, isHidden, log, readJson, readText, sanitize, stampGenerated, titleize, truncate, write, } from "./shared.js";
3
3
  function describe(item) {
4
4
  const name = basename(item);
5
5
  try {
@@ -65,8 +65,6 @@ function shouldOverwrite(context, existing, next) {
65
65
  return "write";
66
66
  if (stored)
67
67
  return "refuse";
68
- if (looksAutoGenerated(existing))
69
- return "write";
70
68
  if (generatedFingerprint(existing) === generatedFingerprint(next))
71
69
  return "write";
72
70
  return "refuse";
@@ -1,6 +1,6 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
- import { at, basename, date, exists, extractKeepFences, generatedFingerprint, generatedStamp, hasUnclosedKeepMarker, immediateEntries, isHidden, log, looksAutoGenerated, projectStatus, readJson, readText, sanitize, stampGenerated, titleize, truncate, write, } from "./shared.js";
3
+ import { at, basename, date, exists, extractKeepFences, generatedFingerprint, generatedStamp, hasUnclosedKeepMarker, immediateEntries, isHidden, log, projectStatus, readJson, readText, sanitize, stampGenerated, titleize, truncate, write, } from "./shared.js";
4
4
  function composeCompanyProjectsIndex(raw, existing) {
5
5
  const stamped = stampGenerated(raw);
6
6
  const fences = existing === undefined ? "" : extractKeepFences(existing);
@@ -20,8 +20,6 @@ function shouldOverwriteCompanyProjectsIndex(context, existing, next) {
20
20
  return "write";
21
21
  if (stored)
22
22
  return "refuse";
23
- if (looksAutoGenerated(existing))
24
- return "write";
25
23
  if (generatedFingerprint(existing) === generatedFingerprint(next))
26
24
  return "write";
27
25
  return "refuse";
@@ -0,0 +1,28 @@
1
+ import { LanesError } from "./errors.js";
2
+ import type { AccountConfig, LaneCompanyRef } from "./types.js";
3
+ type ProviderAccounts = Record<string, AccountConfig | undefined>;
4
+ /**
5
+ * Company enforcement is opt-in per provider: it begins once any account for
6
+ * that provider carries a `company` tag. Until then every account stays open
7
+ * to every lane, so existing installs keep creating company lanes after upgrade.
8
+ */
9
+ export declare function companyEnforcementActive(providerAccounts: ProviderAccounts | undefined): boolean;
10
+ /**
11
+ * Account ownership is explicit; names and homes never imply a tenant.
12
+ * Pass the provider's account map to apply the opt-in rule above.
13
+ */
14
+ export declare function accountMatchesCompany(account: AccountConfig | undefined, company: LaneCompanyRef | null, providerAccounts?: ProviderAccounts): boolean;
15
+ /** Legacy untagged accounts may retain an existing lane, never acquire one. */
16
+ export declare function accountMayRetainLane(account: AccountConfig | undefined, company: LaneCompanyRef | null, providerAccounts?: ProviderAccounts): boolean;
17
+ /**
18
+ * When enforcement is active and every enabled candidate was excluded only by
19
+ * company ownership, name the problem instead of reporting no enabled account.
20
+ */
21
+ export declare function companyMismatchError(input: {
22
+ provider: string;
23
+ providerAccounts: ProviderAccounts;
24
+ candidates: readonly string[];
25
+ company: LaneCompanyRef | null;
26
+ }): LanesError | undefined;
27
+ export {};
28
+ //# sourceMappingURL=account-company.d.ts.map
@@ -0,0 +1,53 @@
1
+ import { LanesError } from "./errors.js";
2
+ /**
3
+ * Company enforcement is opt-in per provider: it begins once any account for
4
+ * that provider carries a `company` tag. Until then every account stays open
5
+ * to every lane, so existing installs keep creating company lanes after upgrade.
6
+ */
7
+ export function companyEnforcementActive(providerAccounts) {
8
+ if (providerAccounts === undefined)
9
+ return true;
10
+ return Object.values(providerAccounts).some((account) => account?.company !== undefined);
11
+ }
12
+ /**
13
+ * Account ownership is explicit; names and homes never imply a tenant.
14
+ * Pass the provider's account map to apply the opt-in rule above.
15
+ */
16
+ export function accountMatchesCompany(account, company, providerAccounts) {
17
+ if (account === undefined)
18
+ return false;
19
+ if (providerAccounts !== undefined && !companyEnforcementActive(providerAccounts))
20
+ return true;
21
+ if (company === null)
22
+ return account.company === undefined;
23
+ return account.company === company.uid || account.company === company.slug;
24
+ }
25
+ /** Legacy untagged accounts may retain an existing lane, never acquire one. */
26
+ export function accountMayRetainLane(account, company, providerAccounts) {
27
+ return account !== undefined && (account.company === undefined || accountMatchesCompany(account, company, providerAccounts));
28
+ }
29
+ /**
30
+ * When enforcement is active and every enabled candidate was excluded only by
31
+ * company ownership, name the problem instead of reporting no enabled account.
32
+ */
33
+ export function companyMismatchError(input) {
34
+ if (!companyEnforcementActive(input.providerAccounts))
35
+ return undefined;
36
+ const enabled = input.candidates.filter((id) => input.providerAccounts[id]?.enabled === true);
37
+ if (enabled.length === 0)
38
+ return undefined;
39
+ if (enabled.some((id) => accountMatchesCompany(input.providerAccounts[id], input.company, input.providerAccounts)))
40
+ return undefined;
41
+ const companyLabel = input.company === null ? "(no company)" : input.company.slug;
42
+ const excluded = enabled.map((id) => ({ account: id, company: input.providerAccounts[id]?.company ?? null }));
43
+ return new LanesError("account_company_mismatch", `No enabled ${input.provider} account belongs to lane company ${companyLabel}. ` +
44
+ `Excluded for company: ${excluded.map((row) => `${row.account} (${row.company ?? "untagged"})`).join(", ")}. ` +
45
+ `Set "company" on an account under providers.${input.provider}.accounts in personal/lanes/config.json.`, {
46
+ provider: input.provider,
47
+ company: input.company?.slug ?? null,
48
+ excluded_accounts: excluded,
49
+ config_key: `providers.${input.provider}.accounts.<id>.company`,
50
+ config_file: "personal/lanes/config.json",
51
+ });
52
+ }
53
+ //# sourceMappingURL=account-company.js.map
@@ -4,11 +4,15 @@
4
4
  * Naming an account and omitting one mean different things: an explicit
5
5
  * disabled id is refused; omitting picks the least-loaded eligible account.
6
6
  * Status reports `configured` and `logged_in` separately. logged_in is
7
- * derived from credential-file existence or a provider status command; this
8
- * module never reads, prints, copies, or hashes credential files.
7
+ * derived from credential-file existence or a provider status command. For
8
+ * Claude, an injected `readClaudeCredential` also checks the access-token
9
+ * expiry of the credential the worker will use (see claude-credential.ts), so
10
+ * an expired sign-in reports `logged_in: false` with `sign_in_state: "expired"`.
11
+ * This module never prints, copies, or hashes credentials.
9
12
  */
10
13
  import { type LaneRecord, type LaneProvider } from "./types.js";
11
14
  import type { LanesConfig } from "./types.js";
15
+ import type { ClaudeCredentialReader, ClaudeTokenState } from "./claude-credential.js";
12
16
  export declare const PROVIDER_HOME_ENV: Record<LaneProvider, string>;
13
17
  /**
14
18
  * Claude Code keys its OS keychain credential by `CLAUDE_CONFIG_DIR`: with
@@ -71,6 +75,12 @@ export interface AccountDeps {
71
75
  /** Provider status output is parsed for a boolean only; it is never printed. */
72
76
  probe?: (command: string, args: string[], env: NodeJS.ProcessEnv) => AccountStatusProbeResult;
73
77
  env?: NodeJS.ProcessEnv;
78
+ /**
79
+ * Reads the access-token expiry of the Claude credential the worker uses.
80
+ * Production callers pass readLaneClaudeCredential; omitted, expiry is not
81
+ * checked and logged_in keeps the presence-only result.
82
+ */
83
+ readClaudeCredential?: ClaudeCredentialReader;
74
84
  }
75
85
  export interface AccountResolveContext {
76
86
  hqRoot?: string;
@@ -110,9 +120,16 @@ export interface AccountStatus {
110
120
  disabled_reason?: string;
111
121
  /** Present in personal/lanes/config.json. */
112
122
  configured: boolean;
113
- /** True/false comes from file existence or the provider status command. */
123
+ /**
124
+ * True/false comes from file existence or the provider status command.
125
+ * For Claude, an expired access token forces false.
126
+ */
114
127
  logged_in: boolean | null;
115
128
  auth_state: AuthState;
129
+ /** Claude only, when the credential was read: whether its access token is still valid. */
130
+ sign_in_state?: ClaudeTokenState;
131
+ /** Claude only: when the access token expires, if the credential records it. */
132
+ sign_in_expires_at?: string | null;
116
133
  envVar: string;
117
134
  }
118
135
  export declare function credentialPaths(provider: LaneProvider, home: string): string[];
@@ -129,6 +146,8 @@ export declare function authStateFor(provider: LaneProvider, present: boolean):
129
146
  export declare function loggedInFromAuthState(state: AuthState): boolean | null;
130
147
  /** Admission and listing share this: refuse only a conclusive logged-out. */
131
148
  export declare function isLoggedOut(status: Pick<AccountStatus, "logged_in">): boolean;
149
+ /** True when the Claude credential exists but its access token has expired. */
150
+ export declare function isSignInExpired(status: Pick<AccountStatus, "sign_in_state">): boolean;
132
151
  /** Auto-select requires a positive file or provider-status login result. */
133
152
  export declare function isCredentialProven(status: Pick<AccountStatus, "logged_in">): boolean;
134
153
  /**
@@ -4,8 +4,11 @@
4
4
  * Naming an account and omitting one mean different things: an explicit
5
5
  * disabled id is refused; omitting picks the least-loaded eligible account.
6
6
  * Status reports `configured` and `logged_in` separately. logged_in is
7
- * derived from credential-file existence or a provider status command; this
8
- * module never reads, prints, copies, or hashes credential files.
7
+ * derived from credential-file existence or a provider status command. For
8
+ * Claude, an injected `readClaudeCredential` also checks the access-token
9
+ * expiry of the credential the worker will use (see claude-credential.ts), so
10
+ * an expired sign-in reports `logged_in: false` with `sign_in_state: "expired"`.
11
+ * This module never prints, copies, or hashes credentials.
9
12
  */
10
13
  import * as fs from "node:fs";
11
14
  import * as os from "node:os";
@@ -184,6 +187,10 @@ export function loggedInFromAuthState(state) {
184
187
  export function isLoggedOut(status) {
185
188
  return status.logged_in === false;
186
189
  }
190
+ /** True when the Claude credential exists but its access token has expired. */
191
+ export function isSignInExpired(status) {
192
+ return status.sign_in_state === "expired";
193
+ }
187
194
  /** Auto-select requires a positive file or provider-status login result. */
188
195
  export function isCredentialProven(status) {
189
196
  return status.logged_in === true;
@@ -330,6 +337,9 @@ export function selectBalancedAccount(provider, config, ctx = {}) {
330
337
  ...(ctx.accountDeps?.probe ? { probe: ctx.accountDeps.probe } : {}),
331
338
  ...(ctx.accountDeps?.env ? { env: ctx.accountDeps.env } : {}),
332
339
  ...(ctx.accountDeps?.homedir ? { homedir: ctx.accountDeps.homedir } : {}),
340
+ ...(ctx.accountDeps?.readClaudeCredential
341
+ ? { readClaudeCredential: ctx.accountDeps.readClaudeCredential }
342
+ : {}),
333
343
  ...(ctx.hostname !== undefined ? { hostname: ctx.hostname } : {}),
334
344
  });
335
345
  if (status.logged_in === true)
@@ -434,6 +444,9 @@ export function resolveAccount(provider, requestedId, config, ctx = {}) {
434
444
  probe: ctx.accountDeps.probe,
435
445
  ...(ctx.accountDeps.env ? { env: ctx.accountDeps.env } : {}),
436
446
  ...(ctx.accountDeps.homedir ? { homedir: ctx.accountDeps.homedir } : {}),
447
+ ...(ctx.accountDeps.readClaudeCredential
448
+ ? { readClaudeCredential: ctx.accountDeps.readClaudeCredential }
449
+ : {}),
437
450
  ...(ctx.hostname !== undefined ? { hostname: ctx.hostname } : {}),
438
451
  });
439
452
  throwIfQuotaBlocked(block, provider, requestedId, status.identity);
@@ -469,6 +482,18 @@ export function accountStatus(provider, accountId, config, deps = defaultAccount
469
482
  let auth_state = homeExists ? authStateFor(provider, present) : "home_missing";
470
483
  let logged_in = homeExists ? loggedInFromAuthState(auth_state) : false;
471
484
  let identity;
485
+ let token;
486
+ if (homeExists && provider === "claude" && deps.readClaudeCredential !== undefined) {
487
+ try {
488
+ token = deps.readClaudeCredential({
489
+ home: effective.home,
490
+ defaultHome: isDefaultProviderHome("claude", effective.home, deps.homedir),
491
+ });
492
+ }
493
+ catch {
494
+ process.stderr.write(`hq lanes: Claude credential expiry check failed for account ${accountId}\n`);
495
+ }
496
+ }
472
497
  if (homeExists && !present && provider === "claude" && deps.probe !== undefined) {
473
498
  try {
474
499
  const result = deps.probe("claude", ["auth", "status"], withProviderHomeEnv(deps.env ?? process.env, "claude", effective.home, deps.homedir));
@@ -483,6 +508,13 @@ export function accountStatus(provider, accountId, config, deps = defaultAccount
483
508
  process.stderr.write(`hq lanes: Claude auth status probe failed for account ${accountId}\n`);
484
509
  }
485
510
  }
511
+ if (token?.state === "expired") {
512
+ // The credential is there but the worker would start with a dead token.
513
+ logged_in = false;
514
+ }
515
+ else if (token?.state === "valid" && logged_in === null) {
516
+ logged_in = true;
517
+ }
486
518
  const status = {
487
519
  provider,
488
520
  id: accountId,
@@ -494,6 +526,10 @@ export function accountStatus(provider, accountId, config, deps = defaultAccount
494
526
  auth_state,
495
527
  envVar,
496
528
  };
529
+ if (token !== undefined) {
530
+ status.sign_in_state = token.state;
531
+ status.sign_in_expires_at = token.expires_at;
532
+ }
497
533
  if (identity)
498
534
  status.identity = identity;
499
535
  if (account.disabled_reason !== undefined) {
@@ -1,6 +1,6 @@
1
1
  import type { AuthState } from "./accounts.js";
2
2
  import type { HostCapacityAccount, HostCapacitySnapshot } from "./host-capacity.js";
3
- import type { LaneHost, LanePlacementPolicy, LaneRecord, LanesConfig } from "./types.js";
3
+ import type { LaneCompanyRef, LaneHost, LanePlacementPolicy, LaneRecord, LanesConfig } from "./types.js";
4
4
  import { type QuotaState } from "./quota.js";
5
5
  export declare const BALANCE_LIVE_STATES: readonly ["running", "queued", "awaiting_input"];
6
6
  export declare const BALANCE_MOVABLE_STATES: readonly ["interrupted", "done", "awaiting_input"];
@@ -71,6 +71,9 @@ export interface BalanceMoveSuggestion {
71
71
  skip_reason?: "running_turn" | "state_not_movable" | "no_provider_session" | "pending_resume";
72
72
  }
73
73
  export declare function selectClaudeAccount(input: {
74
+ company?: LaneRecord["company"];
75
+ /** Only an already-recorded account may use the legacy untagged exception. */
76
+ retainedAccount?: string;
74
77
  hosts: readonly BalanceHostSnapshot[];
75
78
  targetHost: LaneHost;
76
79
  config: LanesConfig;
@@ -95,5 +98,7 @@ export declare function accountLoadsForReport(input: {
95
98
  export declare function planClaudeBalanceMoves(input: {
96
99
  hosts: readonly BalanceHostSnapshot[];
97
100
  config: LanesConfig;
101
+ /** Resolves a lane's effective company (lane, mesh company, then project owner). */
102
+ laneCompany?: (lane: LaneRecord) => LaneCompanyRef | null;
98
103
  }): BalanceMoveSuggestion[];
99
104
  //# sourceMappingURL=claude-balance.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import { LanesError } from "./errors.js";
2
+ import { accountMatchesCompany, accountMayRetainLane } from "./account-company.js";
2
3
  import { quotaBlockFor } from "./quota.js";
3
4
  export const BALANCE_LIVE_STATES = ["running", "queued", "awaiting_input"];
4
5
  export const BALANCE_MOVABLE_STATES = ["interrupted", "done", "awaiting_input"];
@@ -134,7 +135,10 @@ function buildLoads(input) {
134
135
  const quotaBlock = input.quotaState === undefined
135
136
  ? undefined
136
137
  : quotaBlockFor(input.quotaState, "claude", account, quotaModel, input.now);
137
- const ineligible = targetIneligibilityReason(account, configAccounts[account]?.enabled === true, input.allowedAccounts, targetLoad) ?? (quotaBlock?.blocked === true ? "quota_held" : undefined);
138
+ const companyMismatch = input.company !== undefined && !(account === input.retainedAccount
139
+ ? accountMayRetainLane(configAccounts[account], input.company, configAccounts)
140
+ : accountMatchesCompany(configAccounts[account], input.company, configAccounts));
141
+ const ineligible = companyMismatch ? "company_mismatch" : targetIneligibilityReason(account, configAccounts[account]?.enabled === true, input.allowedAccounts, targetLoad) ?? (quotaBlock?.blocked === true ? "quota_held" : undefined);
138
142
  if (ineligible !== undefined)
139
143
  skipped.push({ account, host: targetHost, reason: ineligible });
140
144
  const knownCounts = hosts.flatMap((host) => host.live_lanes === null ? [] : [host.live_lanes]);
@@ -285,6 +289,7 @@ export function planClaudeBalanceMoves(input) {
285
289
  if (sourceStatus === undefined)
286
290
  continue;
287
291
  const candidates = Object.keys(input.config.providers.claude.accounts)
292
+ .filter((account) => accountMatchesCompany(input.config.providers.claude.accounts[account], input.laneCompany ? input.laneCompany(lane) : lane.company, input.config.providers.claude.accounts))
288
293
  .filter((account) => account !== source && input.config.providers.claude.accounts[account]?.enabled === true)
289
294
  .map((account) => ({
290
295
  account,
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Expiry check for the Claude OAuth credential a lane worker will use.
3
+ *
4
+ * `hq lanes accounts list` used to report `logged_in: true` when a
5
+ * credential merely existed (a `.credentials.json` file, or `claude auth
6
+ * status` saying a keychain item is present). An expired access token still
7
+ * passed, and the lane exited seconds after start with an OAuth expiry
8
+ * error. This module reads the same credential the worker reads and reports
9
+ * whether its access token is still valid.
10
+ *
11
+ * The worker's credential is keyed by CLAUDE_CONFIG_DIR:
12
+ * - macOS: the login user's Keychain item `Claude Code-credentials` for the
13
+ * default home (the worker runs with the variable unset), or the
14
+ * hash-suffixed item for any other home; `<home>/.credentials.json` when no
15
+ * Keychain item exists.
16
+ * - elsewhere: `<home>/.credentials.json`.
17
+ *
18
+ * An access token past its expiry is only reported expired when there is no
19
+ * refresh token, or the capacity collector has recorded the refresh token as
20
+ * revoked. Otherwise Claude Code renews the access token at startup, so the
21
+ * account is still usable.
22
+ *
23
+ * Only `claudeAiOauth.expiresAt` and the presence of the tokens are read.
24
+ * Token values are never returned, logged, or copied; the refresh token is
25
+ * only passed to the revoked check, which compares a fingerprint.
26
+ */
27
+ /**
28
+ * valid: an access token whose expiry is in the future (or not recorded).
29
+ * expired: an access token whose expiry has passed and that cannot be renewed
30
+ * (no refresh token, or the refresh token is recorded as revoked). A lane
31
+ * started now fails.
32
+ * missing: no OAuth credential for this home (API-key setups land here).
33
+ * unknown: the credential could not be read (Keychain timeout, bad JSON).
34
+ */
35
+ export type ClaudeTokenState = "valid" | "expired" | "missing" | "unknown";
36
+ export interface ClaudeCredentialCheck {
37
+ state: ClaudeTokenState;
38
+ /** ISO time the access token expires, when the credential records it. */
39
+ expires_at: string | null;
40
+ source: "keychain" | "file" | null;
41
+ }
42
+ export interface ClaudeCredentialTarget {
43
+ /** The account home the lane runs with. */
44
+ home: string;
45
+ /** True when the worker runs with CLAUDE_CONFIG_DIR unset for this home. */
46
+ defaultHome: boolean;
47
+ }
48
+ export type ClaudeCredentialReader = (target: ClaudeCredentialTarget) => ClaudeCredentialCheck;
49
+ export interface SecurityResult {
50
+ status: number | null;
51
+ /** Holds the credential JSON on success. Parsed in memory, never printed. */
52
+ stdout: string;
53
+ timedOut: boolean;
54
+ }
55
+ export interface ClaudeCredentialReaderDeps {
56
+ platform?: NodeJS.Platform;
57
+ now?: () => number;
58
+ security?: (args: readonly string[]) => SecurityResult;
59
+ readFile?: (file: string) => string;
60
+ /** Keychain account name; defaults to the login user. */
61
+ username?: string;
62
+ /** True when this refresh token is recorded as revoked. */
63
+ isRefreshRevoked?: (refreshToken: string) => boolean;
64
+ }
65
+ /** Revoked check against the capacity collector's marker file. Never throws. */
66
+ export declare function defaultIsRefreshRevoked(refreshToken: string): boolean;
67
+ export declare const CLAUDE_CREDENTIAL_SECURITY_TIMEOUT_MS = 5000;
68
+ /** Keychain service the worker reads for this home. */
69
+ export declare function laneClaudeKeychainService(target: ClaudeCredentialTarget): string;
70
+ /** Classify a credential document. Returns only state and expiry. */
71
+ export declare function claudeTokenStateFromDocument(text: string, nowMs: number, isRefreshRevoked?: (refreshToken: string) => boolean): {
72
+ state: ClaudeTokenState;
73
+ expires_at: string | null;
74
+ };
75
+ export declare function createClaudeCredentialReader(deps?: ClaudeCredentialReaderDeps): ClaudeCredentialReader;
76
+ /** Production reader: real Keychain on macOS, the credentials file elsewhere. */
77
+ export declare const readLaneClaudeCredential: ClaudeCredentialReader;
78
+ //# sourceMappingURL=claude-credential.d.ts.map
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Expiry check for the Claude OAuth credential a lane worker will use.
3
+ *
4
+ * `hq lanes accounts list` used to report `logged_in: true` when a
5
+ * credential merely existed (a `.credentials.json` file, or `claude auth
6
+ * status` saying a keychain item is present). An expired access token still
7
+ * passed, and the lane exited seconds after start with an OAuth expiry
8
+ * error. This module reads the same credential the worker reads and reports
9
+ * whether its access token is still valid.
10
+ *
11
+ * The worker's credential is keyed by CLAUDE_CONFIG_DIR:
12
+ * - macOS: the login user's Keychain item `Claude Code-credentials` for the
13
+ * default home (the worker runs with the variable unset), or the
14
+ * hash-suffixed item for any other home; `<home>/.credentials.json` when no
15
+ * Keychain item exists.
16
+ * - elsewhere: `<home>/.credentials.json`.
17
+ *
18
+ * An access token past its expiry is only reported expired when there is no
19
+ * refresh token, or the capacity collector has recorded the refresh token as
20
+ * revoked. Otherwise Claude Code renews the access token at startup, so the
21
+ * account is still usable.
22
+ *
23
+ * Only `claudeAiOauth.expiresAt` and the presence of the tokens are read.
24
+ * Token values are never returned, logged, or copied; the refresh token is
25
+ * only passed to the revoked check, which compares a fingerprint.
26
+ */
27
+ import { spawnSync } from "node:child_process";
28
+ import * as fs from "node:fs";
29
+ import * as os from "node:os";
30
+ import * as path from "node:path";
31
+ import { CLAUDE_KEYCHAIN_SERVICE, claudeKeychainServiceName, isRefreshTokenRevoked, } from "../capacity/collectors/claude-oauth.js";
32
+ import { resolveLanesHqRoot } from "./hq-root.js";
33
+ /** Revoked check against the capacity collector's marker file. Never throws. */
34
+ export function defaultIsRefreshRevoked(refreshToken) {
35
+ try {
36
+ return isRefreshTokenRevoked(resolveLanesHqRoot(), refreshToken);
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ }
42
+ function safeUsername() {
43
+ try {
44
+ return os.userInfo().username || null;
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ export const CLAUDE_CREDENTIAL_SECURITY_TIMEOUT_MS = 5_000;
51
+ /** `security find-generic-password` exit status when the item does not exist. */
52
+ const SECURITY_ITEM_NOT_FOUND = 44;
53
+ /** Keychain service the worker reads for this home. */
54
+ export function laneClaudeKeychainService(target) {
55
+ return target.defaultHome ? CLAUDE_KEYCHAIN_SERVICE : claudeKeychainServiceName(target.home);
56
+ }
57
+ /** Classify a credential document. Returns only state and expiry. */
58
+ export function claudeTokenStateFromDocument(text, nowMs, isRefreshRevoked = () => false) {
59
+ let parsed;
60
+ try {
61
+ parsed = JSON.parse(text);
62
+ }
63
+ catch {
64
+ return { state: "unknown", expires_at: null };
65
+ }
66
+ if (!isRecord(parsed))
67
+ return { state: "unknown", expires_at: null };
68
+ const oauth = parsed.claudeAiOauth;
69
+ if (!isRecord(oauth))
70
+ return { state: "missing", expires_at: null };
71
+ const token = typeof oauth.accessToken === "string" ? oauth.accessToken : oauth.access_token;
72
+ if (typeof token !== "string" || token.trim() === "")
73
+ return { state: "missing", expires_at: null };
74
+ const raw = oauth.expiresAt;
75
+ if (typeof raw !== "number" || !Number.isFinite(raw))
76
+ return { state: "valid", expires_at: null };
77
+ const ms = raw < 1e12 ? raw * 1000 : raw;
78
+ const date = new Date(ms);
79
+ const expires_at = Number.isNaN(date.getTime()) ? null : date.toISOString();
80
+ if (ms > nowMs)
81
+ return { state: "valid", expires_at };
82
+ // Past expiry. Claude Code renews the access token from the refresh token
83
+ // at startup, so this is only a dead sign-in when there is nothing to renew
84
+ // with or the refresh token is known to be revoked.
85
+ const refresh = typeof oauth.refreshToken === "string" ? oauth.refreshToken : oauth.refresh_token;
86
+ if (typeof refresh !== "string" || refresh.trim() === "")
87
+ return { state: "expired", expires_at };
88
+ let revoked = false;
89
+ try {
90
+ revoked = isRefreshRevoked(refresh);
91
+ }
92
+ catch {
93
+ revoked = false;
94
+ }
95
+ return { state: revoked ? "expired" : "valid", expires_at };
96
+ }
97
+ function isRecord(value) {
98
+ return value !== null && typeof value === "object" && !Array.isArray(value);
99
+ }
100
+ function defaultSecurity(args) {
101
+ const result = spawnSync("security", [...args], {
102
+ encoding: "utf8",
103
+ timeout: CLAUDE_CREDENTIAL_SECURITY_TIMEOUT_MS,
104
+ stdio: ["ignore", "pipe", "ignore"],
105
+ maxBuffer: 8 * 1024 * 1024,
106
+ });
107
+ const timedOut = result.error?.code === "ETIMEDOUT";
108
+ return {
109
+ status: result.error ? null : result.status,
110
+ stdout: typeof result.stdout === "string" ? result.stdout : "",
111
+ timedOut,
112
+ };
113
+ }
114
+ export function createClaudeCredentialReader(deps = {}) {
115
+ const platform = deps.platform ?? process.platform;
116
+ const now = deps.now ?? (() => Date.now());
117
+ const security = deps.security ?? defaultSecurity;
118
+ const readFile = deps.readFile ?? ((file) => fs.readFileSync(file, "utf8"));
119
+ const isRefreshRevoked = deps.isRefreshRevoked ?? defaultIsRefreshRevoked;
120
+ const fromFile = (home) => {
121
+ let text;
122
+ try {
123
+ text = readFile(path.join(home, ".credentials.json"));
124
+ }
125
+ catch (err) {
126
+ const code = err?.code;
127
+ return { state: code === "ENOENT" ? "missing" : "unknown", expires_at: null, source: null };
128
+ }
129
+ return { ...claudeTokenStateFromDocument(text, now(), isRefreshRevoked), source: "file" };
130
+ };
131
+ return (target) => {
132
+ if (platform !== "darwin")
133
+ return fromFile(target.home);
134
+ const service = laneClaudeKeychainService(target);
135
+ let read;
136
+ try {
137
+ // Claude Code writes its item under the login user's account name. A
138
+ // second item with the same service and another account (MCP OAuth
139
+ // only) can exist, so ask for the user's item first, as the capacity
140
+ // collector does, and fall back to any item for the service.
141
+ const username = deps.username ?? safeUsername();
142
+ read = username
143
+ ? security(["find-generic-password", "-s", service, "-a", username, "-w"])
144
+ : { status: SECURITY_ITEM_NOT_FOUND, stdout: "", timedOut: false };
145
+ if (!read.timedOut && read.status === SECURITY_ITEM_NOT_FOUND) {
146
+ read = security(["find-generic-password", "-s", service, "-w"]);
147
+ }
148
+ }
149
+ catch {
150
+ return { state: "unknown", expires_at: null, source: null };
151
+ }
152
+ if (read.timedOut)
153
+ return { state: "unknown", expires_at: null, source: null };
154
+ if (read.status === SECURITY_ITEM_NOT_FOUND)
155
+ return fromFile(target.home);
156
+ if (read.status !== 0)
157
+ return { state: "unknown", expires_at: null, source: null };
158
+ return { ...claudeTokenStateFromDocument(read.stdout.replace(/\n$/, ""), now(), isRefreshRevoked), source: "keychain" };
159
+ };
160
+ }
161
+ /** Production reader: real Keychain on macOS, the credentials file elsewhere. */
162
+ export const readLaneClaudeCredential = createClaudeCredentialReader();
163
+ //# sourceMappingURL=claude-credential.js.map
@@ -79,6 +79,8 @@ export type RunCompactionFn = (input: {
79
79
  }) => CompactionCommandResult;
80
80
  /** Synchronous `/compact`. stdout is discarded; stderr goes to the run dir. */
81
81
  export declare const defaultRunCompaction: RunCompactionFn;
82
+ /** Stderr line printed before a resume-time `/compact` starts. */
83
+ export declare function compactionStartNotice(sessionId: string): string;
82
84
  export interface CompactLaneSessionInput {
83
85
  command: string;
84
86
  /** Full argv of `claude -p --resume <sid> "/compact" …`, built by buildProviderCommand. */
@@ -388,6 +388,12 @@ export const defaultRunCompaction = (input) => {
388
388
  fs.closeSync(errFd);
389
389
  }
390
390
  };
391
+ /** Stderr line printed before a resume-time `/compact` starts. */
392
+ export function compactionStartNotice(sessionId) {
393
+ const minutes = Math.round(COMPACTION_TIMEOUT_MS / 60_000);
394
+ return `hq lanes: compacting session ${sessionId} before resume; this can take up to ${minutes} minutes. ` +
395
+ `Re-run with --no-compact to skip it.\n`;
396
+ }
391
397
  /**
392
398
  * Run `/compact` on the recorded session and report what happened. A failed
393
399
  * or ineffective compaction is recorded, not thrown: the resume that needed
@@ -398,6 +404,9 @@ export function compactLaneSession(input) {
398
404
  const locate = input.locateTranscript ?? findSessionTranscript;
399
405
  const started = input.now();
400
406
  const beforeProbe = probeCompactBoundaries(locate(input.accountHome, input.sessionId));
407
+ // `/compact` runs synchronously and can take minutes. Say so before it
408
+ // starts, so a resume that is waiting on it does not look hung.
409
+ process.stderr.write(compactionStartNotice(input.sessionId));
401
410
  const result = run({
402
411
  command: input.command,
403
412
  args: input.args,
@@ -186,6 +186,12 @@ function parseAccount(provider, id, raw, deps) {
186
186
  home: canonicalizeHome(raw.home, deps),
187
187
  enabled: raw.enabled,
188
188
  };
189
+ if (raw.company !== undefined) {
190
+ if (typeof raw.company !== "string" || raw.company.trim() === "" || raw.company.trim() !== raw.company) {
191
+ throw new LanesConfigError("invalid_config", `providers.${provider}.accounts.${id}.company must be a non-empty company slug or UID`, { provider, account: id });
192
+ }
193
+ account.company = raw.company;
194
+ }
189
195
  if (raw.hosts !== undefined) {
190
196
  const field = `providers.${provider}.accounts.${id}.hosts`;
191
197
  if (!isPlainObject(raw.hosts)) {
@@ -1,6 +1,7 @@
1
1
  import { spawnSync as nodeSpawnSync } from "node:child_process";
2
2
  import * as path from "node:path";
3
3
  import { LanesError } from "./errors.js";
4
+ import { liveNodeBinary } from "./node-binary.js";
4
5
  const LANE_RUNNER_ENTRY_NAMES = new Set(["watcher-main", "worker-process", "remote-control-lane"]);
5
6
  /**
6
7
  * True for the detached lane runner scripts. They are not the hq CLI: running
@@ -42,7 +43,7 @@ export function spawnEnvelopeRepairViaCurrentCli(hqRoot, lane, input, deps = {})
42
43
  isLaneRunnerEntry(cliEntry)) {
43
44
  throw new LanesError("repair_cli_entry_invalid", "Lane watcher has no valid absolute hq CLI entrypoint for envelope repair", { lane_id: lane.lane_id });
44
45
  }
45
- const result = run(process.execPath, [cliEntry, "lanes", "_spawn-envelope-repair"], {
46
+ const result = run(liveNodeBinary(), [cliEntry, "lanes", "_spawn-envelope-repair"], {
46
47
  encoding: "utf8",
47
48
  timeout: 120_000,
48
49
  input: JSON.stringify(request),
@@ -25,6 +25,7 @@ import * as path from "node:path";
25
25
  import { fileURLToPath } from "node:url";
26
26
  import { parse as parseToml, TomlError } from "smol-toml";
27
27
  import { LanesError } from "./errors.js";
28
+ import { liveNodeBinary } from "./node-binary.js";
28
29
  import { parseLaneProvider } from "./types.js";
29
30
  export const DRAIN_HOOK_BASENAME = "hq-lanes-drain";
30
31
  export const DRAIN_HOOK_TIMEOUT_SECONDS = 30;
@@ -49,7 +50,7 @@ export const PROVIDER_REGISTRATION_KIND = {
49
50
  };
50
51
  export function drainHookCommand(_shPath, provider) {
51
52
  const providerEnv = provider === "grok" ? "HQ_LANE_PROVIDER=grok " : "";
52
- return `${providerEnv}${shellQuote(process.execPath)} ${shellQuote(drainHookEntryPath())}`;
53
+ return `${providerEnv}${shellQuote(liveNodeBinary())} ${shellQuote(drainHookEntryPath())}`;
53
54
  }
54
55
  function legacyDrainHookCommand(shPath) {
55
56
  return `bash ${shPath}`;
@@ -1,4 +1,5 @@
1
1
  import { type AuthState } from "./accounts.js";
2
+ import type { ClaudeCredentialReader } from "./claude-credential.js";
2
3
  import { type QuotaState } from "./quota.js";
3
4
  import type { LaneHost, LaneProvider, LaneRecord, LanesConfig } from "./types.js";
4
5
  export interface HostCapacityAccount {
@@ -63,6 +64,7 @@ export declare function buildHostCapacitySnapshot(input: {
63
64
  hostname?: string;
64
65
  now: Date;
65
66
  quotaState?: QuotaState;
67
+ readClaudeCredential?: ClaudeCredentialReader;
66
68
  }): HostCapacitySnapshot;
67
69
  /** Reject malformed remote snapshots before they can influence host selection. */
68
70
  export declare function parseHostCapacitySnapshot(raw: unknown): HostCapacitySnapshot;