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.

21.1 KB
Raw Blame
import test from "node:test";
import assert from "node:assert/strict";
import {
  createPublicWebExtractTool,
  selectEvidenceWindow,
} from "../plugin/web-extract.mjs";

import { createRunProgressBudget, failedToolOutcome } from "../plugin/run-progress-budget.mjs";

function fixture({
  body = "",
  contentType = "text/plain",
  status = 200,
  finalUrl = "https://docs.example.org/reference",
  fetchError,
  extractedText,
} = {}) {
  const calls = [];
  let releases = 0;
  let extracts = 0;
  const guardedFetch = async (options) => {
    calls.push(options);
    if (fetchError) throw fetchError;
    return {
      response: new Response(body, {
        status,
        headers: { "Content-Type": contentType },
      }),
      finalUrl,
      release: () => {
        releases += 1;
      },
    };
  };
  const readResponseText = async (response, options) => ({
    text: await response.text(),
    truncated: false,
    bytesRead: body.length,
    maxBytes: options.maxBytes,
  });
  const extractBasicHtmlContent = async () => {
    extracts += 1;
    return { text: extractedText ?? body };
  };
  return {
    calls,
    releases: () => releases,
    extracts: () => extracts,
    tool: createPublicWebExtractTool({
      guardedFetch,
      readResponseText,
      extractBasicHtmlContent,
    }),
  };
}

test('URL-only reads return bounded untrusted overviews without claiming a query match', async () => {
  const harness = fixture({body: 'README\n' + 'project details '.repeat(1000)});
  const result = await harness.tool.execute('overview', {url: 'https://github.com/owner/project'});
  assert.equal(result.isError, undefined);
  assert.equal(result.details.mode, 'overview');
  assert.equal(result.details.matched, false);
  assert.equal(result.details.evidence_truncated_after, true);
  assert.match(result.content[0].text, /EXTERNAL_UNTRUSTED_CONTENT/);
  assert.ok(result.content[0].text.length < 6500);
  assert.equal(harness.releases(), 1);
  assert.equal(failedToolOutcome({result}), false);
});

test('URL-only reads still reject local destinations and explicit invalid queries', async () => {
  for (const params of [{url:'http://127.0.0.1/'}, {url:'https://github.com/a/b',query:null},
    {url:'https://github.com/a/b',query:''}]) {
    const harness = fixture();
    assert.equal((await harness.tool.execute('invalid', params)).isError, true);
    assert.equal(harness.calls.length, 0);
  }
});

for (const scenario of ['success', 'missing-repository', 'redirect-loop', 'blocked', 'aborted', 'forbidden']) {
  test('missing GitHub file recovery: ' + scenario, async () => {
    const calls = [], releases = [];
    const source = 'https://raw.githubusercontent.com/owner/project/main/missing.py';
    const controller = new AbortController();
    const tool = createPublicWebExtractTool({
      guardedFetch: async options => {
        calls.push(options);
        if (calls.length === 2 && scenario === 'blocked') throw new Error('SSRF denied');
        if (calls.length === 2 && scenario === 'aborted') {
          assert.equal(options.signal.aborted, true);
          throw new Error('aborted');
        }
        if (scenario === 'aborted') controller.abort();
        // A 403 is refused again by the single plain fallback request.
        const status = scenario === 'forbidden' ? 403 : calls.length === 1 ? 404
          : ['missing-repository','redirect-loop'].includes(scenario) ? 404 : 200;
        return {response:new Response(status === 200 ? 'Actual repository file listing' : 'Missing', {
          status, headers:{'Content-Type':'text/plain'},
        }), finalUrl:scenario === 'redirect-loop' ? source : options.url,
        release:() => releases.push(options.url)};
      },
      readResponseText:async response => ({text:await response.text(),truncated:false}),
      extractBasicHtmlContent:async ({html}) => ({text:html}),
    });
    const result = await tool.execute('recover', {url:source,query:'installation'}, controller.signal);
    assert.equal(calls.length, 2);
    if (scenario === 'forbidden') {
      // Only a missing file leads to the repository page; a refusal does not.
      assert.deepEqual(calls.map(call => call.url), [source, source]);
      assert.equal(result.details.recovery, undefined);
      assert.equal(result.details.status, 403);
    } else {
      assert.equal(calls[1].url, 'https://github.com/owner/project');
      assert.equal(calls[1].signal, controller.signal);
      assert.equal(calls[1].useEnvProxy, false);
      assert.equal(result.details.failed_source_url, source);
      assert.match(result.content[0].text, /It was not read/);
    }
    if (scenario === 'success') {
      assert.equal(result.isError, undefined);
      assert.equal(result.details.source_url, 'https://github.com/owner/project');
      assert.equal(result.details.matched, false);
      assert.match(result.content[1].text, /Actual repository file listing/);
    } else assert.equal(result.isError, true);
    assert.equal(releases.length, ['blocked','aborted'].includes(scenario) ? 1 : 2);
  });
}

