OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Audit request and result pairing in JSON tool events with JavaScript

JavaScript

Find unanswered requests and unmatched results in a supplied ordered event list.

JavaScript code excerpt: Audit request and result pairing in JSON tool events with JavaScript. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Find unanswered requests and unmatched results in a supplied ordered event list. This is a local data check under the documented conventions; it does not execute tools or contact a service.

Before you start

  • Save the code as recipe.cjs and run node recipe.cjs using Node.js 22, supplying JSON on standard input. No CLI arguments are accepted, including help options.
  • Uses only node:fs, exclusively for bounded readSync calls on stdin. It does not open input paths, write files, execute commands or contact a network.
  • Input must be a JSON array containing at most 100 non-null, non-array objects. Each object must have kind exactly request or result and a nonempty string id of at most 80 UTF-16 code units. Additional fields are ignored.
  • Strict UTF-8 decoding uses global TextDecoder with fatal:true and ignoreBOM:true. A leading UTF-8 BOM remains in the decoded text and is rejected by JSON.parse. Native JSON.parse semantics apply, including duplicate-member handling.
  • IDs are case-sensitive. Events are processed in order, starting with an empty pending Set. Repeated requests leave the original pending request unchanged; matching results remove it. An ID may be reused after completion.
  • Successful output is exactly one JSON object followed by a newline. unanswered uses JavaScript default UTF-16 sorting; unmatched_results and repeated_requests contain ascending one-based positions. Pairing issues still exit 0 without stderr.
  • Invalid arguments, invalid input and stdin read failures produce no stdout, report only error: invalid input on stderr, and exit 2. Diagnostics do not reveal input values.
  • There are no integer input fields to validate. Reported positions are generated safe integers between 1 and 100.

Build and check

  1. Use Node.js 22 CommonJS. Save the code as recipe.cjs.
  2. Save the supplied JSON example as input.json, encoded as UTF-8 without a BOM.
  3. Run: node recipe.cjs < input.json
  4. Compare the output with the expected result; handle exit code 2 as invalid input.

Limits to understand

  • Reads at most 65537 bytes and rejects input exceeding 65536 bytes. Valid-sized input is read until EOF, so stdin may block waiting for EOF.
  • Input is held in memory: a fixed 65537-byte buffer, decoded text, the parsed array and reporting collections. Processing is not streaming.
  • ID length is measured using JavaScript string.length, not Unicode code points or grapheme clusters.
  • Successful output includes pending IDs and event positions and may contain sensitive information.
  • Output-write failures, including stdout or stderr failures, are excluded from the stated error-handling guarantee.
  • This audits request/result pairing only. It does not execute tools, validate a provider protocol or establish provider integration or production suitability.

Run it

node recipe.cjs < input.json

Example input

[{"kind": "request", "id": "a"}, {"kind": "result", "id": "b"}]

Expected output

{"unanswered": ["a"], "unmatched_results": [2], "repeated_requests": []}
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

This browser preview builds code locally. It does not contact an API or run the code.

Default example ready.

JavaScript example
'use strict';

const fs = require('node:fs');

function main() {
  let output;

  try {
    if (process.argv.length !== 2) {
      throw new Error();
    }

    const buffer = Buffer.alloc(65537);
    let used = 0;

    while (used < buffer.length) {
      const count = fs.readSync(0, buffer, used, buffer.length - used, null);
      if (count === 0) break;
      used += count;
    }

    if (used > 65536) {
      throw new Error();
    }

    const decoder = new TextDecoder('utf-8', {
      fatal: true,
      ignoreBOM: true
    });
    const text = decoder.decode(buffer.subarray(0, used));
    const events = JSON.parse(text);

    if (!Array.isArray(events) || events.length > 100) {
      throw new Error();
    }

    for (const event of events) {
      if (
        event === null ||
        typeof event !== 'object' ||
        Array.isArray(event) ||
        (event.kind !== 'request' && event.kind !== 'result') ||
        typeof event.id !== 'string' ||
        event.id.length === 0 ||
        event.id.length > 80
      ) {
        throw new Error();
      }
    }

    const pending = new Set();
    const unmatchedResults = [];
    const repeatedRequests = [];

    for (let index = 0; index < events.length; index += 1) {
      const event = events[index];
      const position = index + 1;

      if (event.kind === 'request') {
        if (pending.has(event.id)) {
          repeatedRequests.push(position);
        } else {
          pending.add(event.id);
        }
      } else if (!pending.delete(event.id)) {
        unmatchedResults.push(position);
      }
    }

    output = JSON.stringify({
      unanswered: Array.from(pending).sort(),
      unmatched_results: unmatchedResults,
      repeated_requests: repeatedRequests
    });
  } catch {
    process.stderr.write('error: invalid input\n', () => process.exit(2));
    return;
  }

  // Output-write failures are deliberately outside the input-error handler.
  process.stdout.write(output + '\n');
}

main();
What to verify after running
  • The supplied example must match the documented JSON output.
  • Error cases must exit 2 with no stdout. Review sensitive successful output before sharing it.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 0.1.0 · Documentation reviewed 2026-10-14.

    Six independent CLI fixtures and 10 curated supplementary checks passed in the pinned offline Node.js 22 CommonJS container. This does not establish exhaustive correctness, production performance or compatibility with an external provider.