@powerhousedao/clint 6.2.3-dev.99 → 6.3.0-dev.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{build-skills-Cfj0OGnW.mjs → build-skills-BnqGyuCH.mjs} +2 -2
- package/dist/{build-skills-Cfj0OGnW.mjs.map → build-skills-BnqGyuCH.mjs.map} +1 -1
- package/dist/{drive-BEshRPDR.mjs → drive-Bu9zoFrO.mjs} +7 -6
- package/dist/drive-Bu9zoFrO.mjs.map +1 -0
- package/dist/{folders-C-pFsTXT.mjs → folders-BYO1Wqqb.mjs} +9 -9
- package/dist/folders-BYO1Wqqb.mjs.map +1 -0
- package/dist/index.mjs +1 -1
- package/dist/runners/clint-runner.d.mts.map +1 -1
- package/dist/runners/clint-runner.mjs +1 -4
- package/dist/runners/clint-runner.mjs.map +1 -1
- package/dist/runners/mastra-runner.mjs +1 -1
- package/dist/{src-DD8PWpD5.mjs → src-BebNN3xc.mjs} +4 -4
- package/dist/{src-DD8PWpD5.mjs.map → src-BebNN3xc.mjs.map} +1 -1
- package/package.json +14 -14
- package/dist/drive-BEshRPDR.mjs.map +0 -1
- package/dist/folders-C-pFsTXT.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { T as renderSkillTemplate } from "./src-
|
|
1
|
+
import { T as renderSkillTemplate } from "./src-BebNN3xc.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-
|
|
293
|
+
//# sourceMappingURL=build-skills-BnqGyuCH.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-skills-Cfj0OGnW.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;EAChC,IAAI,UAAU;EACd,KAAK,MAAM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E5E,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"}
|
|
1
|
+
{"version":3,"file":"build-skills-BnqGyuCH.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;EAChC,IAAI,UAAU;EACd,KAAK,MAAM,WAAW,QAAQ,UAAU;GACtC,MAAM,QAAQ,eAAe,OAAO,SAAS,gBAAgB,OAAO;GACpE,IAAI,CAAC,OAAO;IACV,IAAI,UAAU,QAAQ,KAAK,oBAAoB,SAAS;IACxD,UAAU;IACV;GACF;GACA,aAAa,KAAK,KAAK;EACzB;EACA,IAAI,SAAS;EAEb,MAAM,eAAe;GAAE,GAAG,OAAO;GAAS,WAAW,QAAQ;EAAK;EAClE,MAAM,aAAa,OAAO,gBACtB,EAAE,SAAS,OAAO,cAAc,IAChC,KAAA;EAEJ,MAAM,mBAA6B,CAAC;EACpC,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,SAAS,QAAQ,KAAK;GAChD,MAAM,MAAM,GAAG,aAAa,aAAa,IAAI,OAAO;GACpD,MAAM,SAA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AAM,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"}
|
|
@@ -11,7 +11,8 @@ const DRIVE_DOCUMENT_TYPE = "powerhouse/document-drive";
|
|
|
11
11
|
*
|
|
12
12
|
* The Reactor client has no `getDrives()` — drives are documents of type
|
|
13
13
|
* `powerhouse/document-drive`. We use `reactor.findByType()` to locate
|
|
14
|
-
* existing ones and `client.createEmpty()` + `client.rename()`
|
|
14
|
+
* existing ones and `client.write.createEmpty()` + `client.write.rename()`
|
|
15
|
+
* to create.
|
|
15
16
|
*
|
|
16
17
|
* @param reactorModule - The full ReactorClientModule (needs .client and .reactor)
|
|
17
18
|
* @param driveConfig - Optional drive name/icon configuration
|
|
@@ -49,9 +50,9 @@ async function ensureDrive(reactorModule, driveConfig) {
|
|
|
49
50
|
id: wantedId
|
|
50
51
|
} : void 0);
|
|
51
52
|
if (preferredEditor) doc.header.meta = { preferredEditor };
|
|
52
|
-
driveId = (await client.create(doc)).header.id;
|
|
53
|
-
} else driveId = (await client.createEmpty(DRIVE_DOCUMENT_TYPE)).header.id;
|
|
54
|
-
await client.rename(driveId, driveName);
|
|
53
|
+
driveId = (await (await client.write.create(doc)).document()).header.id;
|
|
54
|
+
} else driveId = (await (await client.write.createEmpty(DRIVE_DOCUMENT_TYPE)).document()).header.id;
|
|
55
|
+
await (await client.write.rename(driveId, driveName)).document();
|
|
55
56
|
return {
|
|
56
57
|
id: driveId,
|
|
57
58
|
name: driveName
|
|
@@ -71,7 +72,7 @@ async function ensureRemoteDrive(reactorModule, url, name) {
|
|
|
71
72
|
const result = await client.addRemoteDrive(url);
|
|
72
73
|
const driveId = result.header?.id ?? result.id;
|
|
73
74
|
if (name) try {
|
|
74
|
-
await client.rename(driveId, name);
|
|
75
|
+
await (await client.write.rename(driveId, name)).document();
|
|
75
76
|
} catch {}
|
|
76
77
|
return {
|
|
77
78
|
id: driveId,
|
|
@@ -81,4 +82,4 @@ async function ensureRemoteDrive(reactorModule, url, name) {
|
|
|
81
82
|
//#endregion
|
|
82
83
|
export { drive_exports as t };
|
|
83
84
|
|
|
84
|
-
//# sourceMappingURL=drive-
|
|
85
|
+
//# sourceMappingURL=drive-Bu9zoFrO.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"drive-Bu9zoFrO.mjs","names":[],"sources":["../src/integrations/powerhouse/drive.ts"],"sourcesContent":["/**\n * Drive management — find or create drives on startup.\n */\n\nimport type { DriveConfig, ReactorClientModule } from \"./types.js\";\n\nconst DRIVE_DOCUMENT_TYPE = \"powerhouse/document-drive\" as const;\n\n/**\n * Ensure a drive exists, matching by name. On first run, creates a new drive.\n * On subsequent runs, finds the existing one by name.\n *\n * The Reactor client has no `getDrives()` — drives are documents of type\n * `powerhouse/document-drive`. We use `reactor.findByType()` to locate\n * existing ones and `client.write.createEmpty()` + `client.write.rename()`\n * to create.\n *\n * @param reactorModule - The full ReactorClientModule (needs .client and .reactor)\n * @param driveConfig - Optional drive name/icon configuration\n * @returns The drive ID and name\n */\nexport async function ensureDrive(\n reactorModule: ReactorClientModule,\n driveConfig?: DriveConfig,\n): Promise<{ id: string; name: string }> {\n const { client, reactor } = reactorModule;\n const driveName = driveConfig?.name ?? \"default\";\n const wantedId = driveConfig?.id;\n const preferredEditor = driveConfig?.preferredEditor;\n\n // Find existing document-drive documents\n const existing = await reactor.findByType(DRIVE_DOCUMENT_TYPE);\n if (existing?.results?.length) {\n // If a deterministic ID was requested, check if it already exists\n if (wantedId) {\n const match = existing.results.find((r) => r.header.id === wantedId);\n if (match) return { id: wantedId, name: driveName };\n }\n\n // Match by name — load each to check\n for (const result of existing.results) {\n const doc = (await client.get(result.header.id)) as any;\n const docName = doc.name ?? doc.header?.name ?? doc.state?.global?.name;\n if (docName === driveName) {\n return { id: result.header.id, name: driveName };\n }\n }\n // No name match — if default name and single drive, use it\n if (driveName === \"default\" && existing.results.length === 1) {\n return { id: existing.results[0].header.id, name: driveName };\n }\n }\n\n // Create a new drive document. Goes through the doc-build path when a\n // deterministic id or preferredEditor is set so we can populate the\n // header before persistence; falls back to createEmpty otherwise.\n let driveId: string;\n if (wantedId || preferredEditor) {\n // Only a legacy drive can take a chosen id.\n const doc = await client.newDocument(\n DRIVE_DOCUMENT_TYPE,\n wantedId ? { signaturePolicy: \"legacy\", id: wantedId } : undefined,\n );\n if (preferredEditor) doc.header.meta = { preferredEditor };\n const handle = await client.write.create(doc);\n const created = await handle.document();\n driveId = (created as any).header.id;\n } else {\n const handle = await client.write.createEmpty(DRIVE_DOCUMENT_TYPE);\n const drive = await handle.document();\n driveId = drive.header.id;\n }\n\n await (await client.write.rename(driveId, driveName)).document();\n return { id: driveId, name: driveName };\n}\n\n/**\n * Ensure a remote drive is connected for watching.\n * Uses the reactor client's addRemoteDrive capability.\n *\n * @param reactorModule - The full ReactorClientModule\n * @param url - The Switchboard URL to sync from\n * @param name - Display name for the drive\n * @returns The drive ID and name\n */\nexport async function ensureRemoteDrive(\n reactorModule: ReactorClientModule,\n url: string,\n name: string,\n): Promise<{ id: string; name: string }> {\n const { client } = reactorModule;\n\n // addRemoteDrive is idempotent — calling again for the same URL\n // returns the existing drive\n const result = await (client as any).addRemoteDrive(url);\n const driveId = result.header?.id ?? result.id;\n\n if (name) {\n try {\n await (await client.write.rename(driveId, name)).document();\n } catch {\n // Rename may fail for remote drives — non-fatal\n }\n }\n\n return { id: driveId, name };\n}\n"],"mappings":";;;;;;AAMA,MAAM,sBAAsB;;;;;;;;;;;;;;AAe5B,eAAsB,YACpB,eACA,aACuC;CACvC,MAAM,EAAE,QAAQ,YAAY;CAC5B,MAAM,YAAY,aAAa,QAAQ;CACvC,MAAM,WAAW,aAAa;CAC9B,MAAM,kBAAkB,aAAa;CAGrC,MAAM,WAAW,MAAM,QAAQ,WAAW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AS;CAC5D,QAAQ,CAER;CAGF,OAAO;EAAE,IAAI;EAAS;CAAK;AAC7B"}
|
|
@@ -75,11 +75,11 @@ function createFolderOperations(client, personalDriveId, log) {
|
|
|
75
75
|
const folderId = randomUUID();
|
|
76
76
|
log?.debug(`${TAG} ensureFolder creating folder "${segment}" (${folderId.slice(0, 8)}…) under ${parentFolderId?.slice(0, 8) ?? "root"}`);
|
|
77
77
|
const actions = await getDriveActions();
|
|
78
|
-
await client.execute(personalDriveId, "main", [actions.addFolder({
|
|
78
|
+
await (await client.write.execute(personalDriveId, "main", [actions.addFolder({
|
|
79
79
|
id: folderId,
|
|
80
80
|
name: segment,
|
|
81
81
|
parentFolder: parentFolderId
|
|
82
|
-
})]);
|
|
82
|
+
})])).document();
|
|
83
83
|
parentFolderId = folderId;
|
|
84
84
|
}
|
|
85
85
|
return parentFolderId;
|
|
@@ -96,14 +96,14 @@ function createFolderOperations(client, personalDriveId, log) {
|
|
|
96
96
|
const documentType = doc?.header?.documentType ?? doc?.documentType ?? "unknown";
|
|
97
97
|
const displayName = name ?? doc?.header?.name ?? doc?.name ?? documentId;
|
|
98
98
|
const actions = await getDriveActions();
|
|
99
|
-
await client.execute(personalDriveId, "main", [actions.addFile({
|
|
99
|
+
await (await client.write.execute(personalDriveId, "main", [actions.addFile({
|
|
100
100
|
id: documentId,
|
|
101
101
|
name: displayName,
|
|
102
102
|
documentType,
|
|
103
103
|
parentFolder: folderId
|
|
104
|
-
})]);
|
|
105
|
-
await client.addRelationship(personalDriveId, documentId, "child");
|
|
106
|
-
if (name) await client.rename(documentId, name);
|
|
104
|
+
})])).document();
|
|
105
|
+
await (await client.write.addRelationship(personalDriveId, documentId, "child")).document();
|
|
106
|
+
if (name) await (await client.write.rename(documentId, name)).document();
|
|
107
107
|
log?.debug(`${TAG} addDocument ${documentId.slice(0, 8)}… added as "${displayName}" in folder ${folderId.slice(0, 8)}…`);
|
|
108
108
|
}
|
|
109
109
|
async function createDocument(documentType, folderPath, name) {
|
|
@@ -119,8 +119,8 @@ function createFolderOperations(client, personalDriveId, log) {
|
|
|
119
119
|
}
|
|
120
120
|
async function removeDocument(documentId, _folderPath) {
|
|
121
121
|
const actions = await getDriveActions();
|
|
122
|
-
await client.execute(personalDriveId, "main", [actions.deleteNode({ id: documentId })]);
|
|
123
|
-
await client.removeRelationship(personalDriveId, documentId, "child");
|
|
122
|
+
await (await client.write.execute(personalDriveId, "main", [actions.deleteNode({ id: documentId })])).document();
|
|
123
|
+
await (await client.write.removeRelationship(personalDriveId, documentId, "child")).document();
|
|
124
124
|
}
|
|
125
125
|
async function resolveFolder(folderPath) {
|
|
126
126
|
const segments = splitPath(folderPath);
|
|
@@ -253,4 +253,4 @@ function createFolderCommands(folderOps) {
|
|
|
253
253
|
//#endregion
|
|
254
254
|
export { folders_exports as t };
|
|
255
255
|
|
|
256
|
-
//# sourceMappingURL=folders-
|
|
256
|
+
//# sourceMappingURL=folders-BYO1Wqqb.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"folders-BYO1Wqqb.mjs","names":[],"sources":["../src/integrations/powerhouse/folders.ts"],"sourcesContent":["/**\n * FolderOperations — programmatic API for managing documents\n * in the agent's personal drive using the drive's internal node tree.\n *\n * Folders and file references are stored as nodes in the drive document's\n * `state.global.nodes` array, managed via ADD_FOLDER and ADD_FILE operations.\n * This is distinct from the parent-child document graph (addRelationship/getOutgoingRelationships).\n *\n * Also exports `createFolderCommands()` to auto-generate CLI commands\n * that wrap the folder operations.\n */\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport type { Action } from \"document-model\";\nimport type { TypedReactorClient } from \"./types.js\";\nimport type { FolderEntry, FolderOperations } from \"./types.js\";\nimport type { Command } from \"../../core/types.js\";\nimport type { Logger } from \"../../core/types.js\";\n\nconst TAG = \"[folders]\";\n\n/** Node shape from drive state.global.nodes */\ninterface DriveNode {\n id: string;\n name: string;\n kind: string;\n parentFolder?: string | null;\n documentType?: string;\n}\n\nfunction isFolder(node: DriveNode): boolean {\n return node.kind === \"folder\";\n}\n\n/**\n * Read the drive document's internal nodes array.\n */\nasync function getDriveNodes(\n client: TypedReactorClient<any>,\n driveId: string,\n): Promise<DriveNode[]> {\n const drive = (await client.get(driveId)) as any;\n return (drive?.state?.global?.nodes ?? []) as DriveNode[];\n}\n\n/**\n * Create a FolderOperations instance backed by the reactor client.\n *\n * Folders are nodes inside the drive document's `state.global.nodes` array,\n * created via `ADD_FOLDER` and `ADD_FILE` drive operations executed on the\n * personal drive. This is separate from the document relationship graph.\n */\nexport function createFolderOperations(\n client: TypedReactorClient<any>,\n personalDriveId: string,\n log?: Logger,\n): FolderOperations {\n /**\n * Lazy-load drive action creators from @powerhousedao/shared.\n * Kept lazy so that importing folders.ts doesn't pull in the entire\n * @powerhousedao/shared tree — which is an optional peer dependency\n * and won't be installed in non-Powerhouse projects.\n */\n let _driveActions: {\n addFolder: (input: {\n id: string;\n name: string;\n parentFolder: string | null;\n }) => Action;\n addFile: (input: {\n id: string;\n name: string;\n documentType: string;\n parentFolder: string | null;\n }) => Action;\n deleteNode: (input: { id: string }) => Action;\n } | null = null;\n\n async function getDriveActions() {\n if (!_driveActions) {\n const mod = (await import(\"@powerhousedao/shared/document-drive\")) as any;\n _driveActions = {\n addFolder: mod.addFolder,\n addFile: mod.addFile,\n deleteNode: mod.deleteNode,\n };\n }\n return _driveActions;\n }\n\n function splitPath(folderPath: string): string[] {\n return folderPath.split(\"/\").filter(Boolean);\n }\n\n /**\n * Find a folder node by name under a given parent in the drive's nodes.\n */\n function findFolderInNodes(\n nodes: DriveNode[],\n name: string,\n parentId: string | null,\n ): DriveNode | undefined {\n return nodes.find(\n (n) =>\n isFolder(n) && n.name === name && (n.parentFolder ?? null) === parentId,\n );\n }\n\n async function ensureFolder(folderPath: string): Promise<string> {\n const segments = splitPath(folderPath);\n let parentFolderId: string | null = null;\n\n for (const segment of segments) {\n const nodes = await getDriveNodes(client, personalDriveId);\n const existing = findFolderInNodes(nodes, segment, parentFolderId);\n\n if (existing) {\n log?.debug(\n `${TAG} ensureFolder segment \"${segment}\" → exists ${existing.id.slice(0, 8)}…`,\n );\n parentFolderId = existing.id;\n continue;\n }\n\n // Create folder node inside the drive via ADD_FOLDER operation\n const folderId = randomUUID();\n log?.debug(\n `${TAG} ensureFolder creating folder \"${segment}\" (${folderId.slice(0, 8)}…) ` +\n `under ${parentFolderId?.slice(0, 8) ?? \"root\"}`,\n );\n const actions = await getDriveActions();\n await (\n await client.write.execute(personalDriveId, \"main\", [\n actions.addFolder({\n id: folderId,\n name: segment,\n parentFolder: parentFolderId,\n }),\n ])\n ).document();\n parentFolderId = folderId;\n }\n\n return parentFolderId!;\n }\n\n async function addDocument(\n documentId: string,\n folderPath: string,\n name?: string,\n ): Promise<void> {\n log?.debug(\n `${TAG} addDocument ${documentId.slice(0, 8)}… to \"${folderPath}\" name=${name ?? \"(none)\"}`,\n );\n const folderId = await ensureFolder(folderPath);\n\n // Check if this document is already registered as a file node in the drive\n const nodes = await getDriveNodes(client, personalDriveId);\n const existingFile = nodes.find((n) => !isFolder(n) && n.id === documentId);\n if (existingFile) {\n log?.debug(\n `${TAG} addDocument ${documentId.slice(0, 8)}… already in drive as \"${existingFile.name}\"`,\n );\n return;\n }\n\n // Get the document to read its type\n const doc = (await client.get(documentId)) as any;\n const documentType =\n doc?.header?.documentType ?? doc?.documentType ?? \"unknown\";\n const displayName = name ?? doc?.header?.name ?? doc?.name ?? documentId;\n\n // Add file node to drive via ADD_FILE operation\n const actions = await getDriveActions();\n await (\n await client.write.execute(personalDriveId, \"main\", [\n actions.addFile({\n id: documentId,\n name: displayName,\n documentType,\n parentFolder: folderId,\n }),\n ])\n ).document();\n\n // Also establish the parent-child relationship in the document graph\n await (\n await client.write.addRelationship(personalDriveId, documentId, \"child\")\n ).document();\n\n if (name) {\n await (await client.write.rename(documentId, name)).document();\n }\n\n log?.debug(\n `${TAG} addDocument ${documentId.slice(0, 8)}… added as \"${displayName}\" in folder ${folderId.slice(0, 8)}…`,\n );\n }\n\n async function createDocument(\n documentType: string,\n folderPath: string,\n name?: string,\n ): Promise<{ documentId: string }> {\n log?.debug(\n `${TAG} createDocument type=${documentType} folder=\"${folderPath}\" name=${name ?? \"(none)\"}`,\n );\n const parentFolderId = await ensureFolder(folderPath);\n\n const doc = await client.newDocument(documentType, {\n parentIdentifier: personalDriveId,\n name,\n });\n\n await client.drives.addFile(personalDriveId, doc, parentFolderId);\n\n log?.debug(\n `${TAG} createDocument ${doc.header.id.slice(0, 8)}… created in folder ${parentFolderId.slice(0, 8)}…`,\n );\n return { documentId: doc.header.id };\n }\n\n async function removeDocument(\n documentId: string,\n _folderPath?: string,\n ): Promise<void> {\n // Remove the file node from the drive via DELETE_NODE\n const actions = await getDriveActions();\n await (\n await client.write.execute(personalDriveId, \"main\", [\n actions.deleteNode({ id: documentId }),\n ])\n ).document();\n\n // Also remove the parent-child relationship\n await (\n await client.write.removeRelationship(\n personalDriveId,\n documentId,\n \"child\",\n )\n ).document();\n }\n\n async function resolveFolder(\n folderPath: string,\n ): Promise<string | undefined> {\n const segments = splitPath(folderPath);\n const nodes = await getDriveNodes(client, personalDriveId);\n let parentFolderId: string | null = null;\n\n for (const segment of segments) {\n const match = findFolderInNodes(nodes, segment, parentFolderId);\n if (!match) return undefined;\n parentFolderId = match.id;\n }\n\n return parentFolderId ?? undefined;\n }\n\n async function getDocument(documentId: string): Promise<unknown> {\n return client.get(documentId);\n }\n\n async function listFolder(folderPath?: string): Promise<FolderEntry[]> {\n let parentFolderId: string | null = null;\n\n if (folderPath) {\n const resolved = await resolveFolder(folderPath);\n if (!resolved) return [];\n parentFolderId = resolved;\n }\n\n const nodes = await getDriveNodes(client, personalDriveId);\n const prefix = folderPath ? folderPath.replace(/\\/+$/, \"\") : \"\";\n\n return nodes\n .filter((n) => (n.parentFolder ?? null) === parentFolderId)\n .map((n) => ({\n id: n.id,\n name: n.name,\n type: isFolder(n) ? (\"folder\" as const) : (\"document\" as const),\n documentType: isFolder(n) ? undefined : n.documentType,\n path: prefix ? `${prefix}/${n.name}` : n.name,\n }));\n }\n\n async function findByType(documentType: string): Promise<FolderEntry[]> {\n const nodes = await getDriveNodes(client, personalDriveId);\n return nodes\n .filter((n) => !isFolder(n) && n.documentType === documentType)\n .map((n) => ({\n id: n.id,\n name: n.name,\n type: \"document\" as const,\n documentType: n.documentType,\n path: n.name,\n }));\n }\n\n return {\n addDocument,\n createDocument,\n removeDocument,\n getDocument,\n listFolder,\n ensureFolder,\n findByType,\n };\n}\n\n// ── Folder command schemas ────────────────────────────────────────\n\nconst addDocumentSchema = z.object({\n documentId: z.string().describe(\"Document ID to add\"),\n folderPath: z.string().describe('Folder path (e.g. \"specs/my-project\")'),\n name: z.string().optional().describe(\"Display name for the document\"),\n});\n\nconst removeDocumentSchema = z.object({\n documentId: z.string().describe(\"Document ID to remove\"),\n folderPath: z.string().optional().describe(\"Folder path to remove from\"),\n});\n\nconst getDocumentSchema = z.object({\n documentId: z.string().describe(\"Document ID to retrieve\"),\n});\n\nconst listFolderSchema = z.object({\n folderPath: z.string().optional().describe(\"Folder path (root if omitted)\"),\n});\n\n/**\n * Auto-generate CLI commands that wrap FolderOperations.\n */\nexport function createFolderCommands(folderOps: FolderOperations): Command[] {\n const addDocument: Command<typeof addDocumentSchema> = {\n id: \"folders-add-document\",\n description: \"Add a document to the personal drive at a folder path\",\n inputSchema: addDocumentSchema,\n outputSchema: z.object({ text: z.string() }),\n execute: async (input) => {\n await folderOps.addDocument(\n input.documentId,\n input.folderPath,\n input.name,\n );\n return {\n text: `Added document ${input.documentId} to ${input.folderPath}`,\n };\n },\n };\n\n const removeDocument: Command<typeof removeDocumentSchema> = {\n id: \"folders-remove-document\",\n description: \"Remove a document from the personal drive\",\n inputSchema: removeDocumentSchema,\n outputSchema: z.object({ text: z.string() }),\n execute: async (input) => {\n await folderOps.removeDocument(input.documentId, input.folderPath);\n return { text: `Removed document ${input.documentId}` };\n },\n };\n\n const getDocument: Command<typeof getDocumentSchema> = {\n id: \"folders-get-document\",\n description: \"Get a document from the personal drive\",\n inputSchema: getDocumentSchema,\n outputSchema: z.object({ text: z.string(), data: z.unknown() }),\n execute: async (input) => {\n const doc = await folderOps.getDocument(input.documentId);\n return { text: JSON.stringify(doc, null, 2), data: doc };\n },\n };\n\n const listFolder: Command<typeof listFolderSchema> = {\n id: \"folders-ls\",\n description: \"List folder contents in the personal drive\",\n inputSchema: listFolderSchema,\n outputSchema: z.object({ text: z.string(), data: z.array(z.unknown()) }),\n execute: async (input) => {\n const entries = await folderOps.listFolder(input.folderPath);\n if (entries.length === 0) {\n return { text: \"Empty folder\", data: [] };\n }\n const lines = entries.map((e) => {\n const icon = e.type === \"folder\" ? \"[dir]\" : \"[doc]\";\n const typeInfo = e.documentType ? ` (${e.documentType})` : \"\";\n return ` ${icon} ${e.name}${typeInfo} ${e.id.slice(0, 8)}...`;\n });\n return { text: lines.join(\"\\n\"), data: entries };\n },\n };\n\n return [addDocument, removeDocument, getDocument, listFolder];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,MAAM,MAAM;AAWZ,SAAS,SAAS,MAA0B;CAC1C,OAAO,KAAK,SAAS;AACvB;;;;AAKA,eAAe,cACb,QACA,SACsB;CAEtB,QAAQ,MADa,OAAO,IAAI,OAAO,EAAA,EACxB,OAAO,QAAQ,SAAS,CAAC;AAC1C;;;;;;;;AASA,SAAgB,uBACd,QACA,iBACA,KACkB;;;;;;;CAOlB,IAAI,gBAaO;CAEX,eAAe,kBAAkB;EAC/B,IAAI,CAAC,eAAe;GAClB,MAAM,MAAO,MAAM,OAAO;GAC1B,gBAAgB;IACd,WAAW,IAAI;IACf,SAAS,IAAI;IACb,YAAY,IAAI;GAClB;EACF;EACA,OAAO;CACT;CAEA,SAAS,UAAU,YAA8B;EAC/C,OAAO,WAAW,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;CAC7C;;;;CAKA,SAAS,kBACP,OACA,MACA,UACuB;EACvB,OAAO,MAAM,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;GAC9D,SAAS,OAAO,UAAU;IACxB,MAAM,MAAM,MAAM,UAAU,YAAY,MAAM,UAAU;IACxD,OAAO;KAAE,MAAM,KAAK,UAAU,KAAK,MAAM,CAAC;KAAG,MAAM;IAAI;GACzD;EAsB6C;EAAG;GAlBhD,IAAI;GACJ,aAAa;GACb,aAAa;GACb,cAAc,EAAE,OAAO;IAAE,MAAM,EAAE,OAAO;IAAG,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC;GAAE,CAAC;GACvE,SAAS,OAAO,UAAU;IACxB,MAAM,UAAU,MAAM,UAAU,WAAW,MAAM,UAAU;IAC3D,IAAI,QAAQ,WAAW,GACrB,OAAO;KAAE,MAAM;KAAgB,MAAM,CAAC;IAAE;IAO1C,OAAO;KAAE,MALK,QAAQ,KAAK,MAAM;MAC/B,MAAM,OAAO,EAAE,SAAS,WAAW,UAAU;MAC7C,MAAM,WAAW,EAAE,eAAe,KAAK,EAAE,aAAa,KAAK;MAC3D,OAAO,KAAK,KAAK,GAAG,EAAE,OAAO,SAAS,IAAI,EAAE,GAAG,MAAM,GAAG,CAAC,EAAE;KAC7D,CACmB,CAAC,CAAC,KAAK,IAAI;KAAG,MAAM;IAAQ;GACjD;EAGyD;CAAC;AAC9D"}
|
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-
|
|
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-BebNN3xc.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":"clint-runner.d.mts","names":[],"sources":["../../src/runners/clint-runner.ts"],"mappings":";;;;;;;;;;;;;qBAoDa;;qBA8EA,oBAAkB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAA6B,EAAA,KAAA;;;qBAG/C,YAAU,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAAqB,EAAA,KAAA;;YAShC,iBAAiB,EAAE,aAAa;;YAEhC,YAAY,EAAE,cAAc;;qBAI3B;;;YAID,oBAAoB;EAE5B;EAAc;;;;;qBAmFL,eAAa,EAAA;;;;;GAGxB,EAAA,KAAA;YAEU,eAAe,EAAE,aAAa;QAElC;YACI;IACR;MACE,MAAM;MACN,SAAS;;;;;
|
|
1
|
+
{"version":3,"file":"clint-runner.d.mts","names":[],"sources":["../../src/runners/clint-runner.ts"],"mappings":";;;;;;;;;;;;;qBAoDa;;qBA8EA,oBAAkB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAA6B,EAAA,KAAA;;;qBAG/C,YAAU,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAAqB,EAAA,KAAA;;YAShC,iBAAiB,EAAE,aAAa;;YAEhC,YAAY,EAAE,cAAc;;qBAI3B;;;YAID,oBAAoB;EAE5B;EAAc;;;;;qBAmFL,eAAa,EAAA;;;;;GAGxB,EAAA,KAAA;YAEU,eAAe,EAAE,aAAa;QAElC;YACI;IACR;MACE,MAAM;MACN,SAAS;;;;;iBAgFE,qBAAqB,aAAa;EACjD,UAAU;;wBAmSU,IACpB,MAAM,WACN,KAAK,gBACJ,QAAQ;qBAaE,cAAK;;wBAGI,IAAI,MAAM,WAAW,KAAK,gBAAgB;;;;wBAS1C,MACpB,MAAM,WACN,KAAK,gBACJ"}
|
|
@@ -287,10 +287,7 @@ function childServices(host, ctx, phCliEntry) {
|
|
|
287
287
|
id: name,
|
|
288
288
|
name,
|
|
289
289
|
command: () => `node "${phCliEntry}" run ${wrapper.host}`,
|
|
290
|
-
env: () => ({
|
|
291
|
-
FEATURE_UNIFORM_RUNNERS_ENABLED: "1",
|
|
292
|
-
PH_USER_DATA_DIR: defaultUserDataDir(ctx.projectRoot, ctx.env)
|
|
293
|
-
}),
|
|
290
|
+
env: () => ({ PH_USER_DATA_DIR: defaultUserDataDir(ctx.projectRoot, ctx.env) }),
|
|
294
291
|
readiness: {
|
|
295
292
|
patterns: [{
|
|
296
293
|
name: "up",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clint-runner.mjs","names":[],"sources":["../../src/runners/removed-forms.ts","../../src/runners/proxy-plugin.ts","../../src/runners/member-records.ts","../../src/runners/clint-runner.ts"],"sourcesContent":["import type { z } from \"zod\";\n\n/**\n * Output tokens (typed-host-configs T3) replaced the sibling-host reference\n * forms the clint runners used to resolve themselves. A removed key is not\n * just \"unrecognized\": its error names the token form that replaces it.\n * Pass the result as a strict object's `error` option.\n */\nexport function removedKeyError(\n key: string,\n hint: (input: Record<string, unknown>) => string,\n): z.core.$ZodErrorMap {\n return (issue) => {\n if (issue.code !== \"unrecognized_keys\" || !issue.keys.includes(key)) {\n return undefined;\n }\n const input =\n typeof issue.input === \"object\" && issue.input !== null\n ? (issue.input as Record<string, unknown>)\n : {};\n return `\\`${key}\\` was removed; ${hint(input)}`;\n };\n}\n\n/** A quoted host name from a removed reference, or a placeholder. */\nexport function quotedHost(value: unknown, placeholder: string): string {\n return typeof value === \"string\" && value.length > 0\n ? JSON.stringify(value)\n : placeholder;\n}\n","import type { HostPlugin } from \"@powerhousedao/host-core\";\nimport { ref } from \"@powerhousedao/host-core/schema\";\nimport { z } from \"zod\";\nimport { removedKeyError } from \"./removed-forms.js\";\n\n/**\n * R5 — the clint proxy as a COMPOUND plugin (rewire plan: appliesTo\n * \"compound\", the member-set branch of the hierarchy). One front port routes\n * to upstream URLs, WebSocket-aware. A route to a member names that member\n * host's own output (e.g. `{ $output: { host: \"assistant\", path: [\"origin\"] } }`),\n * resolved before the runner sees the config — the proxy never derives an\n * address from a declared port. Declarative veneer over the clint package's\n * createProxyServer; the route table assembly is pure\n * (buildProxyRouteTable) and unit-tested without sockets.\n */\n\n/** The token form that replaced a route's `member` reference. */\nfunction memberHint(input: Record<string, unknown>): string {\n const member =\n typeof input.member === \"string\" && input.member.length > 0\n ? `, member: ${JSON.stringify(input.member)}`\n : \"\";\n return `point \\`upstream\\` at the member host's output: upstream: <host>.origin from ../<host>/outputs.js, or { $output: { host: \"<member's host>\"${member}, path: [\"origin\"] } }.`;\n}\n\n/** The proxy config, built once per form: `url` is the upstream field —\n * `ref(z.url())` when declared, `z.url()` when resolved. */\nfunction buildProxyPluginConfigSchema<U extends z.ZodType>(url: U) {\n /** One route: an upstream URL (literal or output token) plus optional\n * path + ws. */\n const proxyRouteSchema = z.strictObject(\n {\n upstream: url,\n path: z.string().optional(),\n ws: z.boolean().optional(),\n },\n { error: removedKeyError(\"member\", memberHint) },\n );\n return z.strictObject({\n /** Front port (0 = any free port). */\n port: z.number().int().min(0),\n /** Bind address (default \"0.0.0.0\"). */\n host: z.string().min(1).optional(),\n publicUrl: z.url().optional(),\n /** Route prefix -> target. */\n routes: z.record(z.string(), proxyRouteSchema),\n });\n}\n\n/** `runner.proxy` on a clint-runner host, resolved (what the runner reads). */\nexport const proxyPluginConfigSchema = buildProxyPluginConfigSchema(z.url());\n\n/** `runner.proxy` as declared: upstreams may be output tokens. */\nexport const declaredProxyPluginConfigSchema = buildProxyPluginConfigSchema(\n ref(z.url()),\n);\n\nexport type ProxyPluginConfig = z.output<typeof proxyPluginConfigSchema>;\nexport type ProxyPluginConfigInput = z.input<\n typeof declaredProxyPluginConfigSchema\n>;\n\nexport interface ResolvedProxyRoute {\n prefix: string;\n upstream: string;\n ws: boolean;\n source: string;\n}\n\n/** Pure route-table assembly: each upstream (+ optional path). */\nexport function buildProxyRouteTable(\n config: ProxyPluginConfig,\n): ResolvedProxyRoute[] {\n return Object.entries(config.routes).map(([prefix, route]) => ({\n prefix,\n upstream: `${route.upstream.replace(/\\/+$/, \"\")}${route.path ?? \"\"}`,\n ws: route.ws ?? false,\n source: `upstream:${route.upstream}`,\n }));\n}\n\nexport interface ClintCompoundContext {\n proxyRoutes?: ResolvedProxyRoute[];\n /** The proxy's listening URL, set at onMembersReady. */\n proxyUrl?: string;\n proxyStop?: () => Promise<void>;\n logger?: { info: (m: string) => void };\n}\n\nexport function createProxyPlugin(config: ProxyPluginConfig): HostPlugin<{\n onMembersReady: (ctx: ClintCompoundContext) => Promise<void>;\n onShutdown: (ctx: ClintCompoundContext) => Promise<void>;\n}> {\n return {\n name: \"clint-proxy\",\n appliesTo: \"compound\",\n hooks: {\n onMembersReady: async (ctx) => {\n const table = buildProxyRouteTable(config);\n ctx.proxyRoutes = table;\n const { createProxyServer } = await import(\"../core/proxy.js\");\n const instance = await createProxyServer({\n port: config.port,\n host: config.host ?? \"0.0.0.0\",\n publicUrl: config.publicUrl,\n logger: (ctx.logger ?? console) as never,\n });\n for (const route of table) {\n instance.addRoute({\n prefix: route.prefix,\n upstream: new URL(route.upstream),\n ws: route.ws,\n source: route.source,\n });\n }\n ctx.proxyUrl = instance.url;\n ctx.proxyStop = () => instance.stop();\n ctx.logger?.info(\n `[clint-proxy] listening on ${instance.url} — ${table.length} route(s)`,\n );\n },\n onShutdown: async (ctx) => {\n await ctx.proxyStop?.();\n },\n },\n };\n}\n\nexport default createProxyPlugin;\n","import { probeRun } from \"@powerhousedao/host-core\";\n\n/* Kept out of clint-runner.ts: a runner module exports only its verb\n * functions (plus schemas and constants). */\n\n/** How often {@link awaitRunRecord} re-reads a member's run record. */\nconst RECORD_POLL_MS = 100;\n\n/** A member whose outputs something reads, and what it waits for. */\nexport interface RecordWait {\n /** The child key (`children.<id>`). */\n id: string;\n /** The member host's `name` (its record is `.ph/run/<host>.json`). */\n host: string;\n /** How long to wait, in ms (the member's readiness timeout). */\n timeout: number;\n /** Who reads the member's outputs, for the error. */\n readers: string[];\n /** The member's service state, when clint started it: a `failed` or\n * `stopped` member will never publish, so the wait ends early. */\n status?: () => string | undefined;\n}\n\n/**\n * Waits for a started member's LIVE run record. A member counts as up when\n * its stdout matches the readiness pattern, but `ph run` writes the member's\n * run record only after the runner's `ready` resolves, so a reader that\n * looks right after the readiness line can find none. Polls until the\n * record is live, the member's service fails or stops, or `timeout` passes;\n * then throws naming the member, its record, the timeout and its readers.\n * An earlier run's stale record does not count: it is waited past.\n */\nexport async function awaitRunRecord(\n projectRoot: string,\n projectName: string,\n consumer: string,\n wait: RecordWait,\n pollMs = RECORD_POLL_MS,\n): Promise<void> {\n const deadline = Date.now() + wait.timeout;\n for (;;) {\n if (probeRun(projectRoot, wait.host, projectName).status === \"live\") {\n return;\n }\n const status = wait.status?.();\n const gone = status === \"failed\" || status === \"stopped\";\n if (gone || Date.now() >= deadline) {\n const why = gone\n ? `${status} before publishing its live run record`\n : `published no live run record within ${wait.timeout} ms (children.${wait.id}.config.readiness.timeout)`;\n throw new Error(\n `hosts/${consumer}/host.js: member \"${wait.id}\" is up (its readiness line matched) but ${why} (.ph/run/${wait.host}.json); ${wait.readers.join(\", \")} read its outputs.`,\n );\n }\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(pollMs, Math.max(0, deadline - Date.now()))),\n );\n }\n}\n","import { createInterface } from \"node:readline\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n compoundOutputSource,\n defaultUserDataDir,\n loadHost,\n loadProducers,\n outputRefsOf,\n outputSitesOf,\n planCompound,\n probeRun,\n processResolveEnv,\n refineStartOrder,\n resolveHostOutputs,\n runObserveHook,\n runObserveHookSequential,\n resolveHostPlugins,\n runRecordOutputSource,\n type DeferredResolution,\n type LoadedHost,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport { defineHostSchemas, ref } from \"@powerhousedao/host-core/schema\";\nimport { z } from \"zod\";\nimport {\n createProxyPlugin,\n declaredProxyPluginConfigSchema,\n proxyPluginConfigSchema,\n type ClintCompoundContext,\n} from \"./proxy-plugin.js\";\nimport { awaitRunRecord } from \"./member-records.js\";\nimport { quotedHost, removedKeyError } from \"./removed-forms.js\";\nimport fs from \"node:fs\";\nimport { createEventBus } from \"../core/events.js\";\nimport { isPortFree } from \"../core/preflight.js\";\nimport { createServiceManager, defineService } from \"../core/services.js\";\nimport { formatStatus } from \"../core/service-command.js\";\nimport type { ServiceDefinition, ServiceManager } from \"../core/types.js\";\n\n/**\n * clint-runner (P5.4): the clint shell as a compound runner. Each member\n * runs as `ph-cli run <member>` in its own process, scheduled by the ported\n * services manager; `lifecycle: \"detached\"` (default) leaves members running\n * and re-attaches next run, `\"attached\"` tears them down. `config.agents`\n * maps names to OpenAI-compatible endpoints (a literal, or a member's\n * `endpoints.openai` token resolved once it is up). `dev` adds a line chat\n * loop against the first agent; the ink REPL stays the library path.\n */\n\nexport const kind = \"compound\";\n\n/** The token form that replaced an agent's sibling `host` reference. */\nfunction agentHostHint(input: Record<string, unknown>): string {\n const host = quotedHost(input.host, '\"<agent host>\"');\n return `use url: <host>.endpoints.openai from ../<host>/outputs.js, or { url: { $output: { host: ${host}, path: [\"endpoints\", \"openai\"] } } }.`;\n}\n\n/** An agent the shell can chat with: the OpenAI-compatible base URL of an\n * agent API (an agent host's `endpoints.openai` output, or external). */\nfunction agentRefSchema<U extends z.ZodType>(url: U) {\n return z.strictObject(\n { url },\n { error: removedKeyError(\"host\", agentHostHint) },\n );\n}\n\n/**\n * The clint compound host, from one definition in two forms: DECLARED (what\n * host.js authors write) and RESOLVED (what `validateHost` checks).\n *\n * `config.agents.*.url` and `runner.proxy.routes.*.upstream` are DEFERRED\n * self fields: they typically name outputs of this compound's own members,\n * which exist only once clint has started them inside the verb. They take\n * tokens in BOTH forms (`ref`, not `s.tokenable`), and the runner resolves\n * them after its members are up, then parses them with `ownFieldsSchema`.\n */\nconst schemas = defineHostSchemas((base) => {\n /** clint-runner's own `runner` options, on top of the common base. */\n const clintRunnerOptionsSchema = base.runnerBaseSchema\n .extend({\n /** \"detached\" (default): children outlive the shell and are\n * re-attached on the next run. \"attached\": the shell tears them down\n * on exit. */\n lifecycle: z.enum([\"attached\", \"detached\"]).optional(),\n /** One front port routing to upstreams (the clint proxy plugin). */\n proxy: declaredProxyPluginConfigSchema.optional(),\n })\n .strict();\n\n /** A member's scheduling knobs. Members run as their own `ph-cli run\n * <host>` process, so the wrapper's `config` is read by clint (not passed\n * to the member) and holds only these. */\n const clintMemberConfigSchema = z.strictObject({\n /** When the member counts as up: a stdout pattern (regex source, case\n * insensitive) and a timeout in ms. */\n readiness: z\n .strictObject({\n pattern: z.string().min(1).optional(),\n timeout: z.number().int().positive().optional(),\n })\n .optional(),\n });\n\n const cliHostConfigSchema = z.strictObject({\n agents: z.record(z.string(), agentRefSchema(ref(z.url()))).optional(),\n /** Member start order; must name declared children. Unnamed members\n * start after the named ones, in declaration order. */\n startOrder: z.array(z.string().min(1)).optional(),\n });\n\n // Extend the unrefined base, refine last (zod refuses to extend a refined\n // object).\n return base.compoundHostSchema\n .extend({\n runner: clintRunnerOptionsSchema,\n children: z.record(\n z.string(),\n base.childWrapperSchema.extend({\n config: clintMemberConfigSchema.optional(),\n }),\n ),\n config: cliHostConfigSchema.optional(),\n })\n .superRefine(refineStartOrder);\n});\n\n/** Declared form: what a host file may contain before resolution. */\nexport const declaredHostSchema = schemas.declaredHostSchema;\n/** Resolved form: what `validateHost` checks and the verbs receive (the\n * deferred self fields may still carry tokens; see above). */\nexport const hostSchema = schemas.hostSchema;\n\n/** The deferred self fields once resolved (after member start). */\nconst ownFieldsSchema = z.strictObject({\n agents: z.record(z.string(), agentRefSchema(z.url())).optional(),\n proxy: proxyPluginConfigSchema.optional(),\n});\n\n/** What a clint host.js author writes. */\nexport type ClintHostInput = z.input<typeof declaredHostSchema>;\n/** What the verbs receive. */\nexport type ClintHost = z.output<typeof hostSchema>;\ntype OwnFields = z.output<typeof ownFieldsSchema>;\n\n/** The verbs this runner exports (the rest of its exports are not verbs). */\nexport const verbs = [\"run\", \"serve\", \"dev\", \"build\"] as const;\n\n/** Live outputs of the compound's members, keyed by child name\n * (`outputs` undefined when the member published no live run record). */\nexport type LiveMemberOutputs = Record<\n string,\n { host: string; outputs: unknown }\n>;\n\n/**\n * Resolve the shell's own tokens before any member starts: `$env`, the\n * built-ins and other hosts' outputs now (an unset variable or a producer\n * that is not running fails with nothing started); tokens naming its own\n * members' outputs are deferred until those members are up (`finish`).\n * `children` stay as declared: each member resolves its own.\n */\nasync function resolveOwnTokens(\n host: ClintHost,\n ctx: RunnerContext,\n projectName: string,\n): Promise<DeferredResolution<ClintHost>> {\n const members = Object.entries(host.children).map(([key, wrapper]) => ({\n key,\n host: wrapper.host,\n }));\n const foreign = outputRefsOf({ ...host, children: {} }).filter(\n (ref) => !members.some((member) => member.host === ref.host),\n );\n return resolveHostOutputs(\n host,\n {\n outputs: runRecordOutputSource(ctx.projectRoot, {\n consumer: host.name,\n producers: await loadProducers(ctx.projectRoot, foreign),\n projectName,\n }),\n ...processResolveEnv(ctx.projectRoot, ctx.env),\n where: `hosts/${host.name}/host.js`,\n },\n { deferSelf: { members } },\n );\n}\n\n/** Finish the deferred self tokens from the members' live run records. */\nfunction finishOwnTokens(\n pending: DeferredResolution<ClintHost>,\n live: LiveMemberOutputs,\n name: string,\n): ClintHost {\n const started = new Map<string, unknown>();\n for (const [key, member] of Object.entries(live)) {\n if (member.outputs !== undefined) started.set(key, member.outputs);\n }\n const silent = pending.needs.filter((key) => !started.has(key));\n if (silent.length > 0) {\n const paths = pending.deferred\n .filter((d) => d.members.some((key) => silent.includes(key)))\n .map((d) => d.path);\n throw new Error(\n `hosts/${name}/host.js: ${paths.join(\", \")} read the outputs of member ${silent.map((key) => `\"${key}\"`).join(\", \")}, which is up but published no live run record (.ph/run/<host>.json) to read them from.`,\n );\n }\n const members = Object.entries(pending.host.children).map(\n ([key, wrapper]) => ({ key, host: wrapper.host }),\n );\n return pending.finish(compoundOutputSource(members, started, name));\n}\n\n/** Started members' outputs, read from their own run records (members run\n * as separate `ph-cli run` processes, which publish their outputs there). */\nfunction liveMemberOutputs(\n projectRoot: string,\n projectName: string,\n memberHosts: Record<string, string>,\n): LiveMemberOutputs {\n const members: LiveMemberOutputs = {};\n for (const [id, hostName] of Object.entries(memberHosts)) {\n const probe = probeRun(projectRoot, hostName, projectName);\n members[id] = {\n host: hostName,\n outputs: probe.status === \"live\" ? probe.record.outputs : undefined,\n };\n }\n return members;\n}\n\n/** What starting the shell produces: the resolved agent endpoints and, when\n * `runner.proxy` is set, the proxy's URL. Member outputs belong to the\n * members. */\nexport const outputsSchema = z.strictObject({\n agents: z.record(z.string(), z.url()),\n proxy: z.strictObject({ url: z.url() }).optional(),\n});\n\nexport type ClintOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/clint/clint-runner\": {\n host: ClintHostInput;\n outputs: ClintOutputs;\n };\n }\n}\n\n// A URL in stdout is the universal \"I am serving\" signal across member kinds\n// (switchboard prints \"MCP server available at http://…\", preview \"Local:\",\n// the agent \"agent API … http://…\").\nconst DEFAULT_READINESS = \"https?://|listening|ready\";\n/** How long a member may take to print its readiness line, in ms; also how\n * long clint then waits for its run record when something reads it. */\nconst READINESS_TIMEOUT = 180_000;\n\n/** Resolve the project's ph-cli entry the same way host-core resolves runner\n * modules: from the PROJECT's dependency tree. */\nfunction resolvePhCliEntry(projectRoot: string): string {\n const require_ = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n const pkgPath = require_.resolve(\"@powerhousedao/ph-cli/package.json\");\n return path.join(path.dirname(pkgPath), \"dist\", \"cli.mjs\");\n}\n\nfunction childServices(\n host: ClintHost,\n ctx: RunnerContext,\n phCliEntry: string,\n): ServiceDefinition<Record<string, unknown>>[] {\n return Object.entries(host.children).map(([name, wrapper]) =>\n defineService({\n id: name,\n name,\n command: () => `node \"${phCliEntry}\" run ${wrapper.host}`,\n env: () => ({\n FEATURE_UNIFORM_RUNNERS_ENABLED: \"1\",\n PH_USER_DATA_DIR: defaultUserDataDir(ctx.projectRoot, ctx.env),\n }),\n readiness: {\n patterns: [\n {\n name: \"up\",\n pattern: new RegExp(\n wrapper.config?.readiness?.pattern ?? DEFAULT_READINESS,\n \"i\",\n ),\n },\n ],\n timeout: wrapper.config?.readiness?.timeout ?? READINESS_TIMEOUT,\n },\n }),\n );\n}\n\nfunction readProjectName(projectRoot: string, fallback: string): string {\n try {\n return (\n (\n JSON.parse(\n fs.readFileSync(path.join(projectRoot, \"package.json\"), \"utf8\"),\n ) as { name?: string }\n ).name ?? fallback\n );\n } catch {\n return fallback;\n }\n}\n\nasync function stopAll(\n services: ServiceManager,\n names: string[],\n): Promise<void> {\n for (const id of names) {\n try {\n await services.stop(id);\n } catch {\n // already stopped\n }\n }\n}\n\n/** The shell's handle: the runner contract plus the services manager. */\nexport interface CliRunHandle extends RunnerHandle<ClintOutputs> {\n services: ServiceManager;\n}\n\nasync function startShell(\n host: ClintHost,\n ctx: RunnerContext,\n): Promise<CliRunHandle> {\n const projectName = readProjectName(ctx.projectRoot, host.name);\n // resolveOwnTokens also substitutes the \"${userData}\"/\"${projectRoot}\"\n // sugar (processResolveEnv's built-ins); member wrappers stay as declared.\n const pending = await resolveOwnTokens(host, ctx, projectName);\n const resolved = pending.host;\n const config = resolved.config ?? {};\n const lifecycle = resolved.runner.lifecycle ?? \"detached\";\n\n const phCliEntry = resolvePhCliEntry(ctx.projectRoot);\n const children = resolved.children;\n const definitions = childServices(resolved, ctx, phCliEntry);\n const eventBus = createEventBus();\n // R5: compound plugins (appliesTo \"compound\" — e.g. the proxy) run over the\n // member set. Built-ins resolve from a declared `runner.plugins`; the proxy\n // is registered when a `runner.proxy` block is present (ergonomic alias).\n const servicesDir = path.join(ctx.projectRoot, \".ph\", \"services\");\n const services = createServiceManager(definitions, {\n config: {},\n servicesDir,\n eventBus,\n });\n\n // Each member's own host.js: its `$output` tokens on sibling members\n // decide the start order (each member resolves them from its producers'\n // run records as it starts).\n const names = definitions.map((d) => d.id);\n const loaded = new Map<string, LoadedHost>();\n for (const id of names) {\n loaded.set(id, await loadHost(ctx.projectRoot, children[id].host));\n }\n // Start order: the same dependency plan the generic compound uses —\n // producers before consumers (ties keep declaration order); a\n // config.startOrder must agree with the tokens. Tokens on hosts outside\n // the compound read standalone producers and do not order members.\n const memberRefs = names.map((key) => ({ key, host: children[key].host }));\n const plan = planCompound(\n names.map((key) => ({\n key,\n host: children[key].host,\n refs: outputSitesOf(loaded.get(key)?.host)\n .filter(({ ref }) => memberRefs.some((m) => m.host === ref.host))\n .map(({ ref, path }) => ({ ref, path })),\n })),\n config.startOrder,\n );\n const ordered = plan.order;\n // Whose outputs are read, and by whom: the shell's deferred self fields,\n // and the members that consume a sibling.\n const readers = new Map<string, string[]>();\n const addReader = (id: string, reader: string) =>\n readers.set(id, [...(readers.get(id) ?? []), reader]);\n for (const deferred of pending.deferred) {\n for (const id of deferred.members) addReader(id, deferred.path);\n }\n for (const edge of plan.edges) {\n addReader(edge.producer, `member \"${edge.consumer}\"`);\n }\n /** Wait for a member's live run record when something reads it. With\n * `managed` (clint's own service state describes it), a failed or stopped\n * service ends the wait early; a member found serving on its port is not\n * clint's to watch, so it gets the full timeout. */\n const waitForRecord = async (\n id: string,\n memberHost: string,\n managed = true,\n ) => {\n const read = readers.get(id);\n if (!read) return;\n try {\n await awaitRunRecord(ctx.projectRoot, projectName, host.name, {\n id,\n host: memberHost,\n timeout: children[id].config?.readiness?.timeout ?? READINESS_TIMEOUT,\n readers: read,\n ...(managed\n ? {\n status: () =>\n services.list(id).find((s) => s.serviceId === id)?.status,\n }\n : {}),\n });\n } catch (error) {\n if (lifecycle === \"attached\") await stopAll(services, names);\n throw error;\n }\n };\n\n const memberHosts: Record<string, string> = {};\n for (const id of ordered) {\n // Re-attach checks, strongest first. (1) The member's OWN run record —\n // written with the member process's real pid (mastra-runner, the generic\n // compound). (2) Port occupancy for record-less bridge members. (3) The\n // service state file — weakest on Windows, where it records the cmd shim\n // pid, which dies on console teardown while the node grandchild survives.\n const wrapper = children[id];\n const member =\n loaded.get(id) ?? (await loadHost(ctx.projectRoot, wrapper.host));\n memberHosts[id] = member.host.name;\n const record = probeRun(ctx.projectRoot, member.host.name, projectName);\n if (record.status === \"live\") {\n console.log(\n `[${resolved.name}] ${id}: already running (pid ${record.record.pid}) — re-attached`,\n );\n continue;\n }\n const memberPort =\n typeof wrapper.runner?.port === \"number\"\n ? wrapper.runner.port\n : typeof member.host.runner.port === \"number\"\n ? member.host.runner.port\n : undefined;\n if (memberPort !== undefined && !(await isPortFree(memberPort))) {\n console.log(\n `[${resolved.name}] ${id}: port ${memberPort} already serving — re-attached`,\n );\n // It may still be booting (an earlier detached run, or started by\n // hand): its readers need its record, as after a fresh start.\n await waitForRecord(id, member.host.name, false);\n continue;\n }\n const already = services\n .list(id)\n .some((s) => s.status === \"ready\" || s.status === \"starting\");\n if (already) {\n console.log(`[${resolved.name}] ${id}: already running — re-attached`);\n await waitForRecord(id, member.host.name);\n continue;\n }\n console.log(`[${resolved.name}] starting ${id}…`);\n await services.start(id, {\n workdir: ctx.projectRoot,\n cwd: ctx.projectRoot,\n });\n const status = services.list(id).find((s) => s.serviceId === id);\n if (status) console.log(` ${formatStatus(status)}`);\n // Before anything reads its outputs (the next member, or the shell's\n // own deferred fields below).\n await waitForRecord(id, member.host.name);\n }\n\n // The deferred self fields (agent urls, proxy upstreams) name the\n // members' outputs, which exist now.\n let own: OwnFields;\n try {\n const finished = finishOwnTokens(\n pending,\n liveMemberOutputs(ctx.projectRoot, projectName, memberHosts),\n host.name,\n );\n const parsedOwn = ownFieldsSchema.safeParse({\n agents: finished.config?.agents,\n proxy: finished.runner.proxy,\n });\n if (!parsedOwn.success) {\n throw new Error(\n `hosts/${host.name}: agents/proxy resolved to invalid values:\\n${z.prettifyError(parsedOwn.error)}`,\n );\n }\n own = parsedOwn.data;\n } catch (error) {\n if (lifecycle === \"attached\") await stopAll(services, names);\n throw error;\n }\n\n // Compound-plugin pipeline (CompoundCore): resolve entries + the proxy\n // ergonomic alias, then fire onMembersReady now that endpoints are known.\n const pluginEntries = resolved.runner.plugins;\n const resolvedPlugins = pluginEntries\n ? (\n await resolveHostPlugins(\n ctx.projectRoot,\n \"compound\",\n ctx.verb,\n pluginEntries,\n `hosts/${host.name}/host.js`,\n )\n ).map((r) => r.plugin)\n : [];\n const proxyBlock = own.proxy;\n if (proxyBlock) {\n resolvedPlugins.push(createProxyPlugin(proxyBlock));\n }\n const compoundCtx: ClintCompoundContext = {\n logger: { info: (m: string) => console.log(m) },\n };\n if (resolvedPlugins.length > 0) {\n await runObserveHook(\"onMembersReady\", resolvedPlugins, compoundCtx);\n }\n\n const agents: Record<string, string> = {};\n for (const [name, agent] of Object.entries(own.agents ?? {})) {\n agents[name] = agent.url.replace(/\\/$/, \"\");\n }\n if (Object.keys(agents).length > 0) {\n console.log(\n `[${resolved.name}] agents: ${Object.entries(agents)\n .map(([n, u]) => `${n} → ${u}`)\n .join(\", \")}`,\n );\n }\n\n const shutdown = async () => {\n if (resolvedPlugins.length > 0) {\n await runObserveHookSequential(\n \"onShutdown\",\n resolvedPlugins,\n compoundCtx,\n );\n }\n if (lifecycle === \"attached\") {\n await stopAll(services, names);\n } else {\n console.log(\n `[${resolved.name}] detached lifecycle: children keep running ` +\n `(stop them with the ${resolved.name} service commands or taskkill).`,\n );\n }\n };\n\n // Validated before the stack is handed out: an invalid output (e.g. a proxy\n // bound to a bare IPv6 host, which does not form a URL) tears down what\n // was started instead of leaving it half-up.\n const parsedOutputs = outputsSchema.safeParse({\n agents,\n ...(compoundCtx.proxyUrl ? { proxy: { url: compoundCtx.proxyUrl } } : {}),\n });\n if (!parsedOutputs.success) {\n await shutdown();\n throw new Error(\n `hosts/${host.name}: the shell produced invalid outputs:\\n${z.prettifyError(parsedOutputs.error)}`,\n );\n }\n const outputs = parsedOutputs.data;\n\n if (lifecycle === \"attached\") {\n const onSignal = () => {\n void shutdown().finally(() => process.exit(130));\n };\n process.once(\"SIGINT\", onSignal);\n process.once(\"SIGTERM\", onSignal);\n }\n\n // Members were started (and awaited to readiness) above.\n return { outputs, ready: Promise.resolve(), services, shutdown };\n}\n\n/** Minimal line chat against an agent's OpenAI-compatible endpoint. */\nasync function chatLoop(agents: Record<string, string>): Promise<void> {\n const [agentName, endpoint] = Object.entries(agents)[0] ?? [];\n if (!agentName || !endpoint) {\n console.log(\"No agents configured (config.agents) — chat unavailable.\");\n return;\n }\n console.log(`Chatting with ${agentName} (${endpoint}). /exit to quit.`);\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const ask = (q: string) =>\n new Promise<string>((resolve) => rl.question(q, resolve));\n for (;;) {\n const line = (await ask(\"> \")).trim();\n if (line === \"/exit\" || line === \"exit\") break;\n if (!line) continue;\n try {\n const res = await fetch(`${endpoint}/chat/completions`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n messages: [{ role: \"user\", content: line }],\n }),\n });\n const body = (await res.json()) as {\n choices?: { message?: { content?: string } }[];\n error?: { message?: string };\n };\n console.log(\n body.choices?.[0]?.message?.content ??\n `[error] ${body.error?.message ?? res.status}`,\n );\n } catch (error) {\n console.log(`[transport error] ${String(error)}`);\n }\n }\n rl.close();\n}\n\nexport async function run(\n host: ClintHost,\n ctx: RunnerContext,\n): Promise<CliRunHandle> {\n const handle = await startShell(host, ctx);\n console.log(\n `[${host.name}] services up. ` +\n `(ph run ${host.name} dev for the chat shell; Ctrl+C ${\n host.runner.lifecycle === \"attached\"\n ? \"stops the children\"\n : \"leaves children running\"\n }.)`,\n );\n return handle;\n}\n\nexport const serve = run;\n\n/** dev = services up + the line chat shell (blocks until /exit). */\nexport async function dev(host: ClintHost, ctx: RunnerContext): Promise<void> {\n const handle = await startShell(host, ctx);\n await chatLoop(handle.outputs.agents);\n await handle.shutdown();\n}\n\n/** build = forward build to each member host that exports it (fail loud on\n * members that do not — a silent skip would report success on an unbuilt\n * set), same posture as the generic compound. */\nexport async function build(\n host: ClintHost,\n ctx: RunnerContext,\n): Promise<void> {\n const { getVerb, resolveRunnerModule, validateHost } =\n await import(\"@powerhousedao/host-core\");\n for (const [name, wrapper] of Object.entries(host.children)) {\n const member = await loadHost(ctx.projectRoot, wrapper.host);\n const specifier = member.host.runner.module;\n const runner = await resolveRunnerModule(ctx.projectRoot, specifier);\n const validated = validateHost(\n runner,\n specifier,\n member.host,\n `hosts/${wrapper.host}/host.js`,\n );\n const fn = getVerb(runner, specifier, \"build\");\n console.log(`[${host.name}] build → ${name} (${wrapper.host})`);\n await fn(validated, {\n ...ctx,\n verb: \"build\",\n parent: { host: host.name, verb: ctx.verb },\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAQA,SAAgB,gBACd,KACA,MACqB;CACrB,QAAQ,UAAU;EAChB,IAAI,MAAM,SAAS,uBAAuB,CAAC,MAAM,KA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AAK,KAAK,YAAY,KAAK,IAAI,QAAQ,KAAK,EAAE;EAC9D,MAAM,GAAG,WAAW;GAClB,GAAG;GACH,MAAM;GACN,QAAQ;IAAE,MAAM,KAAK;IAAM,MAAM,IAAI;GAAK;EAC5C,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"clint-runner.mjs","names":[],"sources":["../../src/runners/removed-forms.ts","../../src/runners/proxy-plugin.ts","../../src/runners/member-records.ts","../../src/runners/clint-runner.ts"],"sourcesContent":["import type { z } from \"zod\";\n\n/**\n * Output tokens (typed-host-configs T3) replaced the sibling-host reference\n * forms the clint runners used to resolve themselves. A removed key is not\n * just \"unrecognized\": its error names the token form that replaces it.\n * Pass the result as a strict object's `error` option.\n */\nexport function removedKeyError(\n key: string,\n hint: (input: Record<string, unknown>) => string,\n): z.core.$ZodErrorMap {\n return (issue) => {\n if (issue.code !== \"unrecognized_keys\" || !issue.keys.includes(key)) {\n return undefined;\n }\n const input =\n typeof issue.input === \"object\" && issue.input !== null\n ? (issue.input as Record<string, unknown>)\n : {};\n return `\\`${key}\\` was removed; ${hint(input)}`;\n };\n}\n\n/** A quoted host name from a removed reference, or a placeholder. */\nexport function quotedHost(value: unknown, placeholder: string): string {\n return typeof value === \"string\" && value.length > 0\n ? JSON.stringify(value)\n : placeholder;\n}\n","import type { HostPlugin } from \"@powerhousedao/host-core\";\nimport { ref } from \"@powerhousedao/host-core/schema\";\nimport { z } from \"zod\";\nimport { removedKeyError } from \"./removed-forms.js\";\n\n/**\n * R5 — the clint proxy as a COMPOUND plugin (rewire plan: appliesTo\n * \"compound\", the member-set branch of the hierarchy). One front port routes\n * to upstream URLs, WebSocket-aware. A route to a member names that member\n * host's own output (e.g. `{ $output: { host: \"assistant\", path: [\"origin\"] } }`),\n * resolved before the runner sees the config — the proxy never derives an\n * address from a declared port. Declarative veneer over the clint package's\n * createProxyServer; the route table assembly is pure\n * (buildProxyRouteTable) and unit-tested without sockets.\n */\n\n/** The token form that replaced a route's `member` reference. */\nfunction memberHint(input: Record<string, unknown>): string {\n const member =\n typeof input.member === \"string\" && input.member.length > 0\n ? `, member: ${JSON.stringify(input.member)}`\n : \"\";\n return `point \\`upstream\\` at the member host's output: upstream: <host>.origin from ../<host>/outputs.js, or { $output: { host: \"<member's host>\"${member}, path: [\"origin\"] } }.`;\n}\n\n/** The proxy config, built once per form: `url` is the upstream field —\n * `ref(z.url())` when declared, `z.url()` when resolved. */\nfunction buildProxyPluginConfigSchema<U extends z.ZodType>(url: U) {\n /** One route: an upstream URL (literal or output token) plus optional\n * path + ws. */\n const proxyRouteSchema = z.strictObject(\n {\n upstream: url,\n path: z.string().optional(),\n ws: z.boolean().optional(),\n },\n { error: removedKeyError(\"member\", memberHint) },\n );\n return z.strictObject({\n /** Front port (0 = any free port). */\n port: z.number().int().min(0),\n /** Bind address (default \"0.0.0.0\"). */\n host: z.string().min(1).optional(),\n publicUrl: z.url().optional(),\n /** Route prefix -> target. */\n routes: z.record(z.string(), proxyRouteSchema),\n });\n}\n\n/** `runner.proxy` on a clint-runner host, resolved (what the runner reads). */\nexport const proxyPluginConfigSchema = buildProxyPluginConfigSchema(z.url());\n\n/** `runner.proxy` as declared: upstreams may be output tokens. */\nexport const declaredProxyPluginConfigSchema = buildProxyPluginConfigSchema(\n ref(z.url()),\n);\n\nexport type ProxyPluginConfig = z.output<typeof proxyPluginConfigSchema>;\nexport type ProxyPluginConfigInput = z.input<\n typeof declaredProxyPluginConfigSchema\n>;\n\nexport interface ResolvedProxyRoute {\n prefix: string;\n upstream: string;\n ws: boolean;\n source: string;\n}\n\n/** Pure route-table assembly: each upstream (+ optional path). */\nexport function buildProxyRouteTable(\n config: ProxyPluginConfig,\n): ResolvedProxyRoute[] {\n return Object.entries(config.routes).map(([prefix, route]) => ({\n prefix,\n upstream: `${route.upstream.replace(/\\/+$/, \"\")}${route.path ?? \"\"}`,\n ws: route.ws ?? false,\n source: `upstream:${route.upstream}`,\n }));\n}\n\nexport interface ClintCompoundContext {\n proxyRoutes?: ResolvedProxyRoute[];\n /** The proxy's listening URL, set at onMembersReady. */\n proxyUrl?: string;\n proxyStop?: () => Promise<void>;\n logger?: { info: (m: string) => void };\n}\n\nexport function createProxyPlugin(config: ProxyPluginConfig): HostPlugin<{\n onMembersReady: (ctx: ClintCompoundContext) => Promise<void>;\n onShutdown: (ctx: ClintCompoundContext) => Promise<void>;\n}> {\n return {\n name: \"clint-proxy\",\n appliesTo: \"compound\",\n hooks: {\n onMembersReady: async (ctx) => {\n const table = buildProxyRouteTable(config);\n ctx.proxyRoutes = table;\n const { createProxyServer } = await import(\"../core/proxy.js\");\n const instance = await createProxyServer({\n port: config.port,\n host: config.host ?? \"0.0.0.0\",\n publicUrl: config.publicUrl,\n logger: (ctx.logger ?? console) as never,\n });\n for (const route of table) {\n instance.addRoute({\n prefix: route.prefix,\n upstream: new URL(route.upstream),\n ws: route.ws,\n source: route.source,\n });\n }\n ctx.proxyUrl = instance.url;\n ctx.proxyStop = () => instance.stop();\n ctx.logger?.info(\n `[clint-proxy] listening on ${instance.url} — ${table.length} route(s)`,\n );\n },\n onShutdown: async (ctx) => {\n await ctx.proxyStop?.();\n },\n },\n };\n}\n\nexport default createProxyPlugin;\n","import { probeRun } from \"@powerhousedao/host-core\";\n\n/* Kept out of clint-runner.ts: a runner module exports only its verb\n * functions (plus schemas and constants). */\n\n/** How often {@link awaitRunRecord} re-reads a member's run record. */\nconst RECORD_POLL_MS = 100;\n\n/** A member whose outputs something reads, and what it waits for. */\nexport interface RecordWait {\n /** The child key (`children.<id>`). */\n id: string;\n /** The member host's `name` (its record is `.ph/run/<host>.json`). */\n host: string;\n /** How long to wait, in ms (the member's readiness timeout). */\n timeout: number;\n /** Who reads the member's outputs, for the error. */\n readers: string[];\n /** The member's service state, when clint started it: a `failed` or\n * `stopped` member will never publish, so the wait ends early. */\n status?: () => string | undefined;\n}\n\n/**\n * Waits for a started member's LIVE run record. A member counts as up when\n * its stdout matches the readiness pattern, but `ph run` writes the member's\n * run record only after the runner's `ready` resolves, so a reader that\n * looks right after the readiness line can find none. Polls until the\n * record is live, the member's service fails or stops, or `timeout` passes;\n * then throws naming the member, its record, the timeout and its readers.\n * An earlier run's stale record does not count: it is waited past.\n */\nexport async function awaitRunRecord(\n projectRoot: string,\n projectName: string,\n consumer: string,\n wait: RecordWait,\n pollMs = RECORD_POLL_MS,\n): Promise<void> {\n const deadline = Date.now() + wait.timeout;\n for (;;) {\n if (probeRun(projectRoot, wait.host, projectName).status === \"live\") {\n return;\n }\n const status = wait.status?.();\n const gone = status === \"failed\" || status === \"stopped\";\n if (gone || Date.now() >= deadline) {\n const why = gone\n ? `${status} before publishing its live run record`\n : `published no live run record within ${wait.timeout} ms (children.${wait.id}.config.readiness.timeout)`;\n throw new Error(\n `hosts/${consumer}/host.js: member \"${wait.id}\" is up (its readiness line matched) but ${why} (.ph/run/${wait.host}.json); ${wait.readers.join(\", \")} read its outputs.`,\n );\n }\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(pollMs, Math.max(0, deadline - Date.now()))),\n );\n }\n}\n","import { createInterface } from \"node:readline\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n compoundOutputSource,\n defaultUserDataDir,\n loadHost,\n loadProducers,\n outputRefsOf,\n outputSitesOf,\n planCompound,\n probeRun,\n processResolveEnv,\n refineStartOrder,\n resolveHostOutputs,\n runObserveHook,\n runObserveHookSequential,\n resolveHostPlugins,\n runRecordOutputSource,\n type DeferredResolution,\n type LoadedHost,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport { defineHostSchemas, ref } from \"@powerhousedao/host-core/schema\";\nimport { z } from \"zod\";\nimport {\n createProxyPlugin,\n declaredProxyPluginConfigSchema,\n proxyPluginConfigSchema,\n type ClintCompoundContext,\n} from \"./proxy-plugin.js\";\nimport { awaitRunRecord } from \"./member-records.js\";\nimport { quotedHost, removedKeyError } from \"./removed-forms.js\";\nimport fs from \"node:fs\";\nimport { createEventBus } from \"../core/events.js\";\nimport { isPortFree } from \"../core/preflight.js\";\nimport { createServiceManager, defineService } from \"../core/services.js\";\nimport { formatStatus } from \"../core/service-command.js\";\nimport type { ServiceDefinition, ServiceManager } from \"../core/types.js\";\n\n/**\n * clint-runner (P5.4): the clint shell as a compound runner. Each member\n * runs as `ph-cli run <member>` in its own process, scheduled by the ported\n * services manager; `lifecycle: \"detached\"` (default) leaves members running\n * and re-attaches next run, `\"attached\"` tears them down. `config.agents`\n * maps names to OpenAI-compatible endpoints (a literal, or a member's\n * `endpoints.openai` token resolved once it is up). `dev` adds a line chat\n * loop against the first agent; the ink REPL stays the library path.\n */\n\nexport const kind = \"compound\";\n\n/** The token form that replaced an agent's sibling `host` reference. */\nfunction agentHostHint(input: Record<string, unknown>): string {\n const host = quotedHost(input.host, '\"<agent host>\"');\n return `use url: <host>.endpoints.openai from ../<host>/outputs.js, or { url: { $output: { host: ${host}, path: [\"endpoints\", \"openai\"] } } }.`;\n}\n\n/** An agent the shell can chat with: the OpenAI-compatible base URL of an\n * agent API (an agent host's `endpoints.openai` output, or external). */\nfunction agentRefSchema<U extends z.ZodType>(url: U) {\n return z.strictObject(\n { url },\n { error: removedKeyError(\"host\", agentHostHint) },\n );\n}\n\n/**\n * The clint compound host, from one definition in two forms: DECLARED (what\n * host.js authors write) and RESOLVED (what `validateHost` checks).\n *\n * `config.agents.*.url` and `runner.proxy.routes.*.upstream` are DEFERRED\n * self fields: they typically name outputs of this compound's own members,\n * which exist only once clint has started them inside the verb. They take\n * tokens in BOTH forms (`ref`, not `s.tokenable`), and the runner resolves\n * them after its members are up, then parses them with `ownFieldsSchema`.\n */\nconst schemas = defineHostSchemas((base) => {\n /** clint-runner's own `runner` options, on top of the common base. */\n const clintRunnerOptionsSchema = base.runnerBaseSchema\n .extend({\n /** \"detached\" (default): children outlive the shell and are\n * re-attached on the next run. \"attached\": the shell tears them down\n * on exit. */\n lifecycle: z.enum([\"attached\", \"detached\"]).optional(),\n /** One front port routing to upstreams (the clint proxy plugin). */\n proxy: declaredProxyPluginConfigSchema.optional(),\n })\n .strict();\n\n /** A member's scheduling knobs. Members run as their own `ph-cli run\n * <host>` process, so the wrapper's `config` is read by clint (not passed\n * to the member) and holds only these. */\n const clintMemberConfigSchema = z.strictObject({\n /** When the member counts as up: a stdout pattern (regex source, case\n * insensitive) and a timeout in ms. */\n readiness: z\n .strictObject({\n pattern: z.string().min(1).optional(),\n timeout: z.number().int().positive().optional(),\n })\n .optional(),\n });\n\n const cliHostConfigSchema = z.strictObject({\n agents: z.record(z.string(), agentRefSchema(ref(z.url()))).optional(),\n /** Member start order; must name declared children. Unnamed members\n * start after the named ones, in declaration order. */\n startOrder: z.array(z.string().min(1)).optional(),\n });\n\n // Extend the unrefined base, refine last (zod refuses to extend a refined\n // object).\n return base.compoundHostSchema\n .extend({\n runner: clintRunnerOptionsSchema,\n children: z.record(\n z.string(),\n base.childWrapperSchema.extend({\n config: clintMemberConfigSchema.optional(),\n }),\n ),\n config: cliHostConfigSchema.optional(),\n })\n .superRefine(refineStartOrder);\n});\n\n/** Declared form: what a host file may contain before resolution. */\nexport const declaredHostSchema = schemas.declaredHostSchema;\n/** Resolved form: what `validateHost` checks and the verbs receive (the\n * deferred self fields may still carry tokens; see above). */\nexport const hostSchema = schemas.hostSchema;\n\n/** The deferred self fields once resolved (after member start). */\nconst ownFieldsSchema = z.strictObject({\n agents: z.record(z.string(), agentRefSchema(z.url())).optional(),\n proxy: proxyPluginConfigSchema.optional(),\n});\n\n/** What a clint host.js author writes. */\nexport type ClintHostInput = z.input<typeof declaredHostSchema>;\n/** What the verbs receive. */\nexport type ClintHost = z.output<typeof hostSchema>;\ntype OwnFields = z.output<typeof ownFieldsSchema>;\n\n/** The verbs this runner exports (the rest of its exports are not verbs). */\nexport const verbs = [\"run\", \"serve\", \"dev\", \"build\"] as const;\n\n/** Live outputs of the compound's members, keyed by child name\n * (`outputs` undefined when the member published no live run record). */\nexport type LiveMemberOutputs = Record<\n string,\n { host: string; outputs: unknown }\n>;\n\n/**\n * Resolve the shell's own tokens before any member starts: `$env`, the\n * built-ins and other hosts' outputs now (an unset variable or a producer\n * that is not running fails with nothing started); tokens naming its own\n * members' outputs are deferred until those members are up (`finish`).\n * `children` stay as declared: each member resolves its own.\n */\nasync function resolveOwnTokens(\n host: ClintHost,\n ctx: RunnerContext,\n projectName: string,\n): Promise<DeferredResolution<ClintHost>> {\n const members = Object.entries(host.children).map(([key, wrapper]) => ({\n key,\n host: wrapper.host,\n }));\n const foreign = outputRefsOf({ ...host, children: {} }).filter(\n (ref) => !members.some((member) => member.host === ref.host),\n );\n return resolveHostOutputs(\n host,\n {\n outputs: runRecordOutputSource(ctx.projectRoot, {\n consumer: host.name,\n producers: await loadProducers(ctx.projectRoot, foreign),\n projectName,\n }),\n ...processResolveEnv(ctx.projectRoot, ctx.env),\n where: `hosts/${host.name}/host.js`,\n },\n { deferSelf: { members } },\n );\n}\n\n/** Finish the deferred self tokens from the members' live run records. */\nfunction finishOwnTokens(\n pending: DeferredResolution<ClintHost>,\n live: LiveMemberOutputs,\n name: string,\n): ClintHost {\n const started = new Map<string, unknown>();\n for (const [key, member] of Object.entries(live)) {\n if (member.outputs !== undefined) started.set(key, member.outputs);\n }\n const silent = pending.needs.filter((key) => !started.has(key));\n if (silent.length > 0) {\n const paths = pending.deferred\n .filter((d) => d.members.some((key) => silent.includes(key)))\n .map((d) => d.path);\n throw new Error(\n `hosts/${name}/host.js: ${paths.join(\", \")} read the outputs of member ${silent.map((key) => `\"${key}\"`).join(\", \")}, which is up but published no live run record (.ph/run/<host>.json) to read them from.`,\n );\n }\n const members = Object.entries(pending.host.children).map(\n ([key, wrapper]) => ({ key, host: wrapper.host }),\n );\n return pending.finish(compoundOutputSource(members, started, name));\n}\n\n/** Started members' outputs, read from their own run records (members run\n * as separate `ph-cli run` processes, which publish their outputs there). */\nfunction liveMemberOutputs(\n projectRoot: string,\n projectName: string,\n memberHosts: Record<string, string>,\n): LiveMemberOutputs {\n const members: LiveMemberOutputs = {};\n for (const [id, hostName] of Object.entries(memberHosts)) {\n const probe = probeRun(projectRoot, hostName, projectName);\n members[id] = {\n host: hostName,\n outputs: probe.status === \"live\" ? probe.record.outputs : undefined,\n };\n }\n return members;\n}\n\n/** What starting the shell produces: the resolved agent endpoints and, when\n * `runner.proxy` is set, the proxy's URL. Member outputs belong to the\n * members. */\nexport const outputsSchema = z.strictObject({\n agents: z.record(z.string(), z.url()),\n proxy: z.strictObject({ url: z.url() }).optional(),\n});\n\nexport type ClintOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/clint/clint-runner\": {\n host: ClintHostInput;\n outputs: ClintOutputs;\n };\n }\n}\n\n// A URL in stdout is the universal \"I am serving\" signal across member kinds\n// (switchboard prints \"MCP server available at http://…\", preview \"Local:\",\n// the agent \"agent API … http://…\").\nconst DEFAULT_READINESS = \"https?://|listening|ready\";\n/** How long a member may take to print its readiness line, in ms; also how\n * long clint then waits for its run record when something reads it. */\nconst READINESS_TIMEOUT = 180_000;\n\n/** Resolve the project's ph-cli entry the same way host-core resolves runner\n * modules: from the PROJECT's dependency tree. */\nfunction resolvePhCliEntry(projectRoot: string): string {\n const require_ = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n const pkgPath = require_.resolve(\"@powerhousedao/ph-cli/package.json\");\n return path.join(path.dirname(pkgPath), \"dist\", \"cli.mjs\");\n}\n\nfunction childServices(\n host: ClintHost,\n ctx: RunnerContext,\n phCliEntry: string,\n): ServiceDefinition<Record<string, unknown>>[] {\n return Object.entries(host.children).map(([name, wrapper]) =>\n defineService({\n id: name,\n name,\n command: () => `node \"${phCliEntry}\" run ${wrapper.host}`,\n env: () => ({\n PH_USER_DATA_DIR: defaultUserDataDir(ctx.projectRoot, ctx.env),\n }),\n readiness: {\n patterns: [\n {\n name: \"up\",\n pattern: new RegExp(\n wrapper.config?.readiness?.pattern ?? DEFAULT_READINESS,\n \"i\",\n ),\n },\n ],\n timeout: wrapper.config?.readiness?.timeout ?? READINESS_TIMEOUT,\n },\n }),\n );\n}\n\nfunction readProjectName(projectRoot: string, fallback: string): string {\n try {\n return (\n (\n JSON.parse(\n fs.readFileSync(path.join(projectRoot, \"package.json\"), \"utf8\"),\n ) as { name?: string }\n ).name ?? fallback\n );\n } catch {\n return fallback;\n }\n}\n\nasync function stopAll(\n services: ServiceManager,\n names: string[],\n): Promise<void> {\n for (const id of names) {\n try {\n await services.stop(id);\n } catch {\n // already stopped\n }\n }\n}\n\n/** The shell's handle: the runner contract plus the services manager. */\nexport interface CliRunHandle extends RunnerHandle<ClintOutputs> {\n services: ServiceManager;\n}\n\nasync function startShell(\n host: ClintHost,\n ctx: RunnerContext,\n): Promise<CliRunHandle> {\n const projectName = readProjectName(ctx.projectRoot, host.name);\n // resolveOwnTokens also substitutes the \"${userData}\"/\"${projectRoot}\"\n // sugar (processResolveEnv's built-ins); member wrappers stay as declared.\n const pending = await resolveOwnTokens(host, ctx, projectName);\n const resolved = pending.host;\n const config = resolved.config ?? {};\n const lifecycle = resolved.runner.lifecycle ?? \"detached\";\n\n const phCliEntry = resolvePhCliEntry(ctx.projectRoot);\n const children = resolved.children;\n const definitions = childServices(resolved, ctx, phCliEntry);\n const eventBus = createEventBus();\n // R5: compound plugins (appliesTo \"compound\" — e.g. the proxy) run over the\n // member set. Built-ins resolve from a declared `runner.plugins`; the proxy\n // is registered when a `runner.proxy` block is present (ergonomic alias).\n const servicesDir = path.join(ctx.projectRoot, \".ph\", \"services\");\n const services = createServiceManager(definitions, {\n config: {},\n servicesDir,\n eventBus,\n });\n\n // Each member's own host.js: its `$output` tokens on sibling members\n // decide the start order (each member resolves them from its producers'\n // run records as it starts).\n const names = definitions.map((d) => d.id);\n const loaded = new Map<string, LoadedHost>();\n for (const id of names) {\n loaded.set(id, await loadHost(ctx.projectRoot, children[id].host));\n }\n // Start order: the same dependency plan the generic compound uses —\n // producers before consumers (ties keep declaration order); a\n // config.startOrder must agree with the tokens. Tokens on hosts outside\n // the compound read standalone producers and do not order members.\n const memberRefs = names.map((key) => ({ key, host: children[key].host }));\n const plan = planCompound(\n names.map((key) => ({\n key,\n host: children[key].host,\n refs: outputSitesOf(loaded.get(key)?.host)\n .filter(({ ref }) => memberRefs.some((m) => m.host === ref.host))\n .map(({ ref, path }) => ({ ref, path })),\n })),\n config.startOrder,\n );\n const ordered = plan.order;\n // Whose outputs are read, and by whom: the shell's deferred self fields,\n // and the members that consume a sibling.\n const readers = new Map<string, string[]>();\n const addReader = (id: string, reader: string) =>\n readers.set(id, [...(readers.get(id) ?? []), reader]);\n for (const deferred of pending.deferred) {\n for (const id of deferred.members) addReader(id, deferred.path);\n }\n for (const edge of plan.edges) {\n addReader(edge.producer, `member \"${edge.consumer}\"`);\n }\n /** Wait for a member's live run record when something reads it. With\n * `managed` (clint's own service state describes it), a failed or stopped\n * service ends the wait early; a member found serving on its port is not\n * clint's to watch, so it gets the full timeout. */\n const waitForRecord = async (\n id: string,\n memberHost: string,\n managed = true,\n ) => {\n const read = readers.get(id);\n if (!read) return;\n try {\n await awaitRunRecord(ctx.projectRoot, projectName, host.name, {\n id,\n host: memberHost,\n timeout: children[id].config?.readiness?.timeout ?? READINESS_TIMEOUT,\n readers: read,\n ...(managed\n ? {\n status: () =>\n services.list(id).find((s) => s.serviceId === id)?.status,\n }\n : {}),\n });\n } catch (error) {\n if (lifecycle === \"attached\") await stopAll(services, names);\n throw error;\n }\n };\n\n const memberHosts: Record<string, string> = {};\n for (const id of ordered) {\n // Re-attach checks, strongest first. (1) The member's OWN run record —\n // written with the member process's real pid (mastra-runner, the generic\n // compound). (2) Port occupancy for record-less bridge members. (3) The\n // service state file — weakest on Windows, where it records the cmd shim\n // pid, which dies on console teardown while the node grandchild survives.\n const wrapper = children[id];\n const member =\n loaded.get(id) ?? (await loadHost(ctx.projectRoot, wrapper.host));\n memberHosts[id] = member.host.name;\n const record = probeRun(ctx.projectRoot, member.host.name, projectName);\n if (record.status === \"live\") {\n console.log(\n `[${resolved.name}] ${id}: already running (pid ${record.record.pid}) — re-attached`,\n );\n continue;\n }\n const memberPort =\n typeof wrapper.runner?.port === \"number\"\n ? wrapper.runner.port\n : typeof member.host.runner.port === \"number\"\n ? member.host.runner.port\n : undefined;\n if (memberPort !== undefined && !(await isPortFree(memberPort))) {\n console.log(\n `[${resolved.name}] ${id}: port ${memberPort} already serving — re-attached`,\n );\n // It may still be booting (an earlier detached run, or started by\n // hand): its readers need its record, as after a fresh start.\n await waitForRecord(id, member.host.name, false);\n continue;\n }\n const already = services\n .list(id)\n .some((s) => s.status === \"ready\" || s.status === \"starting\");\n if (already) {\n console.log(`[${resolved.name}] ${id}: already running — re-attached`);\n await waitForRecord(id, member.host.name);\n continue;\n }\n console.log(`[${resolved.name}] starting ${id}…`);\n await services.start(id, {\n workdir: ctx.projectRoot,\n cwd: ctx.projectRoot,\n });\n const status = services.list(id).find((s) => s.serviceId === id);\n if (status) console.log(` ${formatStatus(status)}`);\n // Before anything reads its outputs (the next member, or the shell's\n // own deferred fields below).\n await waitForRecord(id, member.host.name);\n }\n\n // The deferred self fields (agent urls, proxy upstreams) name the\n // members' outputs, which exist now.\n let own: OwnFields;\n try {\n const finished = finishOwnTokens(\n pending,\n liveMemberOutputs(ctx.projectRoot, projectName, memberHosts),\n host.name,\n );\n const parsedOwn = ownFieldsSchema.safeParse({\n agents: finished.config?.agents,\n proxy: finished.runner.proxy,\n });\n if (!parsedOwn.success) {\n throw new Error(\n `hosts/${host.name}: agents/proxy resolved to invalid values:\\n${z.prettifyError(parsedOwn.error)}`,\n );\n }\n own = parsedOwn.data;\n } catch (error) {\n if (lifecycle === \"attached\") await stopAll(services, names);\n throw error;\n }\n\n // Compound-plugin pipeline (CompoundCore): resolve entries + the proxy\n // ergonomic alias, then fire onMembersReady now that endpoints are known.\n const pluginEntries = resolved.runner.plugins;\n const resolvedPlugins = pluginEntries\n ? (\n await resolveHostPlugins(\n ctx.projectRoot,\n \"compound\",\n ctx.verb,\n pluginEntries,\n `hosts/${host.name}/host.js`,\n )\n ).map((r) => r.plugin)\n : [];\n const proxyBlock = own.proxy;\n if (proxyBlock) {\n resolvedPlugins.push(createProxyPlugin(proxyBlock));\n }\n const compoundCtx: ClintCompoundContext = {\n logger: { info: (m: string) => console.log(m) },\n };\n if (resolvedPlugins.length > 0) {\n await runObserveHook(\"onMembersReady\", resolvedPlugins, compoundCtx);\n }\n\n const agents: Record<string, string> = {};\n for (const [name, agent] of Object.entries(own.agents ?? {})) {\n agents[name] = agent.url.replace(/\\/$/, \"\");\n }\n if (Object.keys(agents).length > 0) {\n console.log(\n `[${resolved.name}] agents: ${Object.entries(agents)\n .map(([n, u]) => `${n} → ${u}`)\n .join(\", \")}`,\n );\n }\n\n const shutdown = async () => {\n if (resolvedPlugins.length > 0) {\n await runObserveHookSequential(\n \"onShutdown\",\n resolvedPlugins,\n compoundCtx,\n );\n }\n if (lifecycle === \"attached\") {\n await stopAll(services, names);\n } else {\n console.log(\n `[${resolved.name}] detached lifecycle: children keep running ` +\n `(stop them with the ${resolved.name} service commands or taskkill).`,\n );\n }\n };\n\n // Validated before the stack is handed out: an invalid output (e.g. a proxy\n // bound to a bare IPv6 host, which does not form a URL) tears down what\n // was started instead of leaving it half-up.\n const parsedOutputs = outputsSchema.safeParse({\n agents,\n ...(compoundCtx.proxyUrl ? { proxy: { url: compoundCtx.proxyUrl } } : {}),\n });\n if (!parsedOutputs.success) {\n await shutdown();\n throw new Error(\n `hosts/${host.name}: the shell produced invalid outputs:\\n${z.prettifyError(parsedOutputs.error)}`,\n );\n }\n const outputs = parsedOutputs.data;\n\n if (lifecycle === \"attached\") {\n const onSignal = () => {\n void shutdown().finally(() => process.exit(130));\n };\n process.once(\"SIGINT\", onSignal);\n process.once(\"SIGTERM\", onSignal);\n }\n\n // Members were started (and awaited to readiness) above.\n return { outputs, ready: Promise.resolve(), services, shutdown };\n}\n\n/** Minimal line chat against an agent's OpenAI-compatible endpoint. */\nasync function chatLoop(agents: Record<string, string>): Promise<void> {\n const [agentName, endpoint] = Object.entries(agents)[0] ?? [];\n if (!agentName || !endpoint) {\n console.log(\"No agents configured (config.agents) — chat unavailable.\");\n return;\n }\n console.log(`Chatting with ${agentName} (${endpoint}). /exit to quit.`);\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const ask = (q: string) =>\n new Promise<string>((resolve) => rl.question(q, resolve));\n for (;;) {\n const line = (await ask(\"> \")).trim();\n if (line === \"/exit\" || line === \"exit\") break;\n if (!line) continue;\n try {\n const res = await fetch(`${endpoint}/chat/completions`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n messages: [{ role: \"user\", content: line }],\n }),\n });\n const body = (await res.json()) as {\n choices?: { message?: { content?: string } }[];\n error?: { message?: string };\n };\n console.log(\n body.choices?.[0]?.message?.content ??\n `[error] ${body.error?.message ?? res.status}`,\n );\n } catch (error) {\n console.log(`[transport error] ${String(error)}`);\n }\n }\n rl.close();\n}\n\nexport async function run(\n host: ClintHost,\n ctx: RunnerContext,\n): Promise<CliRunHandle> {\n const handle = await startShell(host, ctx);\n console.log(\n `[${host.name}] services up. ` +\n `(ph run ${host.name} dev for the chat shell; Ctrl+C ${\n host.runner.lifecycle === \"attached\"\n ? \"stops the children\"\n : \"leaves children running\"\n }.)`,\n );\n return handle;\n}\n\nexport const serve = run;\n\n/** dev = services up + the line chat shell (blocks until /exit). */\nexport async function dev(host: ClintHost, ctx: RunnerContext): Promise<void> {\n const handle = await startShell(host, ctx);\n await chatLoop(handle.outputs.agents);\n await handle.shutdown();\n}\n\n/** build = forward build to each member host that exports it (fail loud on\n * members that do not — a silent skip would report success on an unbuilt\n * set), same posture as the generic compound. */\nexport async function build(\n host: ClintHost,\n ctx: RunnerContext,\n): Promise<void> {\n const { getVerb, resolveRunnerModule, validateHost } =\n await import(\"@powerhousedao/host-core\");\n for (const [name, wrapper] of Object.entries(host.children)) {\n const member = await loadHost(ctx.projectRoot, wrapper.host);\n const specifier = member.host.runner.module;\n const runner = await resolveRunnerModule(ctx.projectRoot, specifier);\n const validated = validateHost(\n runner,\n specifier,\n member.host,\n `hosts/${wrapper.host}/host.js`,\n );\n const fn = getVerb(runner, specifier, \"build\");\n console.log(`[${host.name}] build → ${name} (${wrapper.host})`);\n await fn(validated, {\n ...ctx,\n verb: \"build\",\n parent: { host: host.name, verb: ctx.verb },\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAQA,SAAgB,gBACd,KACA,MACqB;CACrB,QAAQ,UAAU;EAChB,IAAI,MAAM,SAAS,uBAAuB,CAAC,MAAM,KAAK,SAAS,GAAG,GAChE;EAMF,OAAO,KAAK,IAAI,kBAAkB,KAHhC,OAAO,MAAM,UAAU,YAAY,MAAM,UAAU,OAC9C,MAAM,QACP,CAAC,CACqC;CAC9C;AACF;;AAGA,SAAgB,WAAW,OAAgB,aAA6B;CACtE,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAC/C,KAAK,UAAU,KAAK,IACpB;AACN;;;;;;;;;;;;;;ACZA,SAAS,WAAW,OAAwC;CAK1D,OAAO,6IAHL,OAAO,MAAM,WAAW,YAAY,MAAM,OAAO,SAAS,IACtD,aAAa,KAAK,UAAU,MAAM,MAAM,MACxC,GACqJ;AAC7J;;;AAIA,SAAS,6BAAkD,KAAQ;;;CAGjE,MAAM,mBAAmB,EAAE,aACzB;EACE,UAAU;EACV,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS;EAC1B,IAAI,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC3B,GACA,EAAE,OAAO,gBAAgB,UAAU,UAAU,EAAE,CACjD;CACA,OAAO,EAAE,aAAa;;EAEpB,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC;;EAE5B,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;EACjC,WAAW,EAAE,IAAI,CAAC,CAAC,SAAS;;EAE5B,QAAQ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BACpC,MAAM,OAAO;CACf,KAAK,MAAM,CAAC,MAAM,YAAY,OAAO,QAAQ,KAAK,QAAQ,GAAG;EAC3D,MAAM,SAAS,MAAM,SAAS,IAAI,aAAa,QAAQ,IAAI;EAC3D,MAAM,YAAY,OAAO,KAAK,OAAO;EACrC,MAAM,SAAS,MAAM,oBAAoB,IAAI,aAAa,SAAS;EACnE,MAAM,YAAY,aAChB,QACA,WACA,OAAO,MACP,SAAS,QAAQ,KAAK,SACxB;EACA,MAAM,KAAK,QAAQ,QAAQ,WAAW,OAAO;EAC7C,QAAQ,IAAI,IAAI,KAAK,KAAK,YAAY,KAAK,IAAI,QAAQ,KAAK,EAAE;EAC9D,MAAM,GAAG,WAAW;GAClB,GAAG;GACH,MAAM;GACN,QAAQ;IAAE,MAAM,KAAK;IAAM,MAAM,IAAI;GAAK;EAC5C,CAAC;CACH;AACF"}
|
|
@@ -501,7 +501,7 @@ const serve = run;
|
|
|
501
501
|
/** `build` — skill + agent-profile compilation (ph-clint-dev's pipeline). */
|
|
502
502
|
async function build(host, ctx) {
|
|
503
503
|
const config = host.config ?? {};
|
|
504
|
-
const { buildSkills } = await import("../build-skills-
|
|
504
|
+
const { buildSkills } = await import("../build-skills-BnqGyuCH.mjs");
|
|
505
505
|
const result = await buildSkills({
|
|
506
506
|
rootDir: ctx.projectRoot,
|
|
507
507
|
skillsDir: config.prompts?.skillsDir,
|
|
@@ -5,7 +5,7 @@ import { n as createServiceCommands, t as createEventBus } from "./events-BnwGFT
|
|
|
5
5
|
import { t as createProxyServer } from "./proxy-BFR8GScT.mjs";
|
|
6
6
|
import "./reactor-C9VIUX1H.mjs";
|
|
7
7
|
import "./switchboard-CyvOavqL.mjs";
|
|
8
|
-
import "./folders-
|
|
8
|
+
import "./folders-BYO1Wqqb.mjs";
|
|
9
9
|
import { createRequire } from "node:module";
|
|
10
10
|
import fs, { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
11
11
|
import path, { basename, dirname, join, resolve } from "node:path";
|
|
@@ -3058,7 +3058,7 @@ function createCliRuntime(deps) {
|
|
|
3058
3058
|
log.debug(`Reactor storage: ${workspace.getStoreFolder("reactor-storage")}`);
|
|
3059
3059
|
output(`Reactor ready (drive: ${cachedReactor.driveId})`);
|
|
3060
3060
|
if (cachedReactor.personalDriveId) {
|
|
3061
|
-
const { createFolderOperations, createFolderCommands } = await import("./folders-
|
|
3061
|
+
const { createFolderOperations, createFolderCommands } = await import("./folders-BYO1Wqqb.mjs").then((n) => n.t);
|
|
3062
3062
|
const folderOps = createFolderOperations(cachedReactor.client, cachedReactor.personalDriveId, log);
|
|
3063
3063
|
context.folders = folderOps;
|
|
3064
3064
|
const folderCmds = createFolderCommands(folderOps);
|
|
@@ -4708,7 +4708,7 @@ function isDocType(doc, type) {
|
|
|
4708
4708
|
*/
|
|
4709
4709
|
async function buildDefaultReactor(ctx, options) {
|
|
4710
4710
|
const { buildReactor } = await import("./reactor-C9VIUX1H.mjs").then((n) => n.t);
|
|
4711
|
-
const { ensureDrive, ensureRemoteDrive } = await import("./drive-
|
|
4711
|
+
const { ensureDrive, ensureRemoteDrive } = await import("./drive-Bu9zoFrO.mjs").then((n) => n.t);
|
|
4712
4712
|
const reactorModule = await buildReactor({
|
|
4713
4713
|
documentModels: options.documentModels,
|
|
4714
4714
|
storagePath: ctx.workspace.getStoreFolder("reactor-storage"),
|
|
@@ -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-
|
|
4767
|
+
//# sourceMappingURL=src-BebNN3xc.mjs.map
|