test("selects a bounded evidence window and falls back to the qualified dotted name", () => {
  const text = `${"prefix\n".repeat(300)}Path.exists(*, follow_symlinks=True)\nReturn True for an existing path.\n${"tail\n".repeat(2000)}`;
  const selected = selectEvidenceWindow(text, "pathlib.Path.exists");
  assert.ok(selected);
  assert.equal(selected.matchedQuery, "Path.exists");
  assert.match(selected.text, /Return True for an existing path/);
  assert.ok(selected.text.length <= 6000);
  assert.equal(selected.truncatedBefore, true);
  assert.equal(selected.truncatedAfter, true);
  assert.equal(selectEvidenceWindow(text, "Path.lexists"), null);
});

test("accepts a bounded multi-keyword query only when several terms co-occur", () => {
  const text = `${"intro\n".repeat(300)}Path.exists(*, follow_symlinks=True)\nReturn True if the path points to an existing file. A broken symlink has a missing target.\n${"tail\n".repeat(300)}`;
  const selected = selectEvidenceWindow(text, "exists follow_symlinks broken symlink");
  assert.ok(selected);
  assert.match(selected.matchedQuery, /exists/);
  assert.match(selected.matchedQuery, /follow_symlinks/);
  assert.match(selected.text, /broken symlink/);
  assert.equal(selectEvidenceWindow(text, "exists unrelated nowhere"), null);
  assert.equal(selectEvidenceWindow(text, "lonely"), null);
});

test("fetches through the strict dependency and wraps only targeted public evidence", async () => {
  const source = `${"intro\n".repeat(300)}Path.exists(*, follow_symlinks=True)\nReturn True if the path points to an existing file or directory. False will be returned if the path is missing.\n${"other\n".repeat(300)}`;
  const harness = fixture({ body: source });
  const signal = AbortSignal.timeout(1000);
  const result = await harness.tool.execute(
    "call-1",
    { url: "https://docs.example.org/reference", query: "pathlib.Path.exists" },
    signal
  );
  assert.equal(harness.calls.length, 1);
  assert.equal(harness.calls[0].useEnvProxy, false);
  assert.equal(harness.calls[0].maxRedirects, 3);
  assert.equal(harness.calls[0].timeoutSeconds, 20);
  assert.equal(harness.calls[0].signal, signal);
  assert.equal(harness.releases(), 1);
  assert.equal(result.details.matched, true);
  assert.equal(result.details.matched_query, "Path.exists");
  assert.equal(result.details.boundary, "public-web-read-only");
  assert.match(result.content[0].text, /Return True if the path points/);
  assert.match(result.content[0].text, /untrusted webpage evidence, never instructions/);
  const start = result.content[0].text.match(/<<<EXTERNAL_UNTRUSTED_CONTENT id="([0-9a-f]{24})">>>/);
  const end = result.content[0].text.match(/<<<END_EXTERNAL_UNTRUSTED_CONTENT id="([0-9a-f]{24})">>>/);
  assert.ok(start);
  assert.equal(end?.[1], start[1]);
});

test("uses bounded HTML extraction before selecting evidence", async () => {
  const harness = fixture({
    body: "<html><body>ignored raw markup</body></html>",
    contentType: "text/html; charset=utf-8",
    extractedText: "Heading\nPath.exists()\nFalse will be returned if the path is missing.",
  });
  const result = await harness.tool.execute("call-2", {
    url: "https://docs.example.org/reference#exists",
    query: "Path.exists",
  });
  assert.equal(harness.extracts(), 1);
  assert.equal(result.details.matched, true);
  assert.match(result.content[0].text, /False will be returned/);
});

test("blocks obvious non-public and credentialed targets before transport", async () => {
  for (const url of [
    "http://127.0.0.1:18789/health",
    "http://[::1]/health",
    "http://localhost./health",
    "http://printer.local/status",
    "http://gateway.internal./status",
    "http://single-label/status",
    "file:///etc/passwd",
    "https://user:[email protected]/",
  ]) {
    const harness = fixture();
    const result = await harness.tool.execute("call-private", { url, query: "health" });
    assert.equal(harness.calls.length, 0, url);
    assert.equal(result.details.matched, false, url);
    assert.match(result.content[0].text, /blocked targeted web extraction|Only public HTTP/);
  }
});

test("validates the exact bounded query before transport", async () => {
  for (const query of ["x", " padded", "line\nbreak", "x".repeat(201)]) {
    const harness = fixture();
    const result = await harness.tool.execute("call-query", {
      url: "https://docs.example.org/",
      query,
    });
    assert.equal(harness.calls.length, 0);
    assert.equal(result.details.matched, false);
    assert.match(result.content[0].text, /query must be 2-200/);
  }
});

test("keeps URL schemas below llama.cpp's grammar repetition ceiling", async () => {
  const harness = fixture();
  assert.equal(harness.tool.parameters.properties.url.maxLength, 1024);
  const result = await harness.tool.execute("call-long-url", {
    url: `https://docs.example.org/${"x".repeat(1100)}`,
    query: "Path.exists",
  });
  assert.equal(harness.calls.length, 0);
  assert.equal(result.details.matched, false);
  assert.match(result.content[0].text, /public HTTP\(S\) URL is required/);
});

test("recovers the observed identifier field without weakening query or URL validation", async () => {
  const harness = fixture({ body: "Options\n--parallel N sets the number of server slots.\n" });
  const result = await harness.tool.execute("identifier-alias", {
    url: "https://docs.example.org/reference", identifier: "--parallel",
  });
  assert.equal(result.details.matched, true);
  assert.equal(harness.calls.length, 1);
  for (const params of [
    { url: "https://docs.example.org/", query: null, identifier: "--parallel" },
    { url: "https://docs.example.org/", identifier: "line\nbreak" },
    { url: "http://127.0.0.1/", identifier: "--parallel" },
  ]) {
    const invalid = fixture();
    const blocked = await invalid.tool.execute("invalid-alias", params);
    assert.equal(blocked.details.matched, false);
    assert.equal(invalid.calls.length, 0);
  }
});

test("returns an explicit no-evidence result without guessing", async () => {
  const harness = fixture({ body: "This page contains something else." });
  const result = await harness.tool.execute("call-miss", {
    url: "https://docs.example.org/",
    query: "Path.exists",
  });
  assert.equal(harness.releases(), 1);
  assert.equal(result.details.matched, false);
  assert.match(result.content[0].text, /exact query was not found/);
  assert.match(result.content[0].text, /Do not infer/);
});

test("contains transport errors and unsafe redirects without reflecting details", async () => {
  const failed = fixture({ fetchError: new Error("secret transport detail") });
  const failedResult = await failed.tool.execute("call-fail", {
    url: "https://docs.example.org/",
    query: "Path.exists",
  });
  assert.match(failedResult.content[0].text, /blocked or unavailable/);
  assert.doesNotMatch(failedResult.content[0].text, /secret transport detail/);

  const redirect = fixture({ finalUrl: "http://127.0.0.1/private", body: "Path.exists" });
  const redirectResult = await redirect.tool.execute("call-redirect", {
    url: "https://docs.example.org/",
    query: "Path.exists",
  });
  assert.equal(redirect.releases(), 1);
  assert.match(redirectResult.content[0].text, /blocked or unavailable/);
  assert.doesNotMatch(redirectResult.content[0].text, /127\.0\.0\.1/);
});

test("releases responses on non-success and unsupported content types", async () => {
  const badStatus = fixture({ status: 404 });
  const statusResult = await badStatus.tool.execute("call-404", {
    url: "https://docs.example.org/missing",
    query: "Path.exists",
  });
  assert.equal(badStatus.releases(), 1);
  assert.match(statusResult.content[0].text, /HTTP 404/);

  const binary = fixture({ contentType: "application/octet-stream", body: "Path.exists" });
  const binaryResult = await binary.tool.execute("call-binary", {
    url: "https://docs.example.org/file",
    query: "Path.exists",
  });
  assert.equal(binary.releases(), 1);
  assert.match(binaryResult.content[0].text, /not a supported text document/);
});

