import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context"; import { getOrThrow } from "@earendil-works/pi-durable/env"; import type { Environment } from "@berry/api"; import { localEnvironment } from "@berry/api/environment.ts"; import { rootedEnvironment } from "@berry/api/testing.ts"; export function targetEnvironment( root: string, options: Parameters[1] = {}, ): Environment { const env = rootedEnvironment(root, options); const exec = env.exec; env.exec = (command, options, context) => exec( typeof command === "string" ? command : command.map((arg) => arg.startsWith("/") ? root + arg : arg), options, context, ); return env; } export function hostEnvironment(home: string, variables: Record = {}): Environment { const env = localEnvironment(home); Object.defineProperties(env, { home: { value: home }, variables: { value: variables } }); return env; } export async function activeDirectory(env: Environment, prompt: string): Promise { for (const match of prompt.matchAll(/"(?:[^"\\]|\\.)*"/g)) { const directory: string = JSON.parse(match[0]); const file = getOrThrow(await env.joinPath([directory, "SKILL.md"], BACKGROUND_CONTEXT)); const info = await env.fileInfo(file, BACKGROUND_CONTEXT); if (info.ok && info.value.kind === "file") return directory; } throw new Error("The prompt has no readable skill directory"); } export async function writeSkill( env: Environment, collection: string, name: string, body: string, description = `Use ${name} for its workflow.`, ): Promise { const path = getOrThrow(await env.joinPath([collection, name, "SKILL.md"], BACKGROUND_CONTEXT)); getOrThrow( await env.writeFile( path, `---\nname: ${name}\ndescription: ${JSON.stringify(description)}\n---\n${body}`, BACKGROUND_CONTEXT, ), ); return path; }