@indigoai-us/hq-cli 5.221.0 → 5.223.0

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.
@@ -14,6 +14,8 @@ import * as path from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import { PROVIDER_HOME_ENV, accountStatus, isLoggedOut, resolveAccount, selectBalancedAccount, } from "./accounts.js";
16
16
  import { effectiveAccountHome } from "./account-home.js";
17
+ import { buildHostCapacitySnapshot } from "./host-capacity.js";
18
+ import { selectClaudeAccount } from "./claude-account-balance.js";
17
19
  import { COMPACTION_PROMPT, compactionAfterUsage, compactionDue, compactLaneSession, } from "./compaction.js";
18
20
  import { installDrainHook } from "./hooks-install.js";
19
21
  import { loadLanesConfig, providerAutoCompactTokens, providerCompactAfterMs, } from "./config.js";
@@ -159,7 +161,7 @@ function spawnModelFailure(provider, accountId, config, pinnedModel, profileMode
159
161
  }
160
162
  }
161
163
  function selectSpawnAccount(input) {
162
- const { hqRoot, lane, config, existsSync, accountDeps, modelDeps, pinnedModel, profileModel, currentModelValidated, hostname } = input;
164
+ const { hqRoot, lane, config, existsSync, accountDeps, modelDeps, pinnedModel, profileModel, currentModelValidated, hostname, repairRecordedAccount, recordedModel, now } = input;
163
165
  const context = {
164
166
  hqRoot,
165
167
  existsSync,
@@ -187,7 +189,7 @@ function selectSpawnAccount(input) {
187
189
  const operatorMovePending = lane.pending_resume !== undefined &&
188
190
  lane.account_history?.at(-1)?.reason === "operator_move";
189
191
  if (current === undefined || !current.enabled) {
190
- reason = "account_unavailable";
192
+ reason = repairRecordedAccount ? "recorded_account_logged_out" : "account_unavailable";
191
193
  refusal = new AccountResolutionError(current === undefined ? "unknown_account" : "account_disabled", `Account ${JSON.stringify(lane.account)} is unavailable for ${lane.provider}`, { provider: lane.provider, account: lane.account });
192
194
  }
193
195
  else {
@@ -198,7 +200,7 @@ function selectSpawnAccount(input) {
198
200
  ...(accountDeps?.env ? { env: accountDeps.env } : {}),
199
201
  });
200
202
  if (isLoggedOut(status)) {
201
- reason = "account_unavailable";
203
+ reason = repairRecordedAccount ? "recorded_account_logged_out" : "account_unavailable";
202
204
  refusal = new LanesError("account_not_logged_in", `Account ${lane.account} for ${lane.provider} is not logged in`, { provider: lane.provider, account: lane.account });
203
205
  }
204
206
  else {
@@ -242,6 +244,33 @@ function selectSpawnAccount(input) {
242
244
  account: lane.account,
243
245
  });
244
246
  }
247
+ if (reason === "recorded_account_logged_out" && lane.provider === "claude") {
248
+ const lanes = listLaneIds(hqRoot)
249
+ .map((laneId) => readLane(hqRoot, laneId))
250
+ .filter((record) => record.host.kind === lane.host.kind && record.host.id === lane.host.id);
251
+ const capacity = buildHostCapacitySnapshot({
252
+ host: lane.host,
253
+ lanes,
254
+ config,
255
+ existsSync,
256
+ probe: accountDeps?.probe,
257
+ env: accountDeps?.env,
258
+ hostname,
259
+ now,
260
+ });
261
+ const selection = selectClaudeAccount({
262
+ hosts: [{ capacity, lanes, laneListAvailable: true }],
263
+ targetHost: lane.host,
264
+ config,
265
+ ...((recordedModel ?? pinnedModel ?? profileModel) !== undefined
266
+ ? { model: recordedModel ?? pinnedModel ?? profileModel }
267
+ : {}),
268
+ });
269
+ return {
270
+ account: resolveAccount(lane.provider, selection.account, config, context),
271
+ changeReason: "recorded_account_logged_out",
272
+ };
273
+ }
245
274
  const allowedAccounts = Object.entries(config.providers[lane.provider].accounts)
246
275
  .filter(([id, account]) => id !== lane.account && account.enabled)
247
276
  .filter(([id]) => accountStatus(lane.provider, id, config, {
@@ -254,12 +283,15 @@ function selectSpawnAccount(input) {
254
283
  .map(([id]) => id);
255
284
  try {
256
285
  return {
257
- account: selectBalancedAccount(lane.provider, config, { ...context, allowedAccounts }),
286
+ account: selectBalancedAccount(lane.provider, config, {
287
+ ...context,
288
+ allowedAccounts,
289
+ }),
258
290
  changeReason: reason,
259
291
  };
260
292
  }
261
293
  catch (err) {
262
- if (reason === "account_unavailable") {
294
+ if (reason === "account_unavailable" || reason === "recorded_account_logged_out") {
263
295
  if (refusal instanceof Error)
264
296
  throw refusal;
265
297
  throw new LanesError("account_not_logged_in", `Account ${lane.account} for ${lane.provider} is not logged in or available, and no other logged-in account can serve this lane`, { provider: lane.provider, account: lane.account });
@@ -274,7 +306,8 @@ function previouslyUnavailableAccounts(lane) {
274
306
  for (const entry of [...(lane.account_history ?? [])].reverse()) {
275
307
  if (entry.reason === "first_assignment" || entry.reason === "operator_move")
276
308
  break;
277
- if (entry.reason === "account_unavailable" && entry.from !== null)
309
+ if ((entry.reason === "account_unavailable" || entry.reason === "recorded_account_logged_out") &&
310
+ entry.from !== null)
278
311
  excluded.add(entry.from);
279
312
  }
280
313
  return excluded;
@@ -364,7 +397,9 @@ export async function retryLaneOnAlternateAccount(hqRoot, lane, reason, writer =
364
397
  };
365
398
  const profile = lane.worker_profile ? loadWorkerProfile(hqRoot, lane.worker_profile) : undefined;
366
399
  const profileModel = profile?.meta.provider === lane.provider ? profile.meta.model : undefined;
367
- const pinnedModel = lane.model_source === undefined || lane.model_source === "cli" ? lane.model : undefined;
400
+ const pinnedModel = lane.model_source === undefined || lane.model_source === "cli" || lane.model_source === "preserved"
401
+ ? lane.model
402
+ : undefined;
368
403
  const unavailableAccounts = previouslyUnavailableAccounts(lane);
369
404
  const allowedAccounts = Object.entries(config.providers[lane.provider].accounts)
370
405
  .filter(([id, account]) => id !== lane.account && !unavailableAccounts.has(id) && account.enabled)
@@ -1649,7 +1684,12 @@ export function spawnLaneWorker(hqRoot, lane, deps = {}, launch = {}) {
1649
1684
  : undefined;
1650
1685
  const profileChanged = profile !== undefined && existing.worker_profile_hash !== profile.contentHash;
1651
1686
  const config = loadLanesConfig(hqRoot);
1652
- const pinnedModel = existing.model_source === undefined || existing.model_source === "cli"
1687
+ const repairRecordedAccount = plan.mode === "resume" &&
1688
+ (trigger.kind === "resume" || pendingResume?.trigger === "resume");
1689
+ const recordedModel = repairRecordedAccount && existing.model_source === "account"
1690
+ ? existing.model
1691
+ : undefined;
1692
+ let pinnedModel = existing.model_source === undefined || existing.model_source === "cli" || existing.model_source === "preserved"
1653
1693
  ? existing.model
1654
1694
  : undefined;
1655
1695
  const accountDeps = {
@@ -1669,6 +1709,9 @@ export function spawnLaneWorker(hqRoot, lane, deps = {}, launch = {}) {
1669
1709
  profileModel,
1670
1710
  currentModelValidated: deps.currentModelValidated === true,
1671
1711
  hostname,
1712
+ repairRecordedAccount,
1713
+ ...(recordedModel !== undefined ? { recordedModel } : {}),
1714
+ now: (deps.now ?? (() => new Date()))(),
1672
1715
  });
1673
1716
  }
1674
1717
  catch (err) {
@@ -1683,6 +1726,9 @@ export function spawnLaneWorker(hqRoot, lane, deps = {}, launch = {}) {
1683
1726
  process.stderr.write(`hq lanes: account bind failed for ${lane.lane_id}: ${err instanceof Error ? err.message : String(err)}\n`);
1684
1727
  throw err;
1685
1728
  }
1729
+ const preservedAccountModel = selection.changeReason === "recorded_account_logged_out" ? recordedModel : undefined;
1730
+ if (preservedAccountModel !== undefined)
1731
+ pinnedModel = preservedAccountModel;
1686
1732
  const resolved = selection.account;
1687
1733
  const status = accountStatus(lane.provider, resolved.id, config, { existsSync, hostname });
1688
1734
  if (isLoggedOut(status)) {
@@ -1738,6 +1784,9 @@ export function spawnLaneWorker(hqRoot, lane, deps = {}, launch = {}) {
1738
1784
  return {
1739
1785
  ...current,
1740
1786
  account: resolved.id,
1787
+ ...(preservedAccountModel !== undefined
1788
+ ? { model: preservedAccountModel, model_source: "preserved" }
1789
+ : {}),
1741
1790
  account_history: appendCappedHistory(current.account_history ?? [], entry),
1742
1791
  };
1743
1792
  });
@@ -1934,7 +1983,9 @@ export function spawnLaneWorker(hqRoot, lane, deps = {}, launch = {}) {
1934
1983
  ...(model !== undefined
1935
1984
  ? {
1936
1985
  model_source: pinnedModel !== undefined
1937
- ? "cli"
1986
+ ? preservedAccountModel !== undefined || existing.model_source === "preserved"
1987
+ ? "preserved"
1988
+ : "cli"
1938
1989
  : profileModel !== undefined
1939
1990
  ? "profile"
1940
1991
  : accountCfg?.model !== undefined
@@ -2195,7 +2246,7 @@ export function spawnEnvelopeRepair(hqRoot, lane, input, deps = {}) {
2195
2246
  ignoredFields: ignoredProfileFields,
2196
2247
  }
2197
2248
  : undefined;
2198
- const pinnedModel = lane.model_source === undefined || lane.model_source === "cli"
2249
+ const pinnedModel = lane.model_source === undefined || lane.model_source === "cli" || lane.model_source === "preserved"
2199
2250
  ? lane.model
2200
2251
  : undefined;
2201
2252
  const resolved = resolveAccount(lane.provider, lane.account, config, {
@@ -2307,7 +2358,7 @@ export function spawnEnvelopeRepair(hqRoot, lane, input, deps = {}) {
2307
2358
  if (model !== undefined) {
2308
2359
  next.model = model;
2309
2360
  next.model_source = pinnedModel !== undefined
2310
- ? "cli"
2361
+ ? lane.model_source === "preserved" ? "preserved" : "cli"
2311
2362
  : profileModel !== undefined
2312
2363
  ? "profile"
2313
2364
  : accountCfg?.model !== undefined
@@ -412,8 +412,8 @@ export interface LaneRecord {
412
412
  last_envelope?: LastEnvelopeRef;
413
413
  /** Effective model id recorded at create/spawn. Omitted when the provider chooses. */
414
414
  model?: string;
415
- /** Where the effective model came from; profile values are re-read on spawn. */
416
- model_source?: "cli" | "profile" | "account" | "provider" | "none";
415
+ /** Where the effective model came from; repaired models stay pinned across the account move. */
416
+ model_source?: "cli" | "profile" | "account" | "provider" | "preserved" | "none";
417
417
  /** Effective effort level passed to the provider at the last spawn (effort.ts). */
418
418
  effort?: string;
419
419
  /** Where `effort` came from. `cli` pins it across later spawns. */
@@ -523,7 +523,7 @@ export interface AccountHistoryEntry {
523
523
  from: string | null;
524
524
  to: string;
525
525
  at: string;
526
- reason: "first_assignment" | "model_change" | "usage_limit" | "account_unavailable" | "operator_move";
526
+ reason: "first_assignment" | "model_change" | "usage_limit" | "account_unavailable" | "recorded_account_logged_out" | "operator_move";
527
527
  }
528
528
  export interface PendingResume {
529
529
  /** Fresh answered-question launches need no previous session id. */
@@ -1,16 +1,33 @@
1
- import { type LaneRecord, type QuestionRecord } from "./types.js";
1
+ import { type LaneHost, type LaneProvider, type LaneRecord, type QuestionRecord } from "./types.js";
2
2
  export declare const DEFAULT_LANE_WATCH_INTERVAL_MS = 5000;
3
3
  export declare const MAX_LANE_WATCH_INTERVAL_MS = 30000;
4
4
  export declare const MAX_WATCHED_LANES = 64;
5
5
  export declare const MAX_WATCH_OUTPUT_LINES = 512;
6
+ export interface LaneWatchAccountStatus {
7
+ lane_id: string;
8
+ provider: LaneProvider;
9
+ account: string;
10
+ host: LaneHost;
11
+ logged_in: boolean | null;
12
+ }
13
+ export interface LaneAccountLoggedOutEvent {
14
+ event: "account_logged_out";
15
+ provider: LaneProvider;
16
+ account: string;
17
+ host: LaneHost;
18
+ lane_ids: string[];
19
+ }
6
20
  export interface LaneWatchDeps {
7
21
  readLane?: (hqRoot: string, laneId: string) => LaneRecord | null;
8
22
  listQuestionIds?: (hqRoot: string) => string[];
9
23
  readQuestion?: (hqRoot: string, questionId: string) => QuestionRecord | null;
24
+ readAccountStatuses?: (lanes: readonly LaneRecord[]) => Promise<readonly LaneWatchAccountStatus[]>;
25
+ keepAliveEnabled?: (lane: LaneRecord) => boolean | Promise<boolean>;
10
26
  sleep?: (ms: number) => Promise<void>;
11
27
  intervalMs?: number;
12
28
  maxOutputLines?: number;
13
29
  writeLine?: (line: string) => void;
30
+ writeAccountEvent?: (event: LaneAccountLoggedOutEvent) => void;
14
31
  writeError?: (line: string) => void;
15
32
  }
16
33
  export interface LaneWatchResult {
@@ -1,6 +1,8 @@
1
1
  import { listQuestionIds, readLane, readQuestion, } from "./store.js";
2
2
  import { LaneNotFoundError, LanesError } from "./errors.js";
3
- import { isTerminalLaneState } from "./types.js";
3
+ import { providerSupportsSessionResume } from "./delivery.js";
4
+ import { LEAD_LANE_KEEP_ALIVE_MAX_RESUMES } from "./keep-alive.js";
5
+ import { isTerminalLaneState, } from "./types.js";
4
6
  export const DEFAULT_LANE_WATCH_INTERVAL_MS = 5_000;
5
7
  export const MAX_LANE_WATCH_INTERVAL_MS = 30_000;
6
8
  export const MAX_WATCHED_LANES = 64;
@@ -30,6 +32,30 @@ function validateLaneIds(laneIds) {
30
32
  }
31
33
  return unique;
32
34
  }
35
+ function canResumeKeepAliveLane(lane) {
36
+ if (lane.keep_alive !== true ||
37
+ lane.keep_alive_opted_in_at === undefined ||
38
+ !Number.isFinite(Date.parse(lane.keep_alive_opted_in_at)) ||
39
+ lane.keep_alive_exhausted_at !== undefined ||
40
+ (lane.keep_alive_resume_count ?? 0) >= LEAD_LANE_KEEP_ALIVE_MAX_RESUMES ||
41
+ lane.keep_alive_blocked_reason === "retired" ||
42
+ lane.keep_alive_blocked_reason === "superseded" ||
43
+ lane.keep_alive_blocked_reason === "retired_list_invalid" ||
44
+ lane.keep_alive_blocked_reason === "terminal_state" ||
45
+ !providerSupportsSessionResume(lane.provider) ||
46
+ !(lane.provider_session_id ?? lane.last_resume?.session_id))
47
+ return false;
48
+ if (lane.state === "interrupted") {
49
+ return lane.terminal_reason === "exited_with_partial_output";
50
+ }
51
+ if (lane.state === "done") {
52
+ return lane.last_envelope?.decision === "done" &&
53
+ lane.story_complete !== true &&
54
+ lane.terminal_reason !== "provider_rejected" &&
55
+ lane.terminal_reason !== "account_not_logged_in";
56
+ }
57
+ return false;
58
+ }
33
59
  export async function runLaneWatch(hqRoot, laneIds, deps = {}) {
34
60
  const watchedIds = validateLaneIds(laneIds);
35
61
  const readLaneRecord = deps.readLane ?? readLane;
@@ -37,11 +63,15 @@ export async function runLaneWatch(hqRoot, laneIds, deps = {}) {
37
63
  const readQuestionRecord = deps.readQuestion ?? readQuestion;
38
64
  const sleep = deps.sleep ?? defaultSleep;
39
65
  const writeLine = deps.writeLine ?? ((line) => console.log(line));
66
+ const writeAccountEvent = deps.writeAccountEvent ?? ((event) => {
67
+ writeLine(`account_logged_out provider=${event.provider} account=${event.account} host=${event.host.kind}:${event.host.id} lane_ids=${event.lane_ids.join(",")}`);
68
+ });
40
69
  const writeError = deps.writeError ?? ((line) => process.stderr.write(`${line}\n`));
41
70
  const maxOutputLines = Math.max(1, Math.floor(deps.maxOutputLines ?? MAX_WATCH_OUTPUT_LINES));
42
71
  const intervalMs = boundedInterval(deps.intervalMs);
43
72
  const previousStates = new Map();
44
73
  const previousQuestionStatuses = new Map();
74
+ const previousAccountLogin = new Map();
45
75
  let polls = 0;
46
76
  let lines = 0;
47
77
  let suppressed = false;
@@ -57,6 +87,18 @@ export async function runLaneWatch(hqRoot, laneIds, deps = {}) {
57
87
  suppressed = true;
58
88
  }
59
89
  };
90
+ const emitAccountEvent = (event) => {
91
+ if (lines < maxOutputLines - 1) {
92
+ writeAccountEvent(event);
93
+ lines += 1;
94
+ return;
95
+ }
96
+ if (!suppressed) {
97
+ writeLine("lane watch: output limit reached; further events suppressed");
98
+ lines = maxOutputLines;
99
+ suppressed = true;
100
+ }
101
+ };
60
102
  const unreadable = (kind, id, err) => {
61
103
  const message = `${kind} ${id}: unreadable record (${readableError(err)})`;
62
104
  writeError(`lane watch: ${message}`);
@@ -87,6 +129,15 @@ export async function runLaneWatch(hqRoot, laneIds, deps = {}) {
87
129
  previousStates.set(laneId, record.state);
88
130
  }
89
131
  }
132
+ const keepAliveWaiting = new Set();
133
+ if (deps.keepAliveEnabled !== undefined) {
134
+ for (const record of records) {
135
+ if (isTerminalLaneState(record.state) &&
136
+ canResumeKeepAliveLane(record) &&
137
+ await deps.keepAliveEnabled(record))
138
+ keepAliveWaiting.add(record.lane_id);
139
+ }
140
+ }
90
141
  let questionIds = [];
91
142
  try {
92
143
  questionIds = listQuestions(hqRoot);
@@ -113,7 +164,76 @@ export async function runLaneWatch(hqRoot, laneIds, deps = {}) {
113
164
  }
114
165
  previousQuestionStatuses.set(questionId, record.status);
115
166
  }
116
- if (records.every((record) => isTerminalLaneState(record.state))) {
167
+ if (deps.readAccountStatuses !== undefined) {
168
+ const accountLanes = records.filter((record) => record.account !== undefined &&
169
+ (!isTerminalLaneState(record.state) || keepAliveWaiting.has(record.lane_id)));
170
+ let statuses;
171
+ try {
172
+ statuses = await deps.readAccountStatuses(accountLanes);
173
+ }
174
+ catch (err) {
175
+ const message = `account login status: ${readableError(err)}`;
176
+ writeError(`lane watch: ${message}`);
177
+ throw new LanesError("watch_account_status_unavailable", message, {
178
+ cause: readableError(err),
179
+ });
180
+ }
181
+ const statusLanes = new Map(accountLanes.map((record) => [record.lane_id, record]));
182
+ const grouped = new Map();
183
+ const seenLaneIds = new Set();
184
+ for (const status of statuses) {
185
+ const lane = statusLanes.get(status.lane_id);
186
+ if (!lane || lane.provider !== status.provider || lane.account !== status.account ||
187
+ lane.host.kind !== status.host.kind || lane.host.id !== status.host.id ||
188
+ (status.logged_in !== true && status.logged_in !== false && status.logged_in !== null) ||
189
+ seenLaneIds.has(status.lane_id)) {
190
+ const message = `malformed account login status for lane ${JSON.stringify(status.lane_id)}`;
191
+ writeError(`lane watch: ${message}`);
192
+ throw new LanesError("watch_account_status_invalid", message, {
193
+ lane_id: status.lane_id,
194
+ });
195
+ }
196
+ seenLaneIds.add(status.lane_id);
197
+ const key = JSON.stringify([status.provider, status.account, status.host.kind, status.host.id]);
198
+ const existing = grouped.get(key);
199
+ if (existing && existing.status.logged_in !== status.logged_in) {
200
+ const message = `conflicting account login statuses for ${status.provider} account ${status.account} on ${status.host.kind}:${status.host.id}`;
201
+ writeError(`lane watch: ${message}`);
202
+ throw new LanesError("watch_account_status_invalid", message, {
203
+ provider: status.provider,
204
+ account: status.account,
205
+ host: status.host,
206
+ });
207
+ }
208
+ const group = existing ?? { status, laneIds: new Set() };
209
+ group.laneIds.add(status.lane_id);
210
+ grouped.set(key, group);
211
+ }
212
+ const missingLane = accountLanes.find((lane) => !seenLaneIds.has(lane.lane_id));
213
+ if (missingLane) {
214
+ const message = `account login status is missing for lane ${missingLane.lane_id}`;
215
+ writeError(`lane watch: ${message}`);
216
+ throw new LanesError("watch_account_status_invalid", message, {
217
+ lane_id: missingLane.lane_id,
218
+ });
219
+ }
220
+ for (const [key, group] of grouped) {
221
+ const { status } = group;
222
+ const prior = previousAccountLogin.get(key);
223
+ if (prior === true && status.logged_in === false) {
224
+ emitAccountEvent({
225
+ event: "account_logged_out",
226
+ provider: status.provider,
227
+ account: status.account,
228
+ host: status.host,
229
+ lane_ids: [...group.laneIds].sort(),
230
+ });
231
+ }
232
+ if (status.logged_in !== null)
233
+ previousAccountLogin.set(key, status.logged_in);
234
+ }
235
+ }
236
+ if (records.every((record) => isTerminalLaneState(record.state) && !keepAliveWaiting.has(record.lane_id))) {
117
237
  return { polls, lines, suppressed };
118
238
  }
119
239
  await sleep(intervalMs);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indigoai-us/hq-cli",
3
- "version": "5.221.0",
3
+ "version": "5.223.0",
4
4
  "description": "HQ by Indigo management CLI — modules and cloud sync",
5
5
  "main": "dist/index.js",
6
6
  "bin": {