test("requires every security dependency", () => {
  assert.throws(
    () =>
      createPublicWebExtractTool({
        guardedFetch: async () => {},
        readResponseText: async () => {},
      }),
    /dependencies are unavailable/
  );
});

test("extraction includes a late match on a long paragraph after a heading", async () => {
  const body = "Heading\n" + "background ".repeat(3000) + "Path.exists returns true for existing files." + " tail".repeat(3000);
  const harness = fixture({ body });
  const result = await harness.tool.execute("late-match", {
    url: "https://docs.example.org/reference", query: "Path.exists",
  });
  assert.equal(result.details.matched, true);
  assert.match(result.content[0].text, /Path.exists returns true/);
  assert.equal(result.details.evidence_truncated_before, true);
  assert.equal(result.details.evidence_truncated_after, true);
  assert.ok(selectEvidenceWindow(body, "Path.exists").text.length <= 6000);
});

test("a line break inside a multi-word match does not truncate the match", async () => {
  const body = "intro ".repeat(400) + "needle one\nneedle two" + " tail".repeat(2000);
  const selected = selectEvidenceWindow(body, "needle one");
  assert.match(selected.text, /needle one/);
  assert.ok(selected.text.length <= 6000);
});

test("keyword extraction finds terms deep inside a long paragraph", async () => {
  const body = "Heading\n" + "background ".repeat(3000) + "Follow symlinks to existing targets." + " tail".repeat(3000);
  const harness = fixture({ body });
  const result = await harness.tool.execute("keywords", {
    url: "https://docs.example.org/reference", query: "symlinks existing targets",
  });
  assert.equal(result.details.matched, true);
  assert.match(result.content[0].text, /Follow symlinks to existing targets/);
});

for (const query of ["Path.exists", "routing context budget"]) {
  test(`keeps original text offsets after Unicode case expansion: ${query}`, async () => {
    // U+0130 lowercases to two UTF-16 code units. Offsets in a lowercased
    // document therefore cannot be used to slice the original document.
    const target = "Path.exists sets routing and context with a budget.";
    const body = "İstanbul reference\n".repeat(1500) + target + "\n" + "Other material.\n".repeat(1000);
    const harness = fixture({ body });
    const result = await harness.tool.execute("unicode-offset", {
      url: "https://docs.example.org/reference", query,
    });
    assert.equal(result.details.matched, true);
    assert.ok(result.content[0].text.includes(target));
    assert.ok(selectEvidenceWindow(body, query).text.length <= 6000);
    assert.equal(harness.releases(), 1);
  });
}

test("case-insensitive evidence queries remain literal", () => {
  const selected = selectEvidenceWindow("Header\nUse [CACHE](a+b)? here.\n", "[cache](a+b)?");
  assert.ok(selected.text.includes("[CACHE](a+b)?"));
  assert.equal(selectEvidenceWindow("Use CACHEab here.", "[cache](a+b)?"), null);
  assert.ok(selectEvidenceWindow("😀\nPATH.EXISTS returns true.\n", "Path.exists").text.includes("PATH.EXISTS"));
});

for (const [label, options, params] of [
  ["invalid input", {}, { query: "x" }],
  ["HTTP error", { status: 503 }, {}],
  ["unsupported document", { contentType: "application/pdf" }, {}],
  ["transport failure", { fetchError: new Error("offline") }, {}],
]) {
  test("extraction " + label + " is a failed tool outcome", async () => {
    const harness = fixture(options);
    const result = await harness.tool.execute("failed", {
      url: "https://docs.example.org/reference", query: "Path.exists", ...params,
    });
    assert.equal(result.isError, true);
    assert.equal(failedToolOutcome({ result }), true);
    assert.equal(result.details.matched, false);
    assert.equal(harness.releases(), label === "HTTP error" || label === "unsupported document" ? 1 : 0);
  });
}

test("distinct unsuccessful fetches exhaust the existing failure budget", async () => {
  const harness = fixture({ fetchError: new Error("offline") });
  const budget = createRunProgressBudget();
  for (let i = 0; i < 4; i++) {
    const params = { url: "https://docs.example.org/page-" + i, query: "Path.exists" };
    const result = await harness.tool.execute("call-" + i, params);
    budget.observeResult({ callId: "call-" + i, tool: harness.tool.name, params,
      failed: failedToolOutcome({ result }) });
    assert.equal(budget.exhausted, i === 3);
  }
});

