Compare commits

...
16 changed files with 873 additions and 26 deletions
@@ -338,3 +338,23 @@ it("says when a failure that waits on its retry time is retried, in list and ins
"Reason: Rate limited by Claude. Retrying at 2026-10-09T12:11:00.000Z.",
);
});
it("inspects and refreshes a target-only report absent from the host list", async () => {
const entry = reports[0]!;
const queries: Array<{ reportIds?: string[]; forceRefresh?: boolean } | undefined> = [];
const connect = async () => ({
getLastServerInfoMessage: () => ({ features: { usageSources: true } }),
listUsageReports: async (query?: (typeof queries)[number]) => {
queries.push(query);
return { requestId: "request", reports: query?.reportIds ? [entry] : [] };
},
close: async () => {},
});
const result = await runUsageCommand(
{ ...options, refresh: true },
{ kind: "inspect", id: entry.id },
connect,
);
expect(result.data).toEqual(entry);
expect(queries).toEqual([undefined, { reportIds: [entry.id], forceRefresh: true }]);
});
+2 -2
View File
@@ -47,10 +47,10 @@ export async function runUsageCommand(
// Report-ID queries only select known accounts. Discover before selecting, including on cold hosts.
const { reports } = await client.listUsageReports();
let entry = reports.find((report) => report.id === selection.id);
if (entry && options.refresh) {
if (!entry || options.refresh) {
const refreshed = await client.listUsageReports({
reportIds: [selection.id],
forceRefresh: true,
forceRefresh: options.refresh,
});
entry = refreshed.reports.find((report) => report.id === selection.id);
}
@@ -694,9 +694,6 @@ describe("Suite A: Core Fixes", () => {
let agentId: string | null = null;
try {
agentId = await createTopLevelAgent({ settings: { features: { test_feature: true } } });
const internalSnapshot = daemonHandle.daemon.agentManager.getAgent(agentId);
expect(internalSnapshot?.config.featureValues).toEqual({ test_feature: true });
const status = await callToolStructured(topLevelClient, "get_agent_status", { agentId });
const snapshot = z.record(z.string(), z.unknown()).parse(status.snapshot);
expectAgentFeatureValue(snapshot, "test_feature", true);
@@ -712,9 +709,6 @@ describe("Suite A: Core Fixes", () => {
provider: "claude/claude-test-model",
settings: { features: { test_feature: true } },
});
const internalSnapshot = daemonHandle.daemon.agentManager.getAgent(agentId);
expect(internalSnapshot?.config.featureValues).toEqual({ test_feature: true });
const status = await callToolStructured(topLevelClient, "get_agent_status", { agentId });
const snapshot = z.record(z.string(), z.unknown()).parse(status.snapshot);
expectAgentFeatureValue(snapshot, "test_feature", true);
@@ -732,9 +726,6 @@ describe("Suite A: Core Fixes", () => {
settings: { features: { test_feature: true } },
});
expect(updated.success).toBe(true);
const internalSnapshot = daemonHandle.daemon.agentManager.getAgent(agentId);
expect(internalSnapshot?.config.featureValues).toEqual({ test_feature: true });
const status = await callToolStructured(topLevelClient, "get_agent_status", { agentId });
const snapshot = z.record(z.string(), z.unknown()).parse(status.snapshot);
expectAgentFeatureValue(snapshot, "test_feature", true);
@@ -7462,6 +7462,57 @@ function daemonConfigStoreStub(agentProfiles?: AgentProfile[]): Pick<DaemonConfi
describe("agent profile listing MCP tool", () => {
const logger = createTestLogger();
it("joins shared usage to matching profiles and leaves unmatched profiles intact", async () => {
const { agentManager, agentStorage } = createTestDeps();
const profiles: AgentProfile[] = [
{ id: "one", name: "One", provider: "claude", model: "a" },
{ id: "two", name: "Two", provider: "claude", model: "b" },
{ id: "mock", name: "Mock", provider: "mock" },
];
const report = {
id: "claude:account",
status: "ready" as const,
stale: false,
entry: {
id: "claude:account",
sourceId: "claude",
sourceLabel: "Claude",
account: {},
fetchedAt: "now",
report: {
status: "available" as const,
windows: [{ id: "weekly", label: "Weekly", usedPct: 100 }],
},
},
};
const server = await createAgentMcpServer({
agentManager,
agentStorage,
providerSnapshotManager: createOpenCodeManager().manager,
daemonConfigStore: daemonConfigStoreStub(profiles),
logger,
resolveTargetUsageReports: async () => [[report], [report], []],
});
const response = await registeredTool(server, "list_profiles").handler({});
expect(response.structuredContent).toEqual({
usage: {
"claude:account": {
sourceId: "claude",
sourceLabel: "Claude",
status: "available",
fetchedAt: "now",
stale: false,
windows: [{ id: "weekly", label: "Weekly", usedPct: 100 }],
},
},
profiles: [
{ ...profiles[0], usageReportIds: ["claude:account"] },
{ ...profiles[1], usageReportIds: ["claude:account"] },
profiles[2],
],
});
});
it("returns configured profiles, including systemPrompt and notes", async () => {
const { agentManager, agentStorage } = createTestDeps();
const profiles: AgentProfile[] = [
@@ -7,6 +7,7 @@ import { resolve } from "node:path";
import { isDeepStrictEqual } from "node:util";
import type { Logger } from "pino";
import type { UsageScope } from "@getpaseo/plugin/server/usage";
import pLimit, { type LimitFunction } from "p-limit";
import { expandTilde } from "../../utils/path.js";
@@ -37,6 +38,7 @@ import {
runProviderRefreshWithDeadline,
} from "./provider-refresh-deadline.js";
import type { ManagedAgent } from "./agent-manager.js";
import type { WorkspaceGitService } from "../workspace-git-service.js";
import type { ManagedProcessRegistry } from "../managed-processes/managed-processes.js";
import type { OpenCodeBridge } from "./providers/opencode/bridge.js";
@@ -73,6 +75,12 @@ import {
type ProviderRefreshTimers,
} from "./provider-refresh-schedule.js";
type TargetUsageScope = Extract<UsageScope, { kind: "session" }>;
interface TargetUsageScopeCacheEntry {
at: number;
scope: Promise<TargetUsageScope>;
}
const DEFAULT_REFRESH_TIMEOUT_MS = 120_000;
const MAX_REFRESH_TIMEOUT_MS = 2_147_483_647;
const DEFAULT_DIAGNOSTIC_TIMEOUT_MS = 120_000;
@@ -320,6 +328,7 @@ export class ProviderSnapshotManager {
private providerOverrides: Record<string, ProviderOverride> | undefined;
private baseProviderOverrides: Record<string, ProviderOverride> | undefined;
private generation: RegistryGeneration;
private readonly targetUsageScopes = new Map<string, TargetUsageScopeCacheEntry>();
private readonly shownModelRecords = new WeakMap<
ProviderSnapshotRecord,
ProviderSnapshotRecord
@@ -648,6 +657,30 @@ export class ProviderSnapshotManager {
return this.ensureClient(provider, definition).resolveUsageLaunch?.();
}
async resolveTargetUsageScope(target: { provider: string; model?: string }) {
let cached = this.targetUsageScopes.get(target.provider);
if (!cached || Date.now() - cached.at >= 60_000) {
const definition = this.generation.definitions[target.provider];
if (!definition?.enabled) return null;
const runtimeSettings = definition.configuration?.runtimeSettings;
const env = createProviderEnv({ baseEnv: process.env, runtimeSettings });
const scope = this.resolveUsageLaunch(target.provider).then((launch) => ({
kind: "session" as const,
provider: definition.derivedFromProviderId ?? target.provider,
env,
...(launch ? { launch } : {}),
}));
cached = { at: Date.now(), scope };
this.targetUsageScopes.set(target.provider, cached);
void scope.catch(() => {
if (this.targetUsageScopes.get(target.provider)?.scope === scope)
this.targetUsageScopes.delete(target.provider);
});
}
const scope = await cached.scope;
return { ...scope, model: target.model };
}
/**
* Whether `provider` (or a custom provider derived from it) is enabled and installed on this
* host. Used as a hint for whether discovered usage accounts start shown.
@@ -986,6 +1019,7 @@ export class ProviderSnapshotManager {
clients: Record<AgentProvider, AgentClient>,
changed: ReadonlySet<AgentProvider>,
): void {
this.targetUsageScopes.clear();
for (const provider of changed) {
this.generation.providerStates.get(provider)?.discoveryLimit.clearQueue();
this.usageActivityCache.delete(provider);
@@ -17,6 +17,8 @@ import { stat } from "node:fs/promises";
import { z } from "zod";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import { ensureValidJson } from "../../json-utils.js";
import { CompactUsageReportSchema, projectCompactUsageReport } from "./usage-projection.js";
import type { TargetUsageReport } from "../../plugins/usage-sources/index.js";
import { applyRecordPatch } from "../../record-patch.js";
import type { Logger } from "pino";
@@ -140,6 +142,9 @@ import { isPaseoToolEnabled } from "../paseo-tool-policy.js";
import { createAgentCallerPolicy } from "../agent-caller-policy.js";
export interface PaseoToolHostDependencies {
resolveTargetUsageReports?: (
targets: { provider: string; model?: string }[],
) => Promise<TargetUsageReport[][]>;
agentMessages?: () => AgentMessageDelivery;
changeRequestWatches?: ChangeRequestWatches;
finishSubscriptions?: () => FinishSubscriptions;
@@ -3536,17 +3541,44 @@ function createToolCatalog(
"delegating, then copy its `provider`, `model`, `modeId`, `thinkingOptionId`, " +
"`systemPrompt` (as `settings.systemPrompt`), and `options` (as `settings.features`) " +
"into create_agent (there is no `profile` parameter). " +
"Returns an empty list if none are configured.",
"Returns an empty list if none are configured. When host usage reporting is enabled, " +
"usage is keyed by report ID and matching profiles reference it in usageReportIds. " +
"Factor usage, exhaustion, reset times and staleness into profile choice alongside notes.",
inputSchema: {},
outputSchema: {
profiles: z.array(AgentProfileSchema),
usage: z.record(z.string(), CompactUsageReportSchema).optional(),
profiles: z.array(
AgentProfileSchema.extend({ usageReportIds: z.array(z.string()).optional() }),
),
},
},
async () => {
const profiles = daemonConfigStore?.get().agentProfiles ?? [];
let output: {
usage?: Record<string, z.infer<typeof CompactUsageReportSchema>>;
profiles: typeof profiles;
} = { profiles };
if (options.resolveTargetUsageReports && profiles.length) {
try {
const reports = await options.resolveTargetUsageReports(
profiles.map(({ provider, model }) => ({ provider, model })),
);
const usage: Record<string, z.infer<typeof CompactUsageReportSchema>> = {};
const matched = profiles.map((profile, index) => {
const entries = reports[index] ?? [];
for (const entry of entries) usage[entry.id] = projectCompactUsageReport(entry);
return entries.length
? Object.assign({}, profile, { usageReportIds: entries.map((entry) => entry.id) })
: profile;
});
if (Object.keys(usage).length) output = { usage, profiles: matched };
} catch (error) {
childLogger.warn({ err: error }, "Failed to resolve profile usage");
}
}
return {
content: [],
structuredContent: ensureValidJson({ profiles }),
structuredContent: ensureValidJson(JSON.parse(JSON.stringify(output))),
};
},
);
@@ -0,0 +1,80 @@
import { expect, test } from "vitest";
import { projectCompactUsageReport } from "./usage-projection.js";
test("projects usage without UI chrome and retains quota and balances", () => {
expect(
projectCompactUsageReport({
id: "vendor:a",
status: "ready",
stale: true,
entry: {
id: "vendor:a",
sourceId: "vendor",
sourceLabel: "Vendor",
icon: "icon",
account: { label: "Account" },
fetchedAt: "now",
successfulAt: "now",
report: {
status: "available",
windows: [
{ id: "weekly", label: "Weekly", usedPct: 100, shortLabel: "wk", tone: "danger" },
],
balances: [{ id: "credits", label: "Credits", remaining: 5, unit: "usd", tone: "ok" }],
details: [],
},
},
}),
).toEqual({
sourceId: "vendor",
sourceLabel: "Vendor",
account: "Account",
status: "available",
fetchedAt: "now",
successfulAt: "now",
stale: true,
windows: [{ id: "weekly", label: "Weekly", usedPct: 100 }],
balances: [{ id: "credits", label: "Credits", remaining: 5, unit: "usd" }],
});
});
test("projects pending, manual and errors with retained readings", () => {
expect(
projectCompactUsageReport({ id: "x:a", status: "pending", sourceId: "x", sourceLabel: "X" }),
).toEqual({ sourceId: "x", sourceLabel: "X", status: "pending" });
const base = { id: "x:a", sourceId: "x", sourceLabel: "X", account: {}, fetchedAt: "now" };
expect(
projectCompactUsageReport({
id: "x:a",
status: "ready",
stale: false,
entry: { ...base, refresh: "manual", report: { status: "not_fetched" } },
}),
).toEqual({
sourceId: "x",
sourceLabel: "X",
refresh: "manual",
status: "not_fetched",
fetchedAt: "now",
});
expect(
projectCompactUsageReport({
id: "x:a",
status: "ready",
stale: false,
entry: {
...base,
report: { status: "error", error: "failed" },
lastSuccessful: { fetchedAt: "before", report: { status: "available", windows: [] } },
},
}),
).toEqual({
sourceId: "x",
sourceLabel: "X",
status: "error",
error: "failed",
fetchedAt: "now",
lastSuccessfulAt: "before",
windows: [],
});
});
@@ -0,0 +1,73 @@
import { z } from "zod";
import {
ProviderUsageWindowSchema,
ProviderUsageBalanceSchema,
ProviderUsageDetailSchema,
UsageProblemSchema,
} from "@getpaseo/protocol/messages";
import type { TargetUsageReport } from "../../plugins/usage-sources/index.js";
const WindowSchema = ProviderUsageWindowSchema.omit({
shortLabel: true,
summary: true,
durationSeconds: true,
tone: true,
});
const BalanceSchema = ProviderUsageBalanceSchema.omit({ tone: true });
const DetailSchema = ProviderUsageDetailSchema.omit({ tone: true });
export const CompactUsageReportSchema = z.object({
sourceId: z.string(),
sourceLabel: z.string(),
account: z.string().optional(),
refresh: z.enum(["automatic", "manual"]).optional(),
status: z.enum(["pending", "available", "not_fetched", "unavailable", "error"]),
fetchedAt: z.string().optional(),
successfulAt: z.string().optional(),
lastSuccessfulAt: z.string().optional(),
stale: z.boolean().optional(),
planLabel: z.string().optional(),
observedAt: z.string().optional(),
error: z.string().optional(),
retryAt: z.string().optional(),
problem: UsageProblemSchema.optional(),
windows: z.array(WindowSchema).optional(),
balances: z.array(BalanceSchema).optional(),
details: z.array(DetailSchema).optional(),
});
export function projectCompactUsageReport(
report: TargetUsageReport,
): z.infer<typeof CompactUsageReportSchema> {
if (report.status === "pending") return compact(report);
const { entry, stale } = report;
const outcome = entry.report;
const available = outcome.status === "available" ? outcome : entry.lastSuccessful?.report;
const error = outcome.status === "error" ? outcome.error : undefined;
const retryAt = outcome.status === "error" ? outcome.retryAt : undefined;
const problem = outcome.status === "unavailable" ? outcome.problem : undefined;
const balances = available?.balances?.length ? available.balances : undefined;
const details = available?.details?.length ? available.details : undefined;
return compact({
sourceId: entry.sourceId,
sourceLabel: entry.sourceLabel,
account: entry.account.label,
refresh: entry.refresh,
status: outcome.status,
error,
retryAt,
problem,
fetchedAt: entry.fetchedAt,
successfulAt: entry.successfulAt,
stale: outcome.status === "available" ? stale : undefined,
lastSuccessfulAt: entry.lastSuccessful?.fetchedAt,
planLabel: available?.planLabel,
observedAt: available?.observedAt,
windows: available?.windows,
balances,
details,
});
}
function compact(value: unknown): z.infer<typeof CompactUsageReportSchema> {
return JSON.parse(JSON.stringify(CompactUsageReportSchema.parse(value)));
}
+10
View File
@@ -1691,6 +1691,16 @@ async function assemblePaseoDaemon({
scheduleService,
providerSnapshotManager,
daemonConfigStore,
resolveTargetUsageReports: async (targets) => {
if (daemonConfigStore.get().usage?.enabled === false) return targets.map(() => []);
const scopes = targets.map((target) =>
providerSnapshotManager.resolveTargetUsageScope(target).catch((err) => {
logger.warn({ err, provider: target.provider }, "Failed to resolve target usage scope");
return null;
}),
);
return pluginRuntime.resolveTargetUsageReports(scopes, { maxWaitMs: 1500 });
},
github,
workspaceGitService,
worktreeManagers: pluginRuntime,
@@ -278,6 +278,10 @@ export class PluginService {
return this.usageSources.listReports(options);
}
resolveTargetUsageReports(...args: Parameters<UsageSourceRegistry["resolveTargetReports"]>) {
return this.usageSources.resolveTargetReports(...args);
}
listLegacyUsage() {
return this.usageSources.listLegacyUsage();
}
@@ -23,6 +23,34 @@ import {
} from "../../../../../../plugins/cursor-usage-source/server/usage.js";
import { inputSchema as cursorInputSchema } from "../../../../../../plugins/cursor-usage-source/shared/input.js";
test("target usage returns pending within its budget and warms the cache", async () => {
let finish!: (value: unknown) => void;
let fetches = 0;
const registry = new UsageSourceRegistry();
registry.register({
id: "test",
label: "Test",
discover: async () => [{ key: "account", input: {} }],
fetch: () => {
fetches++;
return new Promise((resolve) => {
finish = resolve;
});
},
});
const scope = { kind: "session", provider: "test", env: {} } as const;
const first = await registry.resolveTargetReports([scope], { maxWaitMs: 10 });
expect(first[0]?.[0]).toMatchObject({ id: "test:account", status: "pending" });
finish({ status: "available", windows: [] });
await new Promise((resolve) => setTimeout(resolve, 0));
const second = await registry.resolveTargetReports([scope], { maxWaitMs: 10 });
expect(second[0]?.[0]).toMatchObject({
id: "test:account",
entry: { report: { status: "available" } },
});
expect(fetches).toBe(1);
});
test("switching a shared Claude home replaces the account without borrowing its usage", async () => {
const root = await mkdtemp(join(tmpdir(), "claude-accounts-"));
try {
@@ -2325,3 +2353,280 @@ test("#11529: selectProviderUsageEnv keeps stock binaries with harmless flags an
expect(SERVER_CLAUDE_ISOLATING_FLAGS).toEqual(PLUGIN_CLAUDE_ISOLATING_FLAGS);
expect(SERVER_CODEX_ISOLATING_FLAGS).toEqual(PLUGIN_CODEX_ISOLATING_FLAGS);
});
test("target discovery shares the deadline and continues warming after a timeout", async () => {
let finish!: (value: unknown) => void;
const registry = new UsageSourceRegistry();
registry.register({
id: "slow",
label: "Slow",
discover: () =>
new Promise((resolve) => {
finish = resolve;
}),
fetch: async () => ({ status: "available", windows: [] }),
});
const scope = { kind: "session", provider: "slow", env: {} } as const;
expect(await registry.resolveTargetReports([scope], { maxWaitMs: 10 })).toEqual([[]]);
finish([{ key: "account", input: {} }]);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(await registry.resolveTargetReports([scope], { maxWaitMs: 10 })).toMatchObject([
[{ id: "slow:account", entry: { report: { status: "available" } } }],
]);
});
test("target reads reuse host account usage and keep target accounts out of the host list", async () => {
let fetches = 0;
const registry = new UsageSourceRegistry();
registry.register({
id: "shared",
label: "Shared",
discover: async (scope) =>
scope.kind === "global"
? [
{ key: "account", input: { login: 1 } },
{ key: "account", input: { login: 2 } },
]
: [
{ key: "account", input: { login: 1 } },
{ key: "target-only", input: {} },
],
fetch: async () => {
fetches++;
return { status: "available", windows: [] };
},
});
expect((await registry.listReports()).map((entry) => entry.id)).toEqual(["shared:account"]);
const hostFetches = fetches;
const scope = { kind: "session", provider: "test", env: {} } as const;
const reports = await registry.resolveTargetReports([scope, scope], { maxWaitMs: 100 });
expect(reports[0]?.map((entry) => entry.id)).toEqual(["shared:account", "shared:target-only"]);
expect(reports[1]).toEqual(reports[0]);
expect(fetches).toBe(hostFetches + 1);
expect((await registry.listReports()).map((entry) => entry.id)).toEqual(["shared:account"]);
});
test("stale target usage returns immediately after the deadline and refreshes in the background", async () => {
let now = 0;
let finish!: (value: unknown) => void;
let fetches = 0;
const registry = new UsageSourceRegistry(() => now, 100);
registry.register({
id: "test",
label: "Test",
discover: async () => [{ key: "account", input: {} }],
fetch: async () =>
++fetches === 1
? { status: "available", windows: [] }
: new Promise((resolve) => {
finish = resolve;
}),
});
const scope = { kind: "session", provider: "test", env: {} } as const;
await registry.resolveTargetReports([scope], { maxWaitMs: 100 });
now = 101;
expect(await registry.resolveTargetReports([scope], { maxWaitMs: 10 })).toMatchObject([
[{ status: "ready", stale: true }],
]);
finish({ status: "available", windows: [] });
await new Promise((resolve) => setTimeout(resolve, 0));
expect(await registry.resolveTargetReports([scope], { maxWaitMs: 10 })).toMatchObject([
[{ status: "ready", stale: false }],
]);
});
test("manual target readings retain their timestamp until explicit refresh", async () => {
let now = 0;
let fetches = 0;
const registry = new UsageSourceRegistry(() => now);
registry.register({
id: "manual",
label: "Manual",
refresh: "manual",
discover: async () => [{ key: "account", input: {} }],
fetch: async () => {
fetches++;
return { status: "available", windows: [] };
},
});
const scope = { kind: "session", provider: "manual", env: {} } as const;
const first = await registry.resolveTargetReports([scope], { maxWaitMs: 100 });
now = 100;
const second = await registry.resolveTargetReports([scope], { maxWaitMs: 100 });
expect(first).toEqual(second);
expect(fetches).toBe(0);
await registry.listReports();
await registry.listReports({ reportIds: ["manual:account"], forceRefresh: true });
expect(await registry.resolveTargetReports([scope], { maxWaitMs: 100 })).toMatchObject([
[{ entry: { report: { status: "available" } } }],
]);
expect(fetches).toBe(1);
});
test("shared account reports do not depend on target order", async () => {
const registry = new UsageSourceRegistry();
registry.register({
id: "shared",
label: "Shared",
discover: async (scope) =>
scope.kind === "session" ? [{ key: "account", input: { provider: scope.provider } }] : [],
fetch: async (input) =>
(input as { provider: string }).provider === "good"
? { status: "available", windows: [] }
: { status: "error", error: "failed" },
});
const good = { kind: "session", provider: "good", env: {} } as const;
const bad = { kind: "session", provider: "bad", env: {} } as const;
for (const scopes of [
[good, bad],
[bad, good],
]) {
const reports = await registry.resolveTargetReports(scopes, { maxWaitMs: 100 });
expect(reports).toMatchObject([
[{ entry: { report: { status: "available" } } }],
[{ entry: { report: { status: "available" } } }],
]);
}
});
test("an exact report lookup can refresh an account discovered only by a target", async () => {
let fetches = 0;
const registry = new UsageSourceRegistry();
registry.register({
id: "manual",
label: "Manual",
refresh: "manual",
discover: async (scope) => (scope.kind === "session" ? [{ key: "account", input: {} }] : []),
fetch: async () => {
fetches++;
return { status: "available", windows: [] };
},
});
const scope = { kind: "session", provider: "test", env: {} } as const;
await registry.resolveTargetReports([scope], { maxWaitMs: 100 });
expect(await registry.listReports()).toEqual([]);
expect(
await registry.listReports({ reportIds: ["manual:account"], forceRefresh: true }),
).toMatchObject([{ report: { status: "available" } }]);
expect(fetches).toBe(1);
expect(await registry.listReports()).toEqual([]);
});
test("a slow scope does not hide a ready target at the shared deadline", async () => {
let finish!: (scope: { kind: "session"; provider: string; env: {} }) => void;
const slow = new Promise<{ kind: "session"; provider: string; env: {} }>((resolve) => {
finish = resolve;
});
const registry = new UsageSourceRegistry();
registry.register({
id: "test",
label: "Test",
discover: async () => [{ key: "account", input: {} }],
fetch: async () => ({ status: "available", windows: [] }),
});
const fast = { kind: "session", provider: "fast", env: {} } as const;
const reports = await registry.resolveTargetReports([Promise.resolve(fast), slow], {
maxWaitMs: 20,
});
expect(reports).toMatchObject([[{ entry: { report: { status: "available" } } }], []]);
finish({ kind: "session", provider: "slow", env: {} });
});
test("abandoned target accounts expire without entering the host list", async () => {
let now = 0;
const registry = new UsageSourceRegistry(() => now);
registry.register({
id: "test",
label: "Test",
discover: async (scope) =>
scope.kind === "session" ? [{ key: scope.provider, input: {} }] : [],
fetch: async () => ({ status: "available", windows: [] }),
});
await registry.resolveTargetReports([{ kind: "session", provider: "old", env: {} }], {
maxWaitMs: 100,
});
now = 300_001;
await registry.resolveTargetReports([{ kind: "session", provider: "new", env: {} }], {
maxWaitMs: 100,
});
expect(await registry.listReports({ reportIds: ["test:old"] })).toEqual([]);
expect(await registry.listReports()).toEqual([]);
});
test("slow source discovery does not hide a ready source", async () => {
let finish!: (value: unknown) => void;
const registry = new UsageSourceRegistry();
registry.register({
id: "slow",
label: "Slow",
discover: () =>
new Promise((resolve) => {
finish = resolve;
}),
fetch: async () => ({ status: "available", windows: [] }),
});
registry.register({
id: "fast",
label: "Fast",
discover: async () => [{ key: "account", input: {} }],
fetch: async () => ({ status: "available", windows: [] }),
});
const scope = { kind: "session", provider: "test", env: {} } as const;
const reports = await registry.resolveTargetReports([scope], { maxWaitMs: 20 });
expect(reports).toMatchObject([
[{ id: "fast:account", entry: { report: { status: "available" } } }],
]);
finish([]);
});
test("a batch preserves manual readings for every still-requested scope after idle", async () => {
let now = 0;
const registry = new UsageSourceRegistry(() => now);
registry.register({
id: "manual",
label: "Manual",
refresh: "manual",
discover: async (scope) =>
scope.kind === "session" ? [{ key: scope.provider, input: {} }] : [],
fetch: async () => ({ status: "available", windows: [] }),
});
const first = { kind: "session", provider: "first", env: {} } as const;
const second = { kind: "session", provider: "second", env: {} } as const;
await registry.resolveTargetReports([first, second], { maxWaitMs: 100 });
await registry.listReports({ reportIds: ["manual:second"], forceRefresh: true });
now = 300_001;
const results = await registry.resolveTargetReports(
[Promise.resolve(first), Promise.resolve(second)],
{ maxWaitMs: 100 },
);
expect(results[1]).toMatchObject([{ entry: { report: { status: "available" } } }]);
});
test("fresh cached readings return while discovery refresh is slow", async () => {
let now = 0;
let discoveries = 0;
let finish!: (value: unknown) => void;
const registry = new UsageSourceRegistry(() => now);
registry.register({
id: "test",
label: "Test",
discover: async () =>
++discoveries === 1
? [{ key: "account", input: {} }]
: new Promise((resolve) => {
finish = resolve;
}),
fetch: async () => ({ status: "available", windows: [] }),
});
const scope = { kind: "session", provider: "test", env: {} } as const;
await registry.resolveTargetReports([scope], { maxWaitMs: 100 });
now = 60_001;
const reading = registry.resolveTargetReports([scope], { maxWaitMs: 1000 });
const returned = await Promise.race([
reading.then(() => true),
new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 40)),
]);
finish([{ key: "account", input: {} }]);
await reading;
expect(returned).toBe(true);
});
@@ -41,6 +41,13 @@ interface KnownReport {
label?: string;
}
interface TargetScope {
at: number;
usedAt: number;
reports: Map<string, KnownReport>;
listeners: Set<() => void>;
}
export interface AgentUsageLookup {
hasAgent(id: string): boolean;
usageSession(id: string): AgentUsageSession | null;
@@ -61,6 +68,7 @@ interface DiscoverOptions {
harness?: string;
/** This scope's last result; a source whose discovery fails keeps its accounts from it. */
previous?: ReadonlyMap<string, KnownReport>;
onSource?: (source: UsageSource, reports: Map<string, KnownReport>) => void;
}
interface PresentReportOptions {
@@ -92,6 +100,10 @@ export interface ListUsageReportsOptions {
onReport?: (report: UsageReportEntry) => void;
}
export type TargetUsageReport =
| { id: string; status: "pending"; sourceId: string; sourceLabel: string; account?: string }
| { id: string; status: "ready"; entry: UsageReportEntry; stale: boolean };
/**
* Groups discovered logins by account and caches their usage for five minutes (failures for
* less, or until the `retryAt` the source gave). Usage an agent observes while working is merged
@@ -105,6 +117,8 @@ export class UsageSourceRegistry {
private defaults = new Map<string, KnownReport>();
private defaultsByScope = new Map<string, Map<string, KnownReport>>();
private readonly byAgent = new Map<string, Map<string, KnownReport>>();
private readonly byTarget = new Map<string, TargetScope>();
private readonly targetDiscovery = new Map<string, Promise<Map<string, KnownReport>>>();
private readonly cache = new Map<
string,
{ at: number; staleAt: number; entry: UsageReportEntry }
@@ -131,6 +145,8 @@ export class UsageSourceRegistry {
register(source: UsageSource): void {
if (this.sources.has(source.id)) throw new Error(`Duplicate usage source: ${source.id}`);
this.sources.set(source.id, source);
this.byTarget.clear();
this.targetDiscovery.clear();
}
unregister(id: string): void {
@@ -145,6 +161,8 @@ export class UsageSourceRegistry {
deletePrefixed(this.pending, prefix);
deletePrefixed(this.failures, prefix);
this.observedAgents.clear();
this.byTarget.clear();
this.targetDiscovery.clear();
}
/** Called with each report the registry updates on its own, outside any list request. */
@@ -163,7 +181,7 @@ export class UsageSourceRegistry {
*/
async observeUsage(agentId: string, observation: UsageObservation): Promise<void> {
const reports =
this.listeners.size > 0
this.listeners.size > 0 || this.byTarget.size > 0
? await this.observedReports(agentId)
: (this.byAgent.get(agentId) ?? new Map<string, KnownReport>());
for (const [id, report] of reports) {
@@ -235,6 +253,12 @@ export class UsageSourceRegistry {
this.mergeKnown();
ids = [...reports.keys()];
} else if (options.reportIds !== undefined) {
reports = new Map(this.known);
for (const target of this.byTarget.values()) {
for (const [id, report] of target.reports) {
if (!reports.has(id)) reports.set(id, report);
}
}
ids = options.reportIds;
} else {
const [defaults] = await Promise.all([
@@ -272,6 +296,194 @@ export class UsageSourceRegistry {
);
}
/** Resolve launch scopes without adding their accounts to the host usage list. */
async resolveTargetReports(
scopes: readonly (
| Extract<UsageScope, { kind: "session" }>
| null
| Promise<Extract<UsageScope, { kind: "session" }> | null>
)[],
{ maxWaitMs }: { maxWaitMs: number },
): Promise<TargetUsageReport[][]> {
const result: TargetUsageReport[][] = scopes.map(() => []);
const tasks = new Map<string, Promise<TargetUsageReport[]>>();
const keys: (string | undefined)[] = scopes.map(() => undefined);
const latest = new Map<string, TargetUsageReport[]>();
const work = scopes.map(async (input, index) => {
const scope = await input;
if (!scope) return;
const key = canonicalJson(scope);
keys[index] = key;
let task = tasks.get(key);
if (!task) {
task = this.resolveScopeReports(key, scope, (reports) => {
latest.set(key, reports);
for (const [i, candidate] of keys.entries()) {
if (candidate === key) result[i] = reports;
}
});
tasks.set(key, task);
}
result[index] = latest.get(key) ?? [];
result[index] = await task;
});
let timer: ReturnType<typeof setTimeout> | undefined;
const finished = Promise.all(work).then(() => {
this.pruneTargets(new Set(keys.filter((key) => key !== undefined)));
return undefined;
});
await Promise.race([
finished,
new Promise<void>((resolve) => {
timer = setTimeout(resolve, Math.max(0, maxWaitMs));
}),
]);
clearTimeout(timer);
const best = new Map<string, TargetUsageReport>();
for (const reports of result)
for (const report of reports) {
const previous = best.get(report.id);
if (!previous || compareTargetReports(report, previous) > 0) best.set(report.id, report);
}
return result.map((reports) => reports.map((report) => best.get(report.id)!));
}
private async resolveScopeReports(
key: string,
scope: Extract<UsageScope, { kind: "session" }>,
publish: (reports: TargetUsageReport[]) => void,
): Promise<TargetUsageReport[]> {
let target = this.byTarget.get(key);
if (!target) {
target = {
at: Number.NEGATIVE_INFINITY,
usedAt: this.now(),
reports: new Map(),
listeners: new Set(),
};
this.byTarget.set(key, target);
}
target.usedAt = this.now();
const current = target;
const hadReports = current.reports.size > 0;
let output: TargetUsageReport[] = [];
const pending = new Map<string, Promise<void>>();
const update = () => {
output = [];
for (const [id, known] of current.reports) {
if (this.sources.get(known.source.id) !== known.source) continue;
const cacheKey = resultKey(id, known);
const exact = this.cache.get(cacheKey);
const shared = [...this.cache.values()].find(
(cached) =>
cached.entry.id === id &&
cached.entry.report.status === "available" &&
this.now() < cached.staleAt,
);
const cached = exact && this.now() < exact.staleAt ? exact : (shared ?? exact);
const fresh = cached && this.now() < cached.staleAt;
if (cached)
output.push({
id,
status: "ready",
entry: presentReport({ entry: cached.entry, known }),
stale: !fresh,
});
else if (known.source.refresh === "manual") {
const entry = this.notFetched(id, known);
this.writeCache(cacheKey, entry, known.source);
output.push({
id,
status: "ready",
entry: presentReport({ entry, known }),
stale: false,
});
} else
output.push({
id,
status: "pending",
sourceId: known.source.id,
sourceLabel: known.source.label,
account: known.label,
});
if (!fresh && known.source.refresh !== "manual" && !pending.has(cacheKey)) {
const request = this.fetchId(id, known).then((entry) => {
const position = output.findIndex((report) => report.id === id);
if (position >= 0) {
output[position] = {
id,
status: "ready",
entry: presentReport({ entry, known }),
stale: false,
};
publish(output.slice());
}
return undefined;
});
pending.set(cacheKey, request);
}
}
publish(output.slice());
};
current.listeners.add(update);
let detached = false;
try {
let discovery = this.targetDiscovery.get(key);
if (!discovery && this.now() - current.at >= 60_000) {
discovery = this.discover({
scope,
previous: new Map(current.reports),
onSource: (source, reports) => {
if (this.byTarget.get(key) !== current || this.sources.get(source.id) !== source)
return;
deletePrefixed(current.reports, `${source.id}:`);
for (const [id, report] of reports) current.reports.set(id, report);
for (const listener of current.listeners) listener();
},
}).then((reports) => {
if (this.targetDiscovery.get(key) === discovery) {
current.at = this.now();
this.targetDiscovery.delete(key);
}
return reports;
});
this.targetDiscovery.set(key, discovery);
}
update();
if (discovery && hadReports) {
detached = true;
void discovery
.then(() => Promise.all(pending.values()))
.catch((err) => this.logger.warn({ err }, "Target usage discovery failed"))
.finally(() => current.listeners.delete(update));
await Promise.all(pending.values());
return output;
}
if (discovery) await discovery;
await Promise.all(pending.values());
return output;
} finally {
if (!detached) current.listeners.delete(update);
}
}
private pruneTargets(currentKeys: ReadonlySet<string>): void {
let removed = false;
for (const [key, target] of this.byTarget) {
if (
currentKeys.has(key) ||
this.now() - target.usedAt < this.ttlMs ||
this.targetDiscovery.has(key)
)
continue;
if ([...target.reports].some(([id, report]) => this.pending.has(resultKey(id, report))))
continue;
this.byTarget.delete(key);
removed = true;
}
if (removed) this.mergeKnown();
}
private configuredProviderScopes(): DiscoverOptions[] {
const scopes: DiscoverOptions[] = [];
for (const {
@@ -418,9 +630,12 @@ export class UsageSourceRegistry {
private activeCacheKeys(): Set<string> {
return new Set(
[this.known, this.defaults, ...this.byAgent.values()].flatMap((reports) =>
[...reports].map(([id, report]) => resultKey(id, report)),
),
[
this.known,
this.defaults,
...this.byAgent.values(),
...[...this.byTarget.values()].map((target) => target.reports),
].flatMap((reports) => [...reports].map(([id, report]) => resultKey(id, report))),
);
}
@@ -429,6 +644,7 @@ export class UsageSourceRegistry {
matchProvider,
harness,
previous = new Map(),
onSource,
}: DiscoverOptions): Promise<Map<string, KnownReport>> {
const targets = matchProvider
? [...this.sources.values()].filter((source) => source.providers?.includes(matchProvider))
@@ -470,6 +686,7 @@ export class UsageSourceRegistry {
if (report.source === source) reports.set(id, report);
}
}
onSource?.(source, reports);
return reports;
}),
);
@@ -599,9 +816,6 @@ export class UsageSourceRegistry {
private writeCache(id: string, entry: UsageReportEntry, source: UsageSource): void {
const at = this.now();
for (const [cachedId, cached] of this.cache) {
if (at >= cached.staleAt) this.cache.delete(cachedId);
}
this.cache.set(id, { at, staleAt: at + this.freshFor(id, entry, source), entry });
}
@@ -649,6 +863,27 @@ export class UsageSourceRegistry {
}
}
function compareTargetReports(a: TargetUsageReport, b: TargetUsageReport): number {
const rank = (report: TargetUsageReport): number => {
if (report.status === "pending") return 0;
switch (report.entry.report.status) {
case "available":
return report.stale ? 4 : 5;
case "error":
return report.entry.lastSuccessful ? 3 : 1;
case "unavailable":
return 2;
case "not_fetched":
return 1;
}
};
const difference = rank(a) - rank(b);
if (difference) return difference;
const timeA = a.status === "ready" ? (a.entry.successfulAt ?? a.entry.fetchedAt) : "";
const timeB = b.status === "ready" ? (b.entry.successfulAt ?? b.entry.fetchedAt) : "";
return timeA.localeCompare(timeB) || canonicalJson(a).localeCompare(canonicalJson(b));
}
// The legacy RPC has only an error string; the current app owns its own presentation.
// COMPAT(providerUsageList): added in v0.1.98, remove after 2027-03-26.
function legacyProblem(problem: UsageProblem, now: number): string {
@@ -21,6 +21,14 @@ test("discovers only host credentials and returns credential-free inputs", async
]);
expect(await discover(scope, { OPENROUTER_API_KEY: " " })).toEqual([]);
expect(await discover({ kind: "session", provider: "pi", env }, env)).toEqual([]);
for (const provider of ["pi", "omp"]) {
expect(
await discover({ kind: "session", provider, model: "openrouter/test", env }, env),
).toEqual([
{ key: "key", label: "API key spend", input: { meter: "key" } },
{ key: "credits", label: "Account credits", input: { meter: "credits" } },
]);
}
expect(
await discover(
{
@@ -32,7 +32,11 @@ export async function discover(
env: NodeJS.ProcessEnv = process.env,
): Promise<UsageAccount[]> {
if (scope.kind === "session") {
if (scope.provider !== "opencode" || !scope.model?.startsWith("openrouter/")) return [];
if (
!["opencode", "pi", "omp"].includes(scope.provider) ||
!scope.model?.startsWith("openrouter/")
)
return [];
return inputSchema.shape.meter.options.flatMap((meter) => {
const { env: variable, label } = meters[meter];
const hostValue = env[variable]?.trim();
+3 -3
View File
@@ -168,9 +168,9 @@ New-agent run workspaces are archived when each run ends by default. Pass `archi
### Agent profiles
| Tool | Function |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `list_profiles` | Return the host's saved agent profiles, including their notes and launch settings. Returns an empty list when none are configured. |
| Tool | Function |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `list_profiles` | Return the host's saved agent profiles, including notes and launch settings. When usage reporting is enabled, matching profiles reference quota and balance reports in the top-level `usage` map through `usageReportIds`. Returns an empty list when none are configured. |
Before delegating, read each profile's `notes` and choose the profile the user named or the one that fits the task. See [Agent profiles](/docs/agent-profiles) for setup and example notes.
+1 -1
View File
@@ -108,7 +108,7 @@ A steer the agent has not read is lost if its turn stops or is interrupted, alon
## Agent profiles and provider discovery
**`list_profiles`** — named launch bundles configured by the human. Before choosing how to launch a delegated agent, call this tool and read every profile's `notes`. Pick a named profile the user requested, or the profile whose notes best match the work.
**`list_profiles`** — named launch bundles configured by the human. Before choosing how to launch a delegated agent, call this tool and read every profile's `notes`. When usage reporting is enabled, matching profiles reference the top-level `usage` map through `usageReportIds`; consider quota, balances, reset times, and staleness when choosing. Pick a named profile the user requested, or the profile whose notes best match the work.
There is no `profile` parameter on `create_agent`. Materialize the selected profile into the call: