@powerhousedao/clint 6.2.3-dev.71 → 6.2.3-dev.72

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.
@@ -1,4 +1,4 @@
1
- import { T as renderSkillTemplate } from "./src-v5f_WnlY.mjs";
1
+ import { T as renderSkillTemplate } from "./src-BdwlBh04.mjs";
2
2
  import { p as slugToTitle } from "./services-9E-r0nWl.mjs";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
@@ -290,4 +290,4 @@ async function buildSkills(options) {
290
290
  //#endregion
291
291
  export { buildSkills };
292
292
 
293
- //# sourceMappingURL=build-skills-C8MlDvTC.mjs.map
293
+ //# sourceMappingURL=build-skills-Bp4IR8R_.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"build-skills-C8MlDvTC.mjs","names":[],"sources":["../src/dev/agent-profiles.ts","../src/dev/skill-builder.ts","../src/dev/skill-copier.ts","../src/dev/build-skills.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { renderSkillTemplate } from \"../index.js\";\nimport type { ResolvedBuildConfig } from \"./types.js\";\n\n/**\n * Find the first existing file across multiple include directories.\n */\nfunction findInIncludes(\n includes: string[],\n subdir: string,\n filename: string,\n): string | undefined {\n for (const dir of includes) {\n const p = path.join(dir, subdir, filename);\n if (fs.existsSync(p)) return p;\n }\n return undefined;\n}\n\n/**\n * Build agent profile instructions by rendering base+specialized template pairs.\n * Writes each profile as a Markdown file in {output}/agents/{ProfileName}.md.\n *\n * @returns Number of profiles built and any warnings.\n */\nexport function buildAgentProfiles(config: ResolvedBuildConfig): {\n count: number;\n warnings: string[];\n} {\n const log = config.logger;\n const profiles = config.agentProfiles;\n if (profiles.length === 0) return { count: 0, warnings: [] };\n\n const profilesSubdir = config.subdirs?.profiles ?? \"agent-profiles\";\n\n log(\"\\n--- Building agent instructions ---\");\n\n const allWarnings: string[] = [];\n let count = 0;\n\n for (const profile of profiles) {\n // Check all section files exist before rendering\n const sectionPaths: string[] = [];\n let missing = false;\n for (const section of profile.sections) {\n const found = findInIncludes(config.include, profilesSubdir, section);\n if (!found) {\n log(` SKIP ${profile.name}: missing section ${section}`);\n missing = true;\n break;\n }\n sectionPaths.push(found);\n }\n if (missing) continue;\n\n const agentContext = { ...config.context, agentName: profile.name };\n const renderOpts = config.customHelpers\n ? { helpers: config.customHelpers }\n : undefined;\n\n const renderedSections: string[] = [];\n for (let i = 0; i < profile.sections.length; i++) {\n const raw = fs.readFileSync(sectionPaths[i], \"utf-8\");\n const result = renderSkillTemplate(raw, agentContext, renderOpts);\n for (const w of result.warnings) {\n const msg = `${profile.name}/${profile.sections[i]}: ${w}`;\n allWarnings.push(msg);\n log(` WARN ${msg}`);\n }\n renderedSections.push(result.rendered.trim());\n }\n\n const combined = renderedSections.join(\"\\n\\n\") + \"\\n\";\n for (const out of config.output) {\n const agentsDir = path.join(out, \"agent-profiles\");\n fs.mkdirSync(agentsDir, { recursive: true });\n fs.writeFileSync(\n path.join(agentsDir, `${profile.name}.md`),\n combined,\n \"utf-8\",\n );\n }\n\n log(` OK ${profile.name} → ${profile.name}.md (${combined.length} chars)`);\n count++;\n }\n\n return { count, warnings: allWarnings };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { renderSkillTemplate, slugToTitle } from \"../index.js\";\nimport type { ResolvedBuildConfig } from \"./types.js\";\n\n/**\n * Find the first existing directory across multiple include paths.\n */\nfunction findSubdir(includes: string[], subdir: string): string | undefined {\n for (const dir of includes) {\n const p = path.join(dir, subdir);\n if (fs.existsSync(p)) return p;\n }\n return undefined;\n}\n\n/**\n * Build SKILL.md files from Handlebars templates in skills-tpl/.\n * Each skill directory produces a SKILL.md + references/ folder.\n *\n * @returns Number of skills built and any warnings.\n */\nexport function buildSkillTemplates(config: ResolvedBuildConfig): {\n count: number;\n warnings: string[];\n} {\n const log = config.logger;\n const skillsTplSubdir = config.subdirs?.skillsTpl ?? \"skills-tpl\";\n const skillsTplDir = findSubdir(config.include, skillsTplSubdir);\n\n log(\"\\n--- Building SKILL.md files (templates) ---\");\n\n if (!skillsTplDir) {\n log(\" No skills-tpl/ directory — skipping.\");\n return { count: 0, warnings: [] };\n }\n\n const skillDirs = fs\n .readdirSync(skillsTplDir, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name)\n .sort();\n\n const allWarnings: string[] = [];\n const renderOpts = config.customHelpers\n ? { helpers: config.customHelpers }\n : undefined;\n let count = 0;\n\n for (const skillName of skillDirs) {\n const skillDir = path.join(skillsTplDir, skillName);\n\n // Preamble\n const preamblePath = path.join(skillDir, \".preamble.md\");\n const preambleRaw = fs.existsSync(preamblePath)\n ? fs.readFileSync(preamblePath, \"utf-8\").trim()\n : \"\";\n let preamble = \"\";\n if (preambleRaw) {\n const r = renderSkillTemplate(preambleRaw, config.context, renderOpts);\n preamble = r.rendered;\n for (const w of r.warnings) {\n const msg = `${skillName}/.preamble.md: ${w}`;\n allWarnings.push(msg);\n log(` WARN ${msg}`);\n }\n }\n\n // Scenario files (NN.name.md)\n const scenarioFiles = fs\n .readdirSync(skillDir)\n .filter((f) => /^\\d+\\..*\\.md$/.test(f))\n .sort();\n\n // Result file\n const resultPath = path.join(skillDir, \".result.md\");\n const hasResult = fs.existsSync(resultPath);\n\n if (!preamble && scenarioFiles.length === 0 && !hasResult) {\n log(` SKIP ${skillName}: no content files found`);\n continue;\n }\n\n // Render references into memory\n const files: Map<string, string> = new Map();\n const refLinks: string[] = [];\n\n for (const scenarioFile of scenarioFiles) {\n const content = fs\n .readFileSync(path.join(skillDir, scenarioFile), \"utf-8\")\n .trim();\n const r = renderSkillTemplate(content, config.context, renderOpts);\n for (const w of r.warnings) {\n const msg = `${skillName}/${scenarioFile}: ${w}`;\n allWarnings.push(msg);\n log(` WARN ${msg}`);\n }\n files.set(path.join(\"references\", scenarioFile), r.rendered + \"\\n\");\n const label = slugToTitle(\n scenarioFile.replace(/^\\d+\\./, \"\").replace(/\\.md$/, \"\"),\n );\n refLinks.push(\n `* **${label}** [references/${scenarioFile}](references/${scenarioFile})`,\n );\n }\n\n if (hasResult) {\n const content = fs.readFileSync(resultPath, \"utf-8\").trim();\n const r = renderSkillTemplate(content, config.context, renderOpts);\n for (const w of r.warnings) {\n const msg = `${skillName}/.result.md: ${w}`;\n allWarnings.push(msg);\n log(` WARN ${msg}`);\n }\n files.set(\n path.join(\"references\", \"expected-outcome.md\"),\n r.rendered + \"\\n\",\n );\n refLinks.push(\n `* **Expected Outcome** [references/expected-outcome.md](references/expected-outcome.md)`,\n );\n }\n\n // Build SKILL.md\n const description =\n config.skillDescriptions[skillName] ?? `${slugToTitle(skillName)} tasks`;\n\n const frontmatter = [\n \"---\",\n `name: ${skillName}`,\n `description: \"${description}\"`,\n \"metadata:\",\n \" author: Powerhouse\",\n ' version: \"1.0.0\"',\n \"---\",\n ].join(\"\\n\");\n\n const sections = [preamble];\n if (refLinks.length > 0) {\n sections.push(\"## Specific tasks\\n\\n\" + refLinks.join(\"\\n\"));\n }\n\n const skillMd =\n frontmatter + \"\\n\\n\" + sections.filter(Boolean).join(\"\\n\\n\") + \"\\n\";\n files.set(\"SKILL.md\", skillMd);\n\n // Copy .cli-docs.md if present (render through Handlebars)\n const cliDocsPath = path.join(skillDir, \".cli-docs.md\");\n if (fs.existsSync(cliDocsPath)) {\n const cliDocsRaw = fs.readFileSync(cliDocsPath, \"utf-8\").trim();\n if (cliDocsRaw) {\n const r = renderSkillTemplate(cliDocsRaw, config.context, renderOpts);\n for (const w of r.warnings) {\n const msg = `${skillName}/.cli-docs.md: ${w}`;\n allWarnings.push(msg);\n log(` WARN ${msg}`);\n }\n files.set(\".cli-docs.md\", r.rendered + \"\\n\");\n }\n }\n\n // Write to all output directories\n for (const out of config.output) {\n const outputDir = path.join(out, \"skills\", skillName);\n for (const [relPath, content] of files) {\n const fullPath = path.join(outputDir, relPath);\n fs.mkdirSync(path.dirname(fullPath), { recursive: true });\n fs.writeFileSync(fullPath, content, \"utf-8\");\n }\n }\n\n log(\n ` OK ${skillName} → SKILL.md + ${scenarioFiles.length + (hasResult ? 1 : 0)} references (${skillMd.length} chars)`,\n );\n count++;\n }\n\n return { count, warnings: allWarnings };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ResolvedBuildConfig } from \"./types.js\";\n\n/**\n * Copy external skills from skills-ext/ to the output directory without processing.\n *\n * @returns Number of skills copied.\n */\nexport function copyExternalSkills(config: ResolvedBuildConfig): number {\n const log = config.logger;\n const skillsExtSubdir = config.subdirs?.skillsExt ?? \"skills-ext\";\n\n log(\"\\n--- Copying external skills ---\");\n\n // Search all include dirs for skills-ext/\n let found = false;\n let total = 0;\n\n for (const dir of config.include) {\n const skillsExtDir = path.join(dir, skillsExtSubdir);\n if (!fs.existsSync(skillsExtDir)) continue;\n found = true;\n\n const skillDirs = fs\n .readdirSync(skillsExtDir, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name)\n .sort();\n\n for (const skillName of skillDirs) {\n const srcDir = path.join(skillsExtDir, skillName);\n for (const out of config.output) {\n fs.cpSync(srcDir, path.join(out, \"skills\", skillName), {\n recursive: true,\n });\n }\n log(` OK ${skillName} → copied as-is`);\n }\n\n total += skillDirs.length;\n }\n\n if (!found) {\n log(\" No skills-ext/ directory — skipping.\");\n }\n\n return total;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { buildAgentProfiles } from \"./agent-profiles.js\";\nimport { buildSkillTemplates } from \"./skill-builder.js\";\nimport { copyExternalSkills } from \"./skill-copier.js\";\nimport type { AgentProfile, ResolvedBuildConfig } from \"./types.js\";\n\n/**\n * Path-driven skill/profile compilation (ph-clint-dev's pipeline, decoupled\n * from the old BuildConfig.cli metadata coupling). Conventions:\n *\n * <skillsDir>/ include root (default: prompts/ then agents/)\n * agent-profiles/ profile section templates\n * skills-tpl/<skill>/ Handlebars skill templates → SKILL.md\n * skills-ext/<skill>/ external skills copied as-is\n * profiles.json optional [{ name, sections: [...] }]\n *\n * Output: <outDir> (default: dist/skills).\n */\nexport interface BuildSkillsOptions {\n rootDir: string;\n skillsDir?: string;\n agentsDir?: string;\n outDir?: string;\n context?: Record<string, unknown>;\n logger?: (msg: string) => void;\n}\n\nexport interface BuildSkillsResult {\n skills: number;\n profiles: number;\n copied: number;\n warnings: string[];\n outDir: string;\n}\n\nfunction firstExisting(\n rootDir: string,\n candidates: (string | undefined)[],\n): string[] {\n const dirs: string[] = [];\n for (const candidate of candidates) {\n if (!candidate) continue;\n const abs = path.resolve(rootDir, candidate);\n if (fs.existsSync(abs)) dirs.push(abs);\n }\n return dirs;\n}\n\nfunction readProfilesManifest(include: string[]): AgentProfile[] {\n for (const dir of include) {\n const manifest = path.join(dir, \"profiles.json\");\n if (fs.existsSync(manifest)) {\n try {\n return JSON.parse(fs.readFileSync(manifest, \"utf8\")) as AgentProfile[];\n } catch {\n return [];\n }\n }\n }\n return [];\n}\n\nexport async function buildSkills(\n options: BuildSkillsOptions,\n): Promise<BuildSkillsResult> {\n const log = options.logger ?? console.log;\n const include = firstExisting(options.rootDir, [\n options.skillsDir,\n options.agentsDir,\n \"prompts\",\n \"agents\",\n ]);\n const outDir = path.resolve(options.rootDir, options.outDir ?? \"dist/skills\");\n\n if (include.length === 0) {\n log(\n \"No prompt template directories found (prompts/ or agents/) — nothing to build.\",\n );\n return { skills: 0, profiles: 0, copied: 0, warnings: [], outDir };\n }\n\n const resolved: ResolvedBuildConfig = {\n include,\n output: [outDir],\n context: { builtAt: new Date().toISOString(), ...options.context },\n agentProfiles: readProfilesManifest(include),\n skillDescriptions: {},\n clean: true,\n logger: log,\n };\n\n for (const dir of resolved.output) {\n if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true });\n }\n\n const profiles = buildAgentProfiles(resolved);\n const templates = buildSkillTemplates(resolved);\n const copied = copyExternalSkills(resolved);\n\n return {\n skills: templates.count,\n profiles: profiles.count,\n copied,\n warnings: [...profiles.warnings, ...templates.warnings],\n outDir,\n };\n}\n"],"mappings":";;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ills-Bp4IR8R_.mjs","names":[],"sources":["../src/dev/agent-profiles.ts","../src/dev/skill-builder.ts","../src/dev/skill-copier.ts","../src/dev/build-skills.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { renderSkillTemplate } from \"../index.js\";\nimport type { ResolvedBuildConfig } from \"./types.js\";\n\n/**\n * Find the first existing file across multiple include directories.\n */\nfunction findInIncludes(\n includes: string[],\n subdir: string,\n filename: string,\n): string | undefined {\n for (const dir of includes) {\n const p = path.join(dir, subdir, filename);\n if (fs.existsSync(p)) return p;\n }\n return undefined;\n}\n\n/**\n * Build agent profile instructions by rendering base+specialized template pairs.\n * Writes each profile as a Markdown file in {output}/agents/{ProfileName}.md.\n *\n * @returns Number of profiles built and any warnings.\n */\nexport function buildAgentProfiles(config: ResolvedBuildConfig): {\n count: number;\n warnings: string[];\n} {\n const log = config.logger;\n const profiles = config.agentProfiles;\n if (profiles.length === 0) return { count: 0, warnings: [] };\n\n const profilesSubdir = config.subdirs?.profiles ?? \"agent-profiles\";\n\n log(\"\\n--- Building agent instructions ---\");\n\n const allWarnings: string[] = [];\n let count = 0;\n\n for (const profile of profiles) {\n // Check all section files exist before rendering\n const sectionPaths: string[] = [];\n let missing = false;\n for (const section of profile.sections) {\n const found = findInIncludes(config.include, profilesSubdir, section);\n if (!found) {\n log(` SKIP ${profile.name}: missing section ${section}`);\n missing = true;\n break;\n }\n sectionPaths.push(found);\n }\n if (missing) continue;\n\n const agentContext = { ...config.context, agentName: profile.name };\n const renderOpts = config.customHelpers\n ? { helpers: config.customHelpers }\n : undefined;\n\n const renderedSections: string[] = [];\n for (let i = 0; i < profile.sections.length; i++) {\n const raw = fs.readFileSync(sectionPaths[i], \"utf-8\");\n const result = renderSkillTemplate(raw, agentContext, renderOpts);\n for (const w of result.warnings) {\n const msg = `${profile.name}/${profile.sections[i]}: ${w}`;\n allWarnings.push(msg);\n log(` WARN ${msg}`);\n }\n renderedSections.push(result.rendered.trim());\n }\n\n const combined = renderedSections.join(\"\\n\\n\") + \"\\n\";\n for (const out of config.output) {\n const agentsDir = path.join(out, \"agent-profiles\");\n fs.mkdirSync(agentsDir, { recursive: true });\n fs.writeFileSync(\n path.join(agentsDir, `${profile.name}.md`),\n combined,\n \"utf-8\",\n );\n }\n\n log(` OK ${profile.name} → ${profile.name}.md (${combined.length} chars)`);\n count++;\n }\n\n return { count, warnings: allWarnings };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { renderSkillTemplate, slugToTitle } from \"../index.js\";\nimport type { ResolvedBuildConfig } from \"./types.js\";\n\n/**\n * Find the first existing directory across multiple include paths.\n */\nfunction findSubdir(includes: string[], subdir: string): string | undefined {\n for (const dir of includes) {\n const p = path.join(dir, subdir);\n if (fs.existsSync(p)) return p;\n }\n return undefined;\n}\n\n/**\n * Build SKILL.md files from Handlebars templates in skills-tpl/.\n * Each skill directory produces a SKILL.md + references/ folder.\n *\n * @returns Number of skills built and any warnings.\n */\nexport function buildSkillTemplates(config: ResolvedBuildConfig): {\n count: number;\n warnings: string[];\n} {\n const log = config.logger;\n const skillsTplSubdir = config.subdirs?.skillsTpl ?? \"skills-tpl\";\n const skillsTplDir = findSubdir(config.include, skillsTplSubdir);\n\n log(\"\\n--- Building SKILL.md files (templates) ---\");\n\n if (!skillsTplDir) {\n log(\" No skills-tpl/ directory — skipping.\");\n return { count: 0, warnings: [] };\n }\n\n const skillDirs = fs\n .readdirSync(skillsTplDir, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name)\n .sort();\n\n const allWarnings: string[] = [];\n const renderOpts = config.customHelpers\n ? { helpers: config.customHelpers }\n : undefined;\n let count = 0;\n\n for (const skillName of skillDirs) {\n const skillDir = path.join(skillsTplDir, skillName);\n\n // Preamble\n const preamblePath = path.join(skillDir, \".preamble.md\");\n const preambleRaw = fs.existsSync(preamblePath)\n ? fs.readFileSync(preamblePath, \"utf-8\").trim()\n : \"\";\n let preamble = \"\";\n if (preambleRaw) {\n const r = renderSkillTemplate(preambleRaw, config.context, renderOpts);\n preamble = r.rendered;\n for (const w of r.warnings) {\n const msg = `${skillName}/.preamble.md: ${w}`;\n allWarnings.push(msg);\n log(` WARN ${msg}`);\n }\n }\n\n // Scenario files (NN.name.md)\n const scenarioFiles = fs\n .readdirSync(skillDir)\n .filter((f) => /^\\d+\\..*\\.md$/.test(f))\n .sort();\n\n // Result file\n const resultPath = path.join(skillDir, \".result.md\");\n const hasResult = fs.existsSync(resultPath);\n\n if (!preamble && scenarioFiles.length === 0 && !hasResult) {\n log(` SKIP ${skillName}: no content files found`);\n continue;\n }\n\n // Render references into memory\n const files: Map<string, string> = new Map();\n const refLinks: string[] = [];\n\n for (const scenarioFile of scenarioFiles) {\n const content = fs\n .readFileSync(path.join(skillDir, scenarioFile), \"utf-8\")\n .trim();\n const r = renderSkillTemplate(content, config.context, renderOpts);\n for (const w of r.warnings) {\n const msg = `${skillName}/${scenarioFile}: ${w}`;\n allWarnings.push(msg);\n log(` WARN ${msg}`);\n }\n files.set(path.join(\"references\", scenarioFile), r.rendered + \"\\n\");\n const label = slugToTitle(\n scenarioFile.replace(/^\\d+\\./, \"\").replace(/\\.md$/, \"\"),\n );\n refLinks.push(\n `* **${label}** [references/${scenarioFile}](references/${scenarioFile})`,\n );\n }\n\n if (hasResult) {\n const content = fs.readFileSync(resultPath, \"utf-8\").trim();\n const r = renderSkillTemplate(content, config.context, renderOpts);\n for (const w of r.warnings) {\n const msg = `${skillName}/.result.md: ${w}`;\n allWarnings.push(msg);\n log(` WARN ${msg}`);\n }\n files.set(\n path.join(\"references\", \"expected-outcome.md\"),\n r.rendered + \"\\n\",\n );\n refLinks.push(\n `* **Expected Outcome** [references/expected-outcome.md](references/expected-outcome.md)`,\n );\n }\n\n // Build SKILL.md\n const description =\n config.skillDescriptions[skillName] ?? `${slugToTitle(skillName)} tasks`;\n\n const frontmatter = [\n \"---\",\n `name: ${skillName}`,\n `description: \"${description}\"`,\n \"metadata:\",\n \" author: Powerhouse\",\n ' version: \"1.0.0\"',\n \"---\",\n ].join(\"\\n\");\n\n const sections = [preamble];\n if (refLinks.length > 0) {\n sections.push(\"## Specific tasks\\n\\n\" + refLinks.join(\"\\n\"));\n }\n\n const skillMd =\n frontmatter + \"\\n\\n\" + sections.filter(Boolean).join(\"\\n\\n\") + \"\\n\";\n files.set(\"SKILL.md\", skillMd);\n\n // Copy .cli-docs.md if present (render through Handlebars)\n const cliDocsPath = path.join(skillDir, \".cli-docs.md\");\n if (fs.existsSync(cliDocsPath)) {\n const cliDocsRaw = fs.readFileSync(cliDocsPath, \"utf-8\").trim();\n if (cliDocsRaw) {\n const r = renderSkillTemplate(cliDocsRaw, config.context, renderOpts);\n for (const w of r.warnings) {\n const msg = `${skillName}/.cli-docs.md: ${w}`;\n allWarnings.push(msg);\n log(` WARN ${msg}`);\n }\n files.set(\".cli-docs.md\", r.rendered + \"\\n\");\n }\n }\n\n // Write to all output directories\n for (const out of config.output) {\n const outputDir = path.join(out, \"skills\", skillName);\n for (const [relPath, content] of files) {\n const fullPath = path.join(outputDir, relPath);\n fs.mkdirSync(path.dirname(fullPath), { recursive: true });\n fs.writeFileSync(fullPath, content, \"utf-8\");\n }\n }\n\n log(\n ` OK ${skillName} → SKILL.md + ${scenarioFiles.length + (hasResult ? 1 : 0)} references (${skillMd.length} chars)`,\n );\n count++;\n }\n\n return { count, warnings: allWarnings };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ResolvedBuildConfig } from \"./types.js\";\n\n/**\n * Copy external skills from skills-ext/ to the output directory without processing.\n *\n * @returns Number of skills copied.\n */\nexport function copyExternalSkills(config: ResolvedBuildConfig): number {\n const log = config.logger;\n const skillsExtSubdir = config.subdirs?.skillsExt ?? \"skills-ext\";\n\n log(\"\\n--- Copying external skills ---\");\n\n // Search all include dirs for skills-ext/\n let found = false;\n let total = 0;\n\n for (const dir of config.include) {\n const skillsExtDir = path.join(dir, skillsExtSubdir);\n if (!fs.existsSync(skillsExtDir)) continue;\n found = true;\n\n const skillDirs = fs\n .readdirSync(skillsExtDir, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name)\n .sort();\n\n for (const skillName of skillDirs) {\n const srcDir = path.join(skillsExtDir, skillName);\n for (const out of config.output) {\n fs.cpSync(srcDir, path.join(out, \"skills\", skillName), {\n recursive: true,\n });\n }\n log(` OK ${skillName} → copied as-is`);\n }\n\n total += skillDirs.length;\n }\n\n if (!found) {\n log(\" No skills-ext/ directory — skipping.\");\n }\n\n return total;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { buildAgentProfiles } from \"./agent-profiles.js\";\nimport { buildSkillTemplates } from \"./skill-builder.js\";\nimport { copyExternalSkills } from \"./skill-copier.js\";\nimport type { AgentProfile, ResolvedBuildConfig } from \"./types.js\";\n\n/**\n * Path-driven skill/profile compilation (ph-clint-dev's pipeline, decoupled\n * from the old BuildConfig.cli metadata coupling). Conventions:\n *\n * <skillsDir>/ include root (default: prompts/ then agents/)\n * agent-profiles/ profile section templates\n * skills-tpl/<skill>/ Handlebars skill templates → SKILL.md\n * skills-ext/<skill>/ external skills copied as-is\n * profiles.json optional [{ name, sections: [...] }]\n *\n * Output: <outDir> (default: dist/skills).\n */\nexport interface BuildSkillsOptions {\n rootDir: string;\n skillsDir?: string;\n agentsDir?: string;\n outDir?: string;\n context?: Record<string, unknown>;\n logger?: (msg: string) => void;\n}\n\nexport interface BuildSkillsResult {\n skills: number;\n profiles: number;\n copied: number;\n warnings: string[];\n outDir: string;\n}\n\nfunction firstExisting(\n rootDir: string,\n candidates: (string | undefined)[],\n): string[] {\n const dirs: string[] = [];\n for (const candidate of candidates) {\n if (!candidate) continue;\n const abs = path.resolve(rootDir, candidate);\n if (fs.existsSync(abs)) dirs.push(abs);\n }\n return dirs;\n}\n\nfunction readProfilesManifest(include: string[]): AgentProfile[] {\n for (const dir of include) {\n const manifest = path.join(dir, \"profiles.json\");\n if (fs.existsSync(manifest)) {\n try {\n return JSON.parse(fs.readFileSync(manifest, \"utf8\")) as AgentProfile[];\n } catch {\n return [];\n }\n }\n }\n return [];\n}\n\nexport async function buildSkills(\n options: BuildSkillsOptions,\n): Promise<BuildSkillsResult> {\n const log = options.logger ?? console.log;\n const include = firstExisting(options.rootDir, [\n options.skillsDir,\n options.agentsDir,\n \"prompts\",\n \"agents\",\n ]);\n const outDir = path.resolve(options.rootDir, options.outDir ?? \"dist/skills\");\n\n if (include.length === 0) {\n log(\n \"No prompt template directories found (prompts/ or agents/) — nothing to build.\",\n );\n return { skills: 0, profiles: 0, copied: 0, warnings: [], outDir };\n }\n\n const resolved: ResolvedBuildConfig = {\n include,\n output: [outDir],\n context: { builtAt: new Date().toISOString(), ...options.context },\n agentProfiles: readProfilesManifest(include),\n skillDescriptions: {},\n clean: true,\n logger: log,\n };\n\n for (const dir of resolved.output) {\n if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true });\n }\n\n const profiles = buildAgentProfiles(resolved);\n const templates = buildSkillTemplates(resolved);\n const copied = copyExternalSkills(resolved);\n\n return {\n skills: templates.count,\n profiles: profiles.count,\n copied,\n warnings: [...profiles.warnings, ...templates.warnings],\n outDir,\n };\n}\n"],"mappings":";;;;;;;;AAQA,SAAS,eACP,UACA,QACA,UACoB;CACpB,KAAK,MAAM,OAAO,UAAU;EAC1B,MAAM,IAAI,KAAK,KAAK,KAAK,QAAQ,QAAQ;EACzC,IAAI,GAAG,WAAW,CAAC,GAAG,OAAO;CAC/B;AAEF;;;;;;;AAQA,SAAgB,mBAAmB,QAGjC;CACA,MAAM,MAAM,OAAO;CACnB,MAAM,WAAW,OAAO;CACxB,IAAI,SAAS,WAAW,GAAG,OAAO;EAAE,OAAO;EAAG,UAAU,CAAC;CAAE;CAE3D,MAAM,iBAAiB,OAAO,SAAS,YAAY;CAEnD,IAAI,uCAAuC;CAE3C,MAAM,cAAwB,CAAC;CAC/B,IAAI,QAAQ;CAEZ,KAAK,MAAM,WAAW,UAAU;EAE9B,MAAM,eAAyB,CAAC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QAAQ,SAAS,QAAQ,UAAU,aAAa;CAE5E,IAAI,QAAQ,WAAW,GAAG;EACxB,IACE,gFACF;EACA,OAAO;GAAE,QAAQ;GAAG,UAAU;GAAG,QAAQ;GAAG,UAAU,CAAC;GAAG;EAAO;CACnE;CAEA,MAAM,WAAgC;EACpC;EACA,QAAQ,CAAC,MAAM;EACf,SAAS;GAAE,0BAAS,IAAI,KAAK,EAAA,CAAE,YAAY;GAAG,GAAG,QAAQ;EAAQ;EACjE,eAAe,qBAAqB,OAAO;EAC3C,mBAAmB,CAAC;EACpB,OAAO;EACP,QAAQ;CACV;CAEA,KAAK,MAAM,OAAO,SAAS,QACzB,IAAI,GAAG,WAAW,GAAG,GAAG,GAAG,OAAO,KAAK,EAAE,WAAW,KAAK,CAAC;CAG5D,MAAM,WAAW,mBAAmB,QAAQ;CAC5C,MAAM,YAAY,oBAAoB,QAAQ;CAC9C,MAAM,SAAS,mBAAmB,QAAQ;CAE1C,OAAO;EACL,QAAQ,UAAU;EAClB,UAAU,SAAS;EACnB;EACA,UAAU,CAAC,GAAG,SAAS,UAAU,GAAG,UAAU,QAAQ;EACtD;CACF;AACF"}
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as generateConfigCommandHelp, B as createWorkdirStore, C as extractTemplateVars, D as installSkills, E as readSkills, F as resolveConfig, G as formatZodError, H as resolvePort, I as toUpperSnake, K as defineCommand, L as userConfigPath, M as configKeyToEnvVar, N as getMissingRequiredFields, O as createHelpCommand, P as localConfigPath, R as userStoreFolder, S as isSkillInvocation, T as renderSkillTemplate, U as resolveReactorDefaults, V as defaultPort, W as createLogger, _ as IDENTITY_WRAPS, a as getProjectMapping, b as DEFAULT_SKILL_INSTRUCTION, c as defineTrigger, d as createReplSession, f as parseReplInput, g as createRoutine, h as createRoutineServiceAdapter, i as defineRegistry, j as resolveWorkdir, k as createConfigCommand, l as defineCli, m as createCompositeServiceManager, n as isDocType, o as createTypes, p as tokenizeArgs, q as readPackageInfo, r as deterministicId, s as createDocumentChangeTrigger, t as buildDefaultReactor, u as initLifecycle, v as composeWraps, w as registerDefaultHelpers, x as createSkillCommands, y as createProcessManager, z as createMemoryWorkdirStore } from "./src-v5f_WnlY.mjs";
1
+ import { A as generateConfigCommandHelp, B as createWorkdirStore, C as extractTemplateVars, D as installSkills, E as readSkills, F as resolveConfig, G as formatZodError, H as resolvePort, I as toUpperSnake, K as defineCommand, L as userConfigPath, M as configKeyToEnvVar, N as getMissingRequiredFields, O as createHelpCommand, P as localConfigPath, R as userStoreFolder, S as isSkillInvocation, T as renderSkillTemplate, U as resolveReactorDefaults, V as defaultPort, W as createLogger, _ as IDENTITY_WRAPS, a as getProjectMapping, b as DEFAULT_SKILL_INSTRUCTION, c as defineTrigger, d as createReplSession, f as parseReplInput, g as createRoutine, h as createRoutineServiceAdapter, i as defineRegistry, j as resolveWorkdir, k as createConfigCommand, l as defineCli, m as createCompositeServiceManager, n as isDocType, o as createTypes, p as tokenizeArgs, q as readPackageInfo, r as deterministicId, s as createDocumentChangeTrigger, t as buildDefaultReactor, u as initLifecycle, v as composeWraps, w as registerDefaultHelpers, x as createSkillCommands, y as createProcessManager, z as createMemoryWorkdirStore } from "./src-BdwlBh04.mjs";
2
2
  import { a as scanProjects, c as checkCommand, d as isPortFree, f as getSchemaFields, i as PROJECT_INDICATORS, l as checkPort, n as defineService, p as slugToTitle, r as resolveServiceName, t as createServiceManager, u as checkWorkdir } from "./services-9E-r0nWl.mjs";
