fix: keep build green after main rebase (#570) (thanks @azade-c)

This commit is contained in:
Peter Steinberger
2026-01-09 15:40:36 +01:00
parent f7e8cd8ac8
commit c4c0f1349a
8 changed files with 189 additions and 139 deletions

View File

@@ -718,9 +718,7 @@ export async function setAuthProfileOrder(params: {
const providerKey = normalizeProviderId(params.provider); const providerKey = normalizeProviderId(params.provider);
const sanitized = const sanitized =
params.order && Array.isArray(params.order) params.order && Array.isArray(params.order)
? params.order ? params.order.map((entry) => String(entry).trim()).filter(Boolean)
.map((entry) => String(entry).trim())
.filter(Boolean)
: []; : [];
const deduped: string[] = []; const deduped: string[] = [];

View File

@@ -88,7 +88,9 @@ const resolveAuthLabel = async (
mode: ModelAuthDetailMode = "compact", mode: ModelAuthDetailMode = "compact",
): Promise<{ label: string; source: string }> => { ): Promise<{ label: string; source: string }> => {
const formatPath = (value: string) => shortenHomePath(value); const formatPath = (value: string) => shortenHomePath(value);
const store = ensureAuthProfileStore(agentDir, { allowKeychainPrompt: false }); const store = ensureAuthProfileStore(agentDir, {
allowKeychainPrompt: false,
});
const order = resolveAuthProfileOrder({ cfg, store, provider }); const order = resolveAuthProfileOrder({ cfg, store, provider });
const providerKey = normalizeProviderId(provider); const providerKey = normalizeProviderId(provider);
const lastGood = (() => { const lastGood = (() => {
@@ -121,7 +123,8 @@ const resolveAuthLabel = async (
const configProfile = cfg.auth?.profiles?.[profileId]; const configProfile = cfg.auth?.profiles?.[profileId];
const missing = const missing =
!profile || !profile ||
(configProfile?.provider && configProfile.provider !== profile.provider) || (configProfile?.provider &&
configProfile.provider !== profile.provider) ||
(configProfile?.mode && (configProfile?.mode &&
configProfile.mode !== profile.type && configProfile.mode !== profile.type &&
!(configProfile.mode === "oauth" && profile.type === "token")); !(configProfile.mode === "oauth" && profile.type === "token"));
@@ -170,7 +173,11 @@ const resolveAuthLabel = async (
if (lastGood && profileId === lastGood) flags.push("lastGood"); if (lastGood && profileId === lastGood) flags.push("lastGood");
if (isProfileInCooldown(store, profileId)) { if (isProfileInCooldown(store, profileId)) {
const until = store.usageStats?.[profileId]?.cooldownUntil; const until = store.usageStats?.[profileId]?.cooldownUntil;
if (typeof until === "number" && Number.isFinite(until) && until > now) { if (
typeof until === "number" &&
Number.isFinite(until) &&
until > now
) {
flags.push(`cooldown ${formatUntil(until)}`); flags.push(`cooldown ${formatUntil(until)}`);
} else { } else {
flags.push("cooldown"); flags.push("cooldown");
@@ -197,7 +204,11 @@ const resolveAuthLabel = async (
Number.isFinite(profile.expires) && Number.isFinite(profile.expires) &&
profile.expires > 0 profile.expires > 0
) { ) {
flags.push(profile.expires <= now ? "expired" : `exp ${formatUntil(profile.expires)}`); flags.push(
profile.expires <= now
? "expired"
: `exp ${formatUntil(profile.expires)}`,
);
} }
const suffix = flags.length > 0 ? ` (${flags.join(", ")})` : ""; const suffix = flags.length > 0 ? ` (${flags.join(", ")})` : "";
return `${profileId}=token:${maskApiKey(profile.token)}${suffix}`; return `${profileId}=token:${maskApiKey(profile.token)}${suffix}`;
@@ -218,7 +229,11 @@ const resolveAuthLabel = async (
Number.isFinite(profile.expires) && Number.isFinite(profile.expires) &&
profile.expires > 0 profile.expires > 0
) { ) {
flags.push(profile.expires <= now ? "expired" : `exp ${formatUntil(profile.expires)}`); flags.push(
profile.expires <= now
? "expired"
: `exp ${formatUntil(profile.expires)}`,
);
} }
const suffixLabel = suffix ? ` ${suffix}` : ""; const suffixLabel = suffix ? ` ${suffix}` : "";
const suffixFlags = flags.length > 0 ? ` (${flags.join(", ")})` : ""; const suffixFlags = flags.length > 0 ? ` (${flags.join(", ")})` : "";
@@ -242,7 +257,8 @@ const resolveAuthLabel = async (
if (customKey) { if (customKey) {
return { return {
label: maskApiKey(customKey), label: maskApiKey(customKey),
source: mode === "verbose" ? `models.json: ${formatPath(modelsPath)}` : "", source:
mode === "verbose" ? `models.json: ${formatPath(modelsPath)}` : "",
}; };
} }
return { label: "missing", source: "missing" }; return { label: "missing", source: "missing" };
@@ -803,16 +819,16 @@ export async function handleDirectiveOnly(params: {
} }
modelSelection = resolved.selection; modelSelection = resolved.selection;
if (modelSelection) { if (modelSelection) {
if (directives.rawModelProfile) { if (directives.rawModelProfile) {
const profileResolved = resolveProfileOverride({ const profileResolved = resolveProfileOverride({
rawProfile: directives.rawModelProfile, rawProfile: directives.rawModelProfile,
provider: modelSelection.provider, provider: modelSelection.provider,
cfg: params.cfg, cfg: params.cfg,
agentDir, agentDir,
}); });
if (profileResolved.error) { if (profileResolved.error) {
return { text: profileResolved.error }; return { text: profileResolved.error };
} }
profileOverride = profileResolved.profileId; profileOverride = profileResolved.profileId;
} }
const nextLabel = `${modelSelection.provider}/${modelSelection.model}`; const nextLabel = `${modelSelection.provider}/${modelSelection.model}`;
@@ -994,6 +1010,10 @@ export async function persistInlineDirectives(params: {
agentCfg, agentCfg,
} = params; } = params;
let { provider, model } = params; let { provider, model } = params;
const activeAgentId = sessionKey
? resolveAgentIdFromSessionKey(sessionKey)
: resolveDefaultAgentId(cfg);
const agentDir = resolveAgentDir(cfg, activeAgentId);
if (sessionEntry && sessionStore && sessionKey) { if (sessionEntry && sessionStore && sessionKey) {
let updated = false; let updated = false;

View File

@@ -180,7 +180,10 @@ async function ensureDevWorkspace(dir: string) {
path.join(resolvedDir, "TOOLS.md"), path.join(resolvedDir, "TOOLS.md"),
DEV_TOOLS_TEMPLATE, DEV_TOOLS_TEMPLATE,
); );
await writeFileIfMissing(path.join(resolvedDir, "USER.md"), DEV_USER_TEMPLATE); await writeFileIfMissing(
path.join(resolvedDir, "USER.md"),
DEV_USER_TEMPLATE,
);
await writeFileIfMissing( await writeFileIfMissing(
path.join(resolvedDir, "HEARTBEAT.md"), path.join(resolvedDir, "HEARTBEAT.md"),
DEV_HEARTBEAT_TEMPLATE, DEV_HEARTBEAT_TEMPLATE,

View File

@@ -392,7 +392,9 @@ export function registerModelsCli(program: Command) {
order order
.command("set") .command("set")
.description("Set per-agent auth order override (locks rotation to this list)") .description(
"Set per-agent auth order override (locks rotation to this list)",
)
.requiredOption("--provider <name>", "Provider id (e.g. anthropic)") .requiredOption("--provider <name>", "Provider id (e.g. anthropic)")
.option("--agent <id>", "Agent id (default: configured default agent)") .option("--agent <id>", "Agent id (default: configured default agent)")
.argument("<profileIds...>", "Auth profile ids (e.g. anthropic:claude-cli)") .argument("<profileIds...>", "Auth profile ids (e.g. anthropic:claude-cli)")
@@ -414,7 +416,9 @@ export function registerModelsCli(program: Command) {
order order
.command("clear") .command("clear")
.description("Clear per-agent auth order override (fall back to config/round-robin)") .description(
"Clear per-agent auth order override (fall back to config/round-robin)",
)
.requiredOption("--provider <name>", "Provider id (e.g. anthropic)") .requiredOption("--provider <name>", "Provider id (e.g. anthropic)")
.option("--agent <id>", "Agent id (default: configured default agent)") .option("--agent <id>", "Agent id (default: configured default agent)")
.action(async (opts) => { .action(async (opts) => {

View File

@@ -23,12 +23,7 @@ describe("parseCliProfileArgs", () => {
}); });
it("still accepts global --dev before subcommand", () => { it("still accepts global --dev before subcommand", () => {
const res = parseCliProfileArgs([ const res = parseCliProfileArgs(["node", "clawdbot", "--dev", "gateway"]);
"node",
"clawdbot",
"--dev",
"gateway",
]);
if (!res.ok) throw new Error(res.error); if (!res.ok) throw new Error(res.error);
expect(res.profile).toBe("dev"); expect(res.profile).toBe("dev");
expect(res.argv).toEqual(["node", "clawdbot", "gateway"]); expect(res.argv).toEqual(["node", "clawdbot", "gateway"]);

View File

@@ -80,6 +80,7 @@ import {
DEFAULT_WORKSPACE, DEFAULT_WORKSPACE,
ensureWorkspaceAndSessions, ensureWorkspaceAndSessions,
guardCancel, guardCancel,
openUrl,
printWizardHeader, printWizardHeader,
probeGatewayReachable, probeGatewayReachable,
randomToken, randomToken,

View File

@@ -1,16 +1,22 @@
import { resolveAgentDir, resolveDefaultAgentId } from "../../agents/agent-scope.js";
import { import {
resolveAgentDir,
resolveDefaultAgentId,
} from "../../agents/agent-scope.js";
import {
type AuthProfileStore,
ensureAuthProfileStore, ensureAuthProfileStore,
setAuthProfileOrder, setAuthProfileOrder,
type AuthProfileStore,
} from "../../agents/auth-profiles.js"; } from "../../agents/auth-profiles.js";
import { normalizeProviderId } from "../../agents/model-selection.js"; import { normalizeProviderId } from "../../agents/model-selection.js";
import { loadConfig } from "../../config/config.js"; import { loadConfig } from "../../config/config.js";
import { normalizeAgentId } from "../../routing/session-key.js";
import type { RuntimeEnv } from "../../runtime.js"; import type { RuntimeEnv } from "../../runtime.js";
import { shortenHomePath } from "../../utils.js"; import { shortenHomePath } from "../../utils.js";
import { normalizeAgentId } from "../../routing/session-key.js";
function resolveTargetAgent(cfg: ReturnType<typeof loadConfig>, raw?: string): { function resolveTargetAgent(
cfg: ReturnType<typeof loadConfig>,
raw?: string,
): {
agentId: string; agentId: string;
agentDir: string; agentDir: string;
} { } {
@@ -37,7 +43,9 @@ export async function modelsAuthOrderGetCommand(
const cfg = loadConfig(); const cfg = loadConfig();
const { agentId, agentDir } = resolveTargetAgent(cfg, opts.agent); const { agentId, agentDir } = resolveTargetAgent(cfg, opts.agent);
const store = ensureAuthProfileStore(agentDir, { allowKeychainPrompt: false }); const store = ensureAuthProfileStore(agentDir, {
allowKeychainPrompt: false,
});
const order = describeOrder(store, provider); const order = describeOrder(store, provider);
if (opts.json) { if (opts.json) {
@@ -59,9 +67,13 @@ export async function modelsAuthOrderGetCommand(
runtime.log(`Agent: ${agentId}`); runtime.log(`Agent: ${agentId}`);
runtime.log(`Provider: ${provider}`); runtime.log(`Provider: ${provider}`);
runtime.log(`Auth file: ${shortenHomePath(`${agentDir}/auth-profiles.json`)}`);
runtime.log( runtime.log(
order.length > 0 ? `Order override: ${order.join(", ")}` : "Order override: (none)", `Auth file: ${shortenHomePath(`${agentDir}/auth-profiles.json`)}`,
);
runtime.log(
order.length > 0
? `Order override: ${order.join(", ")}`
: "Order override: (none)",
); );
} }
@@ -75,8 +87,13 @@ export async function modelsAuthOrderClearCommand(
const cfg = loadConfig(); const cfg = loadConfig();
const { agentId, agentDir } = resolveTargetAgent(cfg, opts.agent); const { agentId, agentDir } = resolveTargetAgent(cfg, opts.agent);
const updated = await setAuthProfileOrder({ agentDir, provider, order: null }); const updated = await setAuthProfileOrder({
if (!updated) throw new Error("Failed to update auth-profiles.json (lock busy?)."); agentDir,
provider,
order: null,
});
if (!updated)
throw new Error("Failed to update auth-profiles.json (lock busy?).");
runtime.log(`Agent: ${agentId}`); runtime.log(`Agent: ${agentId}`);
runtime.log(`Provider: ${provider}`); runtime.log(`Provider: ${provider}`);
@@ -94,7 +111,9 @@ export async function modelsAuthOrderSetCommand(
const cfg = loadConfig(); const cfg = loadConfig();
const { agentId, agentDir } = resolveTargetAgent(cfg, opts.agent); const { agentId, agentDir } = resolveTargetAgent(cfg, opts.agent);
const store = ensureAuthProfileStore(agentDir, { allowKeychainPrompt: false }); const store = ensureAuthProfileStore(agentDir, {
allowKeychainPrompt: false,
});
const providerKey = normalizeProviderId(provider); const providerKey = normalizeProviderId(provider);
const requested = (opts.order ?? []) const requested = (opts.order ?? [])
.map((entry) => String(entry).trim()) .map((entry) => String(entry).trim())
@@ -120,10 +139,10 @@ export async function modelsAuthOrderSetCommand(
provider, provider,
order: requested, order: requested,
}); });
if (!updated) throw new Error("Failed to update auth-profiles.json (lock busy?)."); if (!updated)
throw new Error("Failed to update auth-profiles.json (lock busy?).");
runtime.log(`Agent: ${agentId}`); runtime.log(`Agent: ${agentId}`);
runtime.log(`Provider: ${provider}`); runtime.log(`Provider: ${provider}`);
runtime.log(`Order override: ${describeOrder(updated, provider).join(", ")}`); runtime.log(`Order override: ${describeOrder(updated, provider).join(", ")}`);
} }

View File

@@ -103,88 +103,92 @@ describe("sessions_send gateway loopback", () => {
}); });
describe("sessions_send label lookup", () => { describe("sessions_send label lookup", () => {
it("finds session by label and sends message", async () => { it(
const port = await getFreePort(); "finds session by label and sends message",
const prevPort = process.env.CLAWDBOT_GATEWAY_PORT; { timeout: 15_000 },
process.env.CLAWDBOT_GATEWAY_PORT = String(port); async () => {
const port = await getFreePort();
const prevPort = process.env.CLAWDBOT_GATEWAY_PORT;
process.env.CLAWDBOT_GATEWAY_PORT = String(port);
const server = await startGatewayServer(port); const server = await startGatewayServer(port);
const spy = vi.mocked(agentCommand); const spy = vi.mocked(agentCommand);
spy.mockImplementation(async (opts) => { spy.mockImplementation(async (opts) => {
const params = opts as { const params = opts as {
sessionId?: string; sessionId?: string;
runId?: string; runId?: string;
extraSystemPrompt?: string; extraSystemPrompt?: string;
}; };
const sessionId = params.sessionId ?? "test-labeled"; const sessionId = params.sessionId ?? "test-labeled";
const runId = params.runId ?? sessionId; const runId = params.runId ?? sessionId;
const sessionFile = resolveSessionTranscriptPath(sessionId); const sessionFile = resolveSessionTranscriptPath(sessionId);
await fs.mkdir(path.dirname(sessionFile), { recursive: true }); await fs.mkdir(path.dirname(sessionFile), { recursive: true });
const startedAt = Date.now(); const startedAt = Date.now();
emitAgentEvent({ emitAgentEvent({
runId, runId,
stream: "lifecycle", stream: "lifecycle",
data: { phase: "start", startedAt }, data: { phase: "start", startedAt },
});
const text = "labeled response";
const message = {
role: "assistant",
content: [{ type: "text", text }],
};
await fs.appendFile(
sessionFile,
`${JSON.stringify({ message })}\n`,
"utf8",
);
emitAgentEvent({
runId,
stream: "lifecycle",
data: { phase: "end", startedAt, endedAt: Date.now() },
});
}); });
const text = "labeled response"; try {
const message = { // First, create a session with a label via sessions.patch
role: "assistant", const { callGateway } = await import("./call.js");
content: [{ type: "text", text }], await callGateway({
}; method: "sessions.patch",
await fs.appendFile( params: { key: "test-labeled-session", label: "my-test-worker" },
sessionFile, timeoutMs: 5000,
`${JSON.stringify({ message })}\n`, });
"utf8",
);
emitAgentEvent({ const tool = createClawdbotTools().find(
runId, (candidate) => candidate.name === "sessions_send",
stream: "lifecycle", );
data: { phase: "end", startedAt, endedAt: Date.now() }, if (!tool) throw new Error("missing sessions_send tool");
});
});
try { // Send using label instead of sessionKey
// First, create a session with a label via sessions.patch const result = await tool.execute("call-by-label", {
const { callGateway } = await import("./call.js"); label: "my-test-worker",
await callGateway({ message: "hello labeled session",
method: "sessions.patch", timeoutSeconds: 5,
params: { key: "test-labeled-session", label: "my-test-worker" }, });
timeoutMs: 5000, const details = result.details as {
}); status?: string;
reply?: string;
const tool = createClawdbotTools().find( sessionKey?: string;
(candidate) => candidate.name === "sessions_send", };
); expect(details.status).toBe("ok");
if (!tool) throw new Error("missing sessions_send tool"); expect(details.reply).toBe("labeled response");
expect(details.sessionKey).toBe("agent:main:test-labeled-session");
// Send using label instead of sessionKey } finally {
const result = await tool.execute("call-by-label", { if (prevPort === undefined) {
label: "my-test-worker", delete process.env.CLAWDBOT_GATEWAY_PORT;
message: "hello labeled session", } else {
timeoutSeconds: 5, process.env.CLAWDBOT_GATEWAY_PORT = prevPort;
}); }
const details = result.details as { await server.close();
status?: string;
reply?: string;
sessionKey?: string;
};
expect(details.status).toBe("ok");
expect(details.reply).toBe("labeled response");
expect(details.sessionKey).toBe("agent:main:test-labeled-session");
} finally {
if (prevPort === undefined) {
delete process.env.CLAWDBOT_GATEWAY_PORT;
} else {
process.env.CLAWDBOT_GATEWAY_PORT = prevPort;
} }
await server.close(); },
} );
});
it("returns error when label not found", async () => { it("returns error when label not found", { timeout: 15_000 }, async () => {
const port = await getFreePort(); const port = await getFreePort();
const prevPort = process.env.CLAWDBOT_GATEWAY_PORT; const prevPort = process.env.CLAWDBOT_GATEWAY_PORT;
process.env.CLAWDBOT_GATEWAY_PORT = String(port); process.env.CLAWDBOT_GATEWAY_PORT = String(port);
@@ -215,33 +219,39 @@ describe("sessions_send label lookup", () => {
} }
}); });
it("returns error when neither sessionKey nor label provided", async () => { it(
const port = await getFreePort(); "returns error when neither sessionKey nor label provided",
const prevPort = process.env.CLAWDBOT_GATEWAY_PORT; { timeout: 15_000 },
process.env.CLAWDBOT_GATEWAY_PORT = String(port); async () => {
const port = await getFreePort();
const prevPort = process.env.CLAWDBOT_GATEWAY_PORT;
process.env.CLAWDBOT_GATEWAY_PORT = String(port);
const server = await startGatewayServer(port); const server = await startGatewayServer(port);
try { try {
const tool = createClawdbotTools().find( const tool = createClawdbotTools().find(
(candidate) => candidate.name === "sessions_send", (candidate) => candidate.name === "sessions_send",
); );
if (!tool) throw new Error("missing sessions_send tool"); if (!tool) throw new Error("missing sessions_send tool");
const result = await tool.execute("call-no-key", { const result = await tool.execute("call-no-key", {
message: "hello", message: "hello",
timeoutSeconds: 5, timeoutSeconds: 5,
}); });
const details = result.details as { status?: string; error?: string }; const details = result.details as { status?: string; error?: string };
expect(details.status).toBe("error"); expect(details.status).toBe("error");
expect(details.error).toContain("Either sessionKey or label is required"); expect(details.error).toContain(
} finally { "Either sessionKey or label is required",
if (prevPort === undefined) { );
delete process.env.CLAWDBOT_GATEWAY_PORT; } finally {
} else { if (prevPort === undefined) {
process.env.CLAWDBOT_GATEWAY_PORT = prevPort; delete process.env.CLAWDBOT_GATEWAY_PORT;
} else {
process.env.CLAWDBOT_GATEWAY_PORT = prevPort;
}
await server.close();
} }
await server.close(); },
} );
});
}); });