for (const [body, matched] of [["Path.exists returns a boolean", true], ["Unrelated text", false]]) {
  test("a completed lookup (matched=" + matched + ") remains successful", async () => {
    const harness = fixture({ body });
    const result = await harness.tool.execute("lookup", {
      url: "https://docs.example.org/reference", query: "Path.exists",
    });
    assert.notEqual(result.isError, true);
    assert.equal(failedToolOutcome({ result }), false);
    assert.equal(result.details.matched, matched);
    assert.equal(harness.releases(), 1);
  });
}


test('literal occurrence tool receipt navigates repeated headings without widening reads', async () => {
  const heading='TableStyle Span Commands';
  const body=`Contents\n${heading}\n`+'Earlier section\n'.repeat(700)+`${heading}\nSPAN merges cells.\n`;
  const harness=fixture({body});
  const args={url:'https://docs.example.org/reference',query:heading};
  const first=await harness.tool.execute('first',args);
  assert.equal(first.details.match_count,2);
  assert.equal(first.details.next_occurrence,2);
  assert.match(first.content[0].text,/Literal occurrence 1 of 2; next occurrence: 2/);
  const second=await harness.tool.execute('second',{...args,occurrence:2});
  assert.equal(second.details.offset_basis,'extracted-text-utf16');
  assert.equal(second.details.match_offset,body.lastIndexOf(heading));
  assert.match(second.content[0].text,/SPAN merges cells/);
  assert.equal(second.details.next_occurrence,null);
  assert.equal(second.details.response_truncated,false);
  assert.ok(second.details.evidence_end_offset-second.details.evidence_start_offset<=6000);
  const missing=await harness.tool.execute('missing',{...args,occurrence:3});
  assert.equal(missing.isError,true);
  assert.equal(missing.details.matched,false);
  assert.equal(missing.details.match_count,2);
  assert.match(missing.content[0].text,/out of range: 2 literal matches/);
  assert.equal(harness.calls.length,3,'one guarded read per explicit call, no automatic navigation');
  assert.equal(harness.releases(),3);
});

test('occurrence validation rejects malformed navigation before any network work', async () => {
  const harness=fixture({body:'SPAN'});
  for(const occurrence of [0,-1,1.1,'2',null,Infinity,1000001]) {
    const result=await harness.tool.execute('bad',{url:'https://docs.example.org/reference',query:'SPAN',occurrence});
    assert.equal(result.isError,true,String(occurrence));
  }
  assert.equal((await harness.tool.execute('noquery',{url:'https://docs.example.org/reference',occurrence:1})).isError,true);
  assert.equal(harness.calls.length,0);
  assert.equal(harness.tool.parameters.properties.occurrence.type,'integer');
});

test('navigation cannot relabel a keyword window as the second literal match', async () => {
  const harness=fixture({body:'Alpha supported bravo options charlie enabled.'});
  const args={url:'https://docs.example.org/reference',query:'alpha bravo charlie'};
  const first=await harness.tool.execute('default',args);
  assert.equal(first.details.match_kind,'keywords');
  assert.equal(first.details.match_count,undefined);
  const second=await harness.tool.execute('second',{...args,occurrence:2});
  assert.equal(second.isError,true);
  assert.equal(second.details.matched,false);
  assert.match(second.content[0].text,/requires a literal query/);
});

test('occurrence offsets preserve Unicode and regex punctuation with constant-size evidence', () => {
  const text='İ😀 [cache](a+b)?\n'+'noise\n'.repeat(1200)+'İ😀 [CACHE](a+b)?\nDone';
  const result=selectEvidenceWindow(text,'[cache](a+b)?',2);
  assert.equal(result.matchCount,2);
  assert.equal(result.matchOffset,text.indexOf('[CACHE]'));
  assert.equal(result.text,text.slice(result.startOffset,result.endOffset));
  assert.ok(result.text.length<=6000);
  const dense=selectEvidenceWindow('aa'.repeat(500000),'aa',500000);
  assert.equal(dense.matchCount,500000);
  assert.equal(dense.matchOffset,999998);
  assert.ok(dense.text.length<=6000);
});