3
3
  import { a as getGhostSuggestion, i as getCompletions, n as applyCompletion, o as formatStreamChunk, r as getCompletionSuffix, s as renderStream, t as renderMarkdown } from "./markdown-D-sP2zw_.mjs";
4
4
  import { a as captureRoutePrefix, i as buildSwitchboardRoutes, r as buildSwitchboardRouteSpecs, s as isWsEndpointType, t as buildServiceRoutes } from "./proxy-routes-DP3ztsnS.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"mastra-runner.d.mts","names":[],"sources":["../../src/runners/mastra-runner.ts"],"mappings":";;;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;YAGhC,kBAAkB,EAAE,aAAa;;YAEjC,aAAa,EAAE,cAAc;YAC7B,kBAAkB,YAAY;;;qBAI7B,eAAa,EAAA;;;;;;GASxB,EAAA,KAAA;YAEU,gBAAgB,EAAE,aAAa;QAEnC;YACI;IACR;MACE,MAAM;MACN,SAAS;;;;KA8BV;EAAgB;EAAc;;;;wBAInB,mBAAmB,UAAU;YAqCjC,mBAAmB,aAAa;wBAmNtB,IACpB,MAAM,YACN,KAAK,gBACJ,QAAQ;qBAIE,cAAK;;wBAGI,MACpB,MAAM,YACN,KAAK,gBACJ"}
