Skip to content

armgit / pibot

Public Imported from GitHub
0

Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.

3.1 KB
Raw Blame
import { createHash } from "node:crypto";
import { readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

/** Reproduce the locked SDK's pure helpers without importing its config/provider graph. */
export function generateContextHelpers(root: string) {
  const version = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")).version;
  if (version !== "1.4.0") throw new Error("pi_context_version_mismatch");
  const groups = [
    [
      "core/session-manager.js",
      [
        "buildEntryIndex",
        "buildSessionPath",
        "getSessionContextSettings",
        "sessionEntryToContextMessages",
        "buildContextEntries",
        "projectContextEntry",
        "buildSessionProjection",
      ],
    ],
    [
      "core/messages.js",
      ["createBranchSummaryMessage", "createCompactionSummaryMessage", "createCustomMessage"],
    ],
    ["core/compaction/compaction.js", ["estimateTextAndImageContentChars", "estimateTokens"]],
  ] as const;
  const chunks: string[] = [];
  const sources: { file: string; sha256: string; functions: readonly string[] }[] = [];
  for (const [file, names] of groups) {
    const source = readFileSync(resolve(root, "dist", file), "utf8");
    sources.push({
      file,
      sha256: createHash("sha256").update(source).digest("hex"),
      functions: names,
    });
    if (file.endsWith("compaction.js")) {
      const constants = source.match(/^const ESTIMATED_IMAGE_CHARS = \d+;$/gm);
      const constant = constants?.[0];
      if (constants?.length !== 1 || !constant) throw new Error("pi_context_constant_changed");
      chunks.push(constant);
    }
    for (const name of names) {
      // Locked tsc output closes each top-level declaration at column zero. If that format or
      // the function shape changes on upgrade, refuse extraction rather than approximate it.
      const matches = [
        ...source.matchAll(new RegExp(`^(?:export )?function ${name}\\([^]*?^\\}`, "gm")),
      ];
      const match = matches[0];
      if (matches.length !== 1 || !match) throw new Error("pi_context_function_changed");
      const body = match[0].replace(/^export /, "");
      chunks.push(
        ["buildSessionProjection", "estimateTokens"].includes(name) ? `export ${body}` : body,
      );
    }
  }
  return {
    code: [
      "// Add-only Pi Bot entry: exact pure function bodies from pi-coding-agent 1.4.0 (MIT).",
      "// Generated by packages/agent/scripts/pi-context-helpers.ts; keep the upstream package license.",
      ...chunks,
      "",
    ].join("\n"),
    sources,
  };
}

if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
  const { values } = parseArgs({
    options: { source: { type: "string" }, output: { type: "string" } },
  });
  if (!values.source || !values.output) throw new Error("pi_context_source_and_output_required");
  const result = generateContextHelpers(resolve(values.source));
  writeFileSync(values.output, result.code);
  console.log(JSON.stringify({ output: values.output, sources: result.sources }));
}