Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

7.0 KB
Raw Blame
import test from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdtemp, mkdir, readdir, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createDownloadPromoteTool } from "../plugin/download-promote.mjs";
import { createPerplexicaResearchTool } from "../plugin/perplexica-research.mjs";
import { createHostCommandProposeTool } from "../plugin/host-observe.mjs";
import {registeredPixelTools, combinedToolSchema} from './tool-grammar-registration.mjs';

const promotion = {
  jobId: "ops-1788130169655-22b40ab50141", filename: "reference.html",
  relativePath: "web/reference.html", sha256: "a".repeat(64), sourceUrl: "https://example.org/",
};
const longUrl = length => "https://example.org/" + "a".repeat(length - 20);
const nativeGrammar = process.env.ODS_TEST_LLAMA_SCHEMA;
const nativeOnly = {skip: !nativeGrammar && 'set ODS_TEST_LLAMA_SCHEMA to the pinned native test bridge'};
const registered = await registeredPixelTools();
const libraryProposal = {repository: 'https://github.com/o/r', serviceId: 'example', name: 'Example',
  pythonVersion: '3.12', pythonImports: ['example']};

function compileSchema(schema) {
  const result = spawnSync(nativeGrammar, [], {
    input: JSON.stringify({schema, compileOnly: true}), encoding: 'utf8', timeout: 30000,
  });
  assert.ifError(result.error);
  assert.equal(result.status, 0, result.stderr.slice(0, 2000));
  assert.ok(JSON.parse(result.stdout).grammarBytes > 0);
}

test('grammar inventory captures every actual Pixel registration', () => {
  assert.equal(registered.length, 28);
  for (const name of ['pixel_ods_image_read', 'pixel_ods_workspace_preview', 'pixel_ods_workspace_bundle', 'pixel_ods_workspace_artifact', 'pixel_ods_source_proposal',
    'pixel_ods_python_library_proposal', 'pixel_ods_extension_request_retry', 'pixel_ods_workspace_preview_inspect',
    'pixel_ods_project_build']) {
    assert.ok(registered.some(tool => tool.name === name), name);
  }
});

test('legacy configuration does not expose an unavailable inspector', async () => {
  const legacy = await registeredPixelTools({inspection:false, project:false});
  assert.equal(legacy.length,26);
  assert.equal(legacy.some(tool => tool.name === 'pixel_ods_workspace_preview_inspect'),false);
  assert.equal(legacy.some(tool => tool.name === 'pixel_ods_project_build'),false);
});

for (const tool of registered) {
  test(`${tool.name} registered schema compiles in llama.cpp`, nativeOnly, () => compileSchema(tool.parameters));
}
test('all registered Pixel schemas compile together, including deferred specialists', nativeOnly,
  () => compileSchema(combinedToolSchema(registered)));

for (const [tool, samples] of [
  [registered.find(tool => tool.name === 'pixel_ods_workspace_artifact'),
    [{relativePath:'report.pdf'}, {relativePath:'project.zip',sourcePath:'Playground/project'},
      {relativePath:'single.zip',sourcePath:'Playground/main.py'}]],
  [registered.find(tool => tool.name === 'pixel_ods_image_read'), [{id:'img-'+'a'.repeat(32),sha256:'b'.repeat(64)}]],
  [registered.find(tool => tool.name === 'pixel_ods_workspace_bundle'),
    [{files:[{source:'project/source.py',key:'source.py',copyTo:'source.txt'}],mappingPath:'sources.json',outputRoot:'project/public'}]],
  [createDownloadPromoteTool(), [promotion, { ...promotion, sourceUrl: longUrl(4096) }]],
  [createPerplexicaResearchTool(), [{ query: "Find public sources" }, { query: "a".repeat(1000) }]],
  [createHostCommandProposeTool(), [{ command: "pwd" }, { command: "a".repeat(16384) }]],
  [registered.find(tool => tool.name === 'pixel_ods_python_library_proposal'),
    [libraryProposal, {...libraryProposal, pythonVerification: {expression: 'a'.repeat(2048), expected: 'a'.repeat(2048)}}]],
]) {
  test(`${tool.name} schema compiles and accepts short and full-size arguments in llama.cpp`,
    { skip: !nativeGrammar && "set ODS_TEST_LLAMA_SCHEMA to the pinned native test bridge" }, () => {
      for (const args of samples) {
        const result = spawnSync(nativeGrammar, [], {
          input: JSON.stringify({ schema: tool.parameters, arguments: args }), encoding: "utf8", timeout: 30000,
        });
        assert.ifError(result.error);
        assert.equal(result.status, 0, `${tool.name}: ${result.stderr}`);
      }
      // Loosening grammar length bounds must preserve required fields/types.
      for (const args of [{}, Object.fromEntries(Object.keys(samples[0]).map(key => [key, 123]))]) {
        const result = spawnSync(nativeGrammar, [], {
          input: JSON.stringify({ schema: tool.parameters, arguments: args }), encoding: "utf8", timeout: 30000,
        });
        assert.ifError(result.error);
        assert.equal(result.status, 2, result.stderr);
      }
    });
}

test("promotion keeps the 4096-character URL limit at execution before any host request", async () => {
  const requests = [];
  const tool = createDownloadPromoteTool({ request: async request => { requests.push(request); throw new Error("test host unavailable"); } });
  await tool.execute("full-url", { ...promotion, sourceUrl: longUrl(4096) });
  assert.equal(requests.length, 1);
  assert.equal(requests[0].sourceUrl.length, 4096);
  const rejected = await tool.execute("oversize", { ...promotion, sourceUrl: longUrl(4097) });
  assert.equal(rejected.details.invalidField, "sourceUrl");
  assert.equal(requests.length, 1);
});

test("research accepts a 1000-character brief and rejects larger input before HTTP", async () => {
  let calls = 0;
  const tool = createPerplexicaResearchTool({ env: {}, fetch: async () => {
    calls++; return Response.json({ values: { preferences: {} } });
  } });
  assert.equal((await tool.execute("full-brief", { query: "a".repeat(1000) })).details.status, "configuration_required");
  assert.equal(calls, 1);
  for (const query of ["a".repeat(1001), "", "   ", "https://example.org/only-a-link"]) {
    assert.equal((await tool.execute("invalid-brief", { query })).details.status, "invalid_request");
  }
  assert.equal(calls, 1);
});

test("host proposals keep their character and byte limits before writing a broker request", async t => {
  const root = await mkdtemp(join(tmpdir(), "pixel-command-length-"));
  t.after(() => rm(root, { recursive: true, force: true }));
  const requestDir = join(root, "requests"), resultDir = join(root, "results");
  await mkdir(requestDir); await mkdir(resultDir);
  const tool = createHostCommandProposeTool({ requestDir, resultDir, timeoutMs: 1, pollIntervalMs: 1 });
  const command = "a".repeat(16384);
  await tool.execute("full-command", { command });
  const files = (await readdir(requestDir)).filter(name => name.endsWith(".json"));
  assert.equal(files.length, 1);
  const receipt = JSON.parse(await readFile(join(requestDir, files[0]), "utf8"));
  assert.equal(receipt.command, command);
  for (const rejected of ["a".repeat(16385), "é".repeat(8193), "", " ", "pwd\0"]) {
    assert.equal((await tool.execute("invalid-command", { command: rejected })).isError, true);
  }
  assert.deepEqual((await readdir(requestDir)).filter(name => name.endsWith(".json")), files);
});