github-router 0.3.378 → 0.3.379
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{attribution-settings-BR5Umj2L.js → attribution-settings-BWYL2b8N.js} +2 -2
- package/dist/{attribution-settings-BR5Umj2L.js.map → attribution-settings-BWYL2b8N.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{claude--4O3wHRq.js → claude-CSuIdaLV.js} +3 -3
- package/dist/{claude--4O3wHRq.js.map → claude-CSuIdaLV.js.map} +1 -1
- package/dist/{codex-DHRMLpSo.js → codex-BG0pfud9.js} +2 -2
- package/dist/{codex-DHRMLpSo.js.map → codex-BG0pfud9.js.map} +1 -1
- package/dist/main.js +5 -5
- package/dist/{pi-B0EFY6l7.js → pi-DmeBxzIo.js} +344 -40
- package/dist/pi-DmeBxzIo.js.map +1 -0
- package/dist/pi-foreign-artifacts-DZ4tioyO.js +660 -0
- package/dist/pi-foreign-artifacts-DZ4tioyO.js.map +1 -0
- package/dist/pi-memory-bridge-Bp9AnYw9.js +1 -0
- package/dist/{pi-memory-bridge-Dvj1T3e3.js → pi-memory-bridge-CICIdDVP.js} +15 -5
- package/dist/pi-memory-bridge-CICIdDVP.js.map +1 -0
- package/dist/{serve-C13q-9w0.js → serve-zbQKfx1E.js} +3 -3
- package/dist/{serve-C13q-9w0.js.map → serve-zbQKfx1E.js.map} +1 -1
- package/dist/{server-setup-CptI7SUT.js → server-setup-ClZdV33Q.js} +2 -2
- package/dist/{server-setup-CptI7SUT.js.map → server-setup-ClZdV33Q.js.map} +1 -1
- package/dist/{start-DioCGjM8.js → start-mnedD5cH.js} +2 -2
- package/dist/{start-DioCGjM8.js.map → start-mnedD5cH.js.map} +1 -1
- package/package.json +1 -1
- package/dist/pi-B0EFY6l7.js.map +0 -1
- package/dist/pi-memory-bridge-Dvj1T3e3.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pi-foreign-artifacts-DZ4tioyO.js","names":[],"sources":["../src/lib/pi-foreign-artifacts.ts"],"sourcesContent":["/**\n * Bridge the INHERITED artifact directories — Claude Code's `.claude/` /\n * `~/.claude/` and Copilot's `.github/` / `~/.copilot/` — into a\n * `github-router pi` launch.\n *\n * Three namespaces, three different failure modes, one rule set:\n *\n * | namespace | same-name outcome in Pi | reported? |\n * |-----------------|-----------------------------------------------|-----------|\n * | agent registry | `mergeRuntimeAgents` throws, EVERY `subagent` | yes |\n * | | call in the process fails until it is removed | |\n * | `skills/*` | the other `SKILL.md` is overwritten in place | **no** |\n * | `prompts/*.md` | the other file is overwritten in place | **no** |\n *\n * So the planner reserves names BEFORE anything is written, and the rule\n * differs by namespace on purpose:\n *\n * - **agents**: a name the router itself already ships (its roster, the\n * pi-subagents builtins, the read-only CLI adapters) means the role\n * already exists — the foreign definition is **skipped and reported**.\n * Two agents with one purpose in one catalog is the ambiguity that\n * produces wrong delegations, and a registry identity is not the only\n * carrier of the content (the skill and prompt are).\n * - **skills and prompts**: the file IS the only carrier, so they are\n * **renamed, never skipped** — `gh-oracle` → `gh-oracle-2`,\n * `review.md` → `review-2.md`.\n *\n * Renaming happens for anything else that is taken, deterministically:\n * agents become `<slug>-<scope>` (then `-2`, `-3`…), skills and prompts\n * become `<slug>-2` (then `-3`…). No source prefix — a prefix is not a\n * namespace (it walks straight into the builtin `claude-code` /\n * `claude-code-writer`) and it renames artifacts the user recognises for no\n * safety gain, since the reservation is what makes collisions unreachable.\n *\n * Foreign `model:` and `aliases:` are never emitted. The model would be a\n * Copilot slug that `isUnavailableSubagentModel` refuses (so every run of\n * that agent fails), and an alias is another registry identity that can\n * collide invisibly. Every bridged agent therefore runs on the launch's\n * lead model. `tools:` is dropped from the frontmatter and folded into the\n * body as prose, because an unresolvable entry in pi-subagents' strict\n * allowlist hard-fails the child.\n *\n * Nothing here imports pi-subagents or Pi: the router owns one rule and\n * reads the same frontmatter the loaders read, so a version bump upstream\n * cannot silently move a name out from under it.\n */\n\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport { capBytes, redactSecrets, splitFrontmatter } from \"./pi-memory-bridge\"\n\n/**\n * Every name pi-subagents reserves for itself — `BUILTIN_AGENT_NAMES` from\n * the installed package plus the live alias map, the read-only CLI adapters,\n * and the router's own roster.\n *\n * Cannot be imported: pi-subagents is an installed Pi extension, never a\n * router dependency (bundling its internals would couple the launcher to a\n * version it does not pin). LAST_VERIFIED against pi-subagents 0.88.0:\n * `src/agents/builtin-names.js` for the 13 names, and a live `snapshot.all`\n * for the aliases (`oracle → advisor`,\n * `worker → developer, coder, implementer, develop`; every other builtin\n * carries none).\n *\n * Drift here is not a correctness hole: the extension's `tool_result` net\n * unregisters anything the registry rejects at merge time. It is a\n * friendliness hole (a foreign agent skipped needlessly), which is why this\n * list is commented rather than guessed.\n */\nexport const PI_FOREIGN_ROUTER_OWNED_AGENTS: ReadonlyArray<string> = Object.freeze([\n // pi-subagents builtins (BUILTIN_AGENT_NAMES, 0.88.0).\n \"advisor\",\n \"claude-code\",\n \"claude-code-writer\",\n \"codex-exec\",\n \"codex-exec-writer\",\n \"cursor-agent\",\n \"cursor-agent-writer\",\n \"delegate\",\n \"evidence-auditor\",\n \"oracle\",\n \"researcher\",\n \"reviewer\",\n \"scout\",\n \"worker\",\n // Live aliases of those builtins (`oracle`, `worker` above).\n \"developer\",\n \"coder\",\n \"implementer\",\n \"develop\",\n])\n\n/**\n * The router's own agent roster is NOT in the constant above: it depends on\n * the launch (`buildPiAgentFiles` writes Explore / General-Purpose / reviewer /\n * oracle / advisor, and `--no-peers` writes none), so `buildReservedNames`\n * takes it as `emittedAgents` instead. A hardcoded copy here would skip a\n * foreign `Explore` on a peerless launch that publishes no such role.\n */\n\n/** Foreign artifact roots. Project + user, Claude + Copilot. */\nconst SKILL_ROOTS_PROJECT = [\".claude/skills\", \".github/skills\"] as const\nconst SKILL_ROOTS_USER = [\".claude/skills\", \".copilot/skills\"] as const\nconst AGENT_ROOTS_PROJECT = [\".claude/agents\", \".github/agents\"] as const\nconst AGENT_ROOTS_USER = [\".claude/agents\", \".copilot/agents\"] as const\nconst PROMPT_ROOTS_PROJECT = [\".claude/commands\", \".github/prompts\"] as const\nconst PROMPT_ROOTS_USER = [\".claude/commands\"] as const\n\n/** Pi's own artifact roots in the mirror / repo / home, for reservation. */\nconst PI_SKILL_ROOTS_REL = [\"skills\", \".pi/skills\", \".agents/skills\"] as const\nconst PI_PROMPT_ROOTS_REL = [\"prompts\", \".pi/prompts\"] as const\nconst PI_AGENT_ROOTS_REL = [\"agents\", \".pi/agents\", \".agents\"] as const\n\n/** Caps. Pi refuses a skill without a description (`core/skills.js:252`). */\nconst MAX_FOREIGN_AGENT_BODY_BYTES = 8 * 1024\nconst MAX_FOREIGN_DESCRIPTION_CHARS = 200\nconst MAX_FOREIGN_SKILL_DESCRIPTION_CHARS = 1_000\nconst MAX_FOREIGN_INDEX_BYTES = 4 * 1024\n/** Mirrors Pi's own limits so a bridged file can never be rejected. */\nconst MAX_SKILL_NAME_CHARS = 64\n\nexport interface PiForeignAgentSpec {\n /** Final, collision-free, slugged (the authored name unless it was taken). */\n name: string\n /** The name as authored in the source file, before any suffix. */\n originalName: string\n /** One line, whitespace-collapsed, ≤ 200 chars. */\n description: string\n /** Frontmatter stripped, provenance line, tool policy as prose, ≤ 8 KiB. */\n body: string\n source: \"claude\" | \"copilot\"\n scope: \"project\" | \"user\"\n /** Repo- or home-relative provenance, shown in the index. */\n file: string\n /** Set when the name had to change (`gh-oracle` → `gh-oracle-2`). */\n renamedFrom?: string\n}\n\nexport interface PiForeignArtifactDoc {\n /** Final name: skill directory, or prompt file stem. */\n name: string\n content: string\n renamedFrom?: string\n}\n\nexport interface PiForeignPlan {\n /** Written to `<mirror>/skills/<name>/SKILL.md`. */\n skills: Array<PiForeignArtifactDoc>\n /** Written to `<mirror>/prompts/<name>.md`. */\n prompts: Array<PiForeignArtifactDoc>\n /**\n * Registered through the pi-subagents runtime-agent event. NO files are\n * written for these: one registry entry, announced in the prompt index,\n * loaded on demand via `subagent({action:\"list\"})`.\n */\n agents: Array<PiForeignAgentSpec>\n /** Everything dropped rather than bridged, with the reason. Never silent. */\n skipped: Array<{ name: string; file: string; reason: string }>\n}\n\nexport interface PiReservedNames {\n /** Builtins + aliases + adapters + this launch's roster. Never renamed to. */\n routerOwnedAgents: Set<string>\n /** Every agent identity key on disk (name, aliases, localName). */\n agents: Set<string>\n /** Skill names and directory slugs on disk, plus this launch's own. */\n skills: Set<string>\n /** Prompt stems on disk, plus this launch's own. */\n prompts: Set<string>\n}\n\nfunction lower(s: string): string {\n return s.trim().toLowerCase()\n}\n\n/** Collapse to a legal Pi/prompt path segment and registry name. */\nexport function piForeignSlug(raw: string): string {\n const slug = String(raw ?? \"\")\n .toLowerCase()\n // Any run of illegal characters is one separator, so `Copilot Deploy!`\n // and `--spaced Name--` both land on a legal, readable segment.\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n const trimmed = slug.length > MAX_SKILL_NAME_CHARS ? slug.slice(0, MAX_SKILL_NAME_CHARS).replace(/-+$/, \"\") : slug\n // An all-symbols name slugs to nothing; it still needs a usable identity.\n return trimmed.length > 0 ? trimmed : \"foreign\"\n}\n\nfunction collapseLine(raw: string): string {\n return raw.replace(/\\s+/g, \" \").trim()\n}\n\nfunction truncateChars(raw: string, max: number): string {\n if (raw.length <= max) return raw\n return `${raw.slice(0, Math.max(0, max - 1)).trimEnd()}…`\n}\n\n/** YAML-ish frontmatter read: `key: value` on one line, quotes stripped. */\nfunction frontmatterValue(frontmatter: string, key: string): string | undefined {\n const re = new RegExp(`^${key}\\\\s*:\\\\s*(.*)$`, \"im\")\n const match = re.exec(frontmatter)\n if (!match) return undefined\n const value = match[1].trim().replace(/^[\"']/, \"\").replace(/[\"']$/, \"\").trim()\n return value.length > 0 ? value : undefined\n}\n\n/** Space- and comma-separated list value (`tools: read, grep, bash`). */\nfunction frontmatterList(frontmatter: string, key: string): Array<string> {\n const raw = frontmatterValue(frontmatter, key)\n if (!raw) return []\n return raw\n .replace(/^\\[/, \"\")\n .replace(/\\]$/, \"\")\n .split(/[,\\s]+/)\n .map((s) => s.trim())\n .filter((s) => s.length > 0)\n}\n\nasync function readIfExists(file: string): Promise<string | undefined> {\n try {\n return await fs.readFile(file, \"utf8\")\n } catch {\n return undefined\n }\n}\n\nasync function isDirectory(dir: string): Promise<boolean> {\n try {\n return (await fs.stat(dir)).isDirectory()\n } catch {\n return false\n }\n}\n\nasync function listDir(dir: string): Promise<Array<string>> {\n try {\n return (await fs.readdir(dir)).sort()\n } catch {\n return []\n }\n}\n\n/** Repo root: walk up for `.git`, else the given cwd. Never throws. */\nexport async function piForeignRepoRoot(cwd: string): Promise<string> {\n let dir = path.resolve(cwd)\n for (let depth = 0; depth < 12; depth++) {\n try {\n await fs.stat(path.join(dir, \".git\"))\n return dir\n } catch {\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n }\n return cwd\n}\n\n/**\n * Which product an artifact came from, from its path alone.\n *\n * Normalized to forward slashes first: the roots above are POSIX literals, so\n * a Windows path (`\\.github\\.`) would otherwise match nothing and every\n * artifact would be labelled Claude. The label reaches the index and the\n * provenance line, i.e. the model's view of where an agent came from.\n */\nexport function piForeignSourceOf(file: string): \"claude\" | \"copilot\" {\n const posix = file.replace(/\\\\/g, \"/\")\n return posix.includes(\"/.github/\") || posix.includes(\"/.copilot/\") ? \"copilot\" : \"claude\"\n}\n\nfunction provenancePath(file: string, repoRoot: string, homeDir: string): string {\n const rel = (base: string, prefix: string): string | undefined => {\n const out = path.relative(base, file)\n return out.length > 0 && !out.startsWith(\"..\") ? `${prefix}${out.split(path.sep).join(\"/\")}` : undefined\n }\n // `~` for home on purpose: the index and the provenance line are read by a\n // human in a transcript, and an absolute path would leak the account name\n // into every bridged artifact.\n return rel(repoRoot, \"\") ?? rel(homeDir, \"~/\") ?? path.basename(file)\n}\n\n/* ------------------------------------------------------------------ */\n/* Reservation */\n/* ------------------------------------------------------------------ */\n\n/** Every `<dir>/*.md` under an agent root (flat — that is all Pi scans). */\nasync function agentIdentityKeys(root: string): Promise<Array<string>> {\n const keys: Array<string> = []\n for (const name of await listDir(root)) {\n if (!name.endsWith(\".md\")) continue\n // `.agent.md` (Copilot) and `*.md` (Claude) both reduce to the stem.\n const stem = name.replace(/\\.agent\\.md$/, \"\").replace(/\\.md$/, \"\")\n const raw = await readIfExists(path.join(root, name))\n if (raw === undefined) continue\n const { frontmatter } = splitFrontmatter(raw)\n const authored = frontmatterValue(frontmatter, \"name\") ?? stem\n keys.push(authored, stem)\n for (const key of [\"aliases\", \"alias\", \"localName\"]) {\n keys.push(...frontmatterList(frontmatter, key))\n }\n }\n return keys\n}\n\nasync function skillNamesUnder(root: string): Promise<Array<string>> {\n const names: Array<string> = []\n for (const entry of await listDir(root)) {\n if (entry.startsWith(\".\")) continue\n const dir = path.join(root, entry)\n if (await isDirectory(dir)) {\n // Directory-based skill: Pi names it from frontmatter, else the dir.\n names.push(entry)\n const raw = await readIfExists(path.join(dir, \"SKILL.md\"))\n if (raw !== undefined) {\n const named = frontmatterValue(splitFrontmatter(raw).frontmatter, \"name\")\n if (named) names.push(named)\n }\n continue\n }\n if (entry.endsWith(\".md\")) {\n // Single-file skill: the stem is the name.\n const stem = entry.replace(/\\.md$/, \"\")\n names.push(stem)\n const raw = await readIfExists(path.join(root, entry))\n if (raw !== undefined) {\n const named = frontmatterValue(splitFrontmatter(raw).frontmatter, \"name\")\n if (named) names.push(named)\n }\n }\n }\n return names\n}\n\nasync function promptNamesUnder(root: string): Promise<Array<string>> {\n const names: Array<string> = []\n for (const entry of await listDir(root)) {\n const full = path.join(root, entry)\n if (await isDirectory(full)) {\n names.push(...(await promptNamesUnder(full)))\n continue\n }\n if (entry.endsWith(\".md\")) names.push(entry.replace(/\\.md$/, \"\"))\n }\n return names\n}\n\n/**\n * Build the four reservation sets.\n *\n * `emittedSkills` / `emittedPrompts` are the names THIS launch is about to\n * write, so a foreign artifact can never land on top of one the router just\n * created in the same process (the `<mirror>/` scan would see a stale copy\n * from the previous launch, not this one).\n */\nexport async function buildReservedNames(opts: {\n mirrorDir: string\n repoRoot: string\n homeDir: string\n /**\n * The router roster THIS launch really publishes (agent-file stems from\n * `buildPiAgentFiles`, empty under `--no-peers`). Part of the router-owned\n * set, because the role exists and the roster must win the name. Kept\n * separate from the constant so a peerless launch does not skip a foreign\n * `Explore` for a roster it never wrote.\n */\n emittedAgents?: ReadonlyArray<string>\n emittedSkills?: ReadonlyArray<string>\n emittedPrompts?: ReadonlyArray<string>\n}): Promise<PiReservedNames> {\n const routerOwnedAgents = new Set<string>(\n PI_FOREIGN_ROUTER_OWNED_AGENTS.map(lower),\n )\n for (const name of opts.emittedAgents ?? []) routerOwnedAgents.add(lower(name))\n const agents = new Set<string>()\n const skills = new Set<string>()\n const prompts = new Set<string>()\n\n for (const root of [\n path.join(opts.mirrorDir, PI_AGENT_ROOTS_REL[0]),\n path.join(opts.repoRoot, PI_AGENT_ROOTS_REL[1]),\n path.join(opts.repoRoot, PI_AGENT_ROOTS_REL[2]),\n path.join(opts.homeDir, \".pi/agent/agents\"),\n path.join(opts.homeDir, \".agents\"),\n ]) {\n for (const key of await agentIdentityKeys(root)) agents.add(lower(key))\n }\n for (const key of routerOwnedAgents) agents.add(key)\n\n for (const root of [\n path.join(opts.mirrorDir, PI_SKILL_ROOTS_REL[0]),\n path.join(opts.repoRoot, PI_SKILL_ROOTS_REL[1]),\n path.join(opts.repoRoot, PI_SKILL_ROOTS_REL[2]),\n path.join(opts.homeDir, \".pi/agent/skills\"),\n path.join(opts.homeDir, \".agents/skills\"),\n ]) {\n for (const name of await skillNamesUnder(root)) skills.add(lower(name))\n }\n for (const name of opts.emittedSkills ?? []) skills.add(lower(name))\n\n for (const root of [\n path.join(opts.mirrorDir, PI_PROMPT_ROOTS_REL[0]),\n path.join(opts.repoRoot, PI_PROMPT_ROOTS_REL[1]),\n ]) {\n for (const name of await promptNamesUnder(root)) prompts.add(lower(name))\n }\n for (const name of opts.emittedPrompts ?? []) prompts.add(lower(name))\n\n return { routerOwnedAgents, agents, skills, prompts }\n}\n\n/* ------------------------------------------------------------------ */\n/* Planner */\n/* ------------------------------------------------------------------ */\n\n/** Deterministic suffix search shared by agents and skills/prompts. */\nfunction claim(\n taken: Set<string>,\n base: string,\n suffixes: () => Iterable<string>,\n): string {\n if (!taken.has(lower(base))) {\n taken.add(lower(base))\n return base\n }\n for (const candidate of suffixes()) {\n if (!taken.has(lower(candidate))) {\n taken.add(lower(candidate))\n return candidate\n }\n }\n // Unreachable: the generator is infinite. Keep TypeScript honest.\n return base\n}\n\nfunction* scopeSuffixes(base: string, scope: string): Generator<string> {\n yield `${base}-${scope}`\n for (let n = 2; n < 1_000; n++) yield `${base}-${scope}-${n}`\n}\n\nfunction* ordinals(base: string): Generator<string> {\n for (let n = 2; n < 1_000; n++) yield `${base}-${n}`\n}\n\nasync function collectAgentFiles(\n roots: ReadonlyArray<{ dir: string; scope: \"project\" | \"user\" }>,\n): Promise<Array<{ file: string; scope: \"project\" | \"user\" }>> {\n const out: Array<{ file: string; scope: \"project\" | \"user\" }> = []\n for (const { dir, scope } of roots) {\n for (const entry of await listDir(dir)) {\n if (!entry.endsWith(\".md\")) continue\n out.push({ file: path.join(dir, entry), scope })\n }\n }\n return byScopeThenPath(out)\n}\n\n/**\n * Scope is the FIRST sort key, not the root order.\n *\n * The two roots per scope (`.claude/…`, `.github/…`) are visited in a fixed\n * order, but `readdir` order is filesystem-dependent and the plan's suffixes\n * (`writer` vs `writer-user`) are assigned first-come. A project artifact must\n * win its authored name over a user artifact of the same name on every machine,\n * so the ordering is stated here rather than inherited from the walk.\n */\nfunction byScopeThenPath<T extends { file: string; scope: \"project\" | \"user\" }>(\n rows: Array<T>,\n): Array<T> {\n return rows.sort((a, b) => {\n if (a.scope !== b.scope) return a.scope === \"project\" ? -1 : 1\n return a.file < b.file ? -1 : a.file > b.file ? 1 : 0\n })\n}\n\nasync function collectSkillFiles(\n roots: ReadonlyArray<{ dir: string; scope: \"project\" | \"user\" }>,\n): Promise<Array<{ file: string; scope: \"project\" | \"user\"; name: string }>> {\n const out: Array<{ file: string; scope: \"project\" | \"user\"; name: string }> = []\n for (const { dir, scope } of roots) {\n for (const entry of await listDir(dir)) {\n if (entry.startsWith(\".\")) continue\n const full = path.join(dir, entry)\n if (await isDirectory(full)) {\n const skillFile = path.join(full, \"SKILL.md\")\n const raw = await readIfExists(skillFile)\n if (raw === undefined) continue\n out.push({\n file: skillFile,\n scope,\n name: frontmatterValue(splitFrontmatter(raw).frontmatter, \"name\") ?? entry,\n })\n continue\n }\n if (entry.endsWith(\".md\")) {\n const raw = await readIfExists(full)\n if (raw === undefined) continue\n out.push({\n file: full,\n scope,\n name:\n frontmatterValue(splitFrontmatter(raw).frontmatter, \"name\")\n ?? entry.replace(/\\.md$/, \"\"),\n })\n }\n }\n }\n return byScopeThenPath(out)\n}\n\nasync function collectPromptFiles(\n roots: ReadonlyArray<{ dir: string; scope: \"project\" | \"user\" }>,\n): Promise<Array<{ file: string; scope: \"project\" | \"user\"; name: string }>> {\n const out: Array<{ file: string; scope: \"project\" | \"user\"; name: string }> = []\n const walk = async (dir: string, scope: \"project\" | \"user\", prefix: string): Promise<void> => {\n for (const entry of await listDir(dir)) {\n if (entry.startsWith(\".\")) continue\n const full = path.join(dir, entry)\n if (await isDirectory(full)) {\n await walk(full, scope, `${prefix}${entry}-`)\n continue\n }\n if (!entry.endsWith(\".md\")) continue\n // `.prompt.md` is Copilot's prompt-file suffix; `deploy.prompt.md` is\n // the command `deploy`, not `deploy-prompt`.\n const stem = entry.replace(/\\.prompt\\.md$/, \"\").replace(/\\.md$/, \"\")\n // Nested commands flatten BEFORE the reservation, because a flattened\n // name can collide with a flat one (`nested/deploy` vs `deploy`).\n out.push({ file: full, scope, name: `${prefix}${stem}` })\n }\n }\n for (const { dir, scope } of roots) await walk(dir, scope, \"\")\n return byScopeThenPath(out)\n}\n\n/**\n * Build the bridge plan. Pure over the filesystem: reads the foreign roots\n * and the reservation sets, writes nothing.\n */\nexport async function planForeignArtifacts(opts: {\n repoRoot: string\n homeDir: string\n mirrorDir: string\n reservedNames: PiReservedNames\n}): Promise<PiForeignPlan> {\n const { repoRoot, homeDir, reservedNames: reserved } = opts\n const plan: PiForeignPlan = { skills: [], prompts: [], agents: [], skipped: [] }\n\n // Reservation sets are copied for the skill/prompt namespaces: they are\n // mutated as this plan claims names, so two foreign files that ask for the\n // same thing disambiguate instead of fighting.\n const skillNames = new Set(reserved.skills)\n const promptNames = new Set(reserved.prompts)\n const agentNames = new Set(reserved.agents)\n\n /* ----- skills (always bridged) ----- */\n const skillFiles = await collectSkillFiles([\n ...SKILL_ROOTS_PROJECT.map((rel) => ({ dir: path.join(repoRoot, rel), scope: \"project\" as const })),\n ...SKILL_ROOTS_USER.map((rel) => ({ dir: path.join(homeDir, rel), scope: \"user\" as const })),\n ])\n for (const { file, name } of skillFiles) {\n const raw = await readIfExists(file)\n if (raw === undefined) continue\n const shown = provenancePath(file, repoRoot, homeDir)\n const { frontmatter, body } = splitFrontmatter(raw)\n const description = collapseLine(frontmatterValue(frontmatter, \"description\") ?? \"\")\n if (!description) {\n // Pi refuses a skill with no description (`core/skills.js:252-254`), so\n // this is a hard skip — reported, never a silent drop.\n plan.skipped.push({ name, file: shown, reason: \"skill has no description (Pi requires one)\" })\n continue\n }\n const authored = piForeignSlug(name)\n const finalName = claim(skillNames, authored, () => ordinals(authored))\n const allowed = frontmatterList(frontmatter, \"allowed-tools\")\n plan.skills.push({\n name: finalName,\n ...(finalName === authored ? {} : { renamedFrom: name }),\n content: `${buildSkillFrontmatter(description)}\\n${buildArtifactBody({\n body,\n source: piForeignSourceOf(file),\n shown,\n allowed,\n })}`,\n })\n }\n\n /* ----- prompts (under --foreign) ----- */\n const promptFiles = await collectPromptFiles([\n ...PROMPT_ROOTS_PROJECT.map((rel) => ({ dir: path.join(repoRoot, rel), scope: \"project\" as const })),\n ...PROMPT_ROOTS_USER.map((rel) => ({ dir: path.join(homeDir, rel), scope: \"user\" as const })),\n ])\n for (const { file, name } of promptFiles) {\n const raw = await readIfExists(file)\n if (raw === undefined) continue\n const shown = provenancePath(file, repoRoot, homeDir)\n const authored = piForeignSlug(name)\n const finalName = claim(promptNames, authored, () => ordinals(authored))\n // A prompt template is prose + `$1`/`$ARGUMENTS` placeholders. The body is\n // otherwise passed through untouched: rewriting placeholders would silently\n // change what the command means, and `$ARGUMENTS` is documented as not\n // bridged. Only a provenance line is prepended, so the command's origin is\n // visible where it runs.\n const { body } = splitFrontmatter(raw)\n plan.prompts.push({\n name: finalName,\n ...(finalName === authored ? {} : { renamedFrom: name }),\n content: `${buildArtifactBody({ body, source: piForeignSourceOf(file), shown, allowed: [] })}\\n`,\n })\n }\n\n /* ----- agents (specs only — no files) ----- */\n const agentFiles = await collectAgentFiles([\n ...AGENT_ROOTS_PROJECT.map((rel) => ({ dir: path.join(repoRoot, rel), scope: \"project\" as const })),\n ...AGENT_ROOTS_USER.map((rel) => ({ dir: path.join(homeDir, rel), scope: \"user\" as const })),\n ])\n // Content-dekeyed dedupe: first-mate dual-emits the same 8 roles into\n // `.github/agents` AND `.claude/agents` with byte-identical bodies, so the\n // second copy of a role must not become `planner-2`.\n const seenBodies = new Set<string>()\n for (const { file, scope } of agentFiles) {\n const raw = await readIfExists(file)\n if (raw === undefined) continue\n const shown = provenancePath(file, repoRoot, homeDir)\n const stem = path.basename(file).replace(/\\.agent\\.md$/, \"\").replace(/\\.md$/, \"\")\n const { frontmatter, body } = splitFrontmatter(raw)\n const originalName = frontmatterValue(frontmatter, \"name\") ?? stem\n const description = collapseLine(frontmatterValue(frontmatter, \"description\") ?? \"\")\n // A flat `.md` without a description is not an agent definition (Copilot\n // requires one; Claude allows it but Pi's index line would be empty).\n if (!description) {\n plan.skipped.push({\n name: originalName,\n file: shown,\n reason: \"no description in frontmatter (not a usable agent definition)\",\n })\n continue\n }\n const authored = piForeignSlug(originalName)\n // Router-owned FIRST: the role already exists under that name, so a second\n // entry with one purpose would only make the catalog ambiguous. Ordered\n // before the dedupe so the dual-emitted `reviewer` from first-mate reports\n // the real reason twice (\"the role exists\") instead of once as a duplicate\n // of a copy that was itself never bridged — the second shape of skip would\n // be true but misleading, since nothing was bridged to duplicate.\n if (reserved.routerOwnedAgents.has(lower(originalName))) {\n plan.skipped.push({\n name: originalName,\n file: shown,\n reason: \"name is owned by gh-router or a pi-subagents builtin (that role already exists)\",\n })\n continue\n }\n const hash = `${authored}\\u0000${body}`\n if (seenBodies.has(hash)) {\n plan.skipped.push({\n name: originalName,\n file: shown,\n reason: \"duplicate of an identical definition already bridged from another emitted path\",\n })\n continue\n }\n seenBodies.add(hash)\n const finalName = claim(agentNames, authored, () => scopeSuffixes(authored, scope))\n const tools = frontmatterList(frontmatter, \"tools\")\n plan.agents.push({\n name: finalName,\n originalName,\n description: truncateChars(description, MAX_FOREIGN_DESCRIPTION_CHARS),\n // Trimmed because pi-subagents' `validateString` rejects a\n // `systemPrompt` that differs from its own `trim()` — and a markdown\n // body always ends with a newline, so an untrimmed body would fail\n // registration for EVERY bridged agent (`runtime-agent-registry.js:48`).\n body: capBytes(\n buildArtifactBody({ body, source: piForeignSourceOf(file), shown, allowed: tools }),\n MAX_FOREIGN_AGENT_BODY_BYTES,\n \"gh-router foreign-agent bridge\",\n ).text.trim(),\n source: piForeignSourceOf(file),\n scope,\n file: shown,\n ...(finalName === authored ? {} : { renamedFrom: originalName }),\n })\n }\n\n return plan\n}\n\n/**\n * Frontmatter for a bridged skill.\n *\n * The `name:` key is deliberately ABSENT: Pi resolves a skill's name from the\n * frontmatter when present and from the parent directory otherwise\n * (`core/skills.js:245`), so dropping it lets the directory we just wrote\n * decide. Keeping the authored `name: gh-oracle` inside `gh-oracle-2/SKILL.md`\n * makes BOTH copies load as `gh-oracle` and the foreign one loses as a\n * `collision` diagnostic — a silent loss.\n */\nfunction buildSkillFrontmatter(description: string): string {\n const safeDescription = truncateChars(description, MAX_FOREIGN_SKILL_DESCRIPTION_CHARS).replace(\n /\\r?\\n/g,\n \" \",\n )\n return `---\\ndescription: ${safeDescription}\\n---\\n`\n}\n\n/**\n * The shared body shape for bridged artifacts: a provenance line (so the\n * origin is visible where it runs, not only where it was written), the\n * original tool policy as prose (Pi cannot enforce a foreign allowlist, and an\n * unresolvable entry would hard-fail the child), then the authored body.\n *\n * The body is secret-redacted on the way through: a foreign agent or command is\n * user-authored prose that has never been through the router, and copying it\n * into a launch mirror verbatim would move any token pasted into it into a\n * second file tree.\n */\nfunction buildArtifactBody(opts: {\n body: string\n source: \"claude\" | \"copilot\"\n shown: string\n allowed: ReadonlyArray<string>\n}): string {\n const provenance = `> Bridged by github-router from ${opts.source === \"copilot\" ? \"Copilot\" : \"Claude\"} \\`${opts.shown}\\`.`\n const policy =\n opts.allowed.length > 0\n ? `> Authored tool policy (advisory in Pi): ${opts.allowed.join(\", \")}.`\n : undefined\n const trimmed = redactSecrets(opts.body).replace(/^\\n+/, \"\")\n return [provenance, ...(policy ? [policy] : []), \"\", trimmed].join(\"\\n\")\n}\n\n/**\n * The one index the model sees. Deliberately a compact list, not the bodies:\n * runtime agents are never advertised (`advertised-agent-prompt.js`), and\n * spending the 16-entry / 12 KiB catalog on foreign agents would crowd out\n * the router's own roster. The model calls\n * `subagent({action:\"list\", options:{search:\"…\"}})` for full descriptions.\n */\nexport function buildForeignAgentIndex(\n agents: ReadonlyArray<PiForeignAgentSpec>,\n opts: { maxBytes?: number } = {},\n): string {\n if (agents.length === 0) return \"\"\n const maxBytes = opts.maxBytes ?? MAX_FOREIGN_INDEX_BYTES\n const header = [\n \"Agents bridged from .claude / .github / ~/.copilot. They are NOT preloaded:\",\n 'call subagent({action:\"list\", options:{search:\"<term>\"}}) for full descriptions,',\n 'then subagent({agent:\"<name>\", task:\"…\"}). They run on this profile\\'s lead model.',\n ]\n const rows = agents.map(\n (a) => `- ${a.name} [${a.source}, ${a.scope}] — ${a.description}`,\n )\n // Ship whole rows: a half-written index line is worse than a count, because\n // the model would call an agent whose description it cannot read.\n const included: Array<string> = []\n let bytes = Buffer.byteLength([...header, ...included].join(\"\\n\"), \"utf8\")\n for (const row of rows) {\n const size = Buffer.byteLength(`${row}\\n`, \"utf8\")\n if (bytes + size > maxBytes) break\n included.push(row)\n bytes += size\n }\n const omitted = rows.length - included.length\n const tail = omitted > 0 ? [`+${omitted} more; {action:\"list\", options:{search:\"<term>\"}}`] : []\n return [...header, ...included, ...tail].join(\"\\n\")\n}\n\n/**\n * Write the plan's skills and prompts into the mirror.\n *\n * `overwritten` counts a target that already existed. It must be `0` on every\n * launch — the reservation is what guarantees it — and the launcher warns when\n * it is not, which is the tripwire for the silent-clobber failure this whole\n * module exists to prevent. Agents are NOT written: they are registry entries.\n */\nexport async function writeForeignArtifacts(\n mirrorDir: string,\n plan: PiForeignPlan,\n): Promise<{ skills: number; prompts: number; overwritten: number }> {\n let skills = 0\n let prompts = 0\n let overwritten = 0\n const write = async (file: string, content: string): Promise<void> => {\n const existing = await readIfExists(file)\n if (existing !== undefined) overwritten += 1\n await fs.mkdir(path.dirname(file), { recursive: true })\n await fs.writeFile(file, content, \"utf8\")\n }\n for (const skill of plan.skills) {\n await write(path.join(mirrorDir, \"skills\", skill.name, \"SKILL.md\"), skill.content)\n skills += 1\n }\n for (const prompt of plan.prompts) {\n await write(path.join(mirrorDir, \"prompts\", `${prompt.name}.md`), prompt.content)\n prompts += 1\n }\n return { skills, prompts, overwritten }\n}\n\n/**\n * Count the foreign AGENT definitions a `--foreign` launch would consider.\n *\n * Exists so a launch without the flag can still say the artifacts are there:\n * the bridge is invisible by design, and a user who has `.github/agents/` has\n * no other way to learn the flag exists. Deliberately a `readdir` count rather\n * than a plan — no reservations, no body reads, and it must stay cheap because\n * it runs on every non-`--foreign` launch.\n *\n * Counts **stems**, not files, because first-mate dual-emits every role into\n * `.github/agents` AND `.claude/agents` with byte-identical bodies: a file\n * count would report 16 where the user has 8 roles, which reads like the bridge\n * found something it did not.\n */\nexport async function countForeignAgentFiles(opts: {\n repoRoot: string\n homeDir: string\n}): Promise<number> {\n const stems = new Set<string>()\n for (const root of [\n ...AGENT_ROOTS_PROJECT.map((rel) => path.join(opts.repoRoot, rel)),\n ...AGENT_ROOTS_USER.map((rel) => path.join(opts.homeDir, rel)),\n ]) {\n for (const entry of await listDir(root)) {\n if (!entry.endsWith(\".md\")) continue\n stems.add(entry.replace(/\\.agent\\.md$/, \"\").replace(/\\.md$/, \"\"))\n }\n }\n return stems.size\n}\n\n/** Default home dir for the planner (separate seam so tests stay hermetic). */\nexport function piForeignHomeDir(): string {\n return os.homedir()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,MAAa,iCAAwD,OAAO,OAAO;CAEjF;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;AAWD,MAAM,sBAAsB,CAAC,kBAAkB,gBAAgB;AAC/D,MAAM,mBAAmB,CAAC,kBAAkB,iBAAiB;AAC7D,MAAM,sBAAsB,CAAC,kBAAkB,gBAAgB;AAC/D,MAAM,mBAAmB,CAAC,kBAAkB,iBAAiB;AAC7D,MAAM,uBAAuB,CAAC,oBAAoB,iBAAiB;AACnE,MAAM,oBAAoB,CAAC,kBAAkB;;AAG7C,MAAM,qBAAqB;CAAC;CAAU;CAAc;AAAgB;AACpE,MAAM,sBAAsB,CAAC,WAAW,aAAa;AACrD,MAAM,qBAAqB;CAAC;CAAU;CAAc;AAAS;;AAG7D,MAAM,+BAA+B;AACrC,MAAM,gCAAgC;AACtC,MAAM,sCAAsC;AAC5C,MAAM,0BAA0B;;AAEhC,MAAM,uBAAuB;AAoD7B,SAAS,MAAM,GAAmB;CAChC,OAAO,EAAE,KAAK,CAAC,CAAC,YAAY;AAC9B;;AAGA,SAAgB,cAAc,KAAq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AAI,GAAG;EACvC,IAAI,CAAC,MAAM,SAAS,KAAK,GAAG;EAC5B,MAAM,IAAI,MAAM,QAAQ,gBAAgB,EAAE,CAAC,CAAC,QAAQ,SAAS,EAAE,CAAC;CAClE;CAEF,OAAO,MAAM;AACf;;AAGA,SAAgB,mBAA2B;CACzC,OAAO,GAAG,QAAQ;AACpB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { i as buildMirrorBridgeSection, o as collectBridgeInputs, l as mergeBridgeIntoAgentsMd } from "./pi-memory-bridge-CICIdDVP.js";
|
|
@@ -29,20 +29,30 @@ const PI_BRIDGE_FENCE_END = "<!-- gh-router memory-bridge end -->";
|
|
|
29
29
|
function byteLength(s) {
|
|
30
30
|
return Buffer.byteLength(s, "utf8");
|
|
31
31
|
}
|
|
32
|
-
|
|
32
|
+
/**
|
|
33
|
+
* Truncate to a UTF-8 byte budget without splitting a code point, marker
|
|
34
|
+
* included in the budget.
|
|
35
|
+
*
|
|
36
|
+
* Exported because the foreign-artifact bridge caps with the same measure Pi's
|
|
37
|
+
* own limits are stated in, and `label` keeps the truncation marker honest
|
|
38
|
+
* about which bridge did the cutting.
|
|
39
|
+
*/
|
|
40
|
+
function capBytes(s, max, label = "gh-router memory bridge") {
|
|
33
41
|
if (byteLength(s) <= max) return {
|
|
34
42
|
text: s,
|
|
35
43
|
truncated: false
|
|
36
44
|
};
|
|
45
|
+
const marker = `\n…[truncated by ${label}]`;
|
|
46
|
+
const budget = Math.max(0, max - byteLength(marker));
|
|
37
47
|
let low = 0;
|
|
38
48
|
let high = s.length;
|
|
39
49
|
while (low < high) {
|
|
40
50
|
const mid = Math.floor((low + high) / 2);
|
|
41
|
-
if (byteLength(s.slice(0, mid)) <=
|
|
51
|
+
if (byteLength(s.slice(0, mid)) <= budget) low = mid + 1;
|
|
42
52
|
else high = mid;
|
|
43
53
|
}
|
|
44
54
|
return {
|
|
45
|
-
text: `${s.slice(0, Math.max(0, low - 1))}
|
|
55
|
+
text: `${s.slice(0, Math.max(0, low - 1))}${marker}`,
|
|
46
56
|
truncated: true
|
|
47
57
|
};
|
|
48
58
|
}
|
|
@@ -398,6 +408,6 @@ function mergeBridgeIntoAgentsMd(existing, section) {
|
|
|
398
408
|
}
|
|
399
409
|
return `${body.endsWith("\n") ? body : `${body}\n`}\n${section}\n`;
|
|
400
410
|
}
|
|
401
|
-
export { buildMirrorBridgeSection, collectBridgeInputs,
|
|
411
|
+
export { capBytes as a, extractScopeGlobs as c, splitFrontmatter as d, buildMirrorBridgeSection as i, mergeBridgeIntoAgentsMd as l, PI_BRIDGE_FENCE_END as n, collectBridgeInputs as o, PI_BRIDGE_STATIC_BUDGET_BYTES as r, extractAtImports as s, PI_BRIDGE_FENCE_BEGIN as t, redactSecrets as u };
|
|
402
412
|
|
|
403
|
-
//# sourceMappingURL=pi-memory-bridge-
|
|
413
|
+
//# sourceMappingURL=pi-memory-bridge-CICIdDVP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pi-memory-bridge-CICIdDVP.js","names":[],"sources":["../src/lib/pi-memory-bridge.ts"],"sourcesContent":["import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\n/**\n * Pi memory bridge: repo instruction + user-global + auto-memory surfacing.\n *\n * Pi natively loads per-dir first-win\n * `AGENTS.override.md > AGENTS.md > AGENTS.MD > CLAUDE.md > CLAUDE.MD`\n * (agentDir global + fs-root → cwd, concatenated, no trust gate).\n * It does NOT load `.github/copilot-instructions.md`,\n * `.github/instructions/*.instructions.md` (`applyTo`), `.claude/rules/`\n * (`paths:`), `@path` imports, `CLAUDE.local.md`, `./.claude/CLAUDE.md`,\n * `~/.claude/CLAUDE.md`, or Claude auto-memory.\n *\n * Strategy (per approved plan): synthesize the static repo-wide slice into\n * the per-launch mirror's `AGENTS.md` (a Pi-native candidate, so no new\n * loader is needed) and lazy-attach path-scoped rules via the\n * `gh-router-pi` extension's `tool_result` hook (mirrors\n * `pi-code/claude-rules.ts`). Auto-memory is on-demand only (`/memory`\n * command + explicit read), never auto-injected.\n *\n * All filesystem access is best-effort: missing/unreadable files are\n * skipped, never fatal. Pure helpers are exported for unit tests.\n */\n\nexport const PI_BRIDGE_STATIC_BUDGET_BYTES = 24_000 as const\nexport const PI_BRIDGE_IMPORT_MAX_DEPTH = 4 as const\nexport const PI_BRIDGE_IMPORT_MAX_FILES = 10 as const\nexport const PI_BRIDGE_MEMORY_INDEX_MAX_LINES = 200 as const\nexport const PI_BRIDGE_MEMORY_INDEX_MAX_BYTES = 25_000 as const\nexport const PI_BRIDGE_FENCE_BEGIN = \"<!-- gh-router memory-bridge begin -->\"\nexport const PI_BRIDGE_FENCE_END = \"<!-- gh-router memory-bridge end -->\"\n\nexport interface PiBridgeScopedRule {\n /** Display path (absolute or repo-relative) for attribution. */\n file: string\n /** Rule body with frontmatter stripped. */\n body: string\n /** Glob list from `paths:` / `applyTo:` / `globs:`. Empty = unscoped. */\n globs: Array<string>\n /** Where the rule came from (for `/context` surfacing). */\n source: string\n}\n\nexport interface PiBridgeCollected {\n /** Repo-wide copilot instructions that were found (after import expansion). */\n copilotInstructions: Array<{ file: string; content: string }>\n /** Unscoped Claude rules (inlined statically). */\n unscopedRules: Array<{ file: string; content: string }>\n /** Path-scoped rules (lazy-attached, not inlined). */\n scopedRules: Array<PiBridgeScopedRule>\n /** User-global files found (capped, inlined). */\n userGlobal: Array<{ file: string; content: string }>\n /** Resolved `@` imports (appended once, deduped). */\n imports: Array<{ file: string; content: string }>\n /** Skipped files with reasons (for `/context`). */\n skipped: Array<{ file: string; reason: string }>\n}\n\nexport interface PiBridgeStats {\n staticFiles: number\n scopedRules: number\n imports: number\n skipped: number\n truncated: boolean\n}\n\nfunction byteLength(s: string): number {\n return Buffer.byteLength(s, \"utf8\")\n}\n\n/**\n * Truncate to a UTF-8 byte budget without splitting a code point, marker\n * included in the budget.\n *\n * Exported because the foreign-artifact bridge caps with the same measure Pi's\n * own limits are stated in, and `label` keeps the truncation marker honest\n * about which bridge did the cutting.\n */\nexport function capBytes(\n s: string,\n max: number,\n label = \"gh-router memory bridge\",\n): { text: string; truncated: boolean } {\n if (byteLength(s) <= max) return { text: s, truncated: false }\n // The marker is part of the budget, not extra: a caller that asserts \"≤ 8\n // KiB\" means the returned string, so the head is cut short enough for the\n // marker to fit inside `max`.\n const marker = `\\n…[truncated by ${label}]`\n const budget = Math.max(0, max - byteLength(marker))\n let low = 0\n let high = s.length\n while (low < high) {\n const mid = Math.floor((low + high) / 2)\n if (byteLength(s.slice(0, mid)) <= budget) low = mid + 1\n else high = mid\n }\n return { text: `${s.slice(0, Math.max(0, low - 1))}${marker}`, truncated: true }\n}\n\n/** Strip YAML frontmatter (`--- ... ---`) and return body + raw frontmatter. */\nexport function splitFrontmatter(raw: string): { frontmatter: string; body: string } {\n const normalized = raw.replace(/\\r\\n/g, \"\\n\")\n if (!normalized.startsWith(\"---\")) return { frontmatter: \"\", body: normalized }\n const end = normalized.indexOf(\"\\n---\", 3)\n if (end === -1) return { frontmatter: \"\", body: normalized }\n return {\n frontmatter: normalized.slice(3, end).trim(),\n body: normalized.slice(end + 4).replace(/^\\n/, \"\"),\n }\n}\n\n/**\n * Minimal frontmatter glob extraction for `paths:` / `applyTo:` / `globs:`.\n * Supports `key: \"glob\"`, `key: a, b`, and YAML lists. Case-insensitive keys.\n * Returns [] when no scoping key is present (unscoped rule).\n */\nexport function extractScopeGlobs(frontmatter: string): Array<string> {\n const out: Array<string> = []\n const lines = frontmatter.split(\"\\n\")\n let i = 0\n while (i < lines.length) {\n const line = lines[i] ?? \"\"\n const m = /^\\s*(paths|applyTo|globs)\\s*:\\s*(.*)$/i.exec(line)\n if (!m) {\n i++\n continue\n }\n const rest = (m[2] ?? \"\").trim()\n if (rest.startsWith(\"[\") && rest.endsWith(\"]\")) {\n for (const part of rest.slice(1, -1).split(\",\")) {\n const v = part.trim().replace(/^[\"']|[\"']$/g, \"\")\n if (v) out.push(v)\n }\n i++\n continue\n }\n if (rest && !rest.startsWith(\"|\") && !rest.startsWith(\">\")) {\n const v = rest.replace(/^[\"']|[\"']$/g, \"\").split(\"#\")[0]?.trim() ?? \"\"\n if (v) {\n for (const part of v.split(\",\")) {\n const p = part.trim()\n if (p) out.push(p)\n }\n }\n i++\n continue\n }\n // Block list on following indented lines (`- \"glob\"`).\n i++\n while (i < lines.length) {\n const item = lines[i] ?? \"\"\n const im = /^\\s+-\\s+(.+)$/.exec(item)\n if (!im) break\n const v = (im[1] ?? \"\").trim().replace(/^[\"']|[\"']$/g, \"\")\n if (v) out.push(v)\n i++\n }\n }\n return out\n}\n\n/** Convert a single glob to RegExp. `*` stays in-segment, `**` crosses. */\nfunction globToRegExp(glob: string): RegExp {\n const g = glob.trim().replace(/^\\.\\//, \"\").replace(/^\\/+/, \"\")\n let re = \"\"\n let k = 0\n while (k < g.length) {\n const c = g[k]\n if (c === \"*\") {\n if (g[k + 1] === \"*\") {\n // `**/` → optional any-prefix; trailing `/**` → any suffix.\n if (g[k + 2] === \"/\") {\n re += \"(?:.*/)?\"\n k += 3\n } else {\n re += \".*\"\n k += 2\n }\n } else {\n re += \"[^/]*\"\n k += 1\n }\n continue\n }\n if (c === \"?\") {\n re += \"[^/]\"\n k += 1\n continue\n }\n if (\"+()|^$.{}[]\\\\\".includes(c ?? \"\")) re += `\\\\${c}`\n else re += c\n k += 1\n }\n // Slashless patterns (`*.ts`) match basename at any depth (gitignore-style).\n if (!g.includes(\"/\")) re = `(?:.*/)?${re}`\n return new RegExp(`^${re}$`)\n}\n\n/**\n * Does a touched file match any of the rule globs?\n * `touchedAbs` may be absolute or repo-relative; `ruleRoot` scopes\n * project-relative globs. Falls back to basename matching.\n */\nexport function ruleMatchesFile(\n globs: ReadonlyArray<string>,\n touchedAbs: string,\n ruleRoot: string,\n): boolean {\n if (globs.length === 0) return false\n const candidates = new Set<string>()\n const norm = touchedAbs.replace(/\\\\/g, \"/\")\n candidates.add(norm)\n const rel = path.relative(ruleRoot, touchedAbs).replace(/\\\\/g, \"/\")\n if (rel && !rel.startsWith(\"..\")) candidates.add(rel)\n candidates.add(path.basename(touchedAbs))\n for (const glob of globs) {\n let re: RegExp\n try {\n re = globToRegExp(glob)\n } catch {\n continue\n }\n for (const c of candidates) {\n if (re.test(c)) return true\n }\n }\n return false\n}\n\n/** Extract `@path` references (whole-line or trailing) ending in a text extension. */\nexport function extractAtImports(content: string): Array<string> {\n const refs: Array<string> = []\n const seen = new Set<string>()\n const pattern = /@([~.]?[\\w./\\\\-]+\\.(?:md|txt|yaml|yml|json|toml))(?:\\s|$)/g\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim()\n if (!trimmed.includes(\"@\")) continue\n // Skip fenced-code `@` mentions (commented-out imports must not expand).\n pattern.lastIndex = 0\n let m: RegExpExecArray | null\n while ((m = pattern.exec(trimmed)) !== null) {\n const ref = m[1] ?? \"\"\n if (ref && !seen.has(ref)) {\n seen.add(ref)\n refs.push(ref)\n }\n }\n }\n return refs\n}\n\n/**\n * Resolve `@` imports against an in-memory file map (pure, testable).\n * Depth-capped, cycle-safe, budget-capped. Returns appended bodies only\n * (base files are never re-appended by the caller).\n */\nexport function resolveImportsPure(\n baseFiles: ReadonlyArray<{ file: string; content: string }>,\n readFile: (absPath: string) => string | undefined,\n homeDir: string,\n maxDepth = PI_BRIDGE_IMPORT_MAX_DEPTH,\n maxFiles = PI_BRIDGE_IMPORT_MAX_FILES,\n): Array<{ file: string; content: string }> {\n const out: Array<{ file: string; content: string }> = []\n const visited = new Set<string>()\n for (const base of baseFiles) {\n try {\n visited.add(path.resolve(base.file))\n } catch {\n visited.add(base.file)\n }\n }\n const visit = (importerAbs: string, content: string, depth: number): void => {\n if (depth > maxDepth || out.length >= maxFiles) return\n const baseDir = path.dirname(importerAbs)\n for (const ref of extractAtImports(content)) {\n if (out.length >= maxFiles) return\n let expanded = ref\n if (expanded.startsWith(\"~\")) expanded = path.join(homeDir, expanded.slice(1))\n const abs = path.isAbsolute(expanded) ? path.normalize(expanded) : path.resolve(baseDir, expanded)\n if (visited.has(abs)) continue\n visited.add(abs)\n const body = readFile(abs)\n if (body === undefined) continue\n out.push({ file: abs, content: splitFrontmatter(body).body })\n visit(abs, body, depth + 1)\n }\n }\n for (const base of baseFiles) {\n let abs = base.file\n try {\n abs = path.resolve(base.file)\n } catch {\n // keep as-is\n }\n visit(abs, base.content, 1)\n }\n return out\n}\n\n/** Cap Claude auto-memory index the way Claude Code measures it. */\nexport function capMemoryIndex(raw: string): string {\n const lines = raw.split(\"\\n\").slice(0, PI_BRIDGE_MEMORY_INDEX_MAX_LINES)\n let text = lines.join(\"\\n\")\n if (byteLength(text) > PI_BRIDGE_MEMORY_INDEX_MAX_BYTES) {\n text = capBytes(text, PI_BRIDGE_MEMORY_INDEX_MAX_BYTES).text\n }\n return text\n}\n\n/** Redact likely secrets before persisting synthesized bridge content. */\nexport function redactSecrets(text: string): string {\n return text\n .replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, \"[REDACTED private key]\")\n .replace(/(sk-(live|test)-[A-Za-z0-9_-]{8,})/g, \"[REDACTED]\")\n .replace(/(gh[pousr]_[A-Za-z0-9_]{8,})/g, \"[REDACTED]\")\n .replace(/(xox[baprs]-[A-Za-z0-9-]{8,})/g, \"[REDACTED]\")\n .replace(/eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}/g, \"[REDACTED jwt]\")\n}\n\nasync function readIfExists(file: string): Promise<string | undefined> {\n try {\n return await fs.readFile(file, \"utf8\")\n } catch {\n return undefined\n }\n}\n\n/**\n * Collect bridge inputs from disk (best-effort). Repo root is the cwd's\n * git top-level when resolvable, else cwd. Only reads files; never writes.\n */\nexport async function collectBridgeInputs(\n cwd = process.cwd(),\n homeDir = os.homedir(),\n): Promise<PiBridgeCollected> {\n const collected: PiBridgeCollected = {\n copilotInstructions: [],\n unscopedRules: [],\n scopedRules: [],\n userGlobal: [],\n imports: [],\n skipped: [],\n }\n // Repo root: walk up for `.git` (cheap, no subprocess).\n let repoRoot = cwd\n try {\n let dir = path.resolve(cwd)\n for (let depth = 0; depth < 12; depth++) {\n try {\n await fs.stat(path.join(dir, \".git\"))\n repoRoot = dir\n break\n } catch {\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n }\n } catch {\n repoRoot = cwd\n }\n\n // 1. Repo-wide Copilot instructions (+ `@` expansion later).\n const copilotFile = path.join(repoRoot, \".github\", \"copilot-instructions.md\")\n const copilotBody = await readIfExists(copilotFile)\n const baseForImports: Array<{ file: string; content: string }> = []\n if (copilotBody !== undefined) {\n collected.copilotInstructions.push({ file: copilotFile, content: splitFrontmatter(copilotBody).body })\n baseForImports.push({ file: copilotFile, content: copilotBody })\n }\n\n // 2. Path-specific Copilot instructions (applyTo).\n try {\n const dir = path.join(repoRoot, \".github\", \"instructions\")\n const entries = await fs.readdir(dir)\n for (const name of entries.sort()) {\n if (!name.endsWith(\".instructions.md\")) continue\n const file = path.join(dir, name)\n const raw = await readIfExists(file)\n if (raw === undefined) continue\n const { frontmatter, body } = splitFrontmatter(raw)\n const globs = extractScopeGlobs(frontmatter)\n if (globs.length === 0 || globs.includes(\"**\") || globs.includes(\"**/*\")) {\n collected.unscopedRules.push({ file, content: body })\n } else {\n collected.scopedRules.push({ file, body, globs, source: \"copilot-instructions\" })\n }\n }\n } catch {\n // no instructions dir — not an error\n }\n\n // 3. Claude rules (nearest `.claude/rules` at-or-above cwd).\n try {\n let dir: string | null = null\n let walk = path.resolve(cwd)\n for (let depth = 0; depth < 12; depth++) {\n try {\n await fs.stat(path.join(walk, \".claude\", \"rules\"))\n dir = path.join(walk, \".claude\", \"rules\")\n break\n } catch {\n const parent = path.dirname(walk)\n if (parent === walk) break\n walk = parent\n }\n }\n if (dir) {\n const entries = await fs.readdir(dir)\n for (const name of entries.sort()) {\n if (!name.endsWith(\".md\")) continue\n const file = path.join(dir, name)\n const raw = await readIfExists(file)\n if (raw === undefined) continue\n const { frontmatter, body } = splitFrontmatter(raw)\n if (!body.trim()) {\n collected.skipped.push({ file, reason: \"empty after frontmatter strip\" })\n continue\n }\n const globs = extractScopeGlobs(frontmatter)\n if (globs.length === 0) collected.unscopedRules.push({ file, content: body })\n else collected.scopedRules.push({ file, body, globs, source: \"claude-rules\" })\n }\n }\n } catch {\n // unreadable rules dir — skip\n }\n\n // 4. Alternate project memory `./.claude/CLAUDE.md` (deduped later\n // against Pi-native context; approval-gated by the caller).\n const dotClaude = path.join(repoRoot, \".claude\", \"CLAUDE.md\")\n const dotBody = await readIfExists(dotClaude)\n if (dotBody !== undefined && dotBody.trim()) {\n collected.unscopedRules.push({ file: dotClaude, content: splitFrontmatter(dotBody).body })\n baseForImports.push({ file: dotClaude, content: dotBody })\n }\n\n // 5. User-global files (inlined, capped downstream).\n for (const file of [\n path.join(homeDir, \".claude\", \"CLAUDE.md\"),\n path.join(homeDir, \".copilot\", \"copilot-instructions.md\"),\n ]) {\n const raw = await readIfExists(file)\n if (raw !== undefined && raw.trim()) {\n collected.userGlobal.push({ file, content: splitFrontmatter(raw).body })\n baseForImports.push({ file, content: raw })\n }\n }\n\n // 6. `@` imports across everything collected so far.\n const fileMap = new Map<string, string>()\n for (const group of [collected.copilotInstructions, collected.unscopedRules, collected.userGlobal]) {\n for (const entry of group) {\n try {\n fileMap.set(path.resolve(entry.file), entry.content)\n } catch {\n fileMap.set(entry.file, entry.content)\n }\n }\n }\n // Async BFS over `@` imports (map first, disk fallback). Seeds `seen`\n // with base files so a self-import never re-appends the base body.\n const seen = new Set<string>()\n for (const b of baseForImports) {\n try {\n seen.add(path.resolve(b.file))\n } catch {\n seen.add(b.file)\n }\n }\n const queue: Array<{ importer: string; content: string; depth: number }> = baseForImports.map((b) => ({\n importer: b.file,\n content: b.content,\n depth: 1,\n }))\n while (queue.length > 0 && collected.imports.length < PI_BRIDGE_IMPORT_MAX_FILES) {\n const head = queue.shift()\n if (!head || head.depth > PI_BRIDGE_IMPORT_MAX_DEPTH) continue\n let importerAbs = head.importer\n try {\n importerAbs = path.resolve(head.importer)\n } catch {\n // keep\n }\n const baseDir = path.dirname(importerAbs)\n for (const ref of extractAtImports(head.content)) {\n if (collected.imports.length + seen.size >= PI_BRIDGE_IMPORT_MAX_FILES) break\n let expanded = ref\n if (expanded.startsWith(\"~\")) expanded = path.join(homeDir, expanded.slice(1))\n const abs = path.isAbsolute(expanded) ? path.normalize(expanded) : path.resolve(baseDir, expanded)\n if (seen.has(abs)) continue\n seen.add(abs)\n const hit = fileMap.get(abs) ?? (await readIfExists(abs))\n if (hit === undefined) {\n collected.skipped.push({ file: abs, reason: `import of ${head.importer} not found` })\n continue\n }\n const body = splitFrontmatter(hit).body\n collected.imports.push({ file: abs, content: body })\n queue.push({ importer: abs, content: hit, depth: head.depth + 1 })\n }\n }\n\n return collected\n}\n\n/** Build the static mirror `AGENTS.md` bridge section. */\nexport function buildMirrorBridgeSection(\n collected: PiBridgeCollected,\n opts: { repoRoot?: string } = {},\n): { section: string; stats: PiBridgeStats } {\n const parts: Array<string> = [PI_BRIDGE_FENCE_BEGIN, \"\", \"# gh-router memory bridge\", \"\"]\n let truncated = false\n\n const pushCapped = (title: string, file: string, content: string, budgetLeft: () => number): void => {\n // Strip NUL bytes: a literal U+0000 in synthesized context breaks\n // strict downstream JSON consumers (workflow-preflight parse errors).\n const body = content.replaceAll(\"\\0\", \"\").trim()\n if (!body) return\n const block = `## ${title}\\n<!-- source: ${file} -->\\n\\n${body}\\n`\n const capped = capBytes(block, Math.max(0, budgetLeft()))\n parts.push(capped.text, \"\")\n if (capped.truncated) truncated = true\n }\n let used = byteLength(parts.join(\"\\n\"))\n const budgetLeft = (): number => Math.max(0, PI_BRIDGE_STATIC_BUDGET_BYTES - used - 512)\n const account = (): void => {\n used = byteLength(parts.join(\"\\n\"))\n }\n\n for (const entry of collected.copilotInstructions) {\n pushCapped(\"Copilot repo instructions\", entry.file, entry.content, budgetLeft)\n account()\n }\n for (const entry of collected.unscopedRules) {\n pushCapped(\"Unscoped project rules\", entry.file, entry.content, budgetLeft)\n account()\n }\n for (const entry of collected.userGlobal) {\n pushCapped(\"User-global instructions\", entry.file, entry.content, budgetLeft)\n account()\n }\n for (const entry of collected.imports) {\n pushCapped(\"Imported context (@path)\", entry.file, entry.content, budgetLeft)\n account()\n }\n\n if (collected.scopedRules.length > 0) {\n parts.push(\n \"## Path-scoped rules (lazy)\",\n \"\",\n \"The following rule files apply only to matching paths and are attached\",\n \"when a matching file is read/edited/written (once per session):\",\n \"\",\n )\n for (const rule of collected.scopedRules) {\n parts.push(`- \\`${rule.file.replaceAll(\"\\0\", \"\")}\\` → \\`${rule.globs.join(\", \").replaceAll(\"\\0\", \"\")}\\` (${rule.source.replaceAll(\"\\0\", \"\")})`)\n }\n parts.push(\"\")\n account()\n }\n\n if (opts.repoRoot) parts.push(`<!-- repo: ${opts.repoRoot.replaceAll(\"\\0\", \"\")} -->`, \"\")\n parts.push(PI_BRIDGE_FENCE_END, \"\")\n const section = redactSecrets(parts.join(\"\\n\")).replaceAll(\"\\0\", \"\")\n return {\n section,\n stats: {\n staticFiles:\n collected.copilotInstructions.length + collected.unscopedRules.length + collected.userGlobal.length,\n scopedRules: collected.scopedRules.length,\n imports: collected.imports.length,\n skipped: collected.skipped.length,\n truncated,\n },\n }\n}\n\n/**\n * Merge a bridge section into mirror `AGENTS.md`: append when absent,\n * replace the fenced block when present (idempotent across relaunches).\n */\nexport function mergeBridgeIntoAgentsMd(existing: string | undefined, section: string): string {\n const body = (existing ?? \"\").replace(/\\r\\n/g, \"\\n\")\n if (!body.trim()) return `${section}\\n`\n const begin = body.indexOf(PI_BRIDGE_FENCE_BEGIN)\n const end = body.indexOf(PI_BRIDGE_FENCE_END)\n if (begin !== -1 && end !== -1 && end > begin) {\n const after = body.slice(end + PI_BRIDGE_FENCE_END.length)\n return `${body.slice(0, begin)}${section}${after.startsWith(\"\\n\") ? after : `\\n${after}`}`\n }\n return `${body.endsWith(\"\\n\") ? body : `${body}\\n`}\\n${section}\\n`\n}\n\n/** Resolve the Claude auto-memory index path for a repo (on-demand read). */\nexport function claudeAutoMemoryIndex(homeDir: string, repoRoot: string): string {\n const slug = repoRoot.replace(/^\\//, \"\").replace(/\\//g, \"-\")\n return path.join(homeDir, \".claude\", \"projects\", slug || \"-\", \"memory\", \"MEMORY.md\")\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,gCAAgC;AAK7C,MAAa,wBAAwB;AACrC,MAAa,sBAAsB;AAoCnC,SAAS,WAAW,GAAmB;CACrC,OAAO,OAAO,WAAW,GAAG,MAAM;AACpC;;;;;;;;;AAUA,SAAgB,SACd,GACA,KACA,QAAQ,2BAC8B;CACtC,IAAI,WAAW,CAAC,KAAK,KAAK,OAAO;EAAE,MAAM;EAAG,WAAW;CAAM;CAI7D,MAAM,SAAS,oBAAoB,MAAM;CACzC,MAAM,SAAS,KAAK,IAAI,GAAG,MAAM,WAAW,MAAM,CAAC;CACnD,IAAI,MAAM;CACV,IAAI,OAAO,EAAE;CACb,OAAO,MAAM,MAAM;EACjB,MAAM,MAAM,KAAK,OAAO,MAAM,QAAQ,CAAC;EACvC,IAAI,WAAW,EAAE,MAAM,GAAG,GAAG,CAAC,KAAK,QAAQ,MAAM,MAAM;OAClD,OAAO;CACd;CACA,OAAO;EAAE,MAAM,GAAG,EAAE,MAAM,GAAG,KAAK,IAAI,GAAG,MAAM,CAAC,CAAC,IAAI;EAAU,WAAW;CAAK;AACjF;;AAGA,SAAgB,iBAAiB,KAAoD;CACnF,MAAM,aAAa,IAAI,QAAQ,SAAS,IAAI;CAC5C,IAAI,CAAC,WAAW,WAAW,KAAK,GAAG,OAAO;EAAE,aAAa;EAAI,MAAM;CAAW;CAC9E,MAAM,MAAM,WAAW,QAAQ,SAAS,CAAC;CACzC,IAAI,QAAQ,IAAI,OAAO;EAAE,aAAa;EAAI,MAAM;CAAW;CAC3D,OAAO;EACL,aAAa,WAAW,MAA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C7C,MAAM,QAAQ,KAAK,MAAM,MAAM,EAA0B;EACzD,OAAO,GAAG,KAAK,MAAM,GAAG,KAAK,IAAI,UAAU,MAAM,WAAW,IAAI,IAAI,QAAQ,KAAK;CACnF;CACA,OAAO,GAAG,KAAK,SAAS,IAAI,IAAI,OAAO,GAAG,KAAK,IAAI,IAAI,QAAQ;AACjE"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { $t as nativeSubagentModel, At as brainstormModel, Bt as cloudAgentToolsEnabled, D as toolbeltEnabled, E as buildToolbeltAwareness, Et as agentToolsEnabled, Jt as fleetToolsEnabled, Mn as provisionBrowserAssets, Mt as browserCompoundToolsEnabled, Nt as browserToolsEnabled, Qt as kustoToolsEnabled, T as availableToolCommands, Tt as adoToolsEnabled, Vn as provisionAndIndexColbert, Xn as DEFAULT_CLAUDE_MODEL_FALLBACKS, Xt as generalPurposeFastModel, Yt as geminiAvailable, Zt as implementerFastModel, an as standInToolEnabled, ar as resolveLeadSlugArg, c as enumerateInjectedMcpToolNames, en as resolveGeminiReviewModel, in as scribeModel, ir as pickClaudeDefault, jt as browseAgentEnabled, nn as reviewerModel, o as buildPeerAwarenessSnippet, on as workerToolsEnabled, rn as scoutModel, sn as workiqToolsEnabled, tn as reviewerFastModel, w as buildEnv, xt as disposeAdoClients } from "./peer-mcp-personas-OWsSm6To.js";
|
|
2
2
|
import { c as disposeBluebirdClients } from "./bluebird-client-BasIdv5J.js";
|
|
3
|
-
import { c as injectAllowRules, d as BUILTIN_SUBAGENT_DEFINITIONS, f as injectPeerMcpIntoMirror, g as writePeerMcpRuntimeFiles, h as workersKeyOf, i as writeInjectedSkill, l as planModeAllowRules, m as resolveGroupKeysFromMirror, n as getInjectedSkills, o as SEAMLESS_BUILTIN_TOOLS, p as resolveCodexCliBackend, s as configureServeDefaultPermissionMode, t as injectAttributionSuppressionIntoSettingsFile, u as sanitizeServeSettingsEnv } from "./attribution-settings-
|
|
3
|
+
import { c as injectAllowRules, d as BUILTIN_SUBAGENT_DEFINITIONS, f as injectPeerMcpIntoMirror, g as writePeerMcpRuntimeFiles, h as workersKeyOf, i as writeInjectedSkill, l as planModeAllowRules, m as resolveGroupKeysFromMirror, n as getInjectedSkills, o as SEAMLESS_BUILTIN_TOOLS, p as resolveCodexCliBackend, s as configureServeDefaultPermissionMode, t as injectAttributionSuppressionIntoSettingsFile, u as sanitizeServeSettingsEnv } from "./attribution-settings-BWYL2b8N.js";
|
|
4
4
|
import { c as runCommandCapture, r as killChildProcessTree, s as resolveExecutable } from "./exec-BC0MAnoA.js";
|
|
5
|
-
import { U as resolveLaunchProfile, Z as runSelfUpdate, a as setupAndServe, b as injectModelPickerSettingsFile, i as parseSharedArgs, o as sharedServerArgs, t as getClaudeCodeEnvVars, v as startKeepAwake, y as stopKeepAwake } from "./server-setup-
|
|
5
|
+
import { U as resolveLaunchProfile, Z as runSelfUpdate, a as setupAndServe, b as injectModelPickerSettingsFile, i as parseSharedArgs, o as sharedServerArgs, t as getClaudeCodeEnvVars, v as startKeepAwake, y as stopKeepAwake } from "./server-setup-ClZdV33Q.js";
|
|
6
6
|
import { n as hookLauncherDegradedWarning, r as resolveSelfInvocation } from "./self-invocation-DMUnXVGT.js";
|
|
7
7
|
import { r as getCodexVersion, t as provisionToolbelt } from "./provision-DPL8aGe2.js";
|
|
8
8
|
import { r as ensureClaudeConfigMirror, s as removeOwnClaudeConfigMirror, t as PATHS } from "./paths-CVEO8jEH.js";
|
|
@@ -1604,4 +1604,4 @@ const serve = defineCommand({
|
|
|
1604
1604
|
});
|
|
1605
1605
|
export { serve };
|
|
1606
1606
|
|
|
1607
|
-
//# sourceMappingURL=serve-
|
|
1607
|
+
//# sourceMappingURL=serve-zbQKfx1E.js.map
|