"use strict"; const assert = require("node:assert/strict"); const fs = require("node:fs"); const path = require("node:path"); const { test } = require("node:test"); const { createServerAgentJobPermissionReader } = require("../services/server-agent-job-auth"); const { parseAiAgentFileOperations } = require("../services/server-agent-file-directives"); const { createAgentFileDiagnostics } = require("../services/server-agent-file-diagnostics"); const { createAgentDiagnostics, createLiveAgentServerSummary } = require("../AgentWorker/panel-diagnostics"); const RUNNER = { id: 8, email: "operator@example.test", session_epoch: 2, agent_access: true }; const JOB = { id: 19, user_id: RUNNER.id, started_at: new Date("2026-11-01T12:00:00Z") }; function setup() { const state = { user: { ...RUNNER }, perms: { planner_access: true, files_write: true }, serverId: 32, access: true, active: true, currentSource: true }; const checkedRuns = []; const readPermissions = createServerAgentJobPermissionReader({ db: { query: async (sql, params) => { checkedRuns.push({ sql, params }); return state.active ? [{}] : []; } }, findUserById: async (accountId) => { assert.equal(accountId, RUNNER.id); return state.user; }, userCanUseAdpanelAgent: (user) => user.agent_access === true, findServer: async (name) => ({ name, id: state.serverId }), isServerSuspended: () => false, userHasAccessToServer: async () => state.access, getEffectivePermsForUserOnServer: async () => state.perms, }, { job: JOB, runner: RUNNER, serverName: "known-server", serverId: 32, requiredPermission: "planner_access", isSourceCurrent: async () => state.currentSource }); return { state, readPermissions, checkedRuns }; } test("an active Agent job reads current permissions and binds to its own claim", async () => { const { state, readPermissions, checkedRuns } = setup(); assert.equal((await readPermissions()).files_write, true); state.perms = { planner_access: true, files_write: false }; assert.equal((await readPermissions()).files_write, false); assert.match(checkedRuns[0].sql, /status = 'running' AND started_at = \?/); assert.deepEqual(checkedRuns[0].params, [19, 8, JOB.started_at]); }); test("a running Agent job refuses revoked, replaced, or suspended principals and targets", async () => { for (const revoke of [ (state) => { state.user.agent_access = false; }, (state) => { state.user.suspended = true; }, (state) => { state.user = null; }, (state) => { state.user.id = 18; }, (state) => { state.user.session_epoch = 3; }, (state) => { state.user.admin = true; }, (state) => { state.access = false; }, (state) => { state.perms.planner_access = false; }, (state) => { state.serverId = 42; }, (state) => { state.active = false; }, ]) { const { state, readPermissions } = setup(); assert.equal((await readPermissions()).files_write, true); revoke(state); await assert.rejects(readPermissions(), { status: 403 }); } }); test("a retired Planner prompt loses authority after its job has started", async () => { const { state, readPermissions } = setup(); assert.equal((await readPermissions()).files_write, true); state.currentSource = false; await assert.rejects(readPermissions(), { status: 403, message: /Planner prompt changed/ }); assert.equal(state.active, true); }); test("Agent status prefers live runtime state and never substitutes a stale inventory label", async () => { const entry = { name: "fixture", id: 11, nodeId: "node-1", status: "stopped" }; const node = { id: entry.nodeId }; let state = { ok: true, state: "online" }; const summary = createLiveAgentServerSummary({ isRemoteEntry: (target) => Boolean(target.nodeId), findNodeByIdOrName: async (id) => { assert.equal(id, entry.nodeId); return node; }, getNodeServerPowerState: async (target, name, timeout, options) => { assert.equal(target, node); assert.equal(name, entry.name); assert.equal(timeout, 5_000); assert.deepEqual(options, { singleOnly: true }); return state; }, verifyLocalDockerStopped: async (name) => { assert.equal(name, entry.name); return { ok: true, state: "stopped" }; }, withTimeout: (lookup) => lookup, }); let checks = 0; const req = { readAiAgentJobPermissions: async (name, id) => { assert.deepEqual([name, id], [entry.name, entry.id]); checks += 1; } }; assert.equal((await summary(req, entry, {})).status, "running"); state = { ok: false, state: null }; const unverified = await summary(req, entry, {}); assert.equal(unverified.status, "unknown"); assert.equal(unverified.statusSource, "unverified"); state = { ok: true, state: "missing" }; assert.equal((await summary(req, entry, {})).status, "missing"); assert.equal((await summary(req, { ...entry, nodeId: null, status: "running" }, {})).status, "stopped"); assert.equal(checks, 4); await assert.rejects(summary({ readAiAgentJobPermissions: async () => { throw new Error("Access revoked"); } }, entry, {}), /Access revoked/); }); test("live Agent tool mistakes return feedback without reaching the filesystem", async () => { const row = { source: "live_chat", started_at: new Date() }; const entry = { name: "fixture", id: 11 }; const claim = { id: "4", generation: "1", token: "ca17f659-08dc-4437-ac7b-ca4884f08ff3" }; const permissions = { files_read: false }; const dispatch = createAgentDiagnostics({ db: { query: async () => [row] }, featureEnabled: () => true, authorizeAgentJobClaim: async () => ({ req: { readAiAgentJobPermissions: async () => permissions }, user: RUNNER, entry, serverName: entry.name, }), getAccessibleServerEntriesForAi: async () => [entry], executeAiAgentFileOperations: () => assert.fail("a refused tool must not touch the filesystem"), }); for (const [name, args, message] of [ ["read_server_file", { path: "/absolute" }, /relative path/i], ["read_server_file", { path: "settings.yml" }, /permission to read/i], ["write_file", { path: "settings.yml", content: "example" }, /not available/i], ]) { const result = await dispatch("tool", { claim, name, args }, new AbortController().signal); assert.equal(result.ok, false); assert.match(result.error, message); } }); function loadFileExecutor(dial) { return createAgentFileDiagnostics({ resolveRemoteFsContext: async () => ({ remote: true, node: {}, serverId: 11, serverName: "srv", baseDir: "/volumes/srv" }), fsRelayDeps: { buildNodeBaseUrl: () => "http://node.example.test", buildNodeAuthHeaders: () => ({}), httpRequestJson: (url, method, headers, body) => { assert.equal(method, "POST"); return dial({}, new URL(url).pathname, body); }, }, }).executeAiAgentFileOperations; } test("diagnostic file dispatch rechecks read permissions for every operation", async () => { const reads = []; const execute = loadFileExecutor(async (_node, endpoint, body) => { assert.equal(endpoint, "/v1/fs/list"); reads.push(body.path); return { status: 200, json: { ok: true, entries: [] } }; }); let checks = 0; const req = { readAiAgentFilePermissions: async () => ({ files_read: ++checks === 1 }) }; const result = await execute({ operations: [{ action: "list", path: "first" }, { action: "list", path: "second" }], serverName: "srv", req, }); assert.deepEqual(reads, ["/volumes/srv/first"]); assert.match(result[1], /No permission to read/); }); test("typed Agent file paths retain literal punctuation after validation", async () => { const { normalizeAgentFileTool } = require("../AgentWorker/action-proposal"); const operation = normalizeAgentFileTool("list_server_files", { path: "server data!" }); assert.ok(operation); const execute = loadFileExecutor(async (_node, _endpoint, body) => { assert.equal(body.path, "/volumes/srv/server data!"); return { status: 200, json: { ok: true, entries: [] } }; }); assert.deepEqual(await execute({ operations: [operation], serverName: "srv", req: { readAiAgentFilePermissions: async () => ({ files_read: true }), } }), ["Contents of server data!:\n(empty)"]); }); test("typed file diagnostics distinguish successful output from a missing file", async () => { const execute = loadFileExecutor(async (_node, endpoint) => endpoint === "/v1/fs/read" ? { status: 404, json: { ok: false, error: "fixture node detail must not be returned" } } : { status: 200, json: { ok: true, entries: [] } }); assert.deepEqual(await execute({ operations: [{ action: "list", path: "." }, { action: "read", path: "missing.yml" }], serverName: "srv", structured: true, req: { readAiAgentFilePermissions: async () => ({ files_read: true }) }, }), [{ ok: true, result: "Contents of .:\n(empty)" }, { ok: false, code: "file_not_found", error: "Could not read missing.yml: file not found." }]); }); test("Agent file diagnostics report an explicit empty file only for verified empty content", async () => { const contents = new Map([ ["empty.txt", ""], ["regular.txt", Buffer.from("some text\n").toString("base64")], ["missing-content.txt", undefined], ["malformed.txt", "!"], ["binary.txt", "AA=="], ]); const execute = loadFileExecutor((_node, endpoint, body) => { assert.equal(endpoint, "/v1/fs/read"); const content = contents.get(path.basename(body.path)); return { status: 200, json: { ok: true, ...(content === undefined ? {} : { content }) } }; }); const results = await execute({ operations: [...contents.keys()].map((path) => ({ action: "read", path })), serverName: "srv", structured: true, req: { readAiAgentFilePermissions: async () => ({ files_read: true }) } }); assert.deepEqual(results, [ { ok: true, result: "Read empty.txt: the file exists and is empty (0 bytes)." }, { ok: true, result: "Read regular.txt:\n```\nsome text\n\n```" }, { ok: false, code: "file_invalid_content", error: "Could not read missing-content.txt: the server node did not return valid file content." }, { ok: false, code: "file_invalid_content", error: "Could not read malformed.txt: the server node did not return valid file content." }, { ok: false, code: "file_not_text", error: "Cannot read binary.txt: binary file (not readable as text)." }, ]); }); test("file diagnostics never dial a node after the server identity changes", async () => { const execute = loadFileExecutor(() => assert.fail("must not dial a replacement server")); assert.deepEqual(await execute({ operations: [{ action: "list", path: "." }], serverName: "srv", serverId: 12, structured: true, req: { readAiAgentFilePermissions: async () => ({ files_read: true }) } }), [ { ok: false, code: "file_target_unavailable", error: "Could not access node files for srv." }, ]); }); test("model-selected file changes never reach the daemon even with file permissions", async () => { const endpoints = []; const execute = loadFileExecutor(async (_node, endpoint) => { endpoints.push(endpoint); return { status: 200, json: { ok: true, entries: [] } }; }); const req = { readAiAgentFilePermissions: async () => ({ files_read: true, files_create: true, files_write: true, files_delete: true }) }; const operations = ["create", "write", "mkdir", "delete"].map((action) => ({ action, path: "sample.txt", content: "sample" })); const result = await execute({ operations, serverName: "srv", req }); assert.deepEqual(endpoints, []); assert.equal(result.length, operations.length); for (const detail of result) assert.match(detail, /cannot change/); }); test("queued file operations ignore quoted directives and keep complete file bodies literal", () => { const reply = [ "For example, FILE_DELETE:sample.txt is a directive.", "```text", "FILE_DELETE:sample.txt", "```", "FILE_WRITE:sample.txt", "---FILE_CONTENT_START---", " leading whitespace", "FILE_DELETE:literal.txt", "", "---FILE_CONTENT_END---", "FILE_LIST:.", ].join("\n"); const parsed = parseAiAgentFileOperations(reply); assert.deepEqual(parsed.operations, [ { action: "write", path: "sample.txt", content: " leading whitespace\nFILE_DELETE:literal.txt\n" }, { action: "list", path: "." }, ]); assert.match(parsed.message, /For example/); assert.deepEqual(parseAiAgentFileOperations("FILE_WRITE:sample.txt\n---FILE_CONTENT_START---\nFILE_DELETE:literal.txt").operations, []); }); test("queued prompts advertise only available file diagnostics", () => { const { buildBackgroundAiAgentMessages: buildMessages } = require("../AgentWorker/run-job"); const perms = { files_read: true, files_write: true }; const messages = buildMessages({ prompt: "Review settings.txt", perms }); assert.match(messages[0].content, /FILE_LIST:.*FILE_READ:/); assert.doesNotMatch(messages[0].content, /FILE_(WRITE|CREATE|DELETE|MKDIR):/); assert.equal(messages[1].content, "Review settings.txt"); assert.match(buildMessages({ prompt: "Review settings.txt", perms: {} })[0].content, /cannot list or read/); });