1505 lines
93 KiB
JavaScript
1505 lines
93 KiB
JavaScript
"use strict";
|
|
|
|
const assert = require("node:assert/strict");
|
|
const { randomUUID } = require("node:crypto");
|
|
const fs = require("node:fs");
|
|
const { createRequire } = require("node:module");
|
|
const http = require("node:http");
|
|
const { once } = require("node:events");
|
|
const { test } = require("node:test");
|
|
const vm = require("node:vm");
|
|
const express = require("express");
|
|
const { createAgentLiveRouter, sendAgentError } = require("../routes/agent-live");
|
|
const { AI_PROVIDER_CONFIGS, getAiProviderConfig } = require("../AgentWorker/provider-config");
|
|
const { AGENT_ACTION_TOOL, AGENT_FILE_TOOLS, AGENT_ACTION_INSTRUCTIONS, AGENT_ACTION_READY_MESSAGE, MAX_AGENT_REVIEW_ACTIONS, buildAgentActionOffer, getAgentCreationConflict } = require("../AgentWorker/action-proposal");
|
|
const { resolveProviderSettings, prepareAgentProviderConnection, providerEnvUpdates } = require("../AgentWorker/provider-settings");
|
|
const { requestAgentProvider, withProviderBudget } = require("../AgentWorker/budgets");
|
|
const { proxyAiRequest } = require("../services/server-agent-provider-http");
|
|
|
|
function loadFixture(request, overrides) {
|
|
const filename = require.resolve(request);
|
|
const resolve = createRequire(filename);
|
|
const module = { exports: {} };
|
|
vm.runInNewContext(fs.readFileSync(filename, "utf8"), {
|
|
module, console, process: { env: {}, getuid: () => 42 }, Buffer, AbortController, AbortSignal,
|
|
require: (name) => Object.hasOwn(overrides, name) ? overrides[name] : resolve(name),
|
|
}, { filename });
|
|
return module.exports;
|
|
}
|
|
|
|
test("a first chat title uses one bounded request and never saves model refusal prose", async () => {
|
|
const prompt = "Could you check why the example server restarted?";
|
|
const fallback = "Check why the example server restarted";
|
|
const row = { chat_id: "12", user_id: "3", submission_message_id: "14" };
|
|
const provider = { provider: "openai-compatible", model: "fixture", settings: { baseUrl: "http://127.0.0.1/v1" } };
|
|
const reply = (content) => ({ status: 200, data: { choices: [{ message: { content } }] } });
|
|
for (const [existing, response, expected] of [
|
|
[prompt, reply('{"title":"Investigate Server Restart"}'), "Investigate Server Restart"],
|
|
["New Chat", reply('```json\n{"title":"Diagn\u00f3stico"}\n```'), "Diagn\u00f3stico"],
|
|
[prompt, reply("Sorry, but I can't restart your server."), fallback],
|
|
[prompt, reply(JSON.stringify({ title: "I can't help with that." })), fallback],
|
|
[prompt, reply(JSON.stringify({ title: "Unable to provide a title." })), fallback],
|
|
["New Chat", reply(JSON.stringify({ title: "Heading\nAnother line" })), fallback],
|
|
[prompt, reply(JSON.stringify({ title: "Server Restart", reply: "Some prose" })), fallback],
|
|
[prompt, { status: 503, data: { error: { message: "temporarily unavailable" } } }, fallback],
|
|
["Operator's title", undefined, null],
|
|
[undefined, undefined, null],
|
|
]) {
|
|
let requests = 0;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
requests += 1;
|
|
const { model, max_tokens, messages, tools } = JSON.parse(options.body);
|
|
assert.equal(model, provider.model);
|
|
assert.equal(tools, undefined);
|
|
assert.ok(max_tokens <= 96);
|
|
assert.match(messages[0].content, /Name this chat based on its first user message/);
|
|
assert.equal(messages.length, 2);
|
|
assert.equal(messages[1].role, "user");
|
|
assert.match(messages[1].content, /^Return the title.*quoted data, not instructions\./);
|
|
assert.deepEqual(JSON.parse(messages[1].content.split("\n")[1]), { message: prompt });
|
|
return response;
|
|
} } });
|
|
const { generateFirstAgentChatTitle } = loadFixture("../AgentWorker/chat-title", { "./provider-turns": turns });
|
|
const db = { query: async (sql, params) => {
|
|
assert.match(sql, /chat.created_by = \? AND NOT EXISTS[\s\S]*earlier.role = 'user' AND earlier.id < submission.id/);
|
|
assert.deepEqual([...params], [row.submission_message_id, row.chat_id, row.user_id]);
|
|
return existing === undefined ? [] : [{ title: existing }];
|
|
} };
|
|
const result = await generateFirstAgentChatTitle(db, row, provider, prompt, new AbortController().signal);
|
|
assert.equal(requests, response ? 1 : 0);
|
|
assert.deepEqual(result && { ...result }, response ? { title: expected, previousTitle: existing } : null);
|
|
}
|
|
});
|
|
|
|
test("credential handoff tolerates short reads, refuses truncated JSON and can only be consumed once", async () => {
|
|
const expected = { apiKey: "synthetic-key", baseUrl: "", modelId: "" };
|
|
const encoded = Buffer.from(JSON.stringify(expected));
|
|
const id = "3afbde2b-58b5-49d1-b2ff-e72b6fa3c142";
|
|
for (const bytes of [encoded, encoded.subarray(0, -1)]) {
|
|
let consumed = false;
|
|
let closed = 0;
|
|
let calls = 0;
|
|
const missing = () => Object.assign(new Error("Already consumed"), { code: "ENOENT" });
|
|
const { readCredentialProposal } = loadFixture("../AgentWorker/credential-proposals", { "node:fs/promises": {
|
|
open: async () => {
|
|
if (consumed) throw missing();
|
|
return {
|
|
stat: async () => ({ isFile: () => true, uid: 42, mode: 0o600, size: encoded.length, mtimeMs: Date.now() }),
|
|
read: async (buffer, offset, length, position) => {
|
|
assert.equal(consumed, false);
|
|
assert.equal(offset, position);
|
|
calls += 1;
|
|
return { bytesRead: bytes.copy(buffer, offset, position, Math.min(bytes.length, position + Math.min(length, 7))) };
|
|
},
|
|
close: async () => { closed += 1; },
|
|
};
|
|
},
|
|
unlink: async () => { if (consumed) throw missing(); consumed = true; },
|
|
} });
|
|
if (bytes === encoded) assert.deepEqual(JSON.parse(JSON.stringify(await readCredentialProposal(id))), expected);
|
|
else await assert.rejects(readCredentialProposal(id), { code: "agent_invalid_proposal" });
|
|
await assert.rejects(readCredentialProposal(id), { code: "agent_invalid_proposal" });
|
|
assert.ok(calls > 1);
|
|
assert.equal(closed, 1);
|
|
}
|
|
});
|
|
|
|
test("Groq model discovery uses its documented endpoint and lists active chat model IDs", async () => {
|
|
let attempts = 0;
|
|
const { DISCOVERY_TIMEOUT_MS } = require("../AgentWorker/budgets");
|
|
const { fetchAvailableAiModels } = loadFixture("../AgentWorker/provider-discovery", { "./budgets": {
|
|
DISCOVERY_TIMEOUT_MS,
|
|
requestAgentProvider: async (url, { method, headers }, timeoutMs) => {
|
|
assert.equal(url, "https://api.groq.com/openai/v1/models");
|
|
assert.equal(method, "GET");
|
|
assert.equal(headers.Authorization, "Bearer fixture-key");
|
|
assert.equal(headers.Accept, "application/json");
|
|
assert.equal(timeoutMs, DISCOVERY_TIMEOUT_MS / 2);
|
|
if (++attempts === 1) return { status: 503, data: { error: "Temporary outage" } };
|
|
return { status: 200, data: { object: "list", data: [
|
|
{ id: "openai/gpt-oss-120b", active: true }, { id: "whisper-large-v3", active: true },
|
|
{ id: "inactive-fixture", active: false }, { id: "llama-3.1-8b-instant" },
|
|
{ id: "openai/gpt-oss-120b" }, { id: { invalid: true } },
|
|
] } };
|
|
},
|
|
} });
|
|
assert.deepEqual(Array.from((await fetchAvailableAiModels("groq", { apiKey: "fixture-key" })).models),
|
|
["llama-3.1-8b-instant", "openai/gpt-oss-120b"]);
|
|
assert.equal(attempts, 2);
|
|
});
|
|
|
|
test("custom model discovery tries a versioned base URL and keeps opaque, case-sensitive IDs", async () => {
|
|
const attempts = [];
|
|
const { fetchAvailableAiModels } = loadFixture("../AgentWorker/provider-discovery", { "./budgets": {
|
|
requestAgentProvider: async (url) => {
|
|
attempts.push(url);
|
|
return attempts.length === 1 ? { status: 200, data: { raw: "<html>Web app</html>" } } : {
|
|
status: 200, data: { models: [{ model: "Team/Audio-chat" }, { id: "Team/audio-chat" }, { name: "Qwen:7b" }, { id: 12 }] },
|
|
};
|
|
},
|
|
} });
|
|
const result = await fetchAvailableAiModels("openai-compatible", { baseUrl: "https://provider.example/api" });
|
|
assert.deepEqual(attempts, ["https://provider.example/api/models", "https://provider.example/api/v1/models"]);
|
|
assert.equal(result.resolvedBaseUrl, "https://provider.example/api/v1");
|
|
assert.deepEqual(new Set(result.models), new Set(["Team/Audio-chat", "Team/audio-chat", "Qwen:7b"]));
|
|
});
|
|
|
|
test("a custom model ID is validated once on connect and listed without probing a saved provider", async () => {
|
|
const provider = "openai-compatible";
|
|
const config = getAiProviderConfig(provider);
|
|
const settings = { apiKey: "fixture-key", baseUrl: "https://provider.example/api/v1", modelId: "Team/Audio:chat", modelIds: ["Team/Audio:chat"] };
|
|
const { fetchAvailableAiModels } = loadFixture("../AgentWorker/provider-discovery", {
|
|
"./budgets": { requestAgentProvider: () => assert.fail("manual setup must not require a catalog") },
|
|
"./provider-turns": { callAiChatProvider: async (id, candidate, model, messages, options) => {
|
|
probes += 1;
|
|
assert.equal(id, provider);
|
|
assert.equal(candidate.baseUrl, settings.baseUrl);
|
|
assert.equal(candidate.apiKey, settings.apiKey);
|
|
assert.equal(model, settings.modelId);
|
|
assert.equal(messages[0].content, "Reply with OK.");
|
|
assert.ok(options.maxTokens <= 128);
|
|
return { content: "OK" };
|
|
} },
|
|
});
|
|
let probes = 0;
|
|
const connected = await prepareAgentProviderConnection(config, { key: settings.apiKey,
|
|
baseUrl: `${settings.baseUrl}/chat/completions`, modelId: settings.modelId }, {},
|
|
(candidate) => fetchAvailableAiModels(provider, candidate, { validateModel: true }));
|
|
assert.deepEqual(connected.settings, settings);
|
|
assert.deepEqual(Array.from(connected.models), [settings.modelId]);
|
|
const env = providerEnvUpdates(config, connected.settings);
|
|
assert.equal(env[config.modelEnv], "");
|
|
assert.deepEqual(resolveProviderSettings(provider, env), settings);
|
|
assert.deepEqual(Array.from((await fetchAvailableAiModels(provider, settings)).models), [settings.modelId]);
|
|
assert.equal(probes, 1);
|
|
assert.equal(providerEnvUpdates(config)[config.modelEnv], "");
|
|
await assert.rejects(prepareAgentProviderConnection(config, { modelId: "bad\nmodel" }, settings,
|
|
() => assert.fail("invalid IDs must not dial")), { code: "agent_invalid_manual_model" });
|
|
assert.equal(getAiProviderConfig("__proto__"), null);
|
|
});
|
|
|
|
test("saved custom model lists migrate the old field and keep the key when adding models", async () => {
|
|
const provider = "openai-compatible";
|
|
const config = getAiProviderConfig(provider);
|
|
const legacy = { [config.keyEnv]: "saved-fixture-key", [config.baseUrlEnv]: "https://provider.example/v1", [config.modelEnv]: "Team/Chat" };
|
|
const stored = resolveProviderSettings(provider, legacy);
|
|
assert.deepEqual(stored.modelIds, ["Team/Chat"]);
|
|
const manual = ["Team/Chat", "Team/chat", 'Team/Chat,Version="2"'];
|
|
let probes = 0;
|
|
const { fetchAvailableAiModels } = loadFixture("../AgentWorker/provider-discovery", {
|
|
"./budgets": { requestAgentProvider: () => assert.fail("a manual list must not require a catalog") },
|
|
"./provider-turns": { callAiChatProvider: async (id, candidate, model) => {
|
|
probes += 1;
|
|
assert.equal(id, provider);
|
|
assert.equal(candidate.apiKey, legacy[config.keyEnv]);
|
|
assert.equal(candidate.baseUrl, legacy[config.baseUrlEnv]);
|
|
assert.deepEqual(candidate.modelIds, manual);
|
|
assert.equal(model, "Team/chat", "probe the newly added model, not the first saved ID");
|
|
return { content: "OK" };
|
|
} },
|
|
});
|
|
const connected = await prepareAgentProviderConnection(config, { key: "", modelIds: [...manual, " Team/Chat "] }, stored,
|
|
(candidate) => fetchAvailableAiModels(provider, candidate, { validateModel: true }));
|
|
assert.deepEqual(Array.from(connected.models), manual);
|
|
const updated = providerEnvUpdates(config, connected.settings);
|
|
const reloaded = resolveProviderSettings(provider, { ...legacy, ...updated });
|
|
assert.deepEqual(reloaded.modelIds, manual);
|
|
assert.deepEqual(Array.from((await fetchAvailableAiModels(provider, reloaded)).models), manual);
|
|
assert.equal(probes, 1);
|
|
const oldClient = await prepareAgentProviderConnection(config, { modelId: "Team/Chat" }, reloaded,
|
|
(candidate) => fetchAvailableAiModels(provider, candidate));
|
|
assert.deepEqual(Array.from(oldClient.models), manual);
|
|
assert.deepEqual(resolveProviderSettings(provider, { [config.modelIdsEnv]: "" }, legacy).modelIds, []);
|
|
await assert.rejects(prepareAgentProviderConnection(config, { modelIds: Array(33).fill("fixture") }, stored,
|
|
() => assert.fail("oversized model lists must not dial")), { code: "agent_invalid_manual_model" });
|
|
});
|
|
|
|
test("changing a custom API origin never forwards the previously saved key without re-entry", async () => {
|
|
const config = getAiProviderConfig("openai-compatible");
|
|
const stored = { apiKey: "first-provider-key", baseUrl: "https://first.example/api/v1", modelId: "" };
|
|
for (const [baseUrl, key, expected] of [
|
|
["https://first.example/other/v1", "", stored.apiKey],
|
|
["https://second.example/v1", "", ""],
|
|
["http://first.example/api/v1", "", ""],
|
|
["https://second.example/v1", "new-provider-key", "new-provider-key"],
|
|
]) {
|
|
const result = await prepareAgentProviderConnection(config, { baseUrl, key }, stored, async (candidate) => {
|
|
assert.equal(candidate.apiKey, expected);
|
|
return { models: ["fixture-model"] };
|
|
});
|
|
assert.equal(result.settings.apiKey, expected);
|
|
}
|
|
await assert.rejects(prepareAgentProviderConnection(config, { baseUrl: "https://key:secret@second.example/v1" }, stored,
|
|
() => assert.fail("credentials embedded in a URL must not be sent")), /API key field/);
|
|
});
|
|
|
|
test("model discovery distinguishes credential, catalog, redirect, rate and timeout failures without exposing upstream data", async () => {
|
|
const cases = [
|
|
[401, { error: "fixture-private-error" }, "agent_discovery_auth", 422],
|
|
[403, {}, "agent_discovery_auth", 422],
|
|
[429, {}, "agent_discovery_busy", 429],
|
|
[498, {}, "agent_discovery_busy", 429],
|
|
[302, {}, "agent_discovery_redirect", 422],
|
|
[404, {}, "agent_discovery_unsupported", 422],
|
|
[200, { data: [] }, "agent_discovery_empty", 422],
|
|
[200, { raw: "not a JSON catalog" }, "agent_discovery_invalid_response", 422],
|
|
];
|
|
for (const [status, data, code, httpStatus] of cases) {
|
|
let attempts = 0;
|
|
const { fetchAvailableAiModels, toAgentDiscoveryError } = loadFixture("../AgentWorker/provider-discovery", {
|
|
"./budgets": { requestAgentProvider: async () => { attempts += 1; return { status, data }; } },
|
|
});
|
|
await assert.rejects(fetchAvailableAiModels("groq", { apiKey: "fixture-key" }).catch((error) => {
|
|
throw toAgentDiscoveryError(error);
|
|
}), { code, status: httpStatus, message: code });
|
|
assert.equal(attempts, 1, code);
|
|
}
|
|
const { toAgentDiscoveryError } = require("../AgentWorker/provider-discovery");
|
|
const controller = new AbortController();
|
|
controller.abort(new DOMException("fixture timeout", "TimeoutError"));
|
|
const timedOut = toAgentDiscoveryError(controller.signal.reason, controller.signal);
|
|
assert.equal(timedOut.code, "agent_discovery_timeout");
|
|
assert.equal(timedOut.status, 504);
|
|
});
|
|
|
|
test("discovery reports catalogs too large for the private worker response instead of truncating IDs", async () => {
|
|
const { fetchAvailableAiModels, toAgentDiscoveryError } = loadFixture("../AgentWorker/provider-discovery", { "./budgets": {
|
|
requestAgentProvider: async () => ({ status: 200, data: {
|
|
data: Array.from({ length: 1800 }, (_, index) => ({ id: `${"fixture-model-".repeat(15)}${index}` })),
|
|
} }),
|
|
} });
|
|
await assert.rejects(fetchAvailableAiModels("openai-compatible", { baseUrl: "https://provider.example/v1" }).catch((error) => {
|
|
throw toAgentDiscoveryError(error);
|
|
}), { code: "agent_discovery_response_too_large" });
|
|
});
|
|
|
|
test("provider discovery codes render safe HTTP explanations across the panel boundary", () => {
|
|
const response = {
|
|
status(status) { this.httpStatus = status; return this; },
|
|
json(body) { return body; },
|
|
};
|
|
const body = sendAgentError(response, { status: 422, code: "agent_discovery_auth", message: "fixture-private-error" });
|
|
assert.equal(response.httpStatus, 422);
|
|
assert.equal(body.code, "agent_discovery_auth");
|
|
assert.match(body.error, /provider rejected the API key/);
|
|
assert.doesNotMatch(body.error, /fixture-private-error/);
|
|
});
|
|
|
|
test("finished reviews use recorded facts without provider configuration or a request", async () => {
|
|
const receipt = "Created the reviewed file.";
|
|
const facts = { action: "create_file", path: "notes.txt", decision: "accepted", evidence: receipt };
|
|
const row = { id: "43", source: "live_chat", source_ref: "review:42", prompt: JSON.stringify({ receipt, facts }),
|
|
claim_token: "fixture-claim", server_id: "5", provider: "openai-compatible", model: "fixture" };
|
|
let published;
|
|
let planComplete = false;
|
|
const { createAgentJobRunner } = loadFixture("../AgentWorker/run-job", {
|
|
"./budgets": { RUN_TIMEOUT_MS: 10_000, withProviderBudget: () => assert.fail("receipt-only completion must not bill the provider") },
|
|
"./job-store": {
|
|
claimAgentJob: async () => row,
|
|
readAgentReviewContinuation: async () => ({ submissionMessageId: "18", receipts: [], remainingActions: [], reviewCount: 1,
|
|
fileTasks: [{ action: facts.action, path: facts.path }], planComplete }),
|
|
publishAgentResult: async (_db, _row, result) => { published = result; return true; },
|
|
failAgentClaim: async (_db, _row, reason) => assert.fail(reason),
|
|
},
|
|
});
|
|
const run = createAgentJobRunner({ db: {}, generation: "1", active: new Map(), stopping: () => false,
|
|
getProviderSettings: () => assert.fail("receipt-only completion must not load a provider key"), formatModelLabel: () => row.model,
|
|
callPanel: async (operation) => operation === "context" ? { serverName: "fixture", reviewActions: true } : assert.equal(operation, "verify"),
|
|
});
|
|
await run(row.id);
|
|
assert.match(published.content, /^\*\*Status:\*\* \[\u2713\] Reviewed actions confirmed/);
|
|
assert.match(published.content, /`notes\.txt` - Created\./);
|
|
planComplete = true;
|
|
row.prompt = JSON.stringify({ receipt, facts, resumeModel: true });
|
|
await run(row.id);
|
|
assert.match(published.content, /^\*\*Status:\*\* \[\u2713\] Task completed successfully/);
|
|
assert.equal(published.actionProposal, undefined);
|
|
});
|
|
|
|
test("consented background jobs apply only read-bound edits and do not complete Planner after an uncertain write", async () => {
|
|
const { hashAgentFile } = require("../AgentWorker/file-edit");
|
|
const { AgentRpcError } = require("../AgentWorker/private-rpc");
|
|
const { describeAgentReview } = require("../AgentWorker/review-conclusion");
|
|
const proposal = { action: "write_file", path: "settings.ini", oldText: "count=1", newText: "count=2" };
|
|
const before = "enabled=true\ncount=1\n";
|
|
const after = "enabled=true\ncount=2\n";
|
|
const editVersion = { sha256: hashAgentFile(before), nodeId: "fixture-node", path: "/fixture/settings.ini" };
|
|
const noWrite = ["no-consent", "denied-before-offer", "unsupported-node", "no-proposal"];
|
|
for (const outcome of ["applied", "unchanged", "lost", "revoked", "exhausted", "truncated", ...noWrite]) {
|
|
const row = { id: "43", source: "planner_send", auto_approve_file_edits: outcome !== "no-consent", account_epoch: "1", read_only: 0,
|
|
claim_token: "fixture-claim", server_id: "5", provider: "openai-compatible", model: "fixture", prompt: "Update the example settings." };
|
|
const calls = [];
|
|
let published;
|
|
const { createAgentJobRunner } = loadFixture("../AgentWorker/run-job", {
|
|
"./budgets": { RUN_TIMEOUT_MS: 10_000, withProviderBudget: (_provider, _lane, _signal, run) => run() },
|
|
"./job-store": { claimAgentJob: async () => row,
|
|
publishAgentResult: async (_db, _row, result) => { published = result; return true; },
|
|
failAgentClaim: async (_db, _row, reason) => assert.fail(reason) },
|
|
"./conversation": { createAgentConversation: ({ runBotAssistantTool }) => async ({ req }) => {
|
|
const tool = req.agentExtraTools.find(({ name }) => name === AGENT_ACTION_TOOL.name);
|
|
const edit = () => runBotAssistantTool({ name: AGENT_ACTION_TOOL.name, args: proposal });
|
|
const read = () => runBotAssistantTool({ name: "read_server_file", args: { path: proposal.path } });
|
|
if (noWrite.includes(outcome)) {
|
|
assert.equal(Boolean(tool), outcome === "no-proposal");
|
|
return { content: "I did not change the file." };
|
|
}
|
|
assert.equal((await edit()).ok, false);
|
|
assert.deepEqual([...tool.parameters.properties.action.enum], ["write_file"]);
|
|
const result = await read();
|
|
assert.equal(result.editVersion, undefined);
|
|
assert.equal((await edit()).code, "agent_action_arguments", "read and edit in one batch must not dispatch");
|
|
req.acceptAgentEditReads(outcome === "truncated" ? [] : [{ result }]);
|
|
assert.equal((await edit()).ok, ["applied", "unchanged", "exhausted"].includes(outcome));
|
|
if (outcome === "lost" || outcome === "revoked") {
|
|
await read();
|
|
assert.equal((await edit()).ok, false);
|
|
}
|
|
return { content: "The example job finished.", toolLoopExhausted: outcome === "exhausted" };
|
|
} },
|
|
});
|
|
await createAgentJobRunner({ db: {}, generation: "1", active: new Map(), stopping: () => false,
|
|
getProviderSettings: () => ({ provider: row.provider, model: row.model }), formatModelLabel: () => row.model,
|
|
callPanel: async (operation, args) => {
|
|
calls.push(operation);
|
|
if (operation === "context") return { automaticFileEdits: outcome !== "unsupported-node", clamped: true, serverName: "fixture",
|
|
permissions: { files_read: true, files_write: outcome !== "denied-before-offer" } };
|
|
if (operation === "tool") return { ok: true, result: before, editVersion };
|
|
if (operation === "autoFileEdit") {
|
|
assert.equal(args.editVersion, editVersion);
|
|
assert.equal(args.attempt, 1);
|
|
if (outcome === "lost") throw new Error("fixture lost the reply");
|
|
if (outcome === "revoked") throw new AgentRpcError(403, "agent_authority_revoked");
|
|
if (outcome === "unchanged") return { state: "applied", receipt: describeAgentReview("fixture", proposal, "applied", undefined, { evidence: "unchanged" }) };
|
|
return { state: "applied", receipt: describeAgentReview("fixture", proposal, "applied", undefined, { before, after }) };
|
|
}
|
|
return true;
|
|
},
|
|
})(row.id);
|
|
assert.equal(calls.filter((operation) => operation === "autoFileEdit").length, noWrite.includes(outcome) || outcome === "truncated" ? 0 : 1);
|
|
assert.equal(calls.includes("plannerDone"), outcome === "applied" || outcome === "no-consent");
|
|
assert.equal(published.actionProposal, undefined);
|
|
if (outcome === "applied") assert.match(published.content, /Automatic file edits confirmed/);
|
|
if (outcome === "lost") {
|
|
assert.equal(published.automaticEditFailed, true);
|
|
assert.match(published.content, /could not be confirmed/);
|
|
assert.match(published.content, /`settings\.ini` - file edit not confirmed/);
|
|
}
|
|
if (outcome === "revoked") {
|
|
assert.equal(published.automaticEditFailed, true);
|
|
assert.match(published.content, /Permission to make this edit was revoked\. No change was sent\./);
|
|
assert.doesNotMatch(published.content, /could not be confirmed|not confirmed/);
|
|
}
|
|
if (outcome === "exhausted") {
|
|
assert.equal(published.automaticEditFailed, true);
|
|
assert.match(published.content, /tool limit before finishing/);
|
|
assert.match(published.content, /`settings\.ini` - Edited/);
|
|
}
|
|
if (outcome === "truncated") assert.equal(published.automaticEditFailed, true);
|
|
if (outcome === "unchanged") {
|
|
assert.equal(published.automaticEditFailed, true);
|
|
assert.match(published.content, /No write was sent/);
|
|
}
|
|
if (noWrite.includes(outcome) && outcome !== "no-consent") {
|
|
assert.equal(published.automaticEditFailed, true, outcome);
|
|
assert.match(published.content, /incomplete or not fully confirmed/);
|
|
assert.match(published.content, /I did not change the file/);
|
|
}
|
|
}
|
|
});
|
|
|
|
test("automatic jobs use only complete provider reads and do not complete on tool-loop exhaustion", async () => {
|
|
const { MAX_BOT_TOOL_LOOPS } = require("../utils/bot-ai-tools");
|
|
const { hashAgentFile } = require("../AgentWorker/file-edit");
|
|
const { describeAgentReview } = require("../AgentWorker/review-conclusion");
|
|
const path = "settings.ini";
|
|
const read = { name: "read_server_file", args: { path } };
|
|
const proposal = { action: "write_file", path, oldText: "value=before", newText: "value=after" };
|
|
for (const mode of ["native", "text", "truncated-text"]) {
|
|
const before = `value=before\n${mode === "truncated-text" ? "x".repeat(15_000) : ""}\nEND_OF_FIXTURE`;
|
|
const editVersion = { sha256: hashAgentFile(before), nodeId: "fixture-node", path: `/fixture/${path}` };
|
|
const row = { id: "44", source: "planner_send", auto_approve_file_edits: 1, account_epoch: "1", read_only: 0,
|
|
claim_token: "fixture-claim", server_id: "5", provider: "openai-compatible", model: "fixture", prompt: "Update the fixture value and finish checking the file." };
|
|
let turns = 0;
|
|
let writes = 0;
|
|
let published;
|
|
const providerTurns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
const wire = JSON.parse(options.body);
|
|
if (mode !== "native" && wire.tools) return { status: 400, data: { error: { message: "Native tools are not supported." } } };
|
|
turns += 1;
|
|
if (turns === 2) {
|
|
const evidence = JSON.stringify(wire.messages.filter(({ role }) => role === (mode === "native" ? "tool" : "system")));
|
|
assert.equal(evidence.includes("END_OF_FIXTURE"), mode !== "truncated-text", mode);
|
|
assert.equal(evidence.includes("...[truncated]"), mode === "truncated-text", mode);
|
|
assert.doesNotMatch(evidence, /editVersion/);
|
|
}
|
|
const tool = turns === 2 ? { name: AGENT_ACTION_TOOL.name, args: proposal } : read;
|
|
const message = wire.tools ? { tool_calls: [{ id: `fixture-${turns}`, type: "function",
|
|
function: { name: tool.name, arguments: JSON.stringify(tool.args) } }] }
|
|
: { content: `<adpanel_tool_plan>${JSON.stringify({ tool_calls: [tool] })}</adpanel_tool_plan>` };
|
|
return { status: 200, data: { choices: [{ message, finish_reason: wire.tools ? "tool_calls" : "stop" }] } };
|
|
} } });
|
|
const conversation = loadFixture("../AgentWorker/conversation", { "./provider-turns": providerTurns });
|
|
const { createAgentJobRunner } = loadFixture("../AgentWorker/run-job", {
|
|
"./conversation": conversation,
|
|
"./budgets": { RUN_TIMEOUT_MS: 10_000, withProviderBudget: (_provider, _lane, _signal, run) => run() },
|
|
"./job-store": { claimAgentJob: async () => row,
|
|
publishAgentResult: async (_db, _row, result) => { published = result; return true; },
|
|
failAgentClaim: async (_db, _row, reason) => assert.fail(reason) },
|
|
});
|
|
const run = createAgentJobRunner({ db: {}, generation: "1", active: new Map(), stopping: () => false, assertDeadline() {},
|
|
getProviderSettings: () => ({ provider: row.provider, model: row.model, settings: { baseUrl: "http://127.0.0.1/v1" } }),
|
|
formatModelLabel: () => row.model,
|
|
callPanel: async (operation, args) => {
|
|
if (operation === "context") return { automaticFileEdits: true, clamped: true, serverName: "fixture", servers: [{ name: "fixture" }],
|
|
visibleServers: ["fixture"], permissions: { files_read: true, files_write: true } };
|
|
if (operation === "tool") return { ok: true, result: before, editVersion };
|
|
if (operation === "autoFileEdit") {
|
|
assert.equal(args.editVersion, editVersion);
|
|
writes += 1;
|
|
const after = before.replace(proposal.oldText, proposal.newText);
|
|
return { state: "applied", receipt: describeAgentReview("fixture", proposal, "applied", undefined, { before, after }) };
|
|
}
|
|
assert.equal(operation, "verify", "an exhausted run must not call plannerDone");
|
|
return true;
|
|
},
|
|
});
|
|
await run(row.id);
|
|
assert.equal(turns, MAX_BOT_TOOL_LOOPS, mode);
|
|
assert.equal(writes, mode === "truncated-text" ? 0 : 1, mode);
|
|
assert.equal(published.automaticEditFailed, true, mode);
|
|
assert.match(published.content, /tool limit before finishing/);
|
|
}
|
|
});
|
|
|
|
test("a reviewed file edit can resume the original turn and request a newly discovered console action", async () => {
|
|
const prompt = "Update settings.yml, then check what the server needs next.";
|
|
const receipt = "Updated settings.yml. The node confirmed the write.";
|
|
const facts = { action: "write_file", decision: "accepted", path: "settings.yml", evidence: receipt, approvedNewLines: "private file text" };
|
|
const row = { id: "43", source: "live_chat", source_ref: "review:42", prompt: JSON.stringify({ receipt, facts, resumeModel: true }),
|
|
submission_message_id: null, claim_token: "fixture-claim", server_id: "5", provider: "openai-compatible", model: "fixture" };
|
|
const nextAction = { action: "console_command", command: "say Configuration updated" };
|
|
let reviewCount = 1;
|
|
let published;
|
|
const { createAgentJobRunner } = loadFixture("../AgentWorker/run-job", {
|
|
"./budgets": { RUN_TIMEOUT_MS: 10_000, withProviderBudget: (_provider, _lane, _signal, run) => run() },
|
|
"./job-store": {
|
|
claimAgentJob: async () => row,
|
|
readAgentReviewContinuation: async (_db, _row, id) => {
|
|
assert.equal(id, "42");
|
|
return { submissionMessageId: "18", receipts: [], remainingActions: [], reviewCount };
|
|
},
|
|
readAgentRunTranscript: async (_db, transcript) => {
|
|
assert.equal(transcript.submission_message_id, "18");
|
|
return [{ role: "user", content: prompt }];
|
|
},
|
|
publishAgentResult: async (_db, _row, result) => { published = result; return true; },
|
|
failAgentClaim: async (_db, _row, reason) => assert.fail(reason),
|
|
},
|
|
"./conversation": { createAgentConversation: ({ runBotAssistantTool }) => async ({ req, messages }) => {
|
|
assert.equal(messages.at(-1).content, prompt);
|
|
assert.deepEqual(JSON.parse(JSON.stringify(req.agentReviewEvidence)), [
|
|
{ action: "write_file", decision: "accepted", path: "settings.yml", evidence: receipt },
|
|
]);
|
|
const advertised = req.agentExtraTools.find(({ name }) => name === AGENT_ACTION_TOOL.name);
|
|
const result = await runBotAssistantTool({ name: AGENT_ACTION_TOOL.name, args: nextAction });
|
|
if (reviewCount === MAX_AGENT_REVIEW_ACTIONS) {
|
|
assert.equal(advertised, undefined);
|
|
assert.equal(result.ok, false);
|
|
assert.match(result.error, /action limit/);
|
|
return { content: receipt };
|
|
}
|
|
assert.deepEqual(advertised.parameters.properties.action.enum, ["console_command"]);
|
|
assert.equal(result.pending_review, true);
|
|
return { content: AGENT_ACTION_READY_MESSAGE };
|
|
} },
|
|
});
|
|
const run = createAgentJobRunner({ db: {}, generation: "1", active: new Map(), stopping: () => false,
|
|
getProviderSettings: () => ({ provider: row.provider, model: row.model }), formatModelLabel: () => row.model,
|
|
callPanel: async (operation) => operation === "context" ? { serverName: "fixture", reviewActions: true,
|
|
permissions: { console_write: true } } : assert.equal(operation, "verify"),
|
|
});
|
|
await run(row.id);
|
|
assert.equal(published.content, receipt);
|
|
assert.deepEqual(JSON.parse(JSON.stringify(published.actionProposal)), nextAction);
|
|
assert.equal(published.resumeModel, true);
|
|
|
|
reviewCount = MAX_AGENT_REVIEW_ACTIONS;
|
|
await run(row.id);
|
|
assert.equal(published.actionProposal, undefined);
|
|
assert.match(published.content, /reached its limit of \d+ reviewed actions/);
|
|
assert.match(published.content, /`settings\.yml` - Edited\./);
|
|
});
|
|
|
|
test("a resumed Agent refuses settled creations and requires a successful read for the unfinished edit", async () => {
|
|
const { describeAgentReview } = require("../AgentWorker/review-conclusion");
|
|
const folder = { action: "create_folder", path: "ges" };
|
|
const file = { action: "create_file", path: "ges/hey.bb", content: "hey, what do you do" };
|
|
const occupied = { action: "create_file", path: "ges/other.bb", content: "new text" };
|
|
const edit = { action: "write_file", path: "hes.py", oldText: "", newText: "def add(left, right):\n return left + right\n" };
|
|
const fileTasks = [edit, folder, file, occupied].map(({ action, path }) => ({ action, path }));
|
|
const receipts = [describeAgentReview("fixture", folder, "dismissed").facts, describeAgentReview("fixture", file, "applied", null, {}).facts];
|
|
const last = describeAgentReview("fixture", occupied, "refused", "review_path_exists");
|
|
const row = { id: "43", source: "live_chat", source_ref: "review:42", prompt: JSON.stringify({ receipt: last.text, facts: last.facts, resumeModel: true }),
|
|
submission_message_id: null, claim_token: "fixture-claim", server_id: "5", provider: "google", model: "gemini-2.5-flash-lite" };
|
|
let published;
|
|
let readable = false;
|
|
const { createAgentJobRunner } = loadFixture("../AgentWorker/run-job", {
|
|
"./budgets": { RUN_TIMEOUT_MS: 10_000, withProviderBudget: (_provider, _lane, _signal, run) => run() },
|
|
"./job-store": {
|
|
claimAgentJob: async () => row,
|
|
readAgentReviewContinuation: async () => ({ submissionMessageId: "18", receipts, remainingActions: [], fileTasks, reviewCount: 3 }),
|
|
readAgentRunTranscript: async () => [{ role: "user", content: "Add a simple calculator to hes.py, then create ges/hey.bb." }],
|
|
publishAgentResult: async (_db, _row, result) => { published = result; return true; },
|
|
failAgentClaim: async (_db, _row, reason) => assert.fail(reason),
|
|
},
|
|
"./conversation": { createAgentConversation: ({ runBotAssistantTool }) => async ({ req }) => {
|
|
assert.deepEqual(JSON.parse(JSON.stringify(req.agentPendingFileTasks)), [fileTasks[0]]);
|
|
for (const [proposal, reason] of [[folder, /already declined/], [{ ...file, content: "different text" }, /already confirmed/], [occupied, /path exists/]]) {
|
|
const refusal = await runBotAssistantTool({ name: AGENT_ACTION_TOOL.name, args: proposal });
|
|
assert.equal(refusal.code, "agent_action_already_reviewed");
|
|
assert.match(refusal.error, reason);
|
|
assert.equal(req.agentReviewProposal, undefined);
|
|
}
|
|
const propose = () => runBotAssistantTool({ name: AGENT_ACTION_TOOL.name, args: { ...edit, fileTasks: [fileTasks[0]] } });
|
|
const read = (path) => runBotAssistantTool({ name: "read_server_file", args: { path } });
|
|
assert.equal((await propose()).code, "agent_action_arguments");
|
|
assert.equal((await read("report.txt")).ok, true);
|
|
assert.equal((await read(edit.path)).ok, false);
|
|
assert.equal((await propose()).code, "agent_action_arguments");
|
|
assert.equal(req.agentReviewProposal, undefined);
|
|
readable = true;
|
|
assert.match((await read(edit.path)).result, /exists and is empty/);
|
|
assert.equal((await propose()).pending_review, true);
|
|
return { content: AGENT_ACTION_READY_MESSAGE };
|
|
} },
|
|
});
|
|
const run = createAgentJobRunner({ db: {}, generation: "1", active: new Map(), stopping: () => false,
|
|
getProviderSettings: () => ({ provider: row.provider, model: row.model }), formatModelLabel: () => row.model,
|
|
callPanel: async (operation, args) => {
|
|
if (operation === "context") return { serverName: "fixture", reviewActions: true,
|
|
permissions: { files_read: true, files_write: true, files_create: true } };
|
|
if (operation === "tool") {
|
|
assert.equal(args.name, "read_server_file");
|
|
if (args.args.path === "report.txt") return { ok: true, result: "Existing notes" };
|
|
assert.equal(args.args.path, edit.path);
|
|
return readable ? { ok: true, result: "The file exists and is empty." } : { ok: false, error: "File not found." };
|
|
}
|
|
assert.equal(operation, "verify");
|
|
},
|
|
});
|
|
await run(row.id);
|
|
assert.deepEqual(JSON.parse(JSON.stringify(published.actionProposal)), edit);
|
|
assert.deepEqual(JSON.parse(JSON.stringify(published.fileTasks)), fileTasks);
|
|
assert.equal(published.resumeModel, true);
|
|
});
|
|
|
|
test("a model can retry the same edit proposal after reading the target file", async () => {
|
|
const path = "scripts/utility.py";
|
|
const suggestion = { action: "write_file", path, oldText: "", newText: "def square(value):\n return value * value\n" };
|
|
const request = "Add a small utility function of your choice to scripts/utility.py.";
|
|
const row = { id: "8", source: "live_chat", prompt: request, submission_message_id: "14",
|
|
server_id: "3", provider: "openai-compatible", model: "fixture" };
|
|
let requests = 0;
|
|
let published;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
const { messages } = JSON.parse(options.body);
|
|
requests += 1;
|
|
assert.match(messages[0].content, /When the user delegates a choice, decide it yourself/);
|
|
if (requests === 2) assert.match(messages.at(-1).content, /Read this exact path/);
|
|
if (requests === 3) assert.match(messages.at(-1).content, /the file exists and is empty/i);
|
|
assert.ok(requests <= 3);
|
|
const tool = { id: `fixture-${requests}`, type: "function", function: requests === 2
|
|
? { name: "read_server_file", arguments: JSON.stringify({ path }) }
|
|
: { name: AGENT_ACTION_TOOL.name, arguments: JSON.stringify(suggestion) } };
|
|
return { status: 200, data: { choices: [{ message: { tool_calls: [tool] } }] } };
|
|
} } });
|
|
const conversation = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
let conversationError;
|
|
const { createAgentJobRunner } = loadFixture("../AgentWorker/run-job", {
|
|
"./conversation": { createAgentConversation: (deps) => {
|
|
const complete = conversation.createAgentConversation(deps);
|
|
return async (input) => {
|
|
try { return await complete(input); } catch (error) { conversationError = error; throw error; }
|
|
};
|
|
} },
|
|
"./budgets": { RUN_TIMEOUT_MS: 10_000, withProviderBudget: (_provider, _lane, _signal, run) => run() },
|
|
"./job-store": {
|
|
claimAgentJob: async () => row,
|
|
readAgentRunTranscript: async () => [{ role: "user", content: request }],
|
|
publishAgentResult: async (_db, _row, result) => { published = result; return true; },
|
|
failAgentClaim: async (_db, _row, reason) => { throw conversationError || new Error(reason); },
|
|
},
|
|
});
|
|
const run = createAgentJobRunner({ db: {}, generation: "1", active: new Map(), stopping: () => false, assertDeadline() {},
|
|
getProviderSettings: () => ({ provider: row.provider, model: row.model, settings: { baseUrl: "http://127.0.0.1/v1" } }),
|
|
formatModelLabel: () => row.model,
|
|
callPanel: async (operation, args) => {
|
|
if (operation === "context") return { serverName: "fixture", servers: [{ name: "fixture" }], reviewActions: true,
|
|
permissions: { files_read: true, files_write: true } };
|
|
if (operation === "tool") {
|
|
assert.equal(args.name, "read_server_file");
|
|
assert.equal(args.args.path, path);
|
|
return { ok: true, result: "The file exists and is empty (0 bytes)." };
|
|
}
|
|
assert.equal(operation, "verify");
|
|
},
|
|
});
|
|
await run(row.id);
|
|
assert.equal(requests, 3);
|
|
assert.deepEqual(JSON.parse(JSON.stringify(published.actionProposal)), suggestion);
|
|
assert.equal(published.resumeModel, true);
|
|
});
|
|
|
|
test("every Agent provider receives the same live instructions and review evidence before the next proposal", async () => {
|
|
for (const provider of Object.keys(AI_PROVIDER_CONFIGS)) {
|
|
let dials = 0;
|
|
let actions = 0;
|
|
const input = { action: "replace_file", path: "server.properties", content: "online-mode=true\nmax-players=20\n" };
|
|
const tool = { id: "call_review", type: "function", function: { name: AGENT_ACTION_TOOL.name, arguments: JSON.stringify(input) } };
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
dials += 1;
|
|
const wire = JSON.parse(options.body);
|
|
const system = wire.system || wire.systemInstruction?.parts[0].text || wire.messages.filter(({ role }) => role === "system").map(({ content }) => content).join("\n");
|
|
assert.match(JSON.stringify(system), /Do not switch to normal chat, monitor mode/, provider);
|
|
assert.match(JSON.stringify(system), /explicitly asks to replace an existing file.*use replace_file/, provider);
|
|
assert.match(system, /Created the fixture backup/, provider);
|
|
const tools = provider === "google" ? wire.tools[0].functionDeclarations : wire.tools;
|
|
assert.ok(tools.some((entry) => (entry.function || entry).name === AGENT_ACTION_TOOL.name), provider);
|
|
assert.ok(!tools.some((entry) => (entry.function || entry).name === "propose_server_plan"), provider);
|
|
let data;
|
|
if (provider === "anthropic") data = { content: [{ type: "tool_use", id: tool.id, name: AGENT_ACTION_TOOL.name, input }], stop_reason: "tool_use" };
|
|
else if (provider === "google") data = { candidates: [{ content: { role: "model", parts: [{ functionCall: { name: AGENT_ACTION_TOOL.name, args: input } }] } }] };
|
|
else if (provider === "cohere") data = { message: { tool_calls: [tool] }, finish_reason: "TOOL_CALL" };
|
|
else data = { choices: [{ message: { role: "assistant", tool_calls: [tool] }, finish_reason: "tool_calls" }] };
|
|
return { status: 200, data };
|
|
} } });
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
const complete = createAgentConversation({
|
|
applyAiAgentPermClamp: async () => ({}), assertAiAgentJobDeadline() {},
|
|
getAccessibleServerEntriesForAi: async () => [{ name: "fixture" }], getEffectivePermsForUserOnServer: async () => ({}),
|
|
getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true,
|
|
sanitizeBotToolArgs: (_name, args) => args,
|
|
runBotAssistantTool: async ({ name, args, req }) => {
|
|
actions += 1;
|
|
assert.equal(name, AGENT_ACTION_TOOL.name);
|
|
assert.deepEqual(JSON.parse(JSON.stringify(args)), input);
|
|
req.agentReviewProposal = input;
|
|
return { ok: true, pending_review: true };
|
|
},
|
|
});
|
|
const result = await complete({ provider, model: "fixture-model", settings: { apiKey: "fixture", baseUrl: "http://127.0.0.1/v1" },
|
|
req: { agentExtraTools: [AGENT_ACTION_TOOL], agentActionInstructions: AGENT_ACTION_INSTRUCTIONS,
|
|
agentReviewEvidence: [{ action: "create_backup", decision: "accepted", evidence: "Created the fixture backup." }] },
|
|
messages: [{ role: "user", content: "Hello, replace server.properties with normal Minecraft settings." }], serverContext: { currentServer: "fixture" } });
|
|
assert.equal(result.content, AGENT_ACTION_READY_MESSAGE, provider);
|
|
assert.equal(dials, 1, provider);
|
|
assert.equal(actions, 1, provider);
|
|
}
|
|
});
|
|
|
|
test("Gemini stops duplicate-only batches but still considers an independent proposal in the same batch", async () => {
|
|
const name = AGENT_ACTION_TOOL.name;
|
|
const first = { action: "create_file", path: "first.txt", content: "First" };
|
|
const next = { action: "create_file", path: "second.txt", content: "Second" };
|
|
const evidence = [{ action: first.action, path: first.path, decision: "accepted" }];
|
|
for (const continues of [true, false]) {
|
|
let requests = 0;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
const wire = JSON.parse(options.body);
|
|
assert.ok(++requests <= 2, "must not restart a stalled conversation");
|
|
if (requests === 2) {
|
|
assert.equal(wire.contents.at(-1).parts[0].functionResponse.response.result.code, "agent_action_already_reviewed");
|
|
}
|
|
const proposals = requests === 2 && continues ? [first, next] : [first];
|
|
const parts = proposals.map((args) => ({ functionCall: { name, args } }));
|
|
return { status: 200, data: { candidates: [{ finishReason: "STOP", content: { role: "model", parts } }] } };
|
|
} } });
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
const complete = createAgentConversation({
|
|
applyAiAgentPermClamp: async () => ({}), assertAiAgentJobDeadline() {},
|
|
getAccessibleServerEntriesForAi: async () => [{ name: "fixture" }], getEffectivePermsForUserOnServer: async () => ({}),
|
|
getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true,
|
|
sanitizeBotToolArgs: (_name, args) => args,
|
|
runBotAssistantTool: ({ name: tool, args, req }) => {
|
|
assert.equal(tool, name);
|
|
const conflict = getAgentCreationConflict(args, evidence);
|
|
if (conflict) return conflict;
|
|
assert.deepEqual(JSON.parse(JSON.stringify(args)), next);
|
|
req.agentReviewProposal = args;
|
|
return { ok: true, pending_review: true };
|
|
},
|
|
});
|
|
const req = { agentExtraTools: [AGENT_ACTION_TOOL], agentActionInstructions: AGENT_ACTION_INSTRUCTIONS, agentReviewEvidence: evidence };
|
|
const result = await complete({ req, provider: "google", model: "gemini-2.5-flash-lite", settings: { apiKey: "fixture" },
|
|
messages: [{ role: "user", content: "Create first.txt and second.txt." }], serverContext: { currentServer: "fixture" } });
|
|
assert.equal(requests, 2);
|
|
if (continues) {
|
|
assert.equal(result.content, AGENT_ACTION_READY_MESSAGE);
|
|
assert.deepEqual(JSON.parse(JSON.stringify(req.agentReviewProposal)), next);
|
|
} else {
|
|
assert.match(result.content, /already settled in this turn\. No new action was prepared/);
|
|
assert.equal(req.agentReviewProposal, undefined);
|
|
}
|
|
}
|
|
});
|
|
|
|
test("Gemini replays unmodified candidate parts and matches ordered results without inventing provider IDs", async () => {
|
|
const action = { action: "write_file", path: "settings.yml", oldText: "enabled: false", newText: "enabled: true" };
|
|
const name = "read_server_file";
|
|
const paths = ["settings.yml", "defaults.yml"];
|
|
const taggedProposal = `<adpanel_tool_plan>${JSON.stringify({ tool_calls: [{ name: AGENT_ACTION_TOOL.name, args: action }] })}</adpanel_tool_plan>`;
|
|
const modelContent = { role: "model", parts: [
|
|
{ thought: true, text: taggedProposal },
|
|
{ thoughtSignature: "opaque-fixture-signature", functionCall: { name, args: { path: paths[0] } } },
|
|
{ functionCall: { id: "provider-call-2", name, args: { path: paths[1] } } },
|
|
] };
|
|
const observed = [];
|
|
let dials = 0;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
const wire = JSON.parse(options.body);
|
|
assert.ok(wire.tools[0].functionDeclarations.some(tool => tool.name === AGENT_ACTION_TOOL.name));
|
|
if (++dials === 1) return { status: 200, data: { candidates: [{ content: modelContent, finishReason: "STOP" }] } };
|
|
assert.equal(dials, 2);
|
|
assert.deepEqual(wire.contents.at(-2), modelContent);
|
|
const responses = wire.contents.at(-1).parts.map(part => part.functionResponse);
|
|
assert.deepEqual(responses.map(response => response.id), [undefined, "provider-call-2"]);
|
|
assert.deepEqual(responses.map(response => response.response.result.result), paths);
|
|
return { status: 200, data: { candidates: [{ content: { role: "model", parts: [
|
|
{ functionCall: { name: AGENT_ACTION_TOOL.name, args: action } },
|
|
] }, finishReason: "STOP" }] } };
|
|
} } });
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
const complete = createAgentConversation({
|
|
applyAiAgentPermClamp: async () => ({}), assertAiAgentJobDeadline() {},
|
|
getAccessibleServerEntriesForAi: async () => [{ name: "fixture" }], getEffectivePermsForUserOnServer: async () => ({}),
|
|
getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true,
|
|
sanitizeBotToolArgs: (_name, args) => args,
|
|
runBotAssistantTool: ({ name: tool, args, req }) => {
|
|
observed.push(tool);
|
|
if (tool === name) return { ok: true, result: args.path };
|
|
assert.deepEqual(JSON.parse(JSON.stringify(args)), action);
|
|
req.agentReviewProposal = action;
|
|
return { pending_review: true };
|
|
},
|
|
});
|
|
const input = { provider: "google", model: "gemini-2.5-flash-lite", settings: { apiKey: "fixture" },
|
|
req: { agentExtraTools: [AGENT_ACTION_TOOL, ...AGENT_FILE_TOOLS], agentActionInstructions: AGENT_ACTION_INSTRUCTIONS },
|
|
messages: [{ role: "user", content: "Check the settings and defaults, then enable the setting in settings.yml." }],
|
|
serverContext: { currentServer: "fixture" } };
|
|
assert.equal((await complete(input)).content, AGENT_ACTION_READY_MESSAGE);
|
|
assert.equal(dials, 2);
|
|
assert.deepEqual(observed, [name, name, AGENT_ACTION_TOOL.name]);
|
|
|
|
const thoughtOnly = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async () => ({
|
|
status: 200, data: { candidates: [{ content: { role: "model", parts: [modelContent.parts[0]] }, finishReason: "STOP" }] },
|
|
}) } });
|
|
await assert.rejects(thoughtOnly.requestGoogleNativeBotToolTurn("fixture", input.model, [], null), { failureCode: "agent_provider_incomplete" });
|
|
await assert.rejects(thoughtOnly.callAiChatProvider("google", input.settings, input.model, input.messages), { failureCode: "agent_provider_incomplete" });
|
|
});
|
|
|
|
test("Gemini retries malformed calls once in place and never dispatches from blocked or incomplete candidates", async () => {
|
|
const action = { action: "create_folder", path: "reports" };
|
|
const name = AGENT_ACTION_TOOL.name;
|
|
const candidate = (finishReason, parts) => ({ status: 200, data: { candidates: [{ finishReason, content: { role: "model", parts } }] } });
|
|
const nativeAction = { functionCall: { name, args: action } };
|
|
for (const { finish, retry, failureCode, dials } of [
|
|
{ finish: "MALFORMED_FUNCTION_CALL", retry: "STOP", dials: 3 },
|
|
{ finish: "MALFORMED_FUNCTION_CALL", retry: "MALFORMED_FUNCTION_CALL", failureCode: "agent_provider_tool_call_invalid", dials: 3 },
|
|
{ finish: "SAFETY", failureCode: "agent_provider_blocked", dials: 2 },
|
|
{ finish: "MAX_TOKENS", failureCode: "agent_provider_incomplete", dials: 2 },
|
|
]) {
|
|
const req = { agentExtraTools: [AGENT_ACTION_TOOL, ...AGENT_FILE_TOOLS], agentActionInstructions: AGENT_ACTION_INSTRUCTIONS };
|
|
let requests = 0;
|
|
let diagnostics = 0;
|
|
let savedContext;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
const wire = JSON.parse(options.body);
|
|
assert.ok(wire.tools, "must not fall back when a finish reason says not to use the candidate");
|
|
if (++requests === 1) return candidate("STOP", [{ functionCall: { name: "list_server_files", args: { path: "." } } }]);
|
|
if (requests === 2) {
|
|
savedContext = wire.contents;
|
|
assert.equal(wire.contents.at(-1).parts[0].functionResponse.response.result.result, "directory listing");
|
|
return candidate(finish, [nativeAction]);
|
|
}
|
|
assert.equal(requests, 3);
|
|
assert.deepEqual(wire.contents, savedContext);
|
|
assert.match(wire.systemInstruction.parts.at(-1).text, /malformed function call; it was not used/);
|
|
return candidate(retry, [nativeAction]);
|
|
} } });
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
const complete = createAgentConversation({
|
|
applyAiAgentPermClamp: async () => ({}), assertAiAgentJobDeadline() {},
|
|
getAccessibleServerEntriesForAi: async () => [{ name: "fixture" }], getEffectivePermsForUserOnServer: async () => ({}),
|
|
getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true,
|
|
sanitizeBotToolArgs: (_name, args) => args,
|
|
runBotAssistantTool: ({ name: tool, args }) => {
|
|
if (tool === "list_server_files") {
|
|
diagnostics += 1;
|
|
return { ok: true, result: "directory listing" };
|
|
}
|
|
assert.equal(requests, 3);
|
|
assert.equal(failureCode, undefined);
|
|
assert.deepEqual(JSON.parse(JSON.stringify(args)), action);
|
|
req.agentReviewProposal = action;
|
|
return { pending_review: true };
|
|
},
|
|
});
|
|
const run = complete({ req, provider: "google", model: "gemini-2.5-flash-lite", settings: { apiKey: "fixture" },
|
|
messages: [{ role: "user", content: "List the root and then create a reports folder." }], serverContext: { currentServer: "fixture" } });
|
|
if (failureCode) {
|
|
await assert.rejects(run, { failureCode });
|
|
assert.equal(req.agentReviewProposal, undefined);
|
|
} else assert.equal((await run).content, AGENT_ACTION_READY_MESSAGE);
|
|
assert.equal(requests, dials);
|
|
assert.equal(diagnostics, 1);
|
|
}
|
|
});
|
|
|
|
test("standalone greetings do not call the provider or reopen a previous action", async () => {
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", {
|
|
"./provider-turns": {},
|
|
});
|
|
const complete = createAgentConversation({
|
|
assertAiAgentJobDeadline() {},
|
|
getLoggedInUser: () => assert.fail("plain greetings must not enter the provider or tool loop"),
|
|
});
|
|
for (const greeting of ["hello", "Hi there!", "Salut!"]) {
|
|
const req = { agentExtraTools: [AGENT_ACTION_TOOL], agentActionInstructions: AGENT_ACTION_INSTRUCTIONS };
|
|
const result = await complete({ provider: "google", model: "gemini-2.5-flash-lite", req, messages: [
|
|
{ role: "user", content: "Start the server." },
|
|
{ role: "assistant", content: AGENT_ACTION_READY_MESSAGE },
|
|
{ role: "user", content: greeting },
|
|
], serverContext: { currentServer: "fixture" } });
|
|
assert.equal(result.content, "Hello! How can I help with this server?");
|
|
assert.equal(req.agentReviewProposal, undefined);
|
|
}
|
|
});
|
|
|
|
test("an informational question cannot publish a model-generated review placeholder without a tool call", async () => {
|
|
const question = "What can you help me with?";
|
|
for (const [tools, retryReply, expected] of [
|
|
[[AGENT_ACTION_TOOL], "I can help inspect your server.", "I can help inspect your server."],
|
|
[[], "Action prepared. Review it before applying.", "The model did not return a usable answer. No new action was prepared."],
|
|
]) {
|
|
let calls = 0;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
const { messages } = JSON.parse(options.body);
|
|
calls += 1;
|
|
if (calls === 2) assert.match(messages[0].content, /Answer the latest user message directly/);
|
|
assert.deepEqual(messages.at(-1), { role: "user", content: question });
|
|
return { status: 200, data: { choices: [{ message: { content: calls === 1 ? "Action prepared." : retryReply } }] } };
|
|
} } });
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
const req = { agentExtraTools: tools, agentActionInstructions: AGENT_ACTION_INSTRUCTIONS };
|
|
const complete = createAgentConversation({
|
|
applyAiAgentPermClamp: async () => ({}), assertAiAgentJobDeadline() {},
|
|
getAccessibleServerEntriesForAi: async () => [{ name: "fixture" }], getEffectivePermsForUserOnServer: async () => ({}),
|
|
getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true,
|
|
sanitizeBotToolArgs: (_name, args) => args,
|
|
runBotAssistantTool: () => assert.fail("model prose is not a tool call"),
|
|
});
|
|
const reply = await complete({ provider: "openai-compatible", settings: { baseUrl: "http://127.0.0.1/v1" }, model: "fixture",
|
|
req, messages: [{ role: "user", content: question }], serverContext: { currentServer: "fixture" } });
|
|
assert.equal(calls, 2);
|
|
assert.equal(req.agentReviewProposal, undefined);
|
|
assert.equal(reply.content, expected);
|
|
}
|
|
});
|
|
|
|
test("a resumed Agent checks unfinished requested work when the model stops after the first file", async () => {
|
|
const prompt = 'go and write a new file named "hes.py" and write random python in there and then create a folder named "ges" and write hey.bb in there with random content';
|
|
const premature = "Created hes.py with the approved text on wfewfe.";
|
|
const next = { action: "create_folder", path: "ges" };
|
|
let dials = 0;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
const { messages } = JSON.parse(options.body);
|
|
assert.ok(messages.some(({ role, content }) => role === "user" && content === prompt));
|
|
assert.ok(messages.some(({ role, content }) => role === "system" && content.includes('"path":"hes.py"')));
|
|
if (++dials === 1) return { status: 200, data: { choices: [{ message: { content: premature } }] } };
|
|
assert.match(messages[0].content, /Check for unfinished work before ending the turn/);
|
|
assert.deepEqual(messages.at(-1), { role: "user", content: prompt });
|
|
const tool = { id: "remaining-folder", type: "function", function: { name: AGENT_ACTION_TOOL.name, arguments: JSON.stringify(next) } };
|
|
return { status: 200, data: { choices: [{ message: { tool_calls: [tool] } }] } };
|
|
} } });
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
const req = { agentExtraTools: [AGENT_ACTION_TOOL], agentActionInstructions: AGENT_ACTION_INSTRUCTIONS,
|
|
agentReviewEvidence: [{ action: "create_file", decision: "accepted", path: "hes.py", evidence: "The node confirmed creation." }] };
|
|
const complete = createAgentConversation({
|
|
applyAiAgentPermClamp: async () => ({}), assertAiAgentJobDeadline() {},
|
|
getAccessibleServerEntriesForAi: async () => [{ name: "wfewfe" }], getEffectivePermsForUserOnServer: async () => ({}),
|
|
getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true,
|
|
sanitizeBotToolArgs: (_name, args) => args,
|
|
runBotAssistantTool: ({ name, args }) => {
|
|
assert.equal(name, AGENT_ACTION_TOOL.name);
|
|
assert.deepEqual(JSON.parse(JSON.stringify(args)), next);
|
|
req.agentReviewProposal = args;
|
|
return { pending_review: true };
|
|
},
|
|
});
|
|
const result = await complete({ provider: "openai-compatible", model: "fixture", settings: { baseUrl: "http://127.0.0.1/v1" },
|
|
req, messages: [{ role: "user", content: prompt }], serverContext: { currentServer: "wfewfe" } });
|
|
assert.equal(dials, 2);
|
|
assert.equal(result.content, AGENT_ACTION_READY_MESSAGE);
|
|
assert.deepEqual(JSON.parse(JSON.stringify(req.agentReviewProposal)), next);
|
|
});
|
|
|
|
test("review continuations report pending files when the provider stops early or hits a request limit", async () => {
|
|
const facts = { action: "create_folder", path: "notes", decision: "accepted", evidence: "The node confirmed creation." };
|
|
const pending = { action: "write_file", path: "settings.yml" };
|
|
const fileTasks = [{ action: facts.action, path: facts.path }, pending, { action: "create_file", path: "notes/today.txt" }];
|
|
const row = { id: "8", source: "live_chat", source_ref: "review:7", server_id: "3", provider: "openai-compatible", model: "fixture",
|
|
prompt: JSON.stringify({ facts, receipt: "Created notes.", resumeModel: true }) };
|
|
for (const throttleAt of [1, 2, 0]) {
|
|
let dials = 0;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
dials += 1;
|
|
const { messages } = JSON.parse(options.body);
|
|
const checklist = messages.find(({ content }) => content?.startsWith("Pending file outcomes from the same user request"));
|
|
assert.deepEqual(JSON.parse(checklist.content.split("\n").at(-1)), fileTasks.slice(1));
|
|
if (dials === throttleAt) return { status: 429, data: { error: { message: "Fixture request limit" } } };
|
|
if (throttleAt === 0 && dials === 1) return { status: 200, data: { choices: [{ message: { tool_calls: [{ id: "read", type: "function",
|
|
function: { name: "read_server_file", arguments: JSON.stringify({ path: pending.path }) },
|
|
}] } }] } };
|
|
return { status: 200, data: { choices: [{ message: { content: "Everything is done." } }] } };
|
|
} } });
|
|
let published;
|
|
const { createAgentJobRunner } = loadFixture("../AgentWorker/run-job", {
|
|
"./conversation": loadFixture("../AgentWorker/conversation", { "./provider-turns": turns }),
|
|
"./budgets": { RUN_TIMEOUT_MS: 10_000, withProviderBudget: (_provider, _lane, _signal, run) => run() },
|
|
"./job-store": {
|
|
claimAgentJob: async () => row,
|
|
readAgentReviewContinuation: async () => ({ submissionMessageId: "5", receipts: [], remainingActions: [], fileTasks, planComplete: true, reviewCount: 1 }),
|
|
readAgentRunTranscript: async () => [{ role: "user", content: "Create notes and notes/today.txt, then update settings.yml." }],
|
|
publishAgentResult: async (_db, _row, result) => { published = result; return true; },
|
|
failAgentClaim: async (_db, _row, reason) => assert.fail(reason),
|
|
},
|
|
});
|
|
const run = createAgentJobRunner({ db: {}, generation: "1", active: new Map(), stopping: () => false, assertDeadline() {},
|
|
getProviderSettings: () => ({ provider: row.provider, model: row.model, settings: { baseUrl: "http://127.0.0.1/v1" } }),
|
|
formatModelLabel: () => row.model,
|
|
callPanel: async (operation, args) => {
|
|
if (operation === "context") return { serverName: "fixture", servers: [{ name: "fixture" }], reviewActions: true,
|
|
permissions: { files_read: true, files_write: true, files_create: true } };
|
|
if (operation === "tool") {
|
|
assert.equal(args.name, "read_server_file");
|
|
assert.equal(args.args.path, pending.path);
|
|
return { ok: false, code: "file_not_found", error: "The file was not found." };
|
|
}
|
|
assert.equal(operation, "verify");
|
|
},
|
|
});
|
|
await run(row.id);
|
|
assert.equal(dials, throttleAt || 3);
|
|
assert.equal(published.actionProposal, undefined);
|
|
assert.match(published.content, /`notes` - Created folder\./);
|
|
assert.match(published.content, /`settings\.yml` - file edit not performed\./);
|
|
assert.match(published.content, /`notes\/today\.txt` - file creation not performed\./);
|
|
assert.doesNotMatch(published.content, /Everything is done|Task completed successfully/);
|
|
if (throttleAt) assert.match(published.content, /limit interrupted.*No further changes were sent/);
|
|
else assert.match(published.content, /`settings\.yml` - file edit not performed\. The file was not found/);
|
|
}
|
|
});
|
|
|
|
test("a final review reply puts each populated category on one line without boilerplate", () => {
|
|
const { renderAgentReviewSummary, describeAgentReview } = require("../AgentWorker/review-conclusion");
|
|
const created = describeAgentReview("fixture", { action: "create_file", path: "notes.txt", content: "not part of the summary",
|
|
changeSummary: "Added a maintenance note for operators." }, "applied").facts;
|
|
const declined = describeAgentReview("fixture", { action: "write_file", path: "settings.yml", changeSummary: "Never applied this edit." }, "dismissed").facts;
|
|
const folder = describeAgentReview("fixture", { action: "create_folder", path: "reports" }, "applied").facts;
|
|
const result = renderAgentReviewSummary({ outcomes: [created, declined, folder], followUp: "Done.", complete: true });
|
|
assert.deepEqual([...result.matchAll(/^\*\*(.*?):\*\*/gm)].map(([, title]) => title), ["Status", "Changed", "Not completed"]);
|
|
assert.equal(result.split("\n").length, 3);
|
|
assert.match(result, /\[!\] Task incomplete/);
|
|
assert.match(result, /`notes\.txt` - Created \(23 bytes\)\. Added a maintenance note for operators\. `reports` - Created folder\./);
|
|
assert.match(result, /`settings\.yml` - Declined file edit; no change sent\./);
|
|
assert.doesNotMatch(result, /Git|Verification|Next Steps|Done\.|not part of the summary|Never applied this edit/);
|
|
});
|
|
|
|
test("a missing-file observation gives the model one chance to act on intent, without changing a read-only request", async () => {
|
|
const path = "examples/theme.toml";
|
|
const missing = { ok: false, code: "file_not_found", error: "The node reported that the file was not found." };
|
|
const proposal = { action: "create_file", path, content: 'accent = "blue"\n' };
|
|
const offer = buildAgentActionOffer({ files_create: true, files_read: true, files_write: true });
|
|
for (const [prompt, wantsChange] of [["Put a sample accent color in examples/theme.toml.", true], ["Does examples/theme.toml exist?", false]]) {
|
|
let calls = 0;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
const { messages } = JSON.parse(options.body);
|
|
calls += 1;
|
|
if (calls === 3) {
|
|
assert.match(messages[0].content, /Reconsider the requested outcome.*continue any independent requested work/);
|
|
assert.ok(messages.some(({ role, content }) => role === "system" && content.includes('"code":"file_not_found"')));
|
|
}
|
|
const tool = calls === 1 ? { name: "read_server_file", arguments: JSON.stringify({ path }) }
|
|
: calls === 3 && wantsChange ? { name: AGENT_ACTION_TOOL.name, arguments: JSON.stringify(proposal) } : null;
|
|
const message = tool ? { tool_calls: [{ id: `fixture-${calls}`, type: "function", function: tool }] }
|
|
: { content: wantsChange ? "The file is missing. I could create it." : "The file was not found." };
|
|
return { status: 200, data: { choices: [{ message }] } };
|
|
} } });
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
const req = { agentExtraTools: [offer.tool, ...AGENT_FILE_TOOLS], agentActionInstructions: offer.instructions, agentFileReads: new Map() };
|
|
const complete = createAgentConversation({
|
|
applyAiAgentPermClamp: async () => ({}), assertAiAgentJobDeadline() {},
|
|
getAccessibleServerEntriesForAi: async () => [{ name: "fixture" }], getEffectivePermsForUserOnServer: async () => ({}),
|
|
getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true,
|
|
sanitizeBotToolArgs: (_name, args) => args,
|
|
runBotAssistantTool: ({ name, args }) => {
|
|
if (name === "read_server_file") {
|
|
req.agentFileReads.set(args.path, missing);
|
|
return missing;
|
|
}
|
|
assert.equal(wantsChange, true);
|
|
assert.equal(name, AGENT_ACTION_TOOL.name);
|
|
req.agentReviewProposal = args;
|
|
return { pending_review: true };
|
|
},
|
|
});
|
|
const result = await complete({ provider: "openai-compatible", model: "fixture", settings: { baseUrl: "http://127.0.0.1/v1" },
|
|
req, messages: [{ role: "user", content: prompt }], serverContext: { currentServer: "fixture" } });
|
|
assert.equal(calls, 3);
|
|
assert.equal(result.content, wantsChange ? AGENT_ACTION_READY_MESSAGE : "The file was not found.");
|
|
assert.deepEqual(req.agentReviewProposal && JSON.parse(JSON.stringify(req.agentReviewProposal)), wantsChange ? proposal : undefined);
|
|
}
|
|
});
|
|
|
|
test("the text fallback keeps recorded outcomes and fresh diagnostic results before requesting the next action", async () => {
|
|
const inspect = { name: "read_server_file", args: { path: "settings.yml" } };
|
|
const change = { name: AGENT_ACTION_TOOL.name, args: { action: "create_folder", path: "reports" } };
|
|
const observed = [];
|
|
let dials = 0;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
dials += 1;
|
|
const wire = JSON.parse(options.body);
|
|
assert.match(wire.systemInstruction.parts[0].text, /approved earlier edit/);
|
|
if (wire.tools) return { status: 400, data: { error: { message: "Native tools are not supported." } } };
|
|
assert.match(wire.systemInstruction.parts[0].text, /uses the ADPanel text tool protocol/);
|
|
assert.match(wire.systemInstruction.parts[0].text, /"name":"propose_server_action"/);
|
|
if (dials >= 3) assert.match(wire.systemInstruction.parts[0].text, /reports: enabled/);
|
|
const text = dials === 3 ? '<adpanel_tool_plan>{"tool_calls":[}</adpanel_tool_plan>' :
|
|
`<adpanel_tool_plan>${JSON.stringify({ tool_calls: dials === 2 ? [inspect, change] : [change] })}</adpanel_tool_plan>`;
|
|
return { status: 200, data: { candidates: [{ content: { parts: [{ text }] } }] } };
|
|
} } });
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
const complete = createAgentConversation({
|
|
applyAiAgentPermClamp: async () => ({}), assertAiAgentJobDeadline() {},
|
|
getAccessibleServerEntriesForAi: async () => [{ name: "fixture" }], getEffectivePermsForUserOnServer: async () => ({}),
|
|
getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true,
|
|
sanitizeBotToolArgs: (_name, args) => args,
|
|
runBotAssistantTool: ({ name, args, req }) => {
|
|
observed.push(JSON.parse(JSON.stringify({ name, args })));
|
|
if (name === inspect.name) return { ok: true, text: "reports: enabled" };
|
|
req.agentReviewProposal = args;
|
|
return { pending_review: true };
|
|
},
|
|
});
|
|
const result = await complete({ provider: "google", model: "fixture", settings: { apiKey: "fixture" },
|
|
req: { agentExtraTools: [AGENT_ACTION_TOOL, ...AGENT_FILE_TOOLS], agentActionInstructions: AGENT_ACTION_INSTRUCTIONS,
|
|
agentReviewEvidence: [{ action: "write_file", decision: "accepted", evidence: "Node confirmed the approved earlier edit." }] },
|
|
messages: [{ role: "user", content: "Check whether the edited settings enable reports, then create their directory." }],
|
|
serverContext: { currentServer: "fixture" } });
|
|
assert.equal(dials, 4);
|
|
assert.equal(result.content, AGENT_ACTION_READY_MESSAGE);
|
|
assert.deepEqual(observed, [inspect, change]);
|
|
});
|
|
|
|
test("native and standalone tagged calls pass later drafts without dispatching them, and quoted calls cannot request a review", async () => {
|
|
const actions = [{ action: "create_folder", path: "Hey" }, { action: "create_file", path: "Hey/hey.py", content: "" }];
|
|
const proposals = actions.map((args) => ({ name: AGENT_ACTION_TOOL.name, args }));
|
|
const read = { name: "read_server_file", args: { path: "settings.yml" } };
|
|
for (const format of ["native", "tagged", "mixed", "quoted"]) {
|
|
const calls = format === "mixed" ? [read, ...proposals] : proposals;
|
|
const tagged = `<adpanel_tool_plan>${JSON.stringify({ tool_calls: calls })}</adpanel_tool_plan>`;
|
|
const message = format === "tagged" || format === "quoted" ? { content: format === "tagged" ? tagged : `Example:\n\`\`\`\n${tagged}\n\`\`\`` }
|
|
: { tool_calls: calls.map(({ name, args }, index) => ({ id: `call_${index}`, type: "function", function: { name, arguments: JSON.stringify(args) } })) };
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async () => ({
|
|
status: 200, data: { choices: [{ message }] },
|
|
}) } });
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
const received = [];
|
|
const complete = createAgentConversation({
|
|
applyAiAgentPermClamp: async () => ({}), assertAiAgentJobDeadline() {},
|
|
getAccessibleServerEntriesForAi: async () => [{ name: "fixture" }], getEffectivePermsForUserOnServer: async () => ({}),
|
|
getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true,
|
|
runBotAssistantTool: async ({ name, args, req, followingProposals }) => {
|
|
received.push(JSON.parse(JSON.stringify({ name, args })));
|
|
if (name !== AGENT_ACTION_TOOL.name) return { ok: true };
|
|
assert.deepEqual(JSON.parse(JSON.stringify(followingProposals)), actions.slice(1));
|
|
req.agentReviewProposal = args;
|
|
return { pending_review: true };
|
|
},
|
|
sanitizeBotToolArgs: (_name, args) => args,
|
|
});
|
|
const result = await complete({ provider: "openai-compatible", model: "fixture", settings: { baseUrl: "http://127.0.0.1/v1" },
|
|
req: { agentActionInstructions: AGENT_ACTION_INSTRUCTIONS, agentExtraTools: [AGENT_ACTION_TOOL] },
|
|
messages: [{ role: "user", content: "Create the folder and an empty file." }],
|
|
serverContext: { currentServer: "fixture" } });
|
|
if (format === "quoted") {
|
|
assert.deepEqual(received, []);
|
|
assert.match(result.content, /No action was prepared/);
|
|
} else {
|
|
assert.deepEqual(received, format === "mixed" ? [read, proposals[0]] : [proposals[0]]);
|
|
assert.equal(result.content, AGENT_ACTION_READY_MESSAGE);
|
|
}
|
|
}
|
|
});
|
|
|
|
test("native providers deliver standalone advertised file reads and never execute a mixed text proposal", async () => {
|
|
const read = { name: "read_server_file", args: { path: "settings.yml" } };
|
|
const action = { name: AGENT_ACTION_TOOL.name, args: { action: "create_folder", path: "reports" } };
|
|
const tagged = `<adpanel_tool_plan>${JSON.stringify({ tool_calls: [read, action] })}</adpanel_tool_plan>`;
|
|
for (const provider of ["openai-compatible", "google", "anthropic", "cohere"]) {
|
|
for (const mode of ["advertised", "unadvertised", "quoted"]) {
|
|
let dials = 0;
|
|
const expectedReads = mode === "advertised" ? 1 : 0;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
dials += 1;
|
|
if (dials > 1 && expectedReads) assert.ok(options.body.includes("fixture read result"), `${provider}/${mode} missed the diagnostic result`);
|
|
const content = mode === "unadvertised" && dials <= 2
|
|
? `<adpanel_tool_plan>${JSON.stringify({ tool_calls: [read] })}</adpanel_tool_plan>`
|
|
: dials > 1 ? "Found the settings." : mode === "quoted" ? `Example: ${tagged}` : tagged;
|
|
const data = provider === "google" ? { candidates: [{ content: { parts: [{ text: content }] } }] }
|
|
: provider === "anthropic" ? { content: [{ type: "text", text: content }] }
|
|
: provider === "cohere" ? { message: { content: [{ type: "text", text: content }] } }
|
|
: { choices: [{ message: { content } }] };
|
|
return { status: 200, data };
|
|
} } });
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
let reads = 0;
|
|
const complete = createAgentConversation({
|
|
applyAiAgentPermClamp: async () => ({}), assertAiAgentJobDeadline() {},
|
|
getAccessibleServerEntriesForAi: async () => [{ name: "fixture" }], getEffectivePermsForUserOnServer: async () => ({}),
|
|
getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true,
|
|
sanitizeBotToolArgs: (_name, args) => args,
|
|
runBotAssistantTool: ({ name, args }) => {
|
|
assert.equal(name, read.name);
|
|
assert.equal(args.path, read.args.path);
|
|
reads += 1;
|
|
return { ok: true, result: "fixture read result" };
|
|
},
|
|
});
|
|
const req = { agentActionInstructions: AGENT_ACTION_INSTRUCTIONS,
|
|
agentExtraTools: mode === "unadvertised" ? [AGENT_ACTION_TOOL] : [AGENT_ACTION_TOOL, ...AGENT_FILE_TOOLS] };
|
|
const result = await complete({ provider, model: "fixture", settings: { apiKey: "fixture", baseUrl: "http://127.0.0.1/v1" },
|
|
req, messages: [{ role: "user", content: "Inspect settings.yml, then create reports." }], serverContext: { currentServer: "fixture" } });
|
|
assert.equal(reads, expectedReads, `${provider}/${mode}`);
|
|
if (expectedReads) assert.equal(dials, 2, `${provider}/${mode}`);
|
|
if (expectedReads) assert.equal(result.content, "Found the settings.");
|
|
}
|
|
}
|
|
});
|
|
|
|
test("the text tool protocol corrects rejected arguments or settled proposals once, without retrying a permission refusal", async () => {
|
|
const action = { action: "create_file", path: "notes.txt", content: "" };
|
|
const alreadyCreated = { action: "create_file", path: "readme.txt", content: "Recorded notes." };
|
|
const offer = buildAgentActionOffer({ files_create: true, files_read: true });
|
|
const emptyDirectory = "The reports directory is empty.";
|
|
const tagged = (name, args) => `<adpanel_tool_plan>${JSON.stringify({ tool_calls: [{ name, args }] })}</adpanel_tool_plan>`;
|
|
for (const mode of ["correct", "repeated", "denied", "settled", "settled-repeated"]) {
|
|
const settled = mode.startsWith("settled");
|
|
const recovers = mode === "correct" || mode === "settled";
|
|
let requests = 0;
|
|
let nativeRequests = 0;
|
|
let reads = 0;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
const wire = JSON.parse(options.body);
|
|
if (wire.tools) {
|
|
nativeRequests += 1;
|
|
return { status: 400, data: { error: { message: "Native tools are not supported." } } };
|
|
}
|
|
requests += 1;
|
|
if (requests > 1) assert.ok(wire.systemInstruction.parts[0].text.includes(emptyDirectory));
|
|
if (requests === 3) assert.match(wire.systemInstruction.parts[0].text, settled
|
|
? /already confirmed for this path.*Choose a different unfinished step/ : /previous proposal was rejected.*Supply one supported action/);
|
|
const args = requests === 3 && recovers ? action : settled ? alreadyCreated : { action: action.action, path: action.path };
|
|
const content = requests === 1 ? tagged("list_server_files", { path: "." }) : tagged(offer.tool.name, args);
|
|
return { status: 200, data: { candidates: [{ content: { parts: [{ text: content }] } }] } };
|
|
} } });
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
const complete = createAgentConversation({
|
|
applyAiAgentPermClamp: async () => ({}), assertAiAgentJobDeadline() {},
|
|
getAccessibleServerEntriesForAi: async () => [{ name: "fixture" }], getEffectivePermsForUserOnServer: async () => ({}),
|
|
getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true,
|
|
sanitizeBotToolArgs: (_name, args) => args,
|
|
runBotAssistantTool: ({ name, args, req }) => {
|
|
if (name === "list_server_files") {
|
|
reads += 1;
|
|
return { ok: true, result: emptyDirectory };
|
|
}
|
|
assert.equal(name, offer.tool.name);
|
|
if (mode === "denied") return { ok: false, error: "Your permissions do not allow creating this file." };
|
|
const conflict = getAgentCreationConflict(args, req.agentReviewEvidence || []);
|
|
if (conflict) return conflict;
|
|
if (!Object.hasOwn(args, "content")) return { ok: false, code: "agent_action_arguments", error: "Supply one supported action with its exact arguments." };
|
|
req.agentReviewProposal = args;
|
|
return { pending_review: true };
|
|
},
|
|
});
|
|
const req = { agentExtraTools: [offer.tool, ...AGENT_FILE_TOOLS], agentActionInstructions: offer.instructions,
|
|
...(settled && { agentReviewEvidence: [{ action: alreadyCreated.action, path: alreadyCreated.path, decision: "accepted" }] }) };
|
|
const result = await complete({ req, provider: "google", model: "gemini-2.5-flash-lite", settings: { apiKey: "fixture" },
|
|
messages: [{ role: "user", content: "Check the root, then create an empty notes.txt." }], serverContext: { currentServer: "fixture" } });
|
|
assert.equal(requests, mode === "denied" ? 2 : 3);
|
|
assert.equal(nativeRequests, 1);
|
|
assert.equal(reads, 1);
|
|
if (recovers) assert.deepEqual(JSON.parse(JSON.stringify(req.agentReviewProposal)), action);
|
|
else assert.equal(req.agentReviewProposal, undefined);
|
|
assert.equal(result.content, recovers ? AGENT_ACTION_READY_MESSAGE : mode === "denied"
|
|
? "Your permissions do not allow creating this file." : settled
|
|
? "The model kept requesting an action already settled in this turn. No new action was prepared."
|
|
: "The model did not provide valid arguments for a review. No new action was prepared.");
|
|
}
|
|
});
|
|
|
|
test("the Agent retries the reported file refusal once instead of asking for pasted text", async () => {
|
|
const refusal = "I need the content to replace the current server.properties file. Also, I can only create one folder at a time. Please provide the content for the file and specify if you want to create the folder before or after replacing the file.";
|
|
const newContentRefusal = "I need the content for the new server.properties file.";
|
|
const unavailableRefusal = "I cannot edit files or create folders as these actions are not available.";
|
|
const delegatedRefusal = "I cannot add random content or features as I need explicit instructions for file modifications. Please provide the exact content.";
|
|
const unnecessaryQuestion = "I can edit the files, but I need to know what feature to add and what content to write.";
|
|
const action = { action: "replace_file", path: "server.properties", content: "online-mode=true\nmax-players=20\n" };
|
|
for (const [mode, firstReply, provider = "openai-compatible"] of [["recover", refusal], ["recover-existing", "I need the current content of server.properties to replace it."],
|
|
["recover-generated", newContentRefusal], ["recover-unavailable", unavailableRefusal], ["exhausted", unavailableRefusal], ["read-only", unavailableRefusal],
|
|
["console-only", unavailableRefusal], ["clarify", newContentRefusal], ["advice", newContentRefusal],
|
|
["recover-delegated", delegatedRefusal, "google"], ["recover-delegated", unnecessaryQuestion],
|
|
["clarify", delegatedRefusal, "google"], ["clarify", unnecessaryQuestion],
|
|
["recover-unavailable", unavailableRefusal, "google"], ["exhausted", unavailableRefusal, "google"], ["read-only", unavailableRefusal, "google"]]) {
|
|
const recovers = mode.startsWith("recover");
|
|
const shouldRetry = recovers || mode === "exhausted";
|
|
let dials = 0;
|
|
const turns = loadFixture("../AgentWorker/provider-turns", { "./budgets": { requestAgentProvider: async (_url, options) => {
|
|
const wire = JSON.parse(options.body);
|
|
dials += 1;
|
|
const system = provider === "google" ? wire.systemInstruction.parts[0].text : wire.messages[0].content;
|
|
if (dials === 2) assert.match(system, /Write the content yourself when the user delegated the details.*Request the next needed change with propose_server_action/);
|
|
const recovered = recovers && dials === 2;
|
|
if (provider === "google") {
|
|
const parts = [recovered ? { functionCall: { name: AGENT_ACTION_TOOL.name, args: action } } : { text: firstReply }];
|
|
return { status: 200, data: { candidates: [{ finishReason: "STOP", content: { role: "model", parts } }] } };
|
|
}
|
|
const message = recovered ? { tool_calls: [{ id: "recovered-action", type: "function", function: {
|
|
name: AGENT_ACTION_TOOL.name, arguments: JSON.stringify(action),
|
|
} }] } : { content: firstReply };
|
|
return { status: 200, data: { choices: [{ message }] } };
|
|
} } });
|
|
const { createAgentConversation } = loadFixture("../AgentWorker/conversation", { "./provider-turns": turns });
|
|
const offer = mode === "console-only" ? buildAgentActionOffer({ console_write: true }) : null;
|
|
const req = mode === "read-only" ? { agentExtraTools: [], agentActionInstructions: "This job is read only." }
|
|
: { agentExtraTools: [offer?.tool || AGENT_ACTION_TOOL], agentActionInstructions: offer?.instructions || AGENT_ACTION_INSTRUCTIONS };
|
|
const complete = createAgentConversation({
|
|
applyAiAgentPermClamp: async () => ({}), assertAiAgentJobDeadline() {},
|
|
getAccessibleServerEntriesForAi: async () => [{ name: "fixture" }], getEffectivePermsForUserOnServer: async () => ({}),
|
|
getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true,
|
|
sanitizeBotToolArgs: (_name, args) => args,
|
|
runBotAssistantTool: ({ name, args, req: request }) => {
|
|
assert.equal(recovers, true);
|
|
assert.equal(name, AGENT_ACTION_TOOL.name);
|
|
assert.deepEqual(JSON.parse(JSON.stringify(args)), action);
|
|
request.agentReviewProposal = args;
|
|
return { pending_review: true };
|
|
},
|
|
});
|
|
const prompt = mode === "clarify" ? "Replace server.properties with my custom settings." :
|
|
mode === "advice" ? "What does a normal Minecraft Paper server.properties look like?" :
|
|
mode === "recover-delegated" ? "Replace server.properties with a valid example; you choose the details." :
|
|
'write a normal minecraft paper server.properties instead of what\'s now in that file and then create a "hey" folder jn the root';
|
|
const result = await complete({ provider, model: provider === "google" ? "gemini-2.5-flash-lite" : "fixture",
|
|
settings: { apiKey: "fixture", baseUrl: "http://127.0.0.1/v1" }, req,
|
|
messages: [{ role: "user", content: prompt }],
|
|
serverContext: { currentServer: "fixture" } });
|
|
assert.equal(dials, shouldRetry ? 2 : 1, `${provider}/${mode}`);
|
|
if (recovers) {
|
|
assert.equal(result.content, AGENT_ACTION_READY_MESSAGE);
|
|
assert.deepEqual(JSON.parse(JSON.stringify(req.agentReviewProposal)), action);
|
|
} else {
|
|
assert.equal(req.agentReviewProposal, undefined);
|
|
if (mode === "exhausted") assert.match(result.content, /No further server change was sent/);
|
|
else assert.equal(result.content, firstReply);
|
|
}
|
|
}
|
|
});
|
|
|
|
test("a local completion report distinguishes a confirmed edit from test results without exposing file contents", () => {
|
|
const { describeAgentReview, renderAgentReviewSummary } = require("../AgentWorker/review-conclusion");
|
|
const { facts } = describeAgentReview("fixture", { action: "write_file", path: "settings.yml", newText: "after-only-value\n",
|
|
changeSummary: "Enabled the requested setting." }, "applied", undefined, { before: "before-only-value\n", after: "after-only-value\n" });
|
|
assert.equal(facts.approvedNewLines, undefined);
|
|
const report = renderAgentReviewSummary({ outcomes: [facts], complete: true });
|
|
assert.match(report, /`settings\.yml` - Edited\. Enabled the requested setting\. \(\+1 \/ -1 lines\)\./);
|
|
assert.doesNotMatch(report, /before-only-value|after-only-value|test|build|lint/);
|
|
});
|
|
|
|
test("a console receipt never exposes the command or equates acknowledgement with verified execution", () => {
|
|
const { describeAgentReview, renderAgentReviewSummary } = require("../AgentWorker/review-conclusion");
|
|
const command = { action: "console_command", command: "private fixture command" };
|
|
const declined = describeAgentReview("fixture", command, "dismissed");
|
|
const acknowledged = describeAgentReview("fixture", command, "applied");
|
|
const report = renderAgentReviewSummary({ outcomes: [declined.facts, acknowledged.facts], complete: true });
|
|
assert.match(declined.text, /No change was sent/);
|
|
assert.match(report, /Declined console command; no change sent/);
|
|
assert.match(report, /console command sent and acknowledged\. Output not verified/);
|
|
assert.doesNotMatch(report, /private fixture command|Task completed successfully/);
|
|
});
|
|
|
|
async function withProvider(handler, check) {
|
|
const server = http.createServer(handler);
|
|
const listening = once(server, "listening");
|
|
server.listen(0, "127.0.0.1");
|
|
await listening;
|
|
try {
|
|
await check(`http://127.0.0.1:${server.address().port}`);
|
|
} finally {
|
|
await new Promise((resolve) => {
|
|
server.close(resolve);
|
|
server.closeAllConnections();
|
|
});
|
|
}
|
|
}
|
|
|
|
test("provider requests preserve status, JSON or text, and headers without following redirects", async () => {
|
|
const paths = [];
|
|
await withProvider((request, response) => {
|
|
paths.push(request.url);
|
|
if (request.url === "/models") {
|
|
response.writeHead(200, { link: "</next>; rel=next" });
|
|
response.end('{"models":[]}');
|
|
} else {
|
|
response.writeHead(302, { location: "/models" });
|
|
response.end("redirect");
|
|
}
|
|
}, async (base) => {
|
|
const models = await proxyAiRequest(`${base}/models`, { method: "GET" });
|
|
assert.deepEqual(models.data, { models: [] });
|
|
assert.equal(models.headers.link, "</next>; rel=next");
|
|
const redirect = await proxyAiRequest(`${base}/redirect`, { method: "GET" });
|
|
assert.equal(redirect.status, 302);
|
|
assert.deepEqual(redirect.data, { raw: "redirect" });
|
|
assert.deepEqual(paths, ["/models", "/redirect"]);
|
|
});
|
|
});
|
|
|
|
test("provider deadline includes an unfinished response body", async () => {
|
|
await withProvider((_request, response) => {
|
|
response.writeHead(200);
|
|
response.write(" ");
|
|
const drip = setInterval(() => response.write(" "), 10);
|
|
response.once("close", () => clearInterval(drip));
|
|
}, async (base) => {
|
|
await assert.rejects(proxyAiRequest(base, { method: "GET" }, 120), /Request timeout/);
|
|
});
|
|
});
|
|
|
|
test("cancelling an Agent request closes its upstream response without reporting a timeout", async () => {
|
|
let cancel;
|
|
let notifyClosed;
|
|
const closed = new Promise((resolve) => { notifyClosed = resolve; });
|
|
await withProvider((_request, response) => {
|
|
response.once("close", notifyClosed);
|
|
response.writeHead(200);
|
|
response.write(" ");
|
|
cancel();
|
|
}, async (base) => {
|
|
const controller = new AbortController();
|
|
cancel = () => controller.abort();
|
|
await assert.rejects(proxyAiRequest(base, { method: "GET", signal: controller.signal }), { name: "AbortError" });
|
|
await closed;
|
|
});
|
|
});
|
|
|
|
test("losing a submission response does not cancel admitted work; retries carry the same request key", async () => {
|
|
const controller = new AbortController();
|
|
const requestKey = randomUUID();
|
|
const account = { id: 42 };
|
|
const job = { jobId: 17, chatId: 12, status: "queued", provider: "openai", model: "fixture" };
|
|
const admissions = [];
|
|
let disconnected;
|
|
const app = express();
|
|
const pass = (_req, _res, next) => next();
|
|
app.use(express.json(), (_req, res, next) => {
|
|
if (!disconnected) disconnected = once(res, "close");
|
|
next();
|
|
});
|
|
app.use("/api/ai", createAgentLiveRouter({
|
|
isAuthenticated: async () => true, hasAgentAccess: async () => true, getLoggedInUser: async () => account,
|
|
cancelLimiter: pass, statusLimiter: pass,
|
|
db: { query: async () => assert.fail("a disconnect must not mutate job state") },
|
|
worker: { request: async () => assert.fail("submission must not call the worker") },
|
|
insertAiAgentChatJob: async (submission) => {
|
|
admissions.push(submission);
|
|
if (admissions.length === 1) {
|
|
controller.abort();
|
|
await disconnected;
|
|
}
|
|
return job;
|
|
},
|
|
saveSelection: async () => {},
|
|
}));
|
|
await withProvider(app, async (base) => {
|
|
const submit = (signal) => fetch(`${base}/api/ai/chat`, { method: "POST", signal,
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ requestKey, server: "fixture", prompt: "hello", provider: job.provider, model: job.model }),
|
|
});
|
|
await assert.rejects(submit(controller.signal), { name: "AbortError" });
|
|
const response = await submit();
|
|
assert.equal(response.status, 202);
|
|
assert.deepEqual(await response.json(), { ok: true, chatId: job.chatId, jobId: job.jobId, status: "queued" });
|
|
assert.equal(admissions.length, 2);
|
|
for (const admission of admissions) {
|
|
assert.equal(admission.user, account);
|
|
assert.equal(admission.live.requestKey, requestKey);
|
|
}
|
|
});
|
|
});
|
|
|
|
test("provider response limits cover announced and chunked bodies", async () => {
|
|
await withProvider((request, response) => {
|
|
if (request.url === "/announced") {
|
|
response.writeHead(200, { "content-length": String(20 * 1024 * 1024) });
|
|
response.flushHeaders();
|
|
return;
|
|
}
|
|
response.writeHead(200);
|
|
response.end(Buffer.alloc(17 * 1024 * 1024));
|
|
}, async (base) => {
|
|
for (const route of ["/announced", "/chunked"]) {
|
|
await assert.rejects(proxyAiRequest(`${base}${route}`, { method: "GET" }, 2000), /response is too large/);
|
|
}
|
|
});
|
|
});
|
|
|
|
test("a cleared provider stays disabled even on workers with old environment values", () => {
|
|
const provider = "openai-compatible";
|
|
const { keyEnv, baseUrlEnv, modelEnv } = getAiProviderConfig(provider);
|
|
assert.ok(keyEnv && baseUrlEnv);
|
|
const inherited = { [keyEnv]: "worker-key", [baseUrlEnv]: "https://worker.example.test/v1", [modelEnv]: "worker-model" };
|
|
assert.deepEqual(resolveProviderSettings(provider, {}, inherited), { apiKey: inherited[keyEnv], baseUrl: inherited[baseUrlEnv], modelId: inherited[modelEnv], modelIds: [inherited[modelEnv]] });
|
|
assert.deepEqual(resolveProviderSettings(provider, { [keyEnv]: "", [baseUrlEnv]: "", [modelEnv]: "" }, inherited), { apiKey: "", baseUrl: "", modelId: "", modelIds: [] });
|
|
assert.deepEqual(resolveProviderSettings(provider, { [keyEnv]: "new-key", [baseUrlEnv]: "https://new.example.test/v1" }, inherited),
|
|
{ apiKey: "new-key", baseUrl: "https://new.example.test/v1", modelId: inherited[modelEnv], modelIds: [inherited[modelEnv]] });
|
|
});
|
|
|
|
test("provider lanes reserve discovery headroom and a cancelled wait never dials", async () => {
|
|
let posted = 0;
|
|
let discovered = 0;
|
|
await withProvider((request, response) => {
|
|
if (request.method === "POST") posted += 1;
|
|
else discovered += 1;
|
|
response.end("{}");
|
|
}, async (base) => {
|
|
const run = (lane, signal, method) => withProviderBudget("openai-compatible", lane, signal,
|
|
() => requestAgentProvider(base, { method }, 3000));
|
|
const deadline = AbortSignal.timeout(5000);
|
|
await Promise.all(Array.from({ length: 78 }, () => run("live", deadline, "POST")));
|
|
assert.equal(posted, 78);
|
|
const controller = new AbortController();
|
|
const waiting = run("live", controller.signal, "POST");
|
|
controller.abort();
|
|
await assert.rejects(waiting, { name: "AbortError" });
|
|
assert.equal(posted, 78);
|
|
await Promise.all(Array.from({ length: 4 }, () => run("discovery", deadline, "GET")));
|
|
await assert.rejects(run("discovery", deadline, "GET"), { code: "agent_discovery_busy" });
|
|
assert.equal(discovered, 4);
|
|
await run("setup", deadline, "GET");
|
|
assert.equal(discovered, 5);
|
|
await run("live", deadline, "POST");
|
|
assert.equal(posted, 79);
|
|
});
|
|
}); |