Fix owner context loss after finalize; green the test suite
Owner continuity: - Seed a freshly created owner task with the previous task's latest owner final on a cold start after the previous task already closed, so a user reply to a finalized TASK_DONE no longer produces a "no context" answer. Activated for this deployment via PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL (.env); carried text is injected as clearly-marked background only. - Skip intermediate STEP_DONE outputs when picking the carry-forward anchor. Single-mode routing: - enforceRoomModeOnLease strips a stale reviewer/arbiter lease from a room switched back to single, preventing single-mode messages from stalling in the paired path on a stuck execution lease. Session auth / credentials: - Pre-sync Claude credentials into each session dir before the agent spawns. - Honor CLAUDE_CREDENTIALS_PATH in setup/login.ts (per-service isolation). - Add a relogin-required gate so a permanently logged-out claude-code room asks the user to re-login instead of spawning a doomed agent. Other: - Arbiter verdicts written in the user's language (verdict keyword stays EN). - status-dashboard chatName field; runtime-inventory credential path resolver. Tests (make suite fully green: 1595 pass / 3 skip): - service-routing: default owner is now the claude service and reviewer is codex-review; update the 7 failover/default expectations accordingly. - migrate-room-registrations: owner inferred as claude-code (configured OWNER_AGENT_TYPE) for a dual legacy room; reviewer becomes codex. - register: mock paired-workspace provisioning + reload signal (registration now provisions a workspace and hot-reloads); assert RELOADED status. - paired-execution-context: force a claude-code reviewer to exercise the Claude read-only branch regardless of the deployment default. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -6,9 +6,12 @@
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import {
|
||||
getClaudeCredentialsPath,
|
||||
hasExplicitClaudeCredentialsPath,
|
||||
} from './claude-credentials-path.js';
|
||||
import { DATA_DIR } from './config.js';
|
||||
import { logger } from './logger.js';
|
||||
import {
|
||||
@@ -32,6 +35,14 @@ export interface ClaudeUsageData {
|
||||
const USAGE_ENDPOINT = 'https://api.anthropic.com/api/oauth/usage';
|
||||
const FETCH_TIMEOUT_MS = 10_000;
|
||||
|
||||
// Master gate for credentials-backed usage queries. When false, the module
|
||||
// uses only env-supplied tokens and skips all credentials-file reads, per-
|
||||
// account cache keys, and on-401 refresh attempts. Enabled when either an
|
||||
// explicit CLAUDE_CREDENTIALS_PATH is set or the home fallback is allowed.
|
||||
const USE_CLAUDE_CREDENTIALS_FOR_USAGE =
|
||||
hasExplicitClaudeCredentialsPath() ||
|
||||
process.env.CLAUDE_USAGE_USE_HOME_CREDENTIALS !== 'false';
|
||||
|
||||
interface UsageApiResponse {
|
||||
five_hour?: { utilization: number; resets_at?: string };
|
||||
seven_day?: { utilization: number; resets_at?: string };
|
||||
@@ -112,7 +123,7 @@ export function getUsageCacheWriteKey(
|
||||
token: string,
|
||||
accountIndex?: number,
|
||||
): string {
|
||||
return accountIndex != null
|
||||
return USE_CLAUDE_CREDENTIALS_FOR_USAGE && accountIndex != null
|
||||
? accountCacheKey(accountIndex)
|
||||
: legacyTokenCacheKey(token);
|
||||
}
|
||||
@@ -123,9 +134,11 @@ export function getUsageCacheReadKeys(
|
||||
credentialsAccessToken?: string | null,
|
||||
): string[] {
|
||||
const keys: string[] = [];
|
||||
if (accountIndex != null) keys.push(accountCacheKey(accountIndex));
|
||||
if (USE_CLAUDE_CREDENTIALS_FOR_USAGE && accountIndex != null) {
|
||||
keys.push(accountCacheKey(accountIndex));
|
||||
}
|
||||
|
||||
if (credentialsAccessToken) {
|
||||
if (USE_CLAUDE_CREDENTIALS_FOR_USAGE && credentialsAccessToken) {
|
||||
const credsKey = legacyTokenCacheKey(credentialsAccessToken);
|
||||
if (!keys.includes(credsKey)) keys.push(credsKey);
|
||||
}
|
||||
@@ -265,7 +278,11 @@ async function fetchUsageForToken(
|
||||
// 401 = token expired; 403 = token lacks `user:profile` scope.
|
||||
// Both are recoverable by exchanging refresh_token for a fresh access
|
||||
// token (mint includes current default scope set). Retry once.
|
||||
if (accountIndex != null && !refreshAttempted) {
|
||||
if (
|
||||
USE_CLAUDE_CREDENTIALS_FOR_USAGE &&
|
||||
accountIndex != null &&
|
||||
!refreshAttempted
|
||||
) {
|
||||
try {
|
||||
const { forceRefreshToken } = await import('./token-refresh.js');
|
||||
const newToken = await forceRefreshToken(accountIndex);
|
||||
@@ -303,7 +320,14 @@ async function fetchUsageForToken(
|
||||
if (res.status === 429) {
|
||||
const staleMs = cached ? Date.now() - cached.fetchedAt : 0;
|
||||
const retryAfterMs = parseRetryAfterMs(res.headers.get('retry-after'));
|
||||
const cooldownMs = retryAfterMs ?? DEFAULT_RATE_LIMIT_COOLDOWN_MS;
|
||||
// A `Retry-After` of 0 (or a past HTTP-date that parses to 0) must NOT
|
||||
// disable the backoff — honoring it literally makes the poller retry on
|
||||
// the next 60s tick and re-trip the 429 indefinitely. Treat any
|
||||
// non-positive value as "no usable hint" and fall back to the default.
|
||||
const cooldownMs =
|
||||
retryAfterMs != null && retryAfterMs > 0
|
||||
? retryAfterMs
|
||||
: DEFAULT_RATE_LIMIT_COOLDOWN_MS;
|
||||
const cooldownUntil = Date.now() + cooldownMs + RATE_LIMIT_MARGIN_MS;
|
||||
logger.warn(
|
||||
{
|
||||
@@ -403,12 +427,11 @@ async function fetchUsageForToken(
|
||||
* Uses the current active token from rotation.
|
||||
*/
|
||||
export async function fetchClaudeUsage(): Promise<ClaudeUsageData | null> {
|
||||
// Prefer the access token in ~/.claude/.credentials.json when present.
|
||||
// The static .env token (CLAUDE_CODE_OAUTH_TOKEN) was issued before the
|
||||
// `user:profile` scope was required for /api/oauth/usage and so always 403s.
|
||||
// The credentials file is the canonical source written by `claude auth
|
||||
// login` and kept fresh by token-refresh.ts — its accessToken carries the
|
||||
// full scope set including user:profile.
|
||||
// Prefer the access token in credentials.json when present. The static .env
|
||||
// token (CLAUDE_CODE_OAUTH_TOKEN) was issued before the `user:profile` scope
|
||||
// was required for /api/oauth/usage and so always 403s. The credentials file
|
||||
// is the canonical source written by `claude auth login` and kept fresh by
|
||||
// token-refresh.ts — its accessToken carries the full scope set.
|
||||
const credsToken = readCredentialsAccessToken(0);
|
||||
const token =
|
||||
credsToken || getCurrentToken() || getConfiguredClaudeTokens()[0];
|
||||
@@ -416,7 +439,8 @@ export async function fetchClaudeUsage(): Promise<ClaudeUsageData | null> {
|
||||
logger.debug('No Claude OAuth token available for usage check');
|
||||
return null;
|
||||
}
|
||||
return (await fetchUsageForToken(token, undefined)).usage;
|
||||
// Pass accountIndex=0 so 401/403 → forceRefreshToken retry path engages.
|
||||
return (await fetchUsageForToken(token, 0)).usage;
|
||||
}
|
||||
|
||||
export interface ClaudeAccountProfile {
|
||||
@@ -428,21 +452,18 @@ const profileCache = new Map<number, ClaudeAccountProfile>();
|
||||
|
||||
/**
|
||||
* Read planType from credentials file as fallback when profile API fails.
|
||||
* Account 0: ~/.claude/.credentials.json
|
||||
* Account 1+: ~/.claude-accounts/{index}/.credentials.json
|
||||
* Path is resolved by getClaudeCredentialsPath (honours CLAUDE_CREDENTIALS_PATH
|
||||
* / CLAUDE_ACCOUNTS_DIR / home fallback). Returns null when the credentials
|
||||
* gate is off or no file is found.
|
||||
*/
|
||||
function readCredentialsPlanType(accountIndex: number): string | null {
|
||||
if (!USE_CLAUDE_CREDENTIALS_FOR_USAGE) return null;
|
||||
try {
|
||||
const credsPath =
|
||||
accountIndex === 0
|
||||
? path.join(os.homedir(), '.claude', '.credentials.json')
|
||||
: path.join(
|
||||
os.homedir(),
|
||||
'.claude-accounts',
|
||||
String(accountIndex),
|
||||
'.credentials.json',
|
||||
);
|
||||
if (!fs.existsSync(credsPath)) return null;
|
||||
const credsPath = getClaudeCredentialsPath(accountIndex, {
|
||||
allowHomeFallback:
|
||||
process.env.CLAUDE_USAGE_USE_HOME_CREDENTIALS !== 'false',
|
||||
});
|
||||
if (!credsPath || !fs.existsSync(credsPath)) return null;
|
||||
const data = readJsonFile<{
|
||||
claudeAiOauth?: { subscriptionType?: string };
|
||||
}>(credsPath);
|
||||
@@ -453,17 +474,13 @@ function readCredentialsPlanType(accountIndex: number): string | null {
|
||||
}
|
||||
|
||||
function readCredentialsAccessToken(accountIndex: number): string | null {
|
||||
if (!USE_CLAUDE_CREDENTIALS_FOR_USAGE) return null;
|
||||
try {
|
||||
const credsPath =
|
||||
accountIndex === 0
|
||||
? path.join(os.homedir(), '.claude', '.credentials.json')
|
||||
: path.join(
|
||||
os.homedir(),
|
||||
'.claude-accounts',
|
||||
String(accountIndex),
|
||||
'.credentials.json',
|
||||
);
|
||||
if (!fs.existsSync(credsPath)) return null;
|
||||
const credsPath = getClaudeCredentialsPath(accountIndex, {
|
||||
allowHomeFallback:
|
||||
process.env.CLAUDE_USAGE_USE_HOME_CREDENTIALS !== 'false',
|
||||
});
|
||||
if (!credsPath || !fs.existsSync(credsPath)) return null;
|
||||
const data = readJsonFile<{
|
||||
claudeAiOauth?: { accessToken?: string };
|
||||
}>(credsPath);
|
||||
@@ -519,7 +536,10 @@ async function fetchProfileForToken(
|
||||
export async function fetchAllClaudeProfiles(): Promise<void> {
|
||||
const allTokens = getAllTokens();
|
||||
for (const t of allTokens) {
|
||||
let profile = await fetchProfileForToken(t.token);
|
||||
// Prefer the per-account credentials access token; the static env token
|
||||
// may lack the `user:profile` scope.
|
||||
const credsToken = readCredentialsAccessToken(t.index);
|
||||
let profile = await fetchProfileForToken(credsToken || t.token);
|
||||
|
||||
// Fallback: if profile API failed or returned unknown plan, use credentials file
|
||||
if (!profile || profile.planType === '?') {
|
||||
|
||||
Reference in New Issue
Block a user