@@ -61,6 +61,142 @@ async function attachRemoteReactor(options) {
61
61
  };
62
62
  }
63
63
  //#endregion
64
+ //#region src/integrations/powerhouse/reactor-tools.ts
65
+ const DRIVE_TYPE = "powerhouse/document-drive";
66
+ function isRecord(v) {
67
+ return typeof v === "object" && v !== null && !Array.isArray(v);
68
+ }
69
+ /** The global scope's state, whichever way the client shaped `state`. */
70
+ function globalState(doc) {
71
+ const state = doc.state;
72
+ if (isRecord(state.global)) return state.global;
73
+ return state;
74
+ }
75
+ /**
76
+ * A one-line view of a state object: its scalar fields, and the length of
77
+ * each array field — enough to pick a document from a list without reading
78
+ * every one.
79
+ */
80
+ function summarizeState(state, maxKeys = 16) {
81
+ const out = {};
82
+ let keys = 0;
83
+ for (const [key, value] of Object.entries(state)) {
84
+ if (keys >= maxKeys) break;
85
+ if (value === null || value === void 0) continue;
86
+ if (Array.isArray(value)) {
87
+ out[`${key}Count`] = value.length;
88
+ keys++;
89
+ } else if (typeof value !== "object") {
90
+ out[key] = typeof value === "string" && value.length > 120 ? `${value.slice(0, 117)}…` : value;
91
+ keys++;
92
+ } else if (isRecord(value) && typeof value.name === "string") {
93
+ out[key] = value.name;
94
+ keys++;
95
+ }
96
+ }
97
+ return out;
98
+ }
99
+ function headerOf(doc) {
100
+ const h = doc.header;
101
+ return {
102
+ id: h.id,
103
+ slug: h.slug ?? void 0,
104
+ name: h.name ?? void 0,
105
+ documentType: h.documentType,
106
+ lastModified: h.lastModifiedAtUtcIso ?? void 0
107
+ };
108
+ }
109
+ async function collect(first, max) {
110
+ const out = [...first.results];
111
+ let page = first;
112
+ while (out.length < max && page.next && page.results.length > 0) {
113
+ page = await page.next();
114
+ out.push(...page.results);
115
+ }
116
+ return out.slice(0, max);
117
+ }
118
+ function truncateJson(value, maxChars) {
119
+ const json = JSON.stringify(value, null, 1);
120
+ if (json.length <= maxChars) return {
121
+ json,
122
+ truncated: false
123
+ };
124
+ return {
125
+ json: `${json.slice(0, maxChars)}…`,
126
+ truncated: true
127
+ };
128
+ }
129
+ /**
130
+ * Build the Mastra tool set over an attached reactor client. Mastra is
131
+ * imported lazily, like the rest of clint's Mastra integration.
132
+ */
133
+ async function createReactorReadTools(client, options = {}) {
134
+ const { createTool } = await import("@mastra/core/tools");
135
+ const maxStateChars = options.maxStateChars ?? 24e3;
136
+ const maxList = options.maxList ?? 200;
137
+ return {
138
+ listDrives: createTool({
139
+ id: "listDrives",
140
+ description: "List the drives on the reactor this agent is attached to: id, slug, name and how many nodes (documents and folders) each holds. Call this first when you do not know a drive id.",
141
+ inputSchema: z.object({}),
142
+ execute: async () => {
143
+ return { drives: (await collect(await client.find({ type: DRIVE_TYPE }, void 0, {
144
+ cursor: "0",
145
+ limit: 100
146
+ }), 100)).map((d) => {
147
+ const state = globalState(d);
148
+ const nodes = Array.isArray(state.nodes) ? state.nodes.length : 0;
149
+ return {
150
+ ...headerOf(d),
151
+ name: typeof state.name === "string" && state.name || d.header.name,
152
+ nodeCount: nodes
153
+ };
154
+ }) };
155
+ }
156
+ }),
157
+ listDocuments: createTool({
158
+ id: "listDocuments",
159
+ description: "List documents on the reactor, optionally within one drive (driveId) and/or of one document type (e.g. sektar/invoice). Returns each document's id, slug, name, type and a one-line summary of its state (scalar fields plus array lengths). Use getDocument for the full state.",
160
+ inputSchema: z.object({
161
+ driveId: z.string().optional().describe("Drive id to list within (from listDrives). Omit for all."),
162
+ documentType: z.string().optional().describe("Document type to filter by, e.g. sektar/invoice."),
163
+ limit: z.number().int().positive().max(maxList).optional().describe(`Maximum documents to return (default 100, max ${maxList}).`)
164
+ }),
165
+ execute: async (input) => {
166
+ const limit = Math.min(input.limit ?? 100, maxList);
167
+ const docs = (await collect(await client.find({
168
+ ...input.documentType ? { type: input.documentType } : {},
169
+ ...input.driveId ? { parentId: input.driveId } : {}
170
+ }, void 0, {
171
+ cursor: "0",
172
+ limit: Math.min(limit, 100)
173
+ }), limit)).filter((d) => d.header.documentType !== DRIVE_TYPE || !!input.documentType);
174
+ return {
175
+ count: docs.length,
176
+ documents: docs.map((d) => ({
177
+ ...headerOf(d),
178
+ summary: summarizeState(globalState(d))
179
+ }))
180
+ };
181
+ }
182
+ }),
183
+ getDocument: createTool({
184
+ id: "getDocument",
185
+ description: "Read one document by id or slug: its header and full global state as JSON (truncated past a size cap; say so if `truncated` is true).",
186
+ inputSchema: z.object({ identifier: z.string().describe("Document id or slug.") }),
187
+ execute: async (input) => {
188
+ const doc = await client.get(input.identifier);
189
+ const { json, truncated } = truncateJson(globalState(doc), maxStateChars);
190
+ return {
191
+ ...headerOf(doc),
192
+ state: json,
193
+ truncated
194
+ };
195
+ }
196
+ })
197
+ };
198
+ }
199
+ //#endregion
64
200
  //#region src/runners/agent-provider.ts
