The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore(scripts): reformat prompt-breakdown source and tests
Steven Enamakel6ccef2e8b907
diff --git a/scripts/__tests__/prompt-breakdown.test.mjs b/scripts/__tests__/prompt-breakdown.test.mjsindex 8707f9aa92..f37fff77a2 100644--- a/scripts/__tests__/prompt-breakdown.test.mjs+++ b/scripts/__tests__/prompt-breakdown.test.mjs@@ -1,94 +1,133 @@-import assert from 'node:assert/strict';-import { spawnSync } from 'node:child_process';-import fs from 'node:fs';-import os from 'node:os';-import path, { dirname, resolve } from 'node:path';-import { fileURLToPath } from 'node:url';-import { test } from 'node:test';+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path, { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { test } from "node:test";-import { analyse, splitSections } from '../debug/prompt-breakdown.mjs';+import { analyse, splitSections } from "../debug/prompt-breakdown.mjs";const HERE = dirname(fileURLToPath(import.meta.url));-const SCRIPT = resolve(HERE, '..', 'debug', 'prompt-breakdown.mjs');+const SCRIPT = resolve(HERE, "..", "debug", "prompt-breakdown.mjs");const SYSTEM = [- '### SOUL.md',- '',- '# Persona',- 'Be direct.',- '## When criticized',- 'Own it.',- '# Writing style',- 'Short sentences.',- '<rules>',- '# not a heading inside a tag',- '</rules>',- '```',- '## not a heading inside a fence',- '```',-].join('\n');+ "### SOUL.md",+ "",+ "# Persona",+ "Be direct.",+ "## When criticized",+ "Own it.",+ "# Writing style",+ "Short sentences.",+ "<rules>",+ "# not a heading inside a tag",+ "</rules>",+ "```",+ "## not a heading inside a fence",+ "```",+].join("\n");-const REPEATED = 'Call tool_search before telling the user something is impossible, every single time.';+const REPEATED =+ "Call tool_search before telling the user something is impossible, every single time.";const BODY = {- model: 'test/model',+ model: "test/model",stream: true,messages: [- { role: 'system', content: SYSTEM },- { role: 'system', content: `## Integrations\n\n${REPEATED}` },- { role: 'user', content: 'hello' },+ { role: "system", content: SYSTEM },+ { role: "system", content: `## Integrations\n\n${REPEATED}` },+ { role: "user", content: "hello" },],tools: [- { type: 'function', function: { name: 'big_tool', description: `${REPEATED}\n\n${'word '.repeat(200)}`, parameters: { type: 'object', properties: {} } } },- { type: 'function', function: { name: 'small_tool', description: 'Tiny.', parameters: { type: 'object', properties: { q: { type: 'string' } } } } },+ {+ type: "function",+ function: {+ name: "big_tool",+ description: `${REPEATED}\n\n${"word ".repeat(200)}`,+ parameters: { type: "object", properties: {} },+ },+ },+ {+ type: "function",+ function: {+ name: "small_tool",+ description: "Tiny.",+ parameters: { type: "object", properties: { q: { type: "string" } } },+ },+ },],};-test('splitSections nests a file marker over its first H1 only, and ignores tags and fences', () => {+test("splitSections nests a file marker over its first H1 only, and ignores tags and fences", () => {const root = splitSections(SYSTEM);assert.deepEqual(- root.children.map(c => c.title),- ['### SOUL.md', '# Writing style']+ root.children.map((c) => c.title),+ ["### SOUL.md", "# Writing style"],);const soul = root.children[0];- assert.deepEqual(soul.children.map(c => c.title), ['# Persona']);- assert.deepEqual(soul.children[0].children.map(c => c.title), ['## When criticized']);+ assert.deepEqual(+ soul.children.map((c) => c.title),+ ["# Persona"],+ );+ assert.deepEqual(+ soul.children[0].children.map((c) => c.title),+ ["## When criticized"],+ );const style = root.children[1];- assert.deepEqual(style.children.map(c => c.title), ['<rules>']);- assert.ok(style.lines.includes('## not a heading inside a fence'));+ assert.deepEqual(+ style.children.map((c) => c.title),+ ["<rules>"],+ );+ assert.ok(style.lines.includes("## not a heading inside a fence"));});-test('analyse splits the request into system, tools, conversation and envelope and finds repeats', () => {+test("analyse splits the request into system, tools, conversation and envelope and finds repeats", () => {const a = analyse(BODY, {});const { totals } = a;- assert.equal(totals.all, totals.system + totals.tools + totals.conversation + totals.envelope);- assert.ok(totals.tools > totals.system, 'the padded tool description dominates');- assert.deepEqual(a.tools.map(t => t.name), ['big_tool', 'small_tool']);- assert.equal(a.scale, null, 'no provider usage, no calibration');+ assert.equal(+ totals.all,+ totals.system + totals.tools + totals.conversation + totals.envelope,+ );+ assert.ok(+ totals.tools > totals.system,+ "the padded tool description dominates",+ );+ assert.deepEqual(+ a.tools.map((t) => t.name),+ ["big_tool", "small_tool"],+ );+ assert.equal(a.scale, null, "no provider usage, no calibration");assert.equal(a.duplicates.length, 1);- assert.deepEqual(a.duplicates[0].where, ['msg 2 (system)', 'tool big_tool']);+ assert.deepEqual(a.duplicates[0].where, ["msg 2 (system)", "tool big_tool"]);});-test('CLI calibrates against the provider usage in an SSE response', () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'prompt-breakdown-'));+test("CLI calibrates against the provider usage in an SSE response", () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "prompt-breakdown-"));try {- const req = path.join(dir, 'req.json');- const res = path.join(dir, 'res.txt');+ const req = path.join(dir, "req.json");+ const res = path.join(dir, "res.txt");fs.writeFileSync(req, JSON.stringify(BODY));fs.writeFileSync(res,'data: {"choices":[{"delta":{"content":"hi"}}]}\n\n' +'data: {"choices":[],"usage":{"prompt_tokens":1000,"completion_tokens":1}}\n\n' +- 'data: [DONE]\n\n'+ "data: [DONE]\n\n",);- const out = spawnSync(process.execPath, [SCRIPT, req, '--response', res], { encoding: 'utf8' });+ const out = spawnSync(process.execPath, [SCRIPT, req, "--response", res], {+ encoding: "utf8",+ });assert.equal(out.status, 0, out.stderr);assert.match(out.stdout, /calibration: o200k total \d+ → provider 1000/);assert.match(out.stdout, /^\s+\d+\s+1000 100\.0% TOTAL$/m);assert.match(out.stdout, /big_tool/);assert.match(out.stdout, /repeated paragraphs/);- const json = spawnSync(process.execPath, [SCRIPT, req, '--prompt-tokens', '500', '--json'], { encoding: 'utf8' });+ const json = spawnSync(+ process.execPath,+ [SCRIPT, req, "--prompt-tokens", "500", "--json"],+ { encoding: "utf8" },+ );assert.equal(json.status, 0, json.stderr);assert.equal(JSON.parse(json.stdout).usage.prompt_tokens, 500);} finally {diff --git a/scripts/debug/prompt-breakdown.mjs b/scripts/debug/prompt-breakdown.mjsindex 2deb5c0720..d4caf02052 100644--- a/scripts/debug/prompt-breakdown.mjs+++ b/scripts/debug/prompt-breakdown.mjs@@ -28,9 +28,9 @@// (scripts/debug/capture-first-inference.mjs), then point this at a numbered// request file under the capture directory.-import fs from 'node:fs';-import { pathToFileURL } from 'node:url';-import { encode } from 'gpt-tokenizer/encoding/o200k_base';+import fs from "node:fs";+import { pathToFileURL } from "node:url";+import { encode } from "gpt-tokenizer/encoding/o200k_base";const USAGE = `usage: prompt-breakdown.mjs <request.json> [--response <file>] [--prompt-tokens N][--depth 1|2|3] [--top N] [--json]`;@@ -40,14 +40,14 @@ function parseArgs(argv) {const rest = [];for (let i = 0; i < argv.length; i++) {const a = argv[i];- if (a === '--help' || a === '-h') {+ if (a === "--help" || a === "-h") {process.stdout.write(`${USAGE}\n`);process.exit(0);- } else if (a === '--response') opts.response = argv[++i];- else if (a === '--prompt-tokens') opts.promptTokens = Number(argv[++i]);- else if (a === '--depth') opts.depth = Number(argv[++i]);- else if (a === '--top') opts.top = Number(argv[++i]);- else if (a === '--json') opts.json = true;+ } else if (a === "--response") opts.response = argv[++i];+ else if (a === "--prompt-tokens") opts.promptTokens = Number(argv[++i]);+ else if (a === "--depth") opts.depth = Number(argv[++i]);+ else if (a === "--top") opts.top = Number(argv[++i]);+ else if (a === "--json") opts.json = true;else rest.push(a);}if (rest.length !== 1) {@@ -58,14 +58,16 @@ function parseArgs(argv) {return opts;}-export const tok = s => (s ? encode(s).length : 0);+export const tok = (s) => (s ? encode(s).length : 0);function contentText(content) {- if (typeof content === 'string') return content;+ if (typeof content === "string") return content;if (Array.isArray(content)) {- return content.map(p => (typeof p === 'string' ? p : (p.text ?? JSON.stringify(p)))).join('');+ return content+ .map((p) => (typeof p === "string" ? p : (p.text ?? JSON.stringify(p))))+ .join("");}- return content == null ? '' : JSON.stringify(content);+ return content == null ? "" : JSON.stringify(content);}// Split text into a section tree. A section opens at a Markdown heading@@ -73,21 +75,22 @@ function contentText(content) {// whose matching `</tag>` closes it later. Text before the first marker is the// preamble. Tags nest as children of the heading they appear under.export function splitSections(text) {- const lines = text.split('\n');- const root = { title: '(root)', level: 0, lines: [], children: [] };+ const lines = text.split("\n");+ const root = { title: "(root)", level: 0, lines: [], children: [] };const stack = [root];let inFence = false;let openTag = null; // name of the tag block we are inside, if any- const push = node => {+ const push = (node) => {// A file marker owns only its file's first `#` heading: the wire text// carries no end-of-file marker, so a second `#` heading is taken to be// the next top-level block (the agent body, STYLE.md) and pops out.if (node.level === 1) {- const file = stack.findLast(n => n.level === 0.25);- if (file?.children.some(c => c.level === 1)) stack.length = 1;+ const file = stack.findLast((n) => n.level === 0.25);+ if (file?.children.some((c) => c.level === 1)) stack.length = 1;}- while (stack.length > 1 && stack[stack.length - 1].level >= node.level) stack.pop();+ while (stack.length > 1 && stack[stack.length - 1].level >= node.level)+ stack.pop();stack[stack.length - 1].children.push(node);stack.push(node);};@@ -100,7 +103,12 @@ export function splitSections(text) {// `### SOUL.md`-style lines mark an injected workspace file: they sit// above the file's own `#` headings, whatever their hash count.const level = /^[\w.-]+\.md$/.test(h[2].trim()) ? 0.25 : h[1].length;- push({ title: `${h[1]} ${h[2].trim()}`, level, lines: [line], children: [] });+ push({+ title: `${h[1]} ${h[2].trim()}`,+ level,+ lines: [line],+ children: [],+ });continue;}const t = /^<([A-Za-z_][\w.-]*)(\s[^>]*)?>\s*$/.exec(line);@@ -122,17 +130,20 @@ export function splitSections(text) {}function priceTree(node) {- node.own = tok(node.lines.join('\n'));+ node.own = tok(node.lines.join("\n"));node.total = node.own;for (const c of node.children) node.total += priceTree(c).total;- node.chars = node.lines.join('\n').length + node.children.reduce((n, c) => n + c.chars, 0);+ node.chars =+ node.lines.join("\n").length ++ node.children.reduce((n, c) => n + c.chars, 0);return node;}function readUsage(opts) {- if (Number.isFinite(opts.promptTokens)) return { prompt_tokens: opts.promptTokens };+ if (Number.isFinite(opts.promptTokens))+ return { prompt_tokens: opts.promptTokens };if (!opts.response) return null;- const raw = fs.readFileSync(opts.response, 'utf8');+ const raw = fs.readFileSync(opts.response, "utf8");// A JSON body, or an SSE stream whose last usage-bearing chunk wins.try {const j = JSON.parse(raw);@@ -141,8 +152,8 @@ function readUsage(opts) {/* SSE */}let usage = null;- for (const line of raw.split('\n')) {- if (!line.startsWith('data:')) continue;+ for (const line of raw.split("\n")) {+ if (!line.startsWith("data:")) continue;try {const j = JSON.parse(line.slice(5).trim());if (j.usage) usage = j.usage;@@ -159,7 +170,7 @@ function findDuplicates(texts) {const seen = new Map();for (const { where, text } of texts) {for (const para of text.split(/\n\s*\n/)) {- const norm = para.replace(/\s+/g, ' ').trim();+ const norm = para.replace(/\s+/g, " ").trim();if (norm.length < 60) continue;const e = seen.get(norm) ?? { text: norm, where: [] };e.where.push(where);@@ -167,26 +178,35 @@ function findDuplicates(texts) {}}return [...seen.values()]- .filter(e => e.where.length > 1)- .map(e => ({ ...e, tokens: tok(e.text), wasted: tok(e.text) * (e.where.length - 1) }))+ .filter((e) => e.where.length > 1)+ .map((e) => ({+ ...e,+ tokens: tok(e.text),+ wasted: tok(e.text) * (e.where.length - 1),+ })).sort((a, b) => b.wasted - a.wasted);}export function analyse(body, opts = {}) {const messages = (body.messages || []).map((m, i) => {const text = contentText(m.content);- const calls = m.tool_calls ? JSON.stringify(m.tool_calls) : '';- const entry = { index: i + 1, role: m.role, tokens: tok(text) + tok(calls), chars: text.length };- if (m.role === 'system') entry.tree = priceTree(splitSections(text));+ const calls = m.tool_calls ? JSON.stringify(m.tool_calls) : "";+ const entry = {+ index: i + 1,+ role: m.role,+ tokens: tok(text) + tok(calls),+ chars: text.length,+ };+ if (m.role === "system") entry.tree = priceTree(splitSections(text));return entry;});- const tools = (body.tools || []).map(t => {+ const tools = (body.tools || []).map((t) => {const fn = t.function ?? t;return {- name: fn.name ?? '(unnamed)',+ name: fn.name ?? "(unnamed)",tokens: tok(JSON.stringify(t)),- description: tok(fn.description ?? ''),+ description: tok(fn.description ?? ""),parameters: tok(JSON.stringify(fn.parameters ?? fn.input_schema ?? {})),};});@@ -196,67 +216,128 @@ export function analyse(body, opts = {}) {delete envelope.tools;const totals = {- system: messages.filter(m => m.role === 'system').reduce((n, m) => n + m.tokens, 0),- conversation: messages.filter(m => m.role !== 'system').reduce((n, m) => n + m.tokens, 0),+ system: messages+ .filter((m) => m.role === "system")+ .reduce((n, m) => n + m.tokens, 0),+ conversation: messages+ .filter((m) => m.role !== "system")+ .reduce((n, m) => n + m.tokens, 0),tools: tools.reduce((n, t) => n + t.tokens, 0),envelope: tok(JSON.stringify(envelope)),};- totals.all = totals.system + totals.conversation + totals.tools + totals.envelope;+ totals.all =+ totals.system + totals.conversation + totals.tools + totals.envelope;const usage = readUsage(opts);const scale = usage?.prompt_tokens ? usage.prompt_tokens / totals.all : null;const dupTexts = [- ...messages.map(m => ({ where: `msg ${m.index} (${m.role})`, text: contentText(body.messages[m.index - 1].content) })),- ...(body.tools || []).map(t => ({ where: `tool ${(t.function ?? t).name}`, text: (t.function ?? t).description ?? '' })),+ ...messages.map((m) => ({+ where: `msg ${m.index} (${m.role})`,+ text: contentText(body.messages[m.index - 1].content),+ })),+ ...(body.tools || []).map((t) => ({+ where: `tool ${(t.function ?? t).name}`,+ text: (t.function ?? t).description ?? "",+ })),];- return { model: body.model, envelope, messages, tools, totals, usage, scale, duplicates: findDuplicates(dupTexts) };+ return {+ model: body.model,+ envelope,+ messages,+ tools,+ totals,+ usage,+ scale,+ duplicates: findDuplicates(dupTexts),+ };}-function fmtRow(label, tokens, all, scale, extra = '') {+function fmtRow(label, tokens, all, scale, extra = "") {const pct = ((100 * tokens) / all).toFixed(1).padStart(5);- const cal = scale ? String(Math.round(tokens * scale)).padStart(7) : '';+ const cal = scale ? String(Math.round(tokens * scale)).padStart(7) : "";return `${String(tokens).padStart(7)} ${cal} ${pct}% ${label}${extra}`;}function report(a, opts) {const out = [];- const w = s => out.push(s);+ const w = (s) => out.push(s);const { totals, scale } = a;- w(`model: ${a.model ?? '?'}`);+ w(`model: ${a.model ?? "?"}`);if (a.usage) {w(`provider usage: ${JSON.stringify(a.usage)}`);- w(`calibration: o200k total ${totals.all} → provider ${a.usage.prompt_tokens} (×${scale.toFixed(3)})`);+ w(+ `calibration: o200k total ${totals.all} → provider ${a.usage.prompt_tokens} (×${scale.toFixed(3)})`,+ );}- w('');- w(`${'o200k'.padStart(7)} ${scale ? 'calib'.padStart(7) : ''} ${'share'.padStart(6)} part`);- w(fmtRow('TOTAL', totals.all, totals.all, scale));- w(fmtRow('system prompt', totals.system, totals.all, scale));- w(fmtRow(`tool schemas (${a.tools.length})`, totals.tools, totals.all, scale));- w(fmtRow('conversation (non-system messages)', totals.conversation, totals.all, scale));- w(fmtRow('request envelope', totals.envelope, totals.all, scale));+ w("");+ w(+ `${"o200k".padStart(7)} ${scale ? "calib".padStart(7) : ""} ${"share".padStart(6)} part`,+ );+ w(fmtRow("TOTAL", totals.all, totals.all, scale));+ w(fmtRow("system prompt", totals.system, totals.all, scale));+ w(+ fmtRow(`tool schemas (${a.tools.length})`, totals.tools, totals.all, scale),+ );+ w(+ fmtRow(+ "conversation (non-system messages)",+ totals.conversation,+ totals.all,+ scale,+ ),+ );+ w(fmtRow("request envelope", totals.envelope, totals.all, scale));- for (const m of a.messages.filter(m => m.tree)) {- w('');+ for (const m of a.messages.filter((m) => m.tree)) {+ w("");w(`== system message #${m.index}: ${m.tokens} tokens, ${m.chars} chars`);const walk = (node, depth) => {for (const c of node.children) {if (depth > opts.depth) continue;- const indent = ' '.repeat(depth - 1);- const own = c.children.length ? ` (own ${c.own})` : '';- w(fmtRow(`${indent}${c.title.slice(0, 90)}`, c.total, totals.all, scale, own));+ const indent = " ".repeat(depth - 1);+ const own = c.children.length ? ` (own ${c.own})` : "";+ w(+ fmtRow(+ `${indent}${c.title.slice(0, 90)}`,+ c.total,+ totals.all,+ scale,+ own,+ ),+ );walk(c, depth + 1);}};- if (m.tree.own) w(fmtRow('(preamble before first section)', m.tree.own, totals.all, scale));+ if (m.tree.own)+ w(+ fmtRow(+ "(preamble before first section)",+ m.tree.own,+ totals.all,+ scale,+ ),+ );walk(m.tree, 1);}- w('');- w(`== tool schemas, largest first (${Math.min(opts.top, a.tools.length)} of ${a.tools.length})`);- for (const t of [...a.tools].sort((x, y) => y.tokens - x.tokens).slice(0, opts.top)) {- w(fmtRow(t.name, t.tokens, totals.all, scale, ` [desc ${t.description} / params ${t.parameters}]`));+ w("");+ w(+ `== tool schemas, largest first (${Math.min(opts.top, a.tools.length)} of ${a.tools.length})`,+ );+ for (const t of [...a.tools]+ .sort((x, y) => y.tokens - x.tokens)+ .slice(0, opts.top)) {+ w(+ fmtRow(+ t.name,+ t.tokens,+ totals.all,+ scale,+ ` [desc ${t.description} / params ${t.parameters}]`,+ ),+ );}const byPrefix = new Map();for (const t of a.tools) {@@ -266,37 +347,52 @@ function report(a, opts) {e.tokens += t.tokens;byPrefix.set(p, e);}- w('');- w('== tool schemas by name prefix');- for (const [p, e] of [...byPrefix].sort((x, y) => y[1].tokens - x[1].tokens)) {+ w("");+ w("== tool schemas by name prefix");+ for (const [p, e] of [...byPrefix].sort(+ (x, y) => y[1].tokens - x[1].tokens,+ )) {w(fmtRow(`${p}* (${e.n})`, e.tokens, totals.all, scale));}- w('');- w('== non-system messages');- for (const m of a.messages.filter(m => m.role !== 'system')) {+ w("");+ w("== non-system messages");+ for (const m of a.messages.filter((m) => m.role !== "system")) {w(fmtRow(`#${m.index} ${m.role}`, m.tokens, totals.all, scale));}if (a.duplicates.length) {- w('');- w('== repeated paragraphs (tokens paid more than once)');+ w("");+ w("== repeated paragraphs (tokens paid more than once)");for (const d of a.duplicates.slice(0, opts.top)) {- w(`${String(d.wasted).padStart(7)} wasted ×${d.where.length} ${d.text.slice(0, 100)}…`);- w(`${''.padStart(18)}in: ${[...new Set(d.where)].join(', ')}`);+ w(+ `${String(d.wasted).padStart(7)} wasted ×${d.where.length} ${d.text.slice(0, 100)}…`,+ );+ w(`${"".padStart(18)}in: ${[...new Set(d.where)].join(", ")}`);}}- return out.join('\n');+ return out.join("\n");}-const isMain = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;+const isMain =+ process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;if (isMain) {const opts = parseArgs(process.argv.slice(2));- const body = JSON.parse(fs.readFileSync(opts.request, 'utf8'));+ const body = JSON.parse(fs.readFileSync(opts.request, "utf8"));const a = analyse(body, opts);if (opts.json) {- const strip = n => ({ title: n.title, own: n.own, total: n.total, children: n.children.map(strip) });- const json = { ...a, messages: a.messages.map(m => (m.tree ? { ...m, tree: strip(m.tree) } : m)) };+ const strip = (n) => ({+ title: n.title,+ own: n.own,+ total: n.total,+ children: n.children.map(strip),+ });+ const json = {+ ...a,+ messages: a.messages.map((m) =>+ m.tree ? { ...m, tree: strip(m.tree) } : m,+ ),+ };process.stdout.write(`${JSON.stringify(json, null, 2)}\n`);} else {process.stdout.write(`${report(a, opts)}\n`);