65
201
  function createDemoProvider(agentName) {
66
202
  return {
@@ -95,14 +231,16 @@ async function createMastraProvider(options) {
95
231
  id: options.agentName,
96
232
  name: options.agentName,
97
233
  instructions: options.instructions,
98
- model: mastraModelConfig(options.model, options.apiKey)
234
+ model: mastraModelConfig(options.model, options.apiKey),
235
+ ...options.tools ? { tools: options.tools } : {}
99
236
  });
100
237
  return {
101
238
  modelId: options.model,
102
239
  async *stream(prompt, streamOptions) {
103
240
  const result = await agent.stream(prompt, {
104
241
  memory: void 0,
105
- threadId: streamOptions.threadId
242
+ threadId: streamOptions.threadId,
243
+ maxSteps: options.maxSteps ?? 8
106
244
  });
107
245
  yield* mapMastraStream(result.fullStream);
108
246
  }
@@ -240,13 +378,17 @@ async function serveAgent(host, ctx) {
240
378
  });
241
379
  console.log(`[${resolved.name}] reactor attached: ${attachment.endpoint}`);
242
380
  let provider;
243
- if (config.model) provider = await createMastraProvider({
244
- agentName: resolved.name,
245
- instructions: config.instructions ?? `You are ${resolved.name}, a Powerhouse project agent.`,
246
- model: config.model,
247
- apiKey: config.apiKey
248
- });
249
- else provider = createDemoProvider(resolved.name);
381
+ if (config.model) {
382
+ const tools = await createReactorReadTools(attachment.client);
383
+ console.log(`[${resolved.name}] reactor tools: ${Object.keys(tools).join(", ")}`);
384
+ provider = await createMastraProvider({
385
+ agentName: resolved.name,
386
+ instructions: config.instructions ?? `You are ${resolved.name}, a Powerhouse project agent.`,
387
+ model: config.model,
388
+ apiKey: config.apiKey,
389
+ tools
390
+ });
391
+ } else provider = createDemoProvider(resolved.name);
250
392
  const server = createServer((req, res) => {
251
393
  (async () => {
252
394
  const url = (req.url ?? "/").split("?")[0];
@@ -358,7 +500,7 @@ const serve = run;
358
500
  /** `build` — skill + agent-profile compilation (ph-clint-dev's pipeline). */
359
501
  async function build(host, ctx) {
360
502
  const config = host.config ?? {};
361
- const { buildSkills } = await import("../build-skills-C8MlDvTC.mjs");
503
+ const { buildSkills } = await import("../build-skills-Bp4IR8R_.mjs");
362
504
  const result = await buildSkills({
363
505
  rootDir: ctx.projectRoot,
364
506
  skillsDir: config.prompts?.skillsDir,
@@ -1 +1 @@
1
- {"version":3,"file":"mastra-runner.mjs","names":[],"sources":["../../src/integrations/powerhouse/remote-reactor.ts","../../src/runners/agent-provider.ts","../../src/runners/mastra-runner.ts"],"sourcesContent":["import type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport type { ReactorProtocol } from \"@powerhousedao/host-core\";\n\n/**\n * P5.5 — the agent host's reactor is a REMOTE attach: a running switchboard,\n * reached over GraphQL, instead of the embedded PGlite reactor glued to the\n * CLI's lifetime. N agents attach to ONE reactor as clients; the switchboard\n * outlives agent sessions. The agent DEPENDS on the switchboard — an\n * unreachable remote fails the attach loudly with the start hint, it never\n * auto-starts one.\n */\n\nexport interface AttachRemoteReactorOptions {\n /**\n * Where the switchboard lives: its GraphQL endpoint\n * (`http://localhost:4001/graphql`), a drive url (`…/d/<drive>`), or a bare\n * origin — the endpoint is derived.\n */\n url: string;\n /** Document models the client signs/reduces with. */\n documentModels: DocumentModelModule[];\n /**\n * What this agent expects of the fleet it joins (the host file's\n * reactor.protocol). Reachability and inspection facts are checked at\n * attach; flag-level comparison engages once the inspection subgraph\n * exposes the enforcement flags (upstream note in the phase-5 WBS) — until\n * then the expectation is carried for the error message and future use.\n */\n expectedProtocol?: ReactorProtocol;\n /** Bearer for authenticated switchboards; omitted = unauthenticated. */\n token?: string;\n /** Reachability probe budget. */\n timeoutMs?: number;\n}\n\nexport interface RemoteReactorAttachment {\n /** The derived GraphQL endpoint actually dialed. */\n endpoint: string;\n /** IReactorClient-compatible GraphQL client (reactor-browser). */\n client: unknown;\n /** Remote facts from the inspection subgraph, when it answers. */\n remoteInfo?: Record<string, unknown>;\n}\n\n/** Derive the GraphQL endpoint from the accepted url spellings. */\nexport function deriveGraphqlEndpoint(url: string): string {\n const parsed = new URL(url);\n if (parsed.pathname.includes(\"/d/\")) {\n return `${parsed.origin}/graphql`;\n }\n if (parsed.pathname.replace(/\\/$/, \"\").endsWith(\"/graphql\")) {\n return `${parsed.origin}${parsed.pathname.replace(/\\/$/, \"\")}`;\n }\n const base = parsed.pathname.replace(/\\/$/, \"\");\n return `${parsed.origin}${base}/graphql`;\n}\n\nasync function probeEndpoint(\n endpoint: string,\n timeoutMs: number,\n): Promise<void> {\n try {\n // A GraphQL endpoint answers POST; any HTTP response (even 400) proves\n // the server is listening. Only transport failure means unreachable.\n await fetch(endpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ query: \"{ __typename }\" }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (cause) {\n throw new Error(\n `Cannot attach to the reactor at ${endpoint}: the switchboard is not ` +\n `answering. The agent depends on a RUNNING switchboard and never ` +\n `starts one — start it first (e.g. \\`ph run switchboard\\`, ` +\n `\\`ph vetra\\`, or the compound that members both) and retry.`,\n { cause },\n );\n }\n}\n\n/** Read the inspection subgraph's info when it answers (dev switchboards\n * under the OPEN policy serve it); absence is not an attach failure. */\nasync function readRemoteInfo(\n endpoint: string,\n token: string | undefined,\n timeoutMs: number,\n): Promise<Record<string, unknown> | undefined> {\n try {\n const res = await fetch(`${endpoint}/inspection`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n body: JSON.stringify({\n query: \"query ReactorInspectionInfo { inspection { info } }\",\n }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!res.ok) return undefined;\n const body = (await res.json()) as {\n data?: { inspection?: { info?: Record<string, unknown> } };\n };\n return body.data?.inspection?.info;\n } catch {\n return undefined;\n }\n}\n\nexport async function attachRemoteReactor(\n options: AttachRemoteReactorOptions,\n): Promise<RemoteReactorAttachment> {\n const timeoutMs = options.timeoutMs ?? 10_000;\n const endpoint = deriveGraphqlEndpoint(options.url);\n\n await probeEndpoint(endpoint, timeoutMs);\n const remoteInfo = await readRemoteInfo(endpoint, options.token, timeoutMs);\n\n const { GraphQLReactorClient } =\n await import(\"@powerhousedao/reactor-browser/graphql-client\");\n const client = new GraphQLReactorClient({\n url: endpoint,\n documentModels: options.documentModels,\n ...(options.token\n ? { tokenProvider: () => Promise.resolve(options.token) }\n : {}),\n } as never);\n\n return { endpoint, client, remoteInfo };\n}\n","import type { StreamChunk } from \"../core/types.js\";\n\n/**\n * The mastra-runner's provider seam: a real Mastra agent when a model is\n * configured, and a DEMO provider otherwise — same posture as the ph-rupert\n * example: the host answers without an API key, loudly saying it is the demo.\n */\nexport interface AgentStreamProvider {\n readonly modelId: string;\n stream(\n prompt: string,\n options: { threadId: string },\n ): AsyncIterable<StreamChunk>;\n}\n\nexport function createDemoProvider(agentName: string): AgentStreamProvider {\n return {\n modelId: \"demo\",\n // eslint-disable-next-line require-yield -- single-chunk generator below\n async *stream(prompt: string) {\n const text =\n `You said: ${JSON.stringify(prompt.slice(0, 2000))}. ` +\n `I'm the ${agentName} demo agent — configure a model (host config ` +\n `\\`model\\` and \\`apiKey\\`) for real responses.`;\n yield { type: \"text-delta\", text } as StreamChunk;\n },\n };\n}\n\nexport interface MastraProviderOptions {\n agentName: string;\n instructions: string;\n /** Mastra model-router string, e.g. `anthropic/claude-sonnet-4-5`. */\n model: string;\n /** The provider's API key (resolved host config). Absent: Mastra's model\n * router looks the provider's key up in the environment itself. */\n apiKey?: string;\n}\n\n/** A model-router id names its provider: `<provider>/<model…>`. */\nfunction isRouterModelId(model: string): model is `${string}/${string}` {\n const slash = model.indexOf(\"/\");\n return slash > 0 && slash < model.length - 1;\n}\n\n/** Mastra's model config: the router id alone, or with an explicit key\n * (Mastra's OpenAI-compatible config object). */\nexport function mastraModelConfig(\n model: string,\n apiKey: string | undefined,\n): string | { id: `${string}/${string}`; apiKey: string } {\n if (apiKey === undefined) return model;\n if (!isRouterModelId(model)) {\n throw new Error(\n `model \"${model}\" is not a model-router id (\"<provider>/<model>\"), so an apiKey cannot be attached to it.`,\n );\n }\n return { id: model, apiKey };\n}\n\nexport async function createMastraProvider(\n options: MastraProviderOptions,\n): Promise<AgentStreamProvider> {\n const { Agent } = await import(\"@mastra/core/agent\");\n const { mapMastraStream } = await import(\"../integrations/mastra/stream.js\");\n const agent = new Agent({\n id: options.agentName,\n name: options.agentName,\n instructions: options.instructions,\n // With an apiKey the router uses it; without, it resolves the\n // provider's key from the environment.\n model: mastraModelConfig(options.model, options.apiKey),\n });\n return {\n modelId: options.model,\n async *stream(prompt: string, streamOptions: { threadId: string }) {\n const result = await agent.stream(prompt, {\n memory: undefined,\n threadId: streamOptions.threadId,\n } as never);\n yield* mapMastraStream(\n (result as { fullStream: AsyncIterable<unknown> }).fullStream as never,\n );\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { createServer, type Server } from \"node:http\";\nimport {\n defaultUserDataDir,\n probeRun,\n resolveUserDataPlaceholders,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport { defineHostSchemas } from \"@powerhousedao/host-core/schema\";\nimport { z } from \"zod\";\nimport {\n attachRemoteReactor,\n type RemoteReactorAttachment,\n} from \"../integrations/powerhouse/remote-reactor.js\";\nimport {\n createDemoProvider,\n createMastraProvider,\n type AgentStreamProvider,\n} from \"./agent-provider.js\";\n\n/**\n * mastra-runner (P5.6): the headless agent host. Its reactor is a REMOTE\n * attach — a lone `remote` backend whose `remote.url` is the running\n * switchboard's GraphQL endpoint (typically the output token\n * `switchboard.endpoints.graphql`, resolved before the verb runs); it depends\n * on that switchboard and never starts one. `run`/`serve` expose an\n * OpenAI-compatible chat-completions endpoint (streaming SSE +\n * non-streaming, stateless baseline — the caller owns session state);\n * without a configured model it answers as the DEMO agent. `build` compiles\n * skills and agent profiles (ph-clint-dev's pipeline, ported).\n */\n\nexport const kind = \"reactor\";\n\n/** The verbs this runner exports (`promptFromMessages` is a helper). */\nexport const verbs = [\"run\", \"serve\", \"build\"] as const;\n\n/** The token a host writes for the switchboard endpoint (error hints). */\nconst REMOTE_URL_HINT =\n 'remote: { url: switchboard.endpoints.graphql } (from ../switchboard/outputs.js), or literally { url: { $output: { host: \"switchboard\", path: [\"endpoints\", \"graphql\"] } } }';\n\n/**\n * The agent host, from one definition in two forms: DECLARED (`apiKey` may\n * be a token, e.g. `{ $env: \"OPENROUTER_API_KEY\" }`; what host.js authors\n * write) and RESOLVED (what the verbs receive).\n *\n * `config` holds OPERATOR SETTINGS only (rewire R5): `model` selects the\n * LLM, `apiKey` authenticates it, `instructions`/`prompts` shape the agent.\n * Framework KNOBS (maxSteps, cacheControl, memory tuning, untilIdle, tool\n * allowlists) stay in code, and the agent CARD (description/image) comes\n * from the host's `profile`, not here.\n */\nconst schemas = defineHostSchemas((s) => {\n const agentHostConfigSchema = z.strictObject({\n /** Mastra model router id (e.g. \"openrouter/<vendor>/<model>\"). Absent:\n * the runner answers as the demo agent. */\n model: z.string().min(1).optional(),\n /** The model provider's API key. A SECRET: write it as\n * `{ $env: \"OPENROUTER_API_KEY\" }` so it comes from the environment at\n * resolve time and never sits in the host file. Passed to the provider\n * as given; the runner does not read `process.env` itself. Absent, the\n * Mastra model router falls back to its own provider env lookup. */\n apiKey: s.tokenable(z.string().min(1)).optional(),\n instructions: z.string().optional(),\n /** `build`: skill + agent-profile compilation inputs and output. */\n prompts: z\n .strictObject({\n skillsDir: z.string().min(1).optional(),\n agentsDir: z.string().min(1).optional(),\n outDir: z.string().min(1).optional(),\n })\n .optional(),\n });\n /** `reactor` is the base block: a lone `remote` backend naming the\n * switchboard to attach to. `runner` takes no options beyond the base. */\n return s.reactorHostSchema.extend({\n runner: s.runnerBaseSchema.strict(),\n config: agentHostConfigSchema.optional(),\n });\n});\n/** Declared form: what a host file may contain before resolution. */\nexport const declaredHostSchema = schemas.declaredHostSchema;\n/** Resolved form: what the verbs receive (and `validateHost` checks). */\nexport const hostSchema = schemas.hostSchema;\n\n/** What an agent host.js author writes. */\nexport type MastraHostInput = z.input<typeof declaredHostSchema>;\n/** What the verbs receive. */\nexport type MastraHost = z.output<typeof hostSchema>;\nexport type AgentHostConfig = NonNullable<MastraHostInput[\"config\"]>;\n\n/** What serving the agent produces: where its OpenAI-compatible API is\n * actually bound. */\nexport const outputsSchema = z.strictObject({\n /** `http://<bound host>:<bound port>`. */\n origin: z.url(),\n endpoints: z.strictObject({\n /** OpenAI-compatible base URL (`<origin>/v1`). */\n openai: z.url(),\n /** Readiness probe (`<origin>/ready`). */\n ready: z.url(),\n }),\n});\n\nexport type MastraOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/clint/mastra-runner\": {\n host: MastraHostInput;\n outputs: MastraOutputs;\n };\n }\n}\n\nconst DEFAULT_AGENT_PORT = 4910;\n\n/** The remote backend's switchboard url, as resolved before the verb. The\n * sibling-reference resolver (`remote: { host }`) is gone: an output token\n * names the endpoint the switchboard actually bound. */\nfunction remoteUrl(host: MastraHost): string {\n const backends = Object.values(host.reactor?.backends ?? {});\n const remote = backends.find((b) => b.kind === \"remote\");\n if (!remote) {\n throw new Error(\n `hosts/${host.name}: an agent host attaches to a RUNNING switchboard — ` +\n `declare a remote backend, e.g. reactor.backends.switchboard = ` +\n `{ kind: \"remote\", ${REMOTE_URL_HINT} }.`,\n );\n }\n const url = remote.remote?.url;\n if (typeof url !== \"string\" || url.length === 0) {\n throw new Error(\n `hosts/${host.name}: the remote backend needs the switchboard's ` +\n `GraphQL url: ${REMOTE_URL_HINT}.`,\n );\n }\n return url;\n}\n\ntype ChatMessage = { role: string; content: unknown };\n\n/** Baseline stateless mapping: the last user message is the prompt (string\n * or OpenAI content-part arrays flattened to their text parts). */\nexport function promptFromMessages(messages: ChatMessage[]): string {\n const lastUser = [...messages].reverse().find((m) => m.role === \"user\");\n const content = lastUser?.content;\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((part: { type?: string; text?: string }) =>\n part.type === \"text\" ? (part.text ?? \"\") : \"\",\n )\n .join(\"\");\n }\n return \"\";\n}\n\nasync function readBody(\n req: import(\"node:http\").IncomingMessage,\n): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction completionChunk(\n id: string,\n model: string,\n delta: Record<string, unknown>,\n finish: string | null,\n): string {\n return `data: ${JSON.stringify({\n id,\n object: \"chat.completion.chunk\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [{ index: 0, delta, finish_reason: finish }],\n })}\\n\\n`;\n}\n\nexport type AgentServeHandle = RunnerHandle<MastraOutputs>;\n\nasync function serveAgent(\n host: MastraHost,\n ctx: RunnerContext,\n): Promise<AgentServeHandle> {\n const userData = defaultUserDataDir(ctx.projectRoot, ctx.env);\n const resolved = resolveUserDataPlaceholders(host, userData);\n const config = resolved.config ?? {};\n const port =\n typeof resolved.runner.port === \"number\"\n ? resolved.runner.port\n : DEFAULT_AGENT_PORT;\n\n // Single-instance lock: refuse before attaching or binding when the record\n // start-run wrote for a running instance of this host is live.\n const projectName = (() => {\n try {\n return (\n (\n JSON.parse(\n fs.readFileSync(`${ctx.projectRoot}/package.json`, \"utf8\"),\n ) as { name?: string }\n ).name ?? host.name\n );\n } catch {\n return host.name;\n }\n })();\n const probe = probeRun(ctx.projectRoot, resolved.name, projectName);\n if (probe.status === \"live\") {\n throw new Error(\n `${resolved.name} is already running (pid ${probe.record.pid}).`,\n );\n }\n\n // The reactor: attach, loudly, before serving anything.\n const attachment: RemoteReactorAttachment = await attachRemoteReactor({\n url: remoteUrl(resolved),\n documentModels: [],\n });\n console.log(`[${resolved.name}] reactor attached: ${attachment.endpoint}`);\n\n // The agent: real Mastra when a model is configured, demo otherwise.\n let provider: AgentStreamProvider;\n if (config.model) {\n provider = await createMastraProvider({\n agentName: resolved.name,\n instructions:\n config.instructions ??\n `You are ${resolved.name}, a Powerhouse project agent.`,\n model: config.model,\n apiKey: config.apiKey,\n });\n } else {\n provider = createDemoProvider(resolved.name);\n }\n\n const server: Server = createServer((req, res) => {\n void (async () => {\n const url = (req.url ?? \"/\").split(\"?\")[0];\n if (req.method === \"GET\" && url === \"/ready\") {\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ ok: true, agent: resolved.name }));\n return;\n }\n if (req.method === \"GET\" && url === \"/v1/models\") {\n // The agent card: id + model, plus description/image from the host's\n // profile (rewire R5 — identity lives in profile, not config).\n const profile = resolved.profile ?? {};\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify({\n object: \"list\",\n data: [\n {\n id: provider.modelId,\n object: \"model\",\n owned_by: \"clint\",\n name: profile.name ?? resolved.name,\n ...(profile.description\n ? { description: profile.description }\n : {}),\n ...(profile.icon ? { image: profile.icon } : {}),\n },\n ],\n }),\n );\n return;\n }\n if (req.method === \"POST\" && url === \"/v1/chat/completions\") {\n let body: { messages?: ChatMessage[]; stream?: boolean };\n try {\n body = JSON.parse(await readBody(req)) as typeof body;\n } catch {\n res.writeHead(400, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: { message: \"invalid JSON body\" } }));\n return;\n }\n const prompt = promptFromMessages(body.messages ?? []);\n const id = `chatcmpl-${randomUUID()}`;\n const threadId = randomUUID(); // stateless baseline: the caller owns sessions\n\n if (body.stream) {\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-store\",\n connection: \"keep-alive\",\n });\n res.write(\n completionChunk(id, provider.modelId, { role: \"assistant\" }, null),\n );\n try {\n for await (const chunk of provider.stream(prompt, { threadId })) {\n if (chunk.type === \"text-delta\" && chunk.text) {\n res.write(\n completionChunk(\n id,\n provider.modelId,\n { content: chunk.text },\n null,\n ),\n );\n } else if (chunk.type === \"error\") {\n res.write(\n completionChunk(\n id,\n provider.modelId,\n {\n content: `\\n[agent error] ${String((chunk as { message?: unknown }).message ?? \"unknown\")}`,\n },\n null,\n ),\n );\n }\n }\n res.write(completionChunk(id, provider.modelId, {}, \"stop\"));\n res.write(\"data: [DONE]\\n\\n\");\n } finally {\n res.end();\n }\n return;\n }\n\n let text = \"\";\n for await (const chunk of provider.stream(prompt, { threadId })) {\n if (chunk.type === \"text-delta\" && chunk.text) text += chunk.text;\n }\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id,\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model: provider.modelId,\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: text },\n finish_reason: \"stop\",\n },\n ],\n }),\n );\n return;\n }\n res.writeHead(404, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: { message: `no route: ${url}` } }));\n })().catch((error: unknown) => {\n if (!res.headersSent) res.writeHead(500);\n res.end(JSON.stringify({ error: { message: String(error) } }));\n });\n });\n\n const ready = new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, \"127.0.0.1\", () => resolve());\n });\n await ready;\n // The actual bound port (a requested 0 means \"any free port\").\n const boundPort = (server.address() as { port: number }).port;\n const origin = `http://127.0.0.1:${boundPort}`;\n const outputs = outputsSchema.parse({\n origin,\n endpoints: { openai: `${origin}/v1`, ready: `${origin}/ready` },\n });\n console.log(\n `[${resolved.name}] agent API (OpenAI-compatible): ${outputs.endpoints.openai} (model: ${provider.modelId})`,\n );\n\n // No run record here: standalone `ph run` (start-run) publishes `outputs`\n // in the v2 record because this module exports `outputsSchema`, and a\n // compound records its members itself. One writer per record.\n return {\n outputs,\n ready,\n shutdown: async () => {\n await new Promise((resolve) => server.close(resolve));\n },\n };\n}\n\nexport async function run(\n host: MastraHost,\n ctx: RunnerContext,\n): Promise<AgentServeHandle> {\n return serveAgent(host, ctx);\n}\n\nexport const serve = run;\n\n/** `build` — skill + agent-profile compilation (ph-clint-dev's pipeline). */\nexport async function build(\n host: MastraHost,\n ctx: RunnerContext,\n): Promise<void> {\n const config = host.config ?? {};\n const { buildSkills } = await import(\"../dev/build-skills.js\");\n const result = await buildSkills({\n rootDir: ctx.projectRoot,\n skillsDir: config.prompts?.skillsDir,\n agentsDir: config.prompts?.agentsDir,\n outDir: config.prompts?.outDir,\n });\n console.log(\n `[${host.name}] compiled ${result.skills} skill(s), ${result.profiles} profile(s) → ${result.outDir}`,\n );\n}\n"],"mappings":";;;;;;;;AA6CA,SAAgB,sBAAsB,KAAqB;CACzD,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,IAAI,OAAO,SAAS,SAAS,KAAK,GAChC,OAAO,GAAG,OAAO,OAAO;CAE1B,IAAI,OAAO,SAAS,QAAQ,OAAO,EAAE,CAAC,CAAC,SAAS,UAAU,GACxD,OAAO,GAAG,OAAO,SAAS,OAAO,SAAS,QAAQ,OAAO,EAAE;CAE7D,MAAM,OA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sources":["../../src/integrations/powerhouse/remote-reactor.ts","../../src/integrations/powerhouse/reactor-tools.ts","../../src/runners/agent-provider.ts","../../src/runners/mastra-runner.ts"],"sourcesContent":["import type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport type { ReactorProtocol } from \"@powerhousedao/host-core\";\n\n/**\n * P5.5 — the agent host's reactor is a REMOTE attach: a running switchboard,\n * reached over GraphQL, instead of the embedded PGlite reactor glued to the\n * CLI's lifetime. N agents attach to ONE reactor as clients; the switchboard\n * outlives agent sessions. The agent DEPENDS on the switchboard — an\n * unreachable remote fails the attach loudly with the start hint, it never\n * auto-starts one.\n */\n\nexport interface AttachRemoteReactorOptions {\n /**\n * Where the switchboard lives: its GraphQL endpoint\n * (`http://localhost:4001/graphql`), a drive url (`…/d/<drive>`), or a bare\n * origin — the endpoint is derived.\n */\n url: string;\n /** Document models the client signs/reduces with. */\n documentModels: DocumentModelModule[];\n /**\n * What this agent expects of the fleet it joins (the host file's\n * reactor.protocol). Reachability and inspection facts are checked at\n * attach; flag-level comparison engages once the inspection subgraph\n * exposes the enforcement flags (upstream note in the phase-5 WBS) — until\n * then the expectation is carried for the error message and future use.\n */\n expectedProtocol?: ReactorProtocol;\n /** Bearer for authenticated switchboards; omitted = unauthenticated. */\n token?: string;\n /** Reachability probe budget. */\n timeoutMs?: number;\n}\n\nexport interface RemoteReactorAttachment {\n /** The derived GraphQL endpoint actually dialed. */\n endpoint: string;\n /** IReactorClient-compatible GraphQL client (reactor-browser). */\n client: unknown;\n /** Remote facts from the inspection subgraph, when it answers. */\n remoteInfo?: Record<string, unknown>;\n}\n\n/** Derive the GraphQL endpoint from the accepted url spellings. */\nexport function deriveGraphqlEndpoint(url: string): string {\n const parsed = new URL(url);\n if (parsed.pathname.includes(\"/d/\")) {\n return `${parsed.origin}/graphql`;\n }\n if (parsed.pathname.replace(/\\/$/, \"\").endsWith(\"/graphql\")) {\n return `${parsed.origin}${parsed.pathname.replace(/\\/$/, \"\")}`;\n }\n const base = parsed.pathname.replace(/\\/$/, \"\");\n return `${parsed.origin}${base}/graphql`;\n}\n\nasync function probeEndpoint(\n endpoint: string,\n timeoutMs: number,\n): Promise<void> {\n try {\n // A GraphQL endpoint answers POST; any HTTP response (even 400) proves\n // the server is listening. Only transport failure means unreachable.\n await fetch(endpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ query: \"{ __typename }\" }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (cause) {\n throw new Error(\n `Cannot attach to the reactor at ${endpoint}: the switchboard is not ` +\n `answering. The agent depends on a RUNNING switchboard and never ` +\n `starts one — start it first (e.g. \\`ph run switchboard\\`, ` +\n `\\`ph vetra\\`, or the compound that members both) and retry.`,\n { cause },\n );\n }\n}\n\n/** Read the inspection subgraph's info when it answers (dev switchboards\n * under the OPEN policy serve it); absence is not an attach failure. */\nasync function readRemoteInfo(\n endpoint: string,\n token: string | undefined,\n timeoutMs: number,\n): Promise<Record<string, unknown> | undefined> {\n try {\n const res = await fetch(`${endpoint}/inspection`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n body: JSON.stringify({\n query: \"query ReactorInspectionInfo { inspection { info } }\",\n }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!res.ok) return undefined;\n const body = (await res.json()) as {\n data?: { inspection?: { info?: Record<string, unknown> } };\n };\n return body.data?.inspection?.info;\n } catch {\n return undefined;\n }\n}\n\nexport async function attachRemoteReactor(\n options: AttachRemoteReactorOptions,\n): Promise<RemoteReactorAttachment> {\n const timeoutMs = options.timeoutMs ?? 10_000;\n const endpoint = deriveGraphqlEndpoint(options.url);\n\n await probeEndpoint(endpoint, timeoutMs);\n const remoteInfo = await readRemoteInfo(endpoint, options.token, timeoutMs);\n\n const { GraphQLReactorClient } =\n await import(\"@powerhousedao/reactor-browser/graphql-client\");\n const client = new GraphQLReactorClient({\n url: endpoint,\n documentModels: options.documentModels,\n ...(options.token\n ? { tokenProvider: () => Promise.resolve(options.token) }\n : {}),\n } as never);\n\n return { endpoint, client, remoteInfo };\n}\n","import { z } from \"zod\";\n\n/**\n * Read-only reactor tools for the agent host (mastra-runner). They wrap the\n * attached reactor client — the switchboard the host joined — so the model\n * can look at the fleet's documents instead of guessing: list drives, list a\n * drive's documents by type, read one document's state. Writes stay out: the\n * agent names the operation it would apply and a person applies it.\n *\n * The client is the IReactorClient-compatible GraphQL client from\n * `attachRemoteReactor`; only `find` and `get` are used, typed structurally so\n * this module does not pull the reactor packages into clint's graph.\n */\n\ninterface DocumentHeader {\n id: string;\n slug?: string;\n name?: string;\n documentType: string;\n createdAtUtcIso?: string;\n lastModifiedAtUtcIso?: string;\n revision?: Record<string, number>;\n}\n\ninterface DocumentLike {\n header: DocumentHeader;\n state: Record<string, unknown>;\n}\n\ninterface Paged<T> {\n results: T[];\n next?: () => Promise<Paged<T>>;\n}\n\nexport interface ReactorReadClient {\n find(\n search: { type?: string; parentId?: string },\n view?: undefined,\n paging?: { cursor: string; limit: number },\n ): Promise<Paged<DocumentLike>>;\n get(identifier: string): Promise<DocumentLike>;\n}\n\nexport interface ReactorReadToolsOptions {\n /** Cap on the serialized state a `getDocument` call returns (default 24k). */\n maxStateChars?: number;\n /** Cap on the documents one `listDocuments` call returns (default 200). */\n maxList?: number;\n}\n\nconst DRIVE_TYPE = \"powerhouse/document-drive\";\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** The global scope's state, whichever way the client shaped `state`. */\nfunction globalState(doc: DocumentLike): Record<string, unknown> {\n const state = doc.state;\n if (isRecord(state.global)) return state.global;\n return state;\n}\n\n/**\n * A one-line view of a state object: its scalar fields, and the length of\n * each array field — enough to pick a document from a list without reading\n * every one.\n */\nexport function summarizeState(\n state: Record<string, unknown>,\n maxKeys = 16,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n let keys = 0;\n for (const [key, value] of Object.entries(state)) {\n if (keys >= maxKeys) break;\n if (value === null || value === undefined) continue;\n if (Array.isArray(value)) {\n out[`${key}Count`] = value.length;\n keys++;\n } else if (typeof value !== \"object\") {\n out[key] =\n typeof value === \"string\" && value.length > 120\n ? `${value.slice(0, 117)}…`\n : value;\n keys++;\n } else if (isRecord(value) && typeof value.name === \"string\") {\n // e.g. counterparty: { name }, submitter: { name }\n out[key] = value.name;\n keys++;\n }\n }\n return out;\n}\n\nfunction headerOf(doc: DocumentLike) {\n const h = doc.header;\n return {\n id: h.id,\n slug: h.slug ?? undefined,\n name: h.name ?? undefined,\n documentType: h.documentType,\n lastModified: h.lastModifiedAtUtcIso ?? undefined,\n };\n}\n\nasync function collect(\n first: Paged<DocumentLike>,\n max: number,\n): Promise<DocumentLike[]> {\n const out = [...first.results];\n let page = first;\n while (out.length < max && page.next && page.results.length > 0) {\n page = await page.next();\n out.push(...page.results);\n }\n return out.slice(0, max);\n}\n\nfunction truncateJson(\n value: unknown,\n maxChars: number,\n): {\n json: string;\n truncated: boolean;\n} {\n const json = JSON.stringify(value, null, 1);\n if (json.length <= maxChars) return { json, truncated: false };\n return { json: `${json.slice(0, maxChars)}…`, truncated: true };\n}\n\n/**\n * Build the Mastra tool set over an attached reactor client. Mastra is\n * imported lazily, like the rest of clint's Mastra integration.\n */\nexport async function createReactorReadTools(\n client: ReactorReadClient,\n options: ReactorReadToolsOptions = {},\n) {\n const { createTool } = await import(\"@mastra/core/tools\");\n const maxStateChars = options.maxStateChars ?? 24_000;\n const maxList = options.maxList ?? 200;\n\n const listDrives = createTool({\n id: \"listDrives\",\n description:\n \"List the drives on the reactor this agent is attached to: id, slug, \" +\n \"name and how many nodes (documents and folders) each holds. Call this \" +\n \"first when you do not know a drive id.\",\n inputSchema: z.object({}),\n execute: async () => {\n const page = await client.find({ type: DRIVE_TYPE }, undefined, {\n cursor: \"0\",\n limit: 100,\n });\n const drives = await collect(page, 100);\n return {\n drives: drives.map((d) => {\n const state = globalState(d);\n const nodes = Array.isArray(state.nodes) ? state.nodes.length : 0;\n return {\n ...headerOf(d),\n name:\n (typeof state.name === \"string\" && state.name) || d.header.name,\n nodeCount: nodes,\n };\n }),\n };\n },\n });\n\n const listDocuments = createTool({\n id: \"listDocuments\",\n description:\n \"List documents on the reactor, optionally within one drive (driveId) \" +\n \"and/or of one document type (e.g. sektar/invoice). Returns each \" +\n \"document's id, slug, name, type and a one-line summary of its state \" +\n \"(scalar fields plus array lengths). Use getDocument for the full state.\",\n inputSchema: z.object({\n driveId: z\n .string()\n .optional()\n .describe(\"Drive id to list within (from listDrives). Omit for all.\"),\n documentType: z\n .string()\n .optional()\n .describe(\"Document type to filter by, e.g. sektar/invoice.\"),\n limit: z\n .number()\n .int()\n .positive()\n .max(maxList)\n .optional()\n .describe(`Maximum documents to return (default 100, max ${maxList}).`),\n }),\n execute: async (input) => {\n const limit = Math.min(input.limit ?? 100, maxList);\n const page = await client.find(\n {\n ...(input.documentType ? { type: input.documentType } : {}),\n ...(input.driveId ? { parentId: input.driveId } : {}),\n },\n undefined,\n { cursor: \"0\", limit: Math.min(limit, 100) },\n );\n const docs = (await collect(page, limit)).filter(\n (d) => d.header.documentType !== DRIVE_TYPE || !!input.documentType,\n );\n return {\n count: docs.length,\n documents: docs.map((d) => ({\n ...headerOf(d),\n summary: summarizeState(globalState(d)),\n })),\n };\n },\n });\n\n const getDocument = createTool({\n id: \"getDocument\",\n description:\n \"Read one document by id or slug: its header and full global state as \" +\n \"JSON (truncated past a size cap; say so if `truncated` is true).\",\n inputSchema: z.object({\n identifier: z.string().describe(\"Document id or slug.\"),\n }),\n execute: async (input) => {\n const doc = await client.get(input.identifier);\n const { json, truncated } = truncateJson(globalState(doc), maxStateChars);\n return { ...headerOf(doc), state: json, truncated };\n },\n });\n\n return { listDrives, listDocuments, getDocument };\n}\n","import type { StreamChunk } from \"../core/types.js\";\n\n/**\n * The mastra-runner's provider seam: a real Mastra agent when a model is\n * configured, and a DEMO provider otherwise — same posture as the ph-rupert\n * example: the host answers without an API key, loudly saying it is the demo.\n */\nexport interface AgentStreamProvider {\n readonly modelId: string;\n stream(\n prompt: string,\n options: { threadId: string },\n ): AsyncIterable<StreamChunk>;\n}\n\nexport function createDemoProvider(agentName: string): AgentStreamProvider {\n return {\n modelId: \"demo\",\n // eslint-disable-next-line require-yield -- single-chunk generator below\n async *stream(prompt: string) {\n const text =\n `You said: ${JSON.stringify(prompt.slice(0, 2000))}. ` +\n `I'm the ${agentName} demo agent — configure a model (host config ` +\n `\\`model\\` and \\`apiKey\\`) for real responses.`;\n yield { type: \"text-delta\", text } as StreamChunk;\n },\n };\n}\n\nexport interface MastraProviderOptions {\n agentName: string;\n instructions: string;\n /** Mastra model-router string, e.g. `anthropic/claude-sonnet-4-5`. */\n model: string;\n /** The provider's API key (resolved host config). Absent: Mastra's model\n * router looks the provider's key up in the environment itself. */\n apiKey?: string;\n /** Tools the agent may call (Mastra `createTool` results), e.g. the\n * reactor read tools over the attached switchboard. */\n tools?: Record<string, unknown>;\n /** Tool-call rounds per turn; a framework knob (stays in code). */\n maxSteps?: number;\n}\n\n/** A model-router id names its provider: `<provider>/<model…>`. */\nfunction isRouterModelId(model: string): model is `${string}/${string}` {\n const slash = model.indexOf(\"/\");\n return slash > 0 && slash < model.length - 1;\n}\n\n/** Mastra's model config: the router id alone, or with an explicit key\n * (Mastra's OpenAI-compatible config object). */\nexport function mastraModelConfig(\n model: string,\n apiKey: string | undefined,\n): string | { id: `${string}/${string}`; apiKey: string } {\n if (apiKey === undefined) return model;\n if (!isRouterModelId(model)) {\n throw new Error(\n `model \"${model}\" is not a model-router id (\"<provider>/<model>\"), so an apiKey cannot be attached to it.`,\n );\n }\n return { id: model, apiKey };\n}\n\nexport async function createMastraProvider(\n options: MastraProviderOptions,\n): Promise<AgentStreamProvider> {\n const { Agent } = await import(\"@mastra/core/agent\");\n const { mapMastraStream } = await import(\"../integrations/mastra/stream.js\");\n const agent = new Agent({\n id: options.agentName,\n name: options.agentName,\n instructions: options.instructions,\n // With an apiKey the router uses it; without, it resolves the\n // provider's key from the environment.\n model: mastraModelConfig(options.model, options.apiKey),\n ...(options.tools ? { tools: options.tools as never } : {}),\n });\n return {\n modelId: options.model,\n async *stream(prompt: string, streamOptions: { threadId: string }) {\n const result = await agent.stream(prompt, {\n memory: undefined,\n threadId: streamOptions.threadId,\n maxSteps: options.maxSteps ?? 8,\n } as never);\n yield* mapMastraStream(\n (result as { fullStream: AsyncIterable<unknown> }).fullStream as never,\n );\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { createServer, type Server } from \"node:http\";\nimport {\n defaultUserDataDir,\n probeRun,\n resolveUserDataPlaceholders,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport { defineHostSchemas } from \"@powerhousedao/host-core/schema\";\nimport { z } from \"zod\";\nimport {\n attachRemoteReactor,\n type RemoteReactorAttachment,\n} from \"../integrations/powerhouse/remote-reactor.js\";\nimport {\n createReactorReadTools,\n type ReactorReadClient,\n} from \"../integrations/powerhouse/reactor-tools.js\";\nimport {\n createDemoProvider,\n createMastraProvider,\n type AgentStreamProvider,\n} from \"./agent-provider.js\";\n\n/**\n * mastra-runner (P5.6): the headless agent host. Its reactor is a REMOTE\n * attach — a lone `remote` backend whose `remote.url` is the running\n * switchboard's GraphQL endpoint (typically the output token\n * `switchboard.endpoints.graphql`, resolved before the verb runs); it depends\n * on that switchboard and never starts one. `run`/`serve` expose an\n * OpenAI-compatible chat-completions endpoint (streaming SSE +\n * non-streaming, stateless baseline — the caller owns session state);\n * without a configured model it answers as the DEMO agent. `build` compiles\n * skills and agent profiles (ph-clint-dev's pipeline, ported).\n */\n\nexport const kind = \"reactor\";\n\n/** The verbs this runner exports (`promptFromMessages` is a helper). */\nexport const verbs = [\"run\", \"serve\", \"build\"] as const;\n\n/** The token a host writes for the switchboard endpoint (error hints). */\nconst REMOTE_URL_HINT =\n 'remote: { url: switchboard.endpoints.graphql } (from ../switchboard/outputs.js), or literally { url: { $output: { host: \"switchboard\", path: [\"endpoints\", \"graphql\"] } } }';\n\n/**\n * The agent host, from one definition in two forms: DECLARED (`apiKey` may\n * be a token, e.g. `{ $env: \"OPENROUTER_API_KEY\" }`; what host.js authors\n * write) and RESOLVED (what the verbs receive).\n *\n * `config` holds OPERATOR SETTINGS only (rewire R5): `model` selects the\n * LLM, `apiKey` authenticates it, `instructions`/`prompts` shape the agent.\n * Framework KNOBS (maxSteps, cacheControl, memory tuning, untilIdle, tool\n * allowlists) stay in code, and the agent CARD (description/image) comes\n * from the host's `profile`, not here.\n */\nconst schemas = defineHostSchemas((s) => {\n const agentHostConfigSchema = z.strictObject({\n /** Mastra model router id (e.g. \"openrouter/<vendor>/<model>\"). Absent:\n * the runner answers as the demo agent. */\n model: z.string().min(1).optional(),\n /** The model provider's API key. A SECRET: write it as\n * `{ $env: \"OPENROUTER_API_KEY\" }` so it comes from the environment at\n * resolve time and never sits in the host file. Passed to the provider\n * as given; the runner does not read `process.env` itself. Absent, the\n * Mastra model router falls back to its own provider env lookup. */\n apiKey: s.tokenable(z.string().min(1)).optional(),\n instructions: z.string().optional(),\n /** `build`: skill + agent-profile compilation inputs and output. */\n prompts: z\n .strictObject({\n skillsDir: z.string().min(1).optional(),\n agentsDir: z.string().min(1).optional(),\n outDir: z.string().min(1).optional(),\n })\n .optional(),\n });\n /** `reactor` is the base block: a lone `remote` backend naming the\n * switchboard to attach to. `runner` takes no options beyond the base. */\n return s.reactorHostSchema.extend({\n runner: s.runnerBaseSchema.strict(),\n config: agentHostConfigSchema.optional(),\n });\n});\n/** Declared form: what a host file may contain before resolution. */\nexport const declaredHostSchema = schemas.declaredHostSchema;\n/** Resolved form: what the verbs receive (and `validateHost` checks). */\nexport const hostSchema = schemas.hostSchema;\n\n/** What an agent host.js author writes. */\nexport type MastraHostInput = z.input<typeof declaredHostSchema>;\n/** What the verbs receive. */\nexport type MastraHost = z.output<typeof hostSchema>;\nexport type AgentHostConfig = NonNullable<MastraHostInput[\"config\"]>;\n\n/** What serving the agent produces: where its OpenAI-compatible API is\n * actually bound. */\nexport const outputsSchema = z.strictObject({\n /** `http://<bound host>:<bound port>`. */\n origin: z.url(),\n endpoints: z.strictObject({\n /** OpenAI-compatible base URL (`<origin>/v1`). */\n openai: z.url(),\n /** Readiness probe (`<origin>/ready`). */\n ready: z.url(),\n }),\n});\n\nexport type MastraOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/clint/mastra-runner\": {\n host: MastraHostInput;\n outputs: MastraOutputs;\n };\n }\n}\n\nconst DEFAULT_AGENT_PORT = 4910;\n\n/** The remote backend's switchboard url, as resolved before the verb. The\n * sibling-reference resolver (`remote: { host }`) is gone: an output token\n * names the endpoint the switchboard actually bound. */\nfunction remoteUrl(host: MastraHost): string {\n const backends = Object.values(host.reactor?.backends ?? {});\n const remote = backends.find((b) => b.kind === \"remote\");\n if (!remote) {\n throw new Error(\n `hosts/${host.name}: an agent host attaches to a RUNNING switchboard — ` +\n `declare a remote backend, e.g. reactor.backends.switchboard = ` +\n `{ kind: \"remote\", ${REMOTE_URL_HINT} }.`,\n );\n }\n const url = remote.remote?.url;\n if (typeof url !== \"string\" || url.length === 0) {\n throw new Error(\n `hosts/${host.name}: the remote backend needs the switchboard's ` +\n `GraphQL url: ${REMOTE_URL_HINT}.`,\n );\n }\n return url;\n}\n\ntype ChatMessage = { role: string; content: unknown };\n\n/** Baseline stateless mapping: the last user message is the prompt (string\n * or OpenAI content-part arrays flattened to their text parts). */\nexport function promptFromMessages(messages: ChatMessage[]): string {\n const lastUser = [...messages].reverse().find((m) => m.role === \"user\");\n const content = lastUser?.content;\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((part: { type?: string; text?: string }) =>\n part.type === \"text\" ? (part.text ?? \"\") : \"\",\n )\n .join(\"\");\n }\n return \"\";\n}\n\nasync function readBody(\n req: import(\"node:http\").IncomingMessage,\n): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction completionChunk(\n id: string,\n model: string,\n delta: Record<string, unknown>,\n finish: string | null,\n): string {\n return `data: ${JSON.stringify({\n id,\n object: \"chat.completion.chunk\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [{ index: 0, delta, finish_reason: finish }],\n })}\\n\\n`;\n}\n\nexport type AgentServeHandle = RunnerHandle<MastraOutputs>;\n\nasync function serveAgent(\n host: MastraHost,\n ctx: RunnerContext,\n): Promise<AgentServeHandle> {\n const userData = defaultUserDataDir(ctx.projectRoot, ctx.env);\n const resolved = resolveUserDataPlaceholders(host, userData);\n const config = resolved.config ?? {};\n const port =\n typeof resolved.runner.port === \"number\"\n ? resolved.runner.port\n : DEFAULT_AGENT_PORT;\n\n // Single-instance lock: refuse before attaching or binding when the record\n // start-run wrote for a running instance of this host is live.\n const projectName = (() => {\n try {\n return (\n (\n JSON.parse(\n fs.readFileSync(`${ctx.projectRoot}/package.json`, \"utf8\"),\n ) as { name?: string }\n ).name ?? host.name\n );\n } catch {\n return host.name;\n }\n })();\n const probe = probeRun(ctx.projectRoot, resolved.name, projectName);\n if (probe.status === \"live\") {\n throw new Error(\n `${resolved.name} is already running (pid ${probe.record.pid}).`,\n );\n }\n\n // The reactor: attach, loudly, before serving anything.\n const attachment: RemoteReactorAttachment = await attachRemoteReactor({\n url: remoteUrl(resolved),\n documentModels: [],\n });\n console.log(`[${resolved.name}] reactor attached: ${attachment.endpoint}`);\n\n // The agent: real Mastra when a model is configured, demo otherwise. A real\n // agent gets read tools over the attached reactor (list drives, list\n // documents, read one) so it answers from the fleet's documents.\n let provider: AgentStreamProvider;\n if (config.model) {\n const tools = await createReactorReadTools(\n attachment.client as ReactorReadClient,\n );\n console.log(\n `[${resolved.name}] reactor tools: ${Object.keys(tools).join(\", \")}`,\n );\n provider = await createMastraProvider({\n agentName: resolved.name,\n instructions:\n config.instructions ??\n `You are ${resolved.name}, a Powerhouse project agent.`,\n model: config.model,\n apiKey: config.apiKey,\n tools,\n });\n } else {\n provider = createDemoProvider(resolved.name);\n }\n\n const server: Server = createServer((req, res) => {\n void (async () => {\n const url = (req.url ?? \"/\").split(\"?\")[0];\n if (req.method === \"GET\" && url === \"/ready\") {\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ ok: true, agent: resolved.name }));\n return;\n }\n if (req.method === \"GET\" && url === \"/v1/models\") {\n // The agent card: id + model, plus description/image from the host's\n // profile (rewire R5 — identity lives in profile, not config).\n const profile = resolved.profile ?? {};\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify({\n object: \"list\",\n data: [\n {\n id: provider.modelId,\n object: \"model\",\n owned_by: \"clint\",\n name: profile.name ?? resolved.name,\n ...(profile.description\n ? { description: profile.description }\n : {}),\n ...(profile.icon ? { image: profile.icon } : {}),\n },\n ],\n }),\n );\n return;\n }\n if (req.method === \"POST\" && url === \"/v1/chat/completions\") {\n let body: { messages?: ChatMessage[]; stream?: boolean };\n try {\n body = JSON.parse(await readBody(req)) as typeof body;\n } catch {\n res.writeHead(400, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: { message: \"invalid JSON body\" } }));\n return;\n }\n const prompt = promptFromMessages(body.messages ?? []);\n const id = `chatcmpl-${randomUUID()}`;\n const threadId = randomUUID(); // stateless baseline: the caller owns sessions\n\n if (body.stream) {\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-store\",\n connection: \"keep-alive\",\n });\n res.write(\n completionChunk(id, provider.modelId, { role: \"assistant\" }, null),\n );\n try {\n for await (const chunk of provider.stream(prompt, { threadId })) {\n if (chunk.type === \"text-delta\" && chunk.text) {\n res.write(\n completionChunk(\n id,\n provider.modelId,\n { content: chunk.text },\n null,\n ),\n );\n } else if (chunk.type === \"error\") {\n res.write(\n completionChunk(\n id,\n provider.modelId,\n {\n content: `\\n[agent error] ${String((chunk as { message?: unknown }).message ?? \"unknown\")}`,\n },\n null,\n ),\n );\n }\n }\n res.write(completionChunk(id, provider.modelId, {}, \"stop\"));\n res.write(\"data: [DONE]\\n\\n\");\n } finally {\n res.end();\n }\n return;\n }\n\n let text = \"\";\n for await (const chunk of provider.stream(prompt, { threadId })) {\n if (chunk.type === \"text-delta\" && chunk.text) text += chunk.text;\n }\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id,\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model: provider.modelId,\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: text },\n finish_reason: \"stop\",\n },\n ],\n }),\n );\n return;\n }\n res.writeHead(404, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: { message: `no route: ${url}` } }));\n })().catch((error: unknown) => {\n if (!res.headersSent) res.writeHead(500);\n res.end(JSON.stringify({ error: { message: String(error) } }));\n });\n });\n\n const ready = new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, \"127.0.0.1\", () => resolve());\n });\n await ready;\n // The actual bound port (a requested 0 means \"any free port\").\n const boundPort = (server.address() as { port: number }).port;\n const origin = `http://127.0.0.1:${boundPort}`;\n const outputs = outputsSchema.parse({\n origin,\n endpoints: { openai: `${origin}/v1`, ready: `${origin}/ready` },\n });\n console.log(\n `[${resolved.name}] agent API (OpenAI-compatible): ${outputs.endpoints.openai} (model: ${provider.modelId})`,\n );\n\n // No run record here: standalone `ph run` (start-run) publishes `outputs`\n // in the v2 record because this module exports `outputsSchema`, and a\n // compound records its members itself. One writer per record.\n return {\n outputs,\n ready,\n shutdown: async () => {\n await new Promise((resolve) => server.close(resolve));\n },\n };\n}\n\nexport async function run(\n host: MastraHost,\n ctx: RunnerContext,\n): Promise<AgentServeHandle> {\n return serveAgent(host, ctx);\n}\n\nexport const serve = run;\n\n/** `build` — skill + agent-profile compilation (ph-clint-dev's pipeline). */\nexport async function build(\n host: MastraHost,\n ctx: RunnerContext,\n): Promise<void> {\n const config = host.config ?? {};\n const { buildSkills } = await import(\"../dev/build-skills.js\");\n const result = await buildSkills({\n rootDir: ctx.projectRoot,\n skillsDir: config.prompts?.skillsDir,\n agentsDir: config.prompts?.agentsDir,\n outDir: config.prompts?.outDir,\n });\n console.log(\n `[${host.name}] compiled ${result.skills} skill(s), ${result.profiles} profile(s) → ${result.outDir}`,\n );\n}\n"],"mappings":";;;;;;;;AA6CA,SAAgB,sBAAsB,KAAqB;CACzD,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,IAAI,OAAO,SAAS,SAAS,KAAK,GAChC,OAAO,GAAG,OAAO,OAAO;CAE1B,IAAI,OAAO,SAAS,QAAQ,OAAO,EAAE,CAAC,CAAC,SAAS,UAAU,GACxD,OAAO,GAAG,OAAO,SAAS,OAAO,SAAS,QAAQ,OAAO,EAAE;CAE7D,MAAM,OAAO,OAAO,SAAS,QAAQ,OAAO,EAAE;CAC9C,OAAO,GAAG,OAAO,SAAS,KAAK;AACjC;AAEA,eAAe,cACb,UACA,WACe;CACf,IAAI;EAGF,MAAM,MAAM,UAAU;GACpB,QAAQ;GACR,SAAS,EAAE,gBAAgB,mBAAmB;GAC9C,MAAM,KAAK,UAAU,EAAE,OAAO,iBAAiB,CAAC;GAChD,QAAQ,YAAY,QAAQ,SAAS;EACvC,CAAC;CACH,SAAS,OAAO;EACd,MAAM,IAAI,MACR,mCAAmC,SAAS,iNAI5C,EAAE,MAAM,CACV;CACF;AACF;;;AAIA,eAAe,eACb,UACA,OACA,WAC8C;CAC9C,IAAI;EACF,MAAM,MAAM,MAAM,MAAM,GAAG,SAAS,cAAc;GAChD,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,GAAI,QAAQ,EAAE,eAAe,UAAU,QAAQ,IAAI,CAAC;GACtD;GACA,MAAM,KAAK,UAAU,EACnB,OAAO,sDACT,CAAC;GACD,QAAQ,YAAY,QAAQ,SAAS;EACvC,CAAC;EACD,IAAI,CAAC,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AM,IAAI,SAAS,YAAY,OAAO,MAAM,OAAO,CAAC;EACtD;CACF;AACF;AAEA,eAAsB,IACpB,MACA,KAC2B;CAC3B,OAAO,WAAW,MAAM,GAAG;AAC7B;AAEA,MAAa,QAAQ;;AAGrB,eAAsB,MACpB,MACA,KACe;CACf,MAAM,SAAS,KAAK,UAAU,CAAC;CAC/B,MAAM,EAAE,gBAAgB,MAAM,OAAO;CACrC,MAAM,SAAS,MAAM,YAAY;EAC/B,SAAS,IAAI;EACb,WAAW,OAAO,SAAS;EAC3B,WAAW,OAAO,SAAS;EAC3B,QAAQ,OAAO,SAAS;CAC1B,CAAC;CACD,QAAQ,IACN,IAAI,KAAK,KAAK,aAAa,OAAO,OAAO,aAAa,OAAO,SAAS,gBAAgB,OAAO,QAC/F;AACF"}
@@ -2290,7 +2290,7 @@ async function buildAuthHeaders(url, jwtHandler) {
2290
2290
  return headers;
2291
2291
  }
2292
2292
  //#endregion
2293
- //#region ../reactor-attachments/dist/null-attachment-transport-Cm_kb5ww.js
2293
+ //#region ../reactor-attachments/dist/null-attachment-transport-BMa3MUA2.js
2294
2294
  function isRecord$3(value) {
2295
2295
  return typeof value === "object" && value !== null && !Array.isArray(value);
2296
2296
  }
@@ -2426,7 +2426,7 @@ var AttachmentService = class {
2426
2426
  async reserveHashFirst(options) {
2427
2427
  const normalized = options.clientHash.toLowerCase();
2428
2428
  if (!CLIENT_HASH_PATTERN.test(normalized)) throw new Error(`clientHash must be a 64-character lowercase hex string, got: ${options.clientHash}`);
2429
- if (options.sizeBytes === void 0 || !Number.isInteger(options.sizeBytes) || options.sizeBytes <= 0 || !Number.isSafeInteger(options.sizeBytes)) throw new Error("sizeBytes must be a positive safe integer when clientHash is provided");
2429
+ if (options.sizeBytes === void 0 || !Number.isSafeInteger(options.sizeBytes) || options.sizeBytes < 0) throw new Error("sizeBytes must be a non-negative safe integer when clientHash is provided");
2430
2430
  const normalizedOptions = {
2431
2431
  ...options,
2432
2432
  clientHash: normalized
@@ -4764,4 +4764,4 @@ async function buildDefaultReactor(ctx, options) {
4764
4764
  //#endregion
4765
4765
  export { generateConfigCommandHelp as A, createWorkdirStore as B, extractTemplateVars as C, installSkills as D, readSkills as E, resolveConfig as F, formatZodError as G, resolvePort as H, toUpperSnake as I, defineCommand as K, userConfigPath as L, configKeyToEnvVar as M, getMissingRequiredFields as N, createHelpCommand as O, localConfigPath as P, userStoreFolder as R, isSkillInvocation as S, renderSkillTemplate as T, resolveReactorDefaults as U, defaultPort as V, createLogger as W, IDENTITY_WRAPS as _, getProjectMapping as a, DEFAULT_SKILL_INSTRUCTION as b, defineTrigger as c, createReplSession as d, parseReplInput as f, createRoutine as g, createRoutineServiceAdapter as h, defineRegistry as i, resolveWorkdir as j, createConfigCommand as k, defineCli as l, createCompositeServiceManager as m, isDocType as n, createTypes as o, tokenizeArgs as p, readPackageInfo as q, deterministicId as r, createDocumentChangeTrigger as s, buildDefaultReactor as t, initLifecycle as u, composeWraps as v, registerDefaultHelpers as w, createSkillCommands as x, createProcessManager as y, createMemoryWorkdirStore as z };
4766
4766
 
4767
- //# sourceMappingURL=src-v5f_WnlY.mjs.map
4767
+ //# sourceMappingURL=src-BdwlBh04.mjs.map