@agentproto/app-kit 1.6.1 → 1.6.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/index.mjs +3 -0
- package/dist/index.mjs.map +1 -1
- package/dist/pack.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1347,6 +1347,9 @@ var RELEASE_DEFAULT_EXCLUDE = [
|
|
|
1347
1347
|
"docs/**",
|
|
1348
1348
|
"data/**",
|
|
1349
1349
|
"scripts/**",
|
|
1350
|
+
// Store listing sources (APP.md `store:`): published next to the catalog
|
|
1351
|
+
// entry, never needed by an installed app.
|
|
1352
|
+
"store/**",
|
|
1350
1353
|
// Root-level only: `**/dev/**` would also drop a shipped agent named
|
|
1351
1354
|
// `dev` (`.agentproto/agents/dev/`); `ui/dev/` is covered by `ui/**`.
|
|
1352
1355
|
// Same for `test/` and `tests/`.
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/refs.ts","../src/emit.ts","../src/version-range.ts","../src/manifest-fields.ts","../src/define-app.ts","../src/errors.ts","../src/load-app-tools.ts","../src/load-app.ts","../src/pack.ts"],"names":["workflowRefs","matter","isAbsolute","relative","join","readFile","readdir","resolve","mkdir","dirname","copyFile","writeFile","cp"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AASO,SAAS,OAAO,GAAA,EAAqB;AAC1C,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,EAAU,OAAO,GAAA;AACpC,EAAA,OAAO,GAAA,CAAI,OAAO,GAAA,CAAI,IAAA,IAAQ,KAAK,SAAA,CAAU,GAAA,CAAI,UAAU,GAAG,CAAA;AAChE;AAGO,SAAS,WAAW,EAAA,EAAoB;AAC7C,EAAA,MAAM,CAAA,GAAI,EAAA,CAAG,KAAA,CAAM,gBAAgB,CAAA;AACnC,EAAA,OAAO,CAAA,GAAI,CAAA,CAAE,CAAC,CAAA,G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n * uses (`packages/mastra/src/build-agent.ts` `refKey`). An AIP-27 ref is\n * a string shorthand or `{ ref | file | inline }`; the key is the string,\n * else `.ref`, else `.file`, else a stable JSON of the inline payload.\n */\n\nimport type { AnyRef } from \"@agentproto/agent\"\n\nexport function refKey(ref: AnyRef): string {\n if (typeof ref === \"string\") return ref\n return ref.ref ?? ref.file ?? JSON.stringify(ref.inline ?? ref)\n}\n\n/** `@agentik/writer` → `writer`; bare ids untouched. */\nexport function stripOwner(id: string): string {\n const m = id.match(/^@[^/]+\\/(.+)$/)\n return m ? m[1]! : id\n}\n","/**\n * `emitApp(app, dir)` — write an app's agents + workflows to disk under an\n * agentproto-owned base, so the manifests don't squat the shared root\n * `.agents/` convention:\n *\n * <dir>/WORKSPACE.md (when the app has a\n * workspace — AIP-34 root\n * manifest; owner = tenant)\n * <dir>/.agentproto/agents/<id>/AGENT.md (one per agent)\n * <dir>/.agentproto/workflows/<wf.id>/WORKFLOW.md (shared — a workflow may\n * be run by several agents)\n * <dir>/.agentproto/APP.md (root index — always\n * written, so a future\n * `app_install` can\n * discover the bundle)\n *\n * The \"tenant\" isn't a `tenants/<t>/…` path segment — it's the `owner` of\n * the AIP-34 WORKSPACE.md (guild / user / org), and local storage is its\n * AIP-35 `storage` block. So there is no bespoke tenant folder to invent.\n *\n * All manifests are plain markdown: frontmatter = the validated handle (or,\n * for APP.md, the identity + a manifest of `{ id, path }` refs to every\n * agent/workflow it bundles), body = the agent's `body` (its system prompt),\n * the workflow description, or the app description. Because a\n * `defineWorkflow` handle is pure data, the WORKFLOW.md needs no `entry:`\n * module — the manifest *is* the workflow, so `loadWorkflowHandle` returns\n * it directly with nothing to reconcile against.\n *\n * `emitApp` stays dependency-light on purpose (no Mastra import) — that\n * split lets a host write/discover an app without paying for the Mastra\n * build path.\n */\n\nimport { copyFile, cp, mkdir, writeFile } from \"node:fs/promises\"\nimport { join, relative } from \"node:path\"\nimport matter from \"gray-matter\"\nimport type { WorkflowHandle } from \"@agentproto/workflow\"\nimport type { WorkspaceHandle } from \"@agentproto/workspace\"\nimport type { AgentEntry, AppAccepts, AppArtifactDecl, AppArtifactSurface, AppBoundariesDefinition, AppDataDefinition, AppDevDefinition, AppExposes, AppPlacement, AppRequirement, AppRequirements, AppSkillSurface, AppUiDefinition, EmittedApp } from \"./types.js\"\nimport { stripOwner } from \"./refs.js\"\n\ninterface EmitInput {\n readonly agents: readonly AgentEntry[]\n readonly workflows: readonly WorkflowHandle[]\n readonly workspace?: WorkspaceHandle\n readonly id?: string\n readonly name?: string\n readonly version?: string\n readonly description?: string\n readonly requires?: readonly string[]\n readonly requirements?: AppRequirements\n readonly appRequirements?: readonly AppRequirement[]\n readonly placement?: AppPlacement\n readonly exposes?: AppExposes\n readonly accepts?: AppAccepts\n readonly ui?: AppUiDefinition\n readonly artifact?: AppArtifactSurface\n readonly skill?: AppSkillSurface\n readonly artifacts?: readonly AppArtifactDecl[]\n readonly dev?: AppDevDefinition\n readonly data?: AppDataDefinition\n readonly externalReadRoots?: readonly string[]\n readonly boundaries?: AppBoundariesDefinition\n readonly category?: string\n}\n\nexport async function emitApp(app: EmitInput, dir: string): Promise<EmittedApp> {\n let workspacePath: string | undefined\n if (app.workspace) {\n await mkdir(dir, { recursive: true })\n workspacePath = join(dir, \"WORKSPACE.md\")\n await writeFile(\n workspacePath,\n toManifest(app.workspace, app.workspace.description ?? app.workspace.name),\n \"utf8\",\n )\n }\n\n const agentPaths: Record<string, string> = {}\n for (const { agent, body } of app.agents) {\n const agentDir = join(dir, \".agentproto\", \"agents\", stripOwner(agent.id))\n await mkdir(agentDir, { recursive: true })\n const agentPath = join(agentDir, \"AGENT.md\")\n await writeFile(agentPath, toManifest(agent, body ?? \"\"), \"utf8\")\n agentPaths[agent.id] = agentPath\n }\n\n let uiPath: string | undefined\n let uiFrontmatter: Record<string, unknown> | undefined\n if (app.ui) {\n const uiDir = join(dir, \".agentproto\", \"ui\")\n await mkdir(uiDir, { recursive: true })\n uiPath = join(uiDir, \"index.html\")\n await writeFile(uiPath, app.ui.html, \"utf8\")\n uiFrontmatter = {\n path: relative(dir, uiPath),\n ...(app.ui.title !== undefined ? { title: app.ui.title } : {}),\n ...(app.ui.description !== undefined ? { description: app.ui.description } : {}),\n ...(app.ui.tools !== undefined ? { tools: app.ui.tools } : {}),\n ...(app.ui.port !== undefined ? { port: app.ui.port } : {}),\n ...(app.ui.csp !== undefined ? { csp: app.ui.csp } : {}),\n ...(app.ui.build !== undefined ? { build: app.ui.build } : {}),\n ...(app.ui.extensions !== undefined ? { extensions: app.ui.extensions } : {}),\n }\n }\n\n let artifactPath: string | undefined\n let artifactFrontmatter: Record<string, unknown> | undefined\n if (app.artifact) {\n const artifactDir = join(dir, \".agentproto\", \"artifact\")\n await mkdir(artifactDir, { recursive: true })\n artifactPath = join(artifactDir, \"index.html\")\n await copyFile(app.artifact.path, artifactPath)\n artifactFrontmatter = {\n path: relative(dir, artifactPath),\n ...(app.artifact.title !== undefined ? { title: app.artifact.title } : {}),\n ...(app.artifact.description !== undefined ? { description: app.artifact.description } : {}),\n }\n }\n\n let skillPath: string | undefined\n let skillFrontmatter: Record<string, unknown> | undefined\n if (app.skill) {\n skillPath = join(dir, \".agentproto\", \"skill\")\n await mkdir(skillPath, { recursive: true })\n await cp(app.skill.path, skillPath, { recursive: true })\n skillFrontmatter = {\n path: relative(dir, skillPath),\n ...(app.skill.title !== undefined ? { title: app.skill.title } : {}),\n ...(app.skill.description !== undefined ? { description: app.skill.description } : {}),\n }\n }\n\n const workflowPaths: string[] = []\n const workflowRefs: { id: string; path: string }[] = []\n for (const wf of app.workflows) {\n const wfDir = join(dir, \".agentproto\", \"workflows\", wf.id)\n await mkdir(wfDir, { recursive: true })\n const wfPath = join(wfDir, \"WORKFLOW.md\")\n await writeFile(wfPath, toManifest(wf, wf.description ?? \"\"), \"utf8\")\n workflowPaths.push(wfPath)\n workflowRefs.push({ id: wf.id, path: relative(dir, wfPath) })\n }\n\n await mkdir(join(dir, \".agentproto\"), { recursive: true })\n const appPath = join(dir, \".agentproto\", \"APP.md\")\n const agentRefs = app.agents.map(({ agent }) => ({\n id: agent.id,\n path: relative(dir, agentPaths[agent.id]!),\n }))\n const appFrontmatter: Record<string, unknown> = {\n schema: \"app/v1\",\n ...(app.id !== undefined ? { id: app.id } : {}),\n ...(app.name !== undefined ? { name: app.name } : {}),\n version: app.version ?? \"0.1.0\",\n ...(app.description !== undefined ? { description: app.description } : {}),\n agents: agentRefs,\n workflows: workflowRefs,\n ...(app.workspace ? { workspace: app.workspace.id } : {}),\n ...requiresFrontmatter(app),\n ...(app.placement !== undefined && app.placement !== \"any\" ? { placement: app.placement } : {}),\n ...(app.exposes && (app.exposes.agents.length > 0 || app.exposes.workflows.length > 0)\n ? { exposes: { agents: app.exposes.agents, workflows: app.exposes.workflows } }\n : {}),\n ...(app.accepts?.tasks ? { accepts: { tasks: true } } : {}),\n ...(uiFrontmatter !== undefined ? { ui: uiFrontmatter } : {}),\n ...(artifactFrontmatter !== undefined ? { artifact: artifactFrontmatter } : {}),\n ...(skillFrontmatter !== undefined ? { skill: skillFrontmatter } : {}),\n ...(app.artifacts !== undefined ? { artifacts: app.artifacts } : {}),\n ...(app.dev !== undefined ? { dev: app.dev } : {}),\n ...(app.data !== undefined ? { data: app.data } : {}),\n ...(app.externalReadRoots !== undefined ? { externalReadRoots: app.externalReadRoots } : {}),\n ...(app.boundaries !== undefined ? { boundaries: app.boundaries } : {}),\n ...(app.category !== undefined ? { category: app.category } : {}),\n }\n await writeFile(appPath, toManifest(appFrontmatter, app.description ?? \"\"), \"utf8\")\n\n return {\n agentPaths,\n workflowPaths,\n appPath,\n ...(workspacePath ? { workspacePath } : {}),\n ...(uiPath ? { uiPath } : {}),\n ...(artifactPath ? { artifactPath } : {}),\n ...(skillPath ? { skillPath } : {}),\n }\n}\n\n/** Legacy flat array while only bare app ids are declared; object form once\n * any host requirement (browser/fs/gpu/secrets) OR any per-dependency detail\n * (a version range / workflow allowlist) is set. Defaults are omitted.\n * `apps` entries carrying no extra fields emit as bare ids (byte-stable with\n * pre-object-form APP.md files). */\nfunction requiresFrontmatter(app: EmitInput): Record<string, unknown> {\n const r = app.requirements\n const apps = appsFrontmatter(app)\n const hasAppDetail = (app.appRequirements ?? []).some(\n e => e.version !== undefined || (e.workflows !== undefined && e.workflows.length > 0),\n )\n if (r && (r.browser || r.fs || r.gpu || r.secrets.length > 0)) {\n return {\n requires: { browser: r.browser, fs: r.fs, gpu: r.gpu, secrets: r.secrets, apps },\n }\n }\n if (hasAppDetail) {\n return { requires: { apps } }\n }\n return app.requires !== undefined ? { requires: app.requires } : {}\n}\n\nfunction appsFrontmatter(app: EmitInput): unknown[] {\n const entries = app.appRequirements ?? app.requires ?? []\n return entries.map(e => {\n if (typeof e === \"string\") return e\n if (e.version === undefined && (e.workflows === undefined || e.workflows.length === 0)) return e.id\n return e\n })\n}\n\nfunction toManifest(handle: object, body: string): string {\n const data: Record<string, unknown> = JSON.parse(JSON.stringify(handle))\n return matter.stringify(`\\n${body}\\n`, data)\n}\n","/**\n * Tiny pure semver-range checker for `requires.apps[].version` — the only\n * version constraint the app→app call mechanism supports. Deliberately small:\n * an exact version, a caret (`^1`, `^1.2`, `^1.2.3`; npm semantics: it pins\n * the leftmost non-zero component, so `^0.2.3` stays on the 0.2 line), or a\n * tilde on the major[.minor] (`~1`, `~1.2`, `~1.2.3`). No dependency on a\n * semver package — the surface is three comparison shapes, not a grammar.\n *\n * Versions are `major.minor.patch` with an optional prerelease/build suffix\n * (the APP.md `version` pattern); the suffix is ignored for comparison, so\n * `1.2.3-rc1` satisfies `^1` exactly as `1.2.3` would.\n */\n\nconst VERSION_RE = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:[-+][\\w.\\-]+)?$/\n\ntype VersionTuple = readonly [number, number, number]\n\nexport type VersionRange =\n | { readonly kind: \"exact\"; readonly version: VersionTuple }\n | { readonly kind: \"caret\"; readonly version: VersionTuple }\n /** `minorGiven` distinguishes `~1` (any minor of that major) from\n * `~1.2` / `~1.2.3` (that minor line only). */\n | { readonly kind: \"tilde\"; readonly version: VersionTuple; readonly minorGiven: boolean }\n\nfunction parseVersion(v: string): VersionTuple {\n const m = VERSION_RE.exec(v)\n if (!m) {\n throw new Error(`invalid version \"${v}\" — expected major.minor.patch (e.g. \"1.2.3\").`)\n }\n return [Number(m[1]), Number(m[2]), Number(m[3])]\n}\n\nfunction compare(a: VersionTuple, b: VersionTuple): number {\n return a[0] - b[0] || a[1] - b[1] || a[2] - b[2]\n}\n\n/** Parse a supported range shape. Throws on anything else — callers with\n * user-authored input wrap this for a field-prefixed diagnostic. */\nexport function parseVersionRange(range: string): VersionRange {\n let m = /^\\^(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?$/.exec(range)\n if (m !== null) {\n return {\n kind: \"caret\",\n version: [Number(m[1]), m[2] !== undefined ? Number(m[2]) : 0, m[3] !== undefined ? Number(m[3]) : 0],\n }\n }\n m = /^~(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?$/.exec(range)\n if (m !== null) {\n return {\n kind: \"tilde\",\n version: [Number(m[1]), m[2] !== undefined ? Number(m[2]) : 0, m[3] !== undefined ? Number(m[3]) : 0],\n minorGiven: m[2] !== undefined,\n }\n }\n if (VERSION_RE.test(range)) return { kind: \"exact\", version: parseVersion(range) }\n throw new Error(\n `invalid version range \"${range}\" — expected an exact version (\"1.2.3\"), ` +\n `a caret (\"^1\", \"^1.2\", \"^1.2.3\"), or a tilde (\"~1\", \"~1.2\", \"~1.2.3\").`,\n )\n}\n\n/** True when `version` satisfies `range`. Throws on a malformed version or\n * range — both are validated at manifest-parse time, so reaching this with\n * bad input is a programming error, not a user one. */\nexport function versionSatisfies(version: string, range: string): boolean {\n const v = parseVersion(version)\n const r = parseVersionRange(range)\n if (r.kind === \"exact\") return compare(v, r.version) === 0\n if (compare(v, r.version) < 0) return false\n if (r.kind === \"caret\") {\n if (r.version[0] > 0) return v[0] === r.version[0]\n if (r.version[1] > 0) return v[0] === 0 && v[1] === r.version[1]\n return v[0] === 0 && v[1] === 0 && v[2] === r.version[2]\n }\n return v[0] === r.version[0] && (!r.minorGiven || v[1] === r.version[1])\n}\n","/**\n * Validation + defaulting for the APP.md placement/requires/exposes/accepts\n * keys. Shared by `defineApp` (throws `AppDefinitionError`) and\n * `loadAppHandle` (throws `AppLoadError`) through the `fail` factory, so a\n * hand-edited APP.md and a bad `defineApp({...})` call get the same diagnostic.\n */\n\nimport type { AppAccepts, AppExposes, AppPlacement, AppRequirement, AppRequirements } from \"./types.js\"\nimport { parseVersionRange } from \"./version-range.js\"\n\nexport const APP_PLACEMENTS: readonly AppPlacement[] = [\"local\", \"box\", \"any\", \"split\"]\n\nexport interface ManifestFieldsInput {\n readonly placement?: unknown\n readonly requires?: unknown\n readonly exposes?: unknown\n readonly accepts?: unknown\n}\n\nexport interface DeclaredIds {\n readonly agents: readonly string[]\n readonly workflows: readonly string[]\n}\n\nexport interface NormalizedManifestFields {\n readonly placement: AppPlacement\n /** Flat app-id list; undefined when `requires` was absent (or an object with no `apps`). */\n readonly requires: readonly string[] | undefined\n readonly requirements: AppRequirements\n /** Every `requires.apps` entry in normalized object form (bare ids become\n * `{ id }`); empty when no app dependency was declared. */\n readonly appRequirements: readonly AppRequirement[]\n readonly exposes: AppExposes\n readonly accepts: AppAccepts\n}\n\ntype Fail = (message: string) => Error\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\nfunction stringList(v: unknown, key: string, fail: Fail): readonly string[] {\n if (v === undefined) return []\n if (!Array.isArray(v) || !v.every(e => typeof e === \"string\" && e.trim() !== \"\")) {\n throw fail(`'${key}' must be an array of non-empty strings.`)\n }\n return [...v] as string[]\n}\n\nfunction bool(v: unknown, key: string, fail: Fail): boolean {\n if (v === undefined) return false\n if (typeof v !== \"boolean\") throw fail(`'${key}' must be a boolean.`)\n return v\n}\n\n/** Parse one `requires.apps` entry — a bare id or an\n * `{ id, version?, workflows? }` object. Shared by the array element check\n * and the object form's `apps` list so both accept exactly the same shape. */\nfunction appRequirementEntry(entry: unknown, key: string, fail: Fail): AppRequirement {\n if (typeof entry === \"string\") {\n if (entry.trim() === \"\") throw fail(`'${key}' entries must be non-empty strings or objects.`)\n return { id: entry }\n }\n if (!isRecord(entry)) {\n throw fail(`'${key}' entries must be non-empty strings or objects, got ${JSON.stringify(entry)}.`)\n }\n const id = entry.id\n if (typeof id !== \"string\" || id.trim() === \"\") {\n throw fail(`'${key}.id' must be a non-empty string.`)\n }\n const version = entry.version\n if (version !== undefined) {\n if (typeof version !== \"string\" || version.trim() === \"\") {\n throw fail(`'${key}.version' must be a non-empty string.`)\n }\n try {\n parseVersionRange(version)\n } catch (err) {\n throw fail(`'${key}.version' ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n const workflows = entry.workflows\n if (workflows !== undefined) {\n if (!Array.isArray(workflows) || !workflows.every(w => typeof w === \"string\" && w.trim() !== \"\")) {\n throw fail(`'${key}.workflows' must be an array of non-empty strings.`)\n }\n }\n const extra = Object.keys(entry).filter(k => k !== \"id\" && k !== \"version\" && k !== \"workflows\")\n if (extra.length > 0) {\n throw fail(`'${key}.${extra[0]}' is not a supported requires.apps entry field (expected id, version, workflows).`)\n }\n return {\n id,\n ...(version !== undefined ? { version } : {}),\n ...(workflows !== undefined ? { workflows: [...workflows] as string[] } : {}),\n }\n}\n\nfunction appRequirementList(v: unknown, key: string, fail: Fail): readonly AppRequirement[] {\n if (v === undefined) return []\n if (!Array.isArray(v)) {\n throw fail(`'${key}' must be an array of non-empty strings or { id, version?, workflows? } objects.`)\n }\n return v.map((e, i) => appRequirementEntry(e, `${key}[${i}]`, fail))\n}\n\nexport function normalizeManifestFields(\n input: ManifestFieldsInput,\n declared: DeclaredIds,\n fail: Fail,\n): NormalizedManifestFields {\n let placement: AppPlacement = \"any\"\n if (input.placement !== undefined) {\n if (typeof input.placement !== \"string\" || !APP_PLACEMENTS.includes(input.placement as AppPlacement)) {\n throw fail(\n `'placement' must be one of ${APP_PLACEMENTS.map(p => `\"${p}\"`).join(\", \")}, got ${JSON.stringify(input.placement)}.`,\n )\n }\n placement = input.placement as AppPlacement\n }\n\n let requires: readonly string[] | undefined\n let requirements: AppRequirements = { browser: false, fs: false, gpu: false, secrets: [], apps: [] }\n let appRequirements: readonly AppRequirement[] = []\n const r = input.requires\n if (r !== undefined) {\n if (Array.isArray(r)) {\n if (!r.every(e => typeof e === \"string\")) {\n throw fail(\"'requires' must be an array of strings or an object { browser, fs, gpu, secrets, apps }.\")\n }\n requires = [...r] as string[]\n requirements = { ...requirements, apps: requires }\n appRequirements = appRequirementList(r, \"requires\", fail)\n } else if (isRecord(r)) {\n const apps = appRequirementList(r.apps, \"requires.apps\", fail)\n requirements = {\n browser: bool(r.browser, \"requires.browser\", fail),\n fs: bool(r.fs, \"requires.fs\", fail),\n gpu: bool(r.gpu, \"requires.gpu\", fail),\n secrets: stringList(r.secrets, \"requires.secrets\", fail),\n apps: apps.map(e => e.id),\n }\n appRequirements = apps\n if (apps.length > 0) requires = apps.map(e => e.id)\n } else {\n throw fail(\"'requires' must be an array of strings or an object { browser, fs, gpu, secrets, apps }.\")\n }\n }\n\n let exposes: AppExposes = { agents: [], workflows: [] }\n if (input.exposes !== undefined) {\n if (!isRecord(input.exposes)) throw fail(\"'exposes' must be an object { agents, workflows }.\")\n const agents = stringList(input.exposes.agents, \"exposes.agents\", fail)\n const workflows = stringList(input.exposes.workflows, \"exposes.workflows\", fail)\n for (const id of agents) {\n if (!declared.agents.includes(id)) {\n throw fail(\n `'exposes.agents' names '${id}' but the app declares no such agent. Declared: [${declared.agents.join(\", \") || \"none\"}].`,\n )\n }\n }\n for (const id of workflows) {\n if (!declared.workflows.includes(id)) {\n throw fail(\n `'exposes.workflows' names '${id}' but the app declares no such workflow. Declared: [${declared.workflows.join(\", \") || \"none\"}].`,\n )\n }\n }\n exposes = { agents, workflows }\n }\n\n let accepts: AppAccepts = { tasks: false }\n if (input.accepts !== undefined) {\n if (!isRecord(input.accepts)) throw fail(\"'accepts' must be an object { tasks }.\")\n accepts = { tasks: bool(input.accepts.tasks, \"accepts.tasks\", fail) }\n }\n\n return { placement, requires, requirements, appRequirements, exposes, accepts }\n}\n","/**\n * `defineApp({ agents, workflows, attach })` — bundle one or more AIP-42\n * agents, the AIP-15 workflows they run, and any other AIP artifacts into\n * one cross-linked, frozen handle.\n *\n * The only new invariant app-kit adds is *attachment*: the agents and the\n * bundled workflows must reference each other. Everything else (field\n * validation) already ran when the caller built the handles with\n * `defineAgent` / `defineWorkflow`, so `defineApp` validates the coupling,\n * not the fields.\n *\n * - agent ids are unique within the app.\n * - every `agent.workflows[]` ref MUST resolve to a bundled workflow id.\n * - every bundled workflow MUST be referenced by at least one agent.\n *\n * A dangling ref (an agent points at a workflow the app didn't bundle) or\n * an orphan (a bundled workflow no agent lists) throws — that is what \"an\n * agent attached to its workflows\" means, made checkable.\n */\n\nimport { isAbsolute } from \"node:path\"\nimport { defineWorkspace } from \"@agentproto/workspace\"\nimport type { AgentHandle, AnyRef } from \"@agentproto/agent\"\nimport type { BuildMastraAgentResult } from \"@agentproto/mastra\"\nimport type { WorkflowHandle } from \"@agentproto/workflow\"\nimport type { WorkspaceHandle } from \"@agentproto/workspace\"\nimport type {\n AgentEntry,\n AppDefinition,\n AppHandle,\n AppRequirement,\n DoctypeHandle,\n OpenAIAppUiExtension,\n OpenAIEntrypoint,\n OpenAIIcon,\n ToMastraAgentOptions,\n WorkspaceInput,\n} from \"./types.js\"\nimport { refKey } from \"./refs.js\"\nimport { emitApp } from \"./emit.js\"\nimport { normalizeManifestFields } from \"./manifest-fields.js\"\n\nexport class AppDefinitionError extends Error {\n constructor(message: string) {\n super(`defineApp (app-kit): ${message}`)\n this.name = \"AppDefinitionError\"\n }\n}\n\nexport function defineApp(def: AppDefinition): AppHandle {\n if (def.id !== undefined && def.id.trim() === \"\") {\n throw new AppDefinitionError(\"`id` must be non-empty when present.\")\n }\n if (def.ui !== undefined && (typeof def.ui.html !== \"string\" || def.ui.html.trim() === \"\")) {\n throw new AppDefinitionError(\"`ui.html` must be a non-empty string when `ui` is present.\")\n }\n if ((def.agents === undefined || def.agents.length === 0) && def.ui === undefined) {\n throw new AppDefinitionError(\n \"an app needs at least one agent, or a `ui` block for a UI-only app — got neither.\",\n )\n }\n if (def.dev !== undefined && (!Array.isArray(def.dev.launch) || def.dev.launch.length === 0)) {\n throw new AppDefinitionError(\"`dev.launch` must be a non-empty array when `dev` is present.\")\n }\n if (def.data !== undefined && def.data.dir !== undefined && (typeof def.data.dir !== \"string\" || def.data.dir.trim() === \"\")) {\n throw new AppDefinitionError(\"`data.dir` must be a non-empty string when present.\")\n }\nif (def.artifact !== undefined && (typeof def.artifact.path !== \"string\" || def.artifact.path.trim() === \"\")) {\n throw new AppDefinitionError(\"`artifact.path` must be a non-empty string when `artifact` is present.\")\n }\n // AIP-53 rule 7: `artifact.path` / `skill.path` MUST be absolute —\n // `emit` copies from them at write time and a relative path has no\n // defined base to resolve against.\n if (def.artifact !== undefined && !isAbsolute(def.artifact.path)) {\n throw new AppDefinitionError(\n `\\`artifact.path\\` must be an absolute filesystem path, got '${def.artifact.path}' — a relative path has no defined base to resolve against (AIP-53 rule 7).`,\n )\n }\n if (def.skill !== undefined && (typeof def.skill.path !== \"string\" || def.skill.path.trim() === \"\")) {\n throw new AppDefinitionError(\"`skill.path` must be a non-empty string when `skill` is present.\")\n }\n if (def.skill !== undefined && !isAbsolute(def.skill.path)) {\n throw new AppDefinitionError(\n `\\`skill.path\\` must be an absolute filesystem path, got '${def.skill.path}' — a relative path has no defined base to resolve against (AIP-53 rule 7).`,\n )\n }\n if (def.category !== undefined && def.category.trim() === \"\") {\n throw new AppDefinitionError(\"`category` must be a non-empty string when present.\")\n }\n\n const agents = (def.agents ?? []).map(normalizeEntry)\n const workflows = def.workflows ?? []\n const tools = def.tools ?? []\n const drivers = def.drivers ?? []\n const attachments = def.attach ?? []\n const workspace = def.workspace ? toWorkspaceHandle(def.workspace) : undefined\n const id = def.id\n const name = def.name\n const version = def.version ?? (id ? \"0.1.0\" : undefined)\n const description = def.description\n const fields = normalizeManifestFields(\n { placement: def.placement, requires: def.requires, exposes: def.exposes, accepts: def.accepts },\n { agents: agents.map(e => e.agent.id), workflows: workflows.map(w => w.id) },\n msg => new AppDefinitionError(msg),\n )\n const requires = fields.requires ? Object.freeze([...fields.requires]) : undefined\n const requirements = Object.freeze({\n ...fields.requirements,\n secrets: Object.freeze([...fields.requirements.secrets]),\n apps: Object.freeze([...fields.requirements.apps]),\n })\n const appRequirements = Object.freeze(\n fields.appRequirements.map(e => Object.freeze({ ...e, ...(e.workflows !== undefined ? { workflows: Object.freeze([...e.workflows]) } : {}) })),\n )\n const placement = fields.placement\n const exposes = Object.freeze({\n agents: Object.freeze([...fields.exposes.agents]),\n workflows: Object.freeze([...fields.exposes.workflows]),\n })\n const accepts = Object.freeze({ ...fields.accepts })\n const uiExtensions =\n def.ui === undefined || def.ui.extensions === undefined\n ? undefined\n : (Object.freeze({\n openai: freezeDeep(\n normalizeOpenAIUiExtension(\n validateOpenAIExtensionsNamespace(def.ui.extensions),\n def.ui.tools,\n msg => new AppDefinitionError(msg),\n ),\n ),\n }) as { readonly openai?: OpenAIAppUiExtension })\n const ui = def.ui\n ? Object.freeze({\n ...def.ui,\n ...(uiExtensions !== undefined ? { extensions: uiExtensions } : {}),\n })\n : undefined\n const artifact = def.artifact ? Object.freeze({ ...def.artifact }) : undefined\n const skill = def.skill ? Object.freeze({ ...def.skill }) : undefined\n const artifacts = def.artifacts ? Object.freeze(def.artifacts.map(a => Object.freeze({ ...a }))) : undefined\n const dev = def.dev\n ? Object.freeze({ launch: Object.freeze(def.dev.launch.map(l => Object.freeze({ ...l }))) })\n : undefined\n const externalReadRoots = def.externalReadRoots ? Object.freeze([...def.externalReadRoots]) : undefined\n const data = def.data ? Object.freeze({ ...def.data }) : undefined\n const boundaries = def.boundaries ? Object.freeze({ ...def.boundaries }) : undefined\n const category = def.category\n\n validateAttachment(agents, workflows)\n validateUniqueIds(tools, \"tool\")\n validateUniqueIds(drivers, \"driver\")\n\n const frozenAgents = Object.freeze(agents.map((e) => Object.freeze({ ...e })))\n const frozenWorkflows = Object.freeze([...workflows])\n const frozenTools = Object.freeze([...tools])\n const frozenDrivers = Object.freeze([...drivers])\n const frozenAttachments = Object.freeze([...attachments])\n\n const handle: AppHandle = {\n agents: frozenAgents,\n workflows: frozenWorkflows,\n tools: frozenTools,\n drivers: frozenDrivers,\n attachments: frozenAttachments,\n ...(workspace ? { workspace } : {}),\n ...(id !== undefined ? { id } : {}),\n ...(name !== undefined ? { name } : {}),\n ...(version !== undefined ? { version } : {}),\n ...(description !== undefined ? { description } : {}),\n ...(requires !== undefined ? { requires } : {}),\n requirements,\n appRequirements,\n placement,\n exposes,\n accepts,\n ...(ui !== undefined ? { ui } : {}),\n ...(artifact !== undefined ? { artifact } : {}),\n ...(skill !== undefined ? { skill } : {}),\n ...(artifacts !== undefined ? { artifacts } : {}),\n ...(dev !== undefined ? { dev } : {}),\n ...(data !== undefined ? { data } : {}),\n ...(externalReadRoots !== undefined ? { externalReadRoots } : {}),\n ...(boundaries !== undefined ? { boundaries } : {}),\n ...(category !== undefined ? { category } : {}),\n\n async toMastraAgents(opts: ToMastraAgentOptions, only?: readonly string[]) {\n const targets = only ? selectAgents(frozenAgents, only) : frozenAgents\n const out: Record<string, BuildMastraAgentResult> = {}\n for (const entry of targets) {\n out[entry.agent.id] = await buildOne(entry, opts)\n }\n return out\n },\n\n pick(ids: readonly string[]) {\n return selectAgents(frozenAgents, ids)\n },\n\n async toMastraAgent(opts: ToMastraAgentOptions) {\n if (frozenAgents.length !== 1) {\n throw new AppDefinitionError(\n `toMastraAgent requires exactly one agent (app has ${frozenAgents.length}); use toMastraAgents.`,\n )\n }\n return buildOne(frozenAgents[0]!, opts)\n },\n\n emit(dir: string) {\n return emitApp(\n {\n agents: frozenAgents,\n workflows: frozenWorkflows,\n ...(workspace ? { workspace } : {}),\n ...(id !== undefined ? { id } : {}),\n ...(name !== undefined ? { name } : {}),\n ...(version !== undefined ? { version } : {}),\n ...(description !== undefined ? { description } : {}),\n ...(requires !== undefined ? { requires } : {}),\n requirements,\n appRequirements,\n placement,\n exposes,\n accepts,\n ...(ui !== undefined ? { ui } : {}),\n ...(artifact !== undefined ? { artifact } : {}),\n ...(skill !== undefined ? { skill } : {}),\n ...(artifacts !== undefined ? { artifacts } : {}),\n ...(dev !== undefined ? { dev } : {}),\n ...(data !== undefined ? { data } : {}),\n ...(externalReadRoots !== undefined ? { externalReadRoots } : {}),\n ...(boundaries !== undefined ? { boundaries } : {}),\n ...(category !== undefined ? { category } : {}),\n },\n dir,\n )\n },\n }\n\n return Object.freeze(handle)\n}\n\n/**\n * Normalize the `workspace` input to an AIP-34 `WorkspaceHandle`. A built\n * handle (already run through `defineWorkspace`) carries `schema:\n * \"workspace/v1\"` and passes straight through; a `WorkspaceShorthand` is\n * completed with a local-fs storage default and a `0.1.0` version, then\n * validated by `defineWorkspace` — so a malformed shorthand fails with the\n * same AIP-34 diagnostic as a malformed WORKSPACE.md.\n */\nfunction toWorkspaceHandle(input: WorkspaceInput): WorkspaceHandle {\n if (\"schema\" in input) return input\n return defineWorkspace({\n schema: \"workspace/v1\",\n version: input.version ?? \"0.1.0\",\n id: input.id,\n name: input.name,\n owner: input.owner,\n storage: input.storage ?? { inline: { provider: \"local-fs\", config: {} } },\n ...(input.description ? { description: input.description } : {}),\n })\n}\n\n/**\n * Resolve `ids` to their app entries, preserving the caller's order. Throws\n * `AppDefinitionError` on any id the app doesn't bundle — a hand-picked list\n * that names a missing agent is a bug, not a silent no-op.\n */\nfunction selectAgents(\n agents: readonly AgentEntry[],\n ids: readonly string[],\n): readonly AgentEntry[] {\n const byId = new Map(agents.map((e) => [e.agent.id, e]))\n return ids.map((id) => {\n const entry = byId.get(id)\n if (!entry) {\n throw new AppDefinitionError(\n `agent '${id}' is not in this app. Bundled: [${[...byId.keys()].join(\", \")}].`,\n )\n }\n return entry\n })\n}\n\nasync function buildOne(entry: AgentEntry, opts: ToMastraAgentOptions): Promise<BuildMastraAgentResult> {\n // Dynamic import, not a static top-level one: `@agentproto/mastra` pulls in\n // `@mastra/core` (a documented peer dependency — see index.ts), which a\n // bundler would otherwise inline into ANY host that merely calls\n // `defineApp()` without ever calling `toMastraAgent(s)` (e.g. a UI-only app\n // consumer). Loading it lazily, only from the one place it's actually used,\n // keeps `defineApp()`/the rest of this module free of that cost.\n const { buildMastraAgent } = await import(\"@agentproto/mastra\")\n // `entry.body` (the AGENT.md body) wins as instructions; an explicit\n // `opts.body` still overrides, matching buildMastraAgent's contract.\n return buildMastraAgent(entry.agent, { body: entry.body, ...opts })\n}\n\nfunction normalizeEntry(input: AgentEntry | AgentHandle): AgentEntry {\n // An AgentEntry has an `.agent`; a bare AgentHandle has `.id`/`.schema`.\n if (\"agent\" in input) return input\n return { agent: input }\n}\n\n/**\n * The attachment invariant across all agents: bundled workflow ids and\n * the union of every agent's `workflows[]` refs must be the same set.\n * External/registry workflow refs are out of scope for an app bundle —\n * if an agent lists it, the app must ship it.\n */\nfunction validateAttachment(\n agents: readonly AgentEntry[],\n workflows: readonly WorkflowHandle[],\n): void {\n const seenAgentIds = new Set<string>()\n for (const { agent } of agents) {\n if (seenAgentIds.has(agent.id)) {\n throw new AppDefinitionError(`duplicate agent id '${agent.id}' in the bundle.`)\n }\n seenAgentIds.add(agent.id)\n }\n\n const bundledIds = new Set<string>()\n for (const wf of workflows) {\n if (bundledIds.has(wf.id)) {\n throw new AppDefinitionError(`duplicate workflow id '${wf.id}' in the bundle.`)\n }\n bundledIds.add(wf.id)\n }\n\n const referenced = new Set<string>()\n for (const { agent } of agents) {\n for (const ref of workflowRefs(agent)) {\n const key = refKey(ref)\n referenced.add(key)\n if (!bundledIds.has(key)) {\n throw new AppDefinitionError(\n `agent '${agent.id}' references workflow '${key}' but the app does not bundle it. ` +\n `Bundled: [${[...bundledIds].join(\", \") || \"none\"}].`,\n )\n }\n }\n }\n\n for (const id of bundledIds) {\n if (!referenced.has(id)) {\n throw new AppDefinitionError(\n `workflow '${id}' is bundled but no agent lists it in workflows[]. ` +\n `Add { ref: \"${id}\" } to an agent, or drop the workflow.`,\n )\n }\n }\n}\n\nfunction workflowRefs(agent: AgentHandle): readonly AnyRef[] {\n return agent.workflows ?? []\n}\n\n/** Duplicate-id guard for `tools`/`drivers` — mirrors the agent/workflow id\n * uniqueness `validateAttachment` already enforces. */\nfunction validateUniqueIds(items: readonly { id: string }[], kind: string): void {\n const seen = new Set()\n for (const item of items) {\n if (seen.has(item.id)) {\n throw new AppDefinitionError(`duplicate ${kind} id '${item.id}' in the bundle.`)\n }\n seen.add(item.id)\n }\n}\n\n/**\n * `ui.extensions` accepts ONLY the `openai` namespace (plan I8). Any other\n * vendor block is rejected with the exact field path rather than silently\n * carried and half-advertised downstream. Returns the `openai` value.\n */\nfunction validateOpenAIExtensionsNamespace(raw: unknown): unknown {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw new AppDefinitionError(\"`ui.extensions` must be an object.\")\n }\n for (const key of Object.keys(raw as Record<string, unknown>)) {\n if (key !== \"openai\") {\n throw new AppDefinitionError(\n `\\`ui.extensions.${key}\\` is not supported — \\`extensions\\` accepts only \\`openai\\` (v1).`,\n )\n }\n }\n return (raw as Record<string, unknown>).openai\n}\n\nconst OPENAI_EXTENSION_KEYS = new Set([\"entrypoints\", \"icons\", \"display\", \"mentions\"])\n/** Cut in v1: forms/elicitation+MRTR, plugin settings, resource writes,\n * raw local-file opening, plugin onboarding manifest, deep links. Any of\n * these keys (or anything unknown) fails with the exact field path. */\nconst OPENAI_CUT_KEY_MESSAGE =\n \"is not a supported OpenAI extension field in v1 (cut would be silently half-advertised)\"\n\nconst DOT_EXTENSION_RE = /^\\.[a-z0-9][a-z0-9._+-]{0,31}$/\nconst OPENAI_MODES = [\"inline\", \"fullscreen\"] as const\n\n/**\n * The single `ui.extensions.openai` validator/normalizer, shared by TS\n * authoring (`defineApp`) and manifest loading (`loadAppHandle` re-runs\n * through `defineApp`), so there is no hand-maintained duplicate. Normalizes\n * file entrypoint extensions to lowercase; validates every shape/range rule\n * with the exact `ui.extensions.openai.*` field path.\n */\nexport function normalizeOpenAIUiExtension(\n raw: unknown,\n tools: readonly string[] | undefined,\n fail: (message: string) => Error,\n): OpenAIAppUiExtension | undefined {\n if (raw === undefined) return undefined\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw fail(\"`ui.extensions.openai` must be an object.\")\n }\n for (const key of Object.keys(raw)) {\n if (!OPENAI_EXTENSION_KEYS.has(key)) {\n throw fail(`\\`ui.extensions.openai.${key}\\` ${OPENAI_CUT_KEY_MESSAGE}.`)\n }\n }\n\n const entrypoints = normalizeOpenAIEntrypoints((raw as Record<string, unknown>).entrypoints, fail)\n const icons = normalizeOpenAIIcons((raw as Record<string, unknown>).icons, fail)\n const display = normalizeOpenAIDisplay((raw as Record<string, unknown>).display, fail)\n const mentions = normalizeOpenAIMentions((raw as Record<string, unknown>).mentions, tools, fail)\n\n return {\n ...(entrypoints !== undefined ? { entrypoints } : {}),\n ...(icons !== undefined ? { icons } : {}),\n ...(display !== undefined ? { display } : {}),\n ...(mentions !== undefined ? { mentions } : {}),\n }\n}\n\nfunction normalizeOpenAIEntrypoints(\n raw: unknown,\n fail: (message: string) => Error,\n): readonly OpenAIEntrypoint[] | undefined {\n if (raw === undefined) return undefined\n if (!Array.isArray(raw)) {\n throw fail(\"`ui.extensions.openai.entrypoints` must be an array.\")\n }\n if (raw.length < 1 || raw.length > 3) {\n throw fail(\n `\\`ui.extensions.openai.entrypoints\\` must contain 1..3 entries, got ${raw.length}.`,\n )\n }\n const seenTypes = new Set<string>()\n const out: OpenAIEntrypoint[] = []\n for (let i = 0; i < raw.length; i++) {\n const path = `ui.extensions.openai.entrypoints[${i}]`\n const ep = raw[i]\n if (typeof ep !== \"object\" || ep === null || Array.isArray(ep)) {\n throw fail(`\\`${path}\\` must be an object.`)\n }\n const keys = Object.keys(ep as Record<string, unknown>)\n const invalidKeys = keys.filter(k => k !== \"type\" && k !== \"extensions\")\n if (invalidKeys.length > 0) {\n throw fail(\n `\\`${path}.${invalidKeys[0]}\\` is not a supported \\`${(ep as { type?: unknown }).type}\\` entrypoint field.`,\n )\n }\n const type = (ep as Record<string, unknown>).type\n if (type !== \"global\" && type !== \"thread\" && type !== \"file\") {\n throw fail(`\\`${path}.type\\` must be \"global\", \"thread\" or \"file\", got ${JSON.stringify(type)}.`)\n }\n if (seenTypes.has(type)) {\n throw fail(`\\`ui.extensions.openai.entrypoints\\` declares \\`${type}\\` more than once.`)\n }\n seenTypes.add(type)\n if (type === \"file\") {\n out.push({ type, extensions: normalizeDotExtensions((ep as Record<string, unknown>).extensions, path, fail) })\n } else {\n out.push({ type })\n }\n }\n return out\n}\n\nfunction normalizeDotExtensions(\n raw: unknown,\n path: string,\n fail: (message: string) => Error,\n): readonly `.${string}`[] {\n if (!Array.isArray(raw)) {\n throw fail(`\\`${path}.extensions\\` must be an array of dot-prefixed strings.`)\n }\n if (raw.length < 1 || raw.length > 32) {\n throw fail(`\\`${path}.extensions\\` must contain 1..32 entries, got ${raw.length}.`)\n }\n const seen = new Set<string>()\n const out: `.${string}`[] = []\n for (let i = 0; i < raw.length; i++) {\n const ext = raw[i]\n if (typeof ext !== \"string\" || ext.trim() === \"\") {\n throw fail(`\\`${path}.extensions[${i}]\\` must be a non-empty string.`)\n }\n const normalized = ext.toLowerCase()\n if (seen.has(normalized)) {\n throw fail(`\\`${path}.extensions\\` declares '${normalized}' more than once.`)\n }\n seen.add(normalized)\n if (!DOT_EXTENSION_RE.test(normalized)) {\n throw fail(\n `\\`${path}.extensions[${i}]\\` ('${ext}') must be a dot-prefixed lowercase suffix matching /^\\\\.[a-z0-9][a-z0-9._+-]{0,31}$/, e.g. '.md'.`,\n )\n }\n out.push(normalized as `.${string}`)\n }\n return out\n}\n\nfunction normalizeOpenAIIcons(\n raw: unknown,\n fail: (message: string) => Error,\n): readonly OpenAIIcon[] | undefined {\n if (raw === undefined) return undefined\n if (!Array.isArray(raw)) throw fail(\"`ui.extensions.openai.icons` must be an array.\")\n if (raw.length < 1) {\n throw fail(\"`ui.extensions.openai.icons` must contain at least one icon when present.\")\n }\n return raw.map((icon, i) => {\n const path = `ui.extensions.openai.icons[${i}]`\n if (typeof icon !== \"object\" || icon === null || Array.isArray(icon)) {\n throw fail(`\\`${path}\\` must be an object.`)\n }\n const keys = Object.keys(icon as Record<string, unknown>)\n for (const key of keys) {\n if (key !== \"src\" && key !== \"mimeType\" && key !== \"sizes\" && key !== \"theme\") {\n throw fail(`\\`${path}.${key}\\` is not a supported icon field.`)\n }\n }\n const src = (icon as Record<string, unknown>).src\n if (typeof src !== \"string\" || src.trim() === \"\") {\n throw fail(`\\`${path}.src\\` must be a non-empty string.`)\n }\n if (!(ICON_SRC_HTTPS_RE.test(src) || hasValidIconSrcDataUrl(src))) {\n throw fail(\n `\\`${path}.src\\` must be an HTTPS URL or a 'data:image/…;base64,…' URL (inline SVG data allowed), got '${src.slice(0, 64)}'.`,\n )\n }\n const mimeType = (icon as Record<string, unknown>).mimeType\n if (mimeType !== undefined && (typeof mimeType !== \"string\" || mimeType.trim() === \"\")) {\n throw fail(`\\`${path}.mimeType\\` must be a non-empty string when present.`)\n }\n const sizes = (icon as Record<string, unknown>).sizes\n if (\n sizes !== undefined &&\n (!Array.isArray(sizes) || (sizes as unknown[]).length === 0 ||\n !(sizes as unknown[]).every((s) => typeof s === \"string\" && s.trim() !== \"\"))\n ) {\n throw fail(`\\`${path}.sizes\\` must be an array of non-empty strings when present.`)\n }\n const theme = (icon as Record<string, unknown>).theme\n if (theme !== undefined && theme !== \"light\" && theme !== \"dark\") {\n throw fail(`\\`${path}.theme\\` must be \"light\" or \"dark\" when present, got ${JSON.stringify(theme)}.`)\n }\n return {\n src,\n ...(mimeType !== undefined ? { mimeType: mimeType as string } : {}),\n ...(sizes !== undefined ? { sizes: Object.freeze([...(sizes as string[])]) } : {}),\n ...(theme !== undefined ? { theme: theme as \"light\" | \"dark\" } : {}),\n }\n })\n}\n\nconst ICON_SRC_HTTPS_RE = /^https:\\/\\/\\S+$/\n\nfunction hasValidIconSrcDataUrl(src: string): boolean {\n const comma = src.indexOf(\",\")\n if (comma < 0) return false\n const header = src.slice(0, comma)\n const payload = src.slice(comma + 1)\n if (!/^data:image\\/[a-z0-9.+-]+(?:;charset=[\\w-]+)?(?:;base64|;utf8)?$/i.test(header)) return false\n if (/;base64$/i.test(header)) return /^[A-Za-z0-9+/=\\r\\n]+$/.test(payload)\n return payload.trim() !== \"\"\n}\n\nfunction normalizeOpenAIDisplay(\n raw: unknown,\n fail: (message: string) => Error,\n):\n | { readonly availableModes?: readonly (\"inline\" | \"fullscreen\")[]\n readonly preferredMode?: \"inline\" | \"fullscreen\" }\n | undefined {\n if (raw === undefined) return undefined\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw fail(\"`ui.extensions.openai.display` must be an object.\")\n }\n const availableModes = (raw as Record<string, unknown>).availableModes\n if (availableModes !== undefined) {\n if (!Array.isArray(availableModes) || availableModes.length === 0) {\n throw fail(\"`ui.extensions.openai.display.availableModes` must be a non-empty array when present.\")\n }\n const seen = new Set<string>()\n for (const mode of availableModes) {\n if (mode !== \"inline\" && mode !== \"fullscreen\") {\n throw fail(\n `\\`ui.extensions.openai.display.availableModes\\` supports only \"inline\" and \"fullscreen\", got ${JSON.stringify(mode)}.`,\n )\n }\n if (seen.has(mode)) {\n throw fail(`\\`ui.extensions.openai.display.availableModes\\` declares '${mode}' more than once.`)\n }\n seen.add(mode)\n }\n }\n const preferredMode = (raw as Record<string, unknown>).preferredMode\n if (\n preferredMode !== undefined &&\n !(OPENAI_MODES as readonly unknown[]).includes(preferredMode)\n ) {\n throw fail(\n `\\`ui.extensions.openai.display.preferredMode\\` must be \"inline\" or \"fullscreen\", got ${JSON.stringify(preferredMode)}.`,\n )\n }\n if (\n availableModes !== undefined &&\n preferredMode !== undefined &&\n !availableModes.includes(preferredMode as \"inline\" | \"fullscreen\")\n ) {\n throw fail(\n `\\`ui.extensions.openai.display.preferredMode\\` ('${preferredMode}') must occur in \\`ui.extensions.openai.display.availableModes\\` when both are declared.`,\n )\n }\n return {\n ...(availableModes !== undefined\n ? { availableModes: Object.freeze([...(availableModes as (\"inline\" | \"fullscreen\")[])]) }\n : {}),\n ...(preferredMode !== undefined ? { preferredMode: preferredMode as \"inline\" | \"fullscreen\" } : {}),\n }\n}\n\nfunction normalizeOpenAIMentions(\n raw: unknown,\n tools: readonly string[] | undefined,\n fail: (message: string) => Error,\n):\n | { readonly searchTool: string }\n | undefined {\n if (raw === undefined) return undefined\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw fail(\"`ui.extensions.openai.mentions` must be an object.\")\n }\n for (const key of Object.keys(raw)) {\n if (key !== \"searchTool\") {\n throw fail(`\\`ui.extensions.openai.mentions.${key}\\` is not a supported mentions field.`)\n }\n }\n const searchTool = (raw as Record<string, unknown>).searchTool\n if (typeof searchTool !== \"string\" || searchTool.trim() === \"\") {\n throw fail(\"`ui.extensions.openai.mentions.searchTool` must be a non-empty string.\")\n }\n if (tools === undefined || !tools.includes(searchTool)) {\n throw fail(\n `\\`ui.extensions.openai.mentions.searchTool\\` '${searchTool}' must be declared in this same ui block's \\`tools\\`${tools ? ` (${tools.join(\", \")})` : \" — the ui declares none\"}.`,\n )\n }\n return { searchTool }\n}\n\n/** Deep-freeze the normalized OpenAI extension tree — same immutability\n * discipline the rest of app-kit applies to top-level handle fields. */\nfunction freezeDeep(value: unknown): unknown {\n if (Array.isArray(value)) return Object.freeze(value.map(freezeDeep))\n if (typeof value === \"object\" && value !== null) {\n const out: Record<string, unknown> = {}\n for (const [key, v] of Object.entries(value)) {\n out[key] = freezeDeep(v)\n }\n return Object.freeze(out)\n }\n return value\n}\n\nexport type { DoctypeHandle }\n","/** Thrown by `loadAppHandle` and its helpers (`loadAppBundledTools`, …) on\n * any disk/parse/validation failure while reading an app bundle off disk. */\nexport class AppLoadError extends Error {\n constructor(message: string) {\n super(`loadAppHandle: ${message}`)\n this.name = \"AppLoadError\"\n }\n}\n","/**\n * Loader for an app's bundled AIP-14 TOOL.md contracts and AIP-30 DRIVER.md\n * implementations — the deterministic-step half of WORKFLOW.md `tool` steps\n * (yt-dlp, an STT HTTP call, a PDF render, …), as opposed to `agent` steps.\n *\n * Neither AIP-53 (app, still Draft with no scaffolded spec) nor AIP-14/30\n * declare a bundle location for these, so this is a convention this loader\n * defines: `<dir>/.agentproto/tools/<id>/TOOL.md` and\n * `<dir>/.agentproto/drivers/<id>/DRIVER.md`, one manifest per `<id>`\n * subdirectory, discovered by listing — not declared as APP.md frontmatter\n * refs like `agents`/`workflows` are. An absent `tools`/`drivers` directory\n * is not an error (most apps have neither); a subdirectory that exists but\n * fails to parse, or is missing its TOOL.md/DRIVER.md, fails the whole load\n * — `loadAppHandle` never silently drops a broken tool/driver bundle.\n *\n * Only `kind: cli` and `kind: http` drivers dispatch (the two\n * `@agentproto/driver-cli` / `@agentproto/driver-http` sugars this package\n * already depends on). Any other `kind` (`mcp`, `sdk`, `builtin`) still\n * loads — a malformed manifest still fails the app load — but its execute\n * body refuses clearly instead of silently no-oping or crashing on a\n * dispatch mechanism this host doesn't implement yet.\n *\n * A `kind: cli` driver's subprocess `cwd` defaults to the app root (`dir`,\n * the directory containing `.agentproto/`) rather than the host process's\n * own cwd — relative paths in an app-bundled cli driver (DRIVER.md argv,\n * `--out-dir`-style flags, …) resolve against the app root. A DRIVER.md can\n * override this with `metadata.cli.cwd`; a relative value there is itself\n * resolved against the app root, and a value that escapes the app root\n * (`../..`) is a load error, not a silent escape.\n */\n\nimport { readdir, readFile } from \"node:fs/promises\"\nimport type { Dirent } from \"node:fs\"\nimport { isAbsolute, join, relative, resolve } from \"node:path\"\nimport {\n parseToolManifest,\n toolFromManifestOnly,\n type ToolHandle,\n} from \"@agentproto/tool\"\nimport {\n driverFromManifest,\n driverDefinitionFromManifest,\n parseDriverManifest,\n type DriverManifest,\n} from \"@agentproto/driver/manifest\"\nimport { normalizeToolId, type DriverHandle, type ExecuteFn } from \"@agentproto/driver\"\nimport { defineCliDriver, type CliDriverDefinition } from \"@agentproto/driver-cli\"\nimport { defineHttpDriver, type HttpDriverDefinition } from \"@agentproto/driver-http\"\nimport { AppLoadError } from \"./errors.js\"\n\n/** List `<id>` subdirectory names under `base`, sorted. Missing `base` (the\n * common case — most apps ship neither tools nor drivers) is not an error. */\nasync function listBundleIds(base: string): Promise<string[]> {\n let entries: Dirent[]\n try {\n entries = await readdir(base, { withFileTypes: true })\n } catch {\n return []\n }\n return entries\n .filter((e) => e.isDirectory())\n .map((e) => e.name)\n .sort()\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\nasync function loadToolEntry(id: string, toolPath: string): Promise<ToolHandle> {\n let source: string\n try {\n source = await readFile(toolPath, \"utf8\")\n } catch (err) {\n throw new AppLoadError(`tool '${id}': cannot read '${toolPath}': ${errMsg(err)}`)\n }\n try {\n return toolFromManifestOnly(parseToolManifest(source))\n } catch (err) {\n throw new AppLoadError(`tool '${id}' at '${toolPath}': ${errMsg(err)}`)\n }\n}\n\n/** Env var names DRIVER.md declares as required secrets — `auth.state.env`,\n * the existing AIP-30 field for \"env var names this provider's auth needs\".\n * Loosely typed at the manifest layer (`auth: z.unknown()`), so this reads\n * defensively rather than trusting a shape. */\nfunction requiredSecretNames(fm: DriverManifest[\"frontmatter\"]): readonly string[] {\n const auth = fm.auth as { state?: { env?: unknown } } | undefined\n const env = auth?.state?.env\n return Array.isArray(env) ? env.filter((e): e is string => typeof e === \"string\") : []\n}\n\n/**\n * Wrap every execute body so a declared-but-unresolved secret fails the\n * STEP with a clear `driver-error` naming the secret — never at app\n * install (secrets are resolved lazily, only when the tool actually\n * dispatches). Resolved values are merged into `driverCtx.secrets` ahead of\n * whatever the caller already put there (a workflow tool step's compiled\n * `secrets` is empty today — see BRIEF-D — so this is the only source for\n * an app-bundled driver), letting `${secrets.X}` templating in\n * `defineCliDriver`/`defineHttpDriver` resolve as authors expect.\n */\nfunction wrapExecuteWithSecretCheck(\n driverId: string,\n execute: Record<string, ExecuteFn>,\n secretNames: readonly string[],\n): Record<string, ExecuteFn> {\n if (secretNames.length === 0) return execute\n const wrapped: Record<string, ExecuteFn> = {}\n for (const [toolId, fn] of Object.entries(execute)) {\n wrapped[toolId] = async (args) => {\n const resolved: Record<string, string> = {}\n for (const name of secretNames) {\n const value = process.env[name]\n if (!value) {\n throw new Error(\n `driver '${driverId}': missing required secret '${name}' (declared in DRIVER.md 'auth.state.env').`,\n )\n }\n resolved[name] = value\n }\n const priorSecrets = (args.driverCtx as { secrets?: Record<string, string> }).secrets ?? {}\n return fn({ ...args, driverCtx: { ...args.driverCtx, secrets: { ...resolved, ...priorSecrets } } })\n }\n }\n return wrapped\n}\n\n/**\n * Resolve a kind:cli DRIVER.md's working directory. Relative paths in an\n * app-bundled cli driver resolve against the app root (the dir containing\n * `.agentproto/`) — not the daemon's own cwd, which is what `runSubprocess`\n * fell back to before this existed and is almost never what a DRIVER.md\n * author means (see `@agentproto/driver-cli`'s README). Defaults to the app\n * root itself when `metadata.cli.cwd` is unset; an explicit value — relative\n * or absolute — that resolves outside the app root is a load error rather\n * than silently escaping the bundle.\n */\nfunction resolveCliCwd(appRoot: string, driverId: string, cwd: unknown): string {\n const absoluteAppRoot = resolve(appRoot)\n if (cwd === undefined) return absoluteAppRoot\n if (typeof cwd !== \"string\" || cwd.trim() === \"\") {\n throw new Error(`driver '${driverId}': 'metadata.cli.cwd' must be a non-empty string.`)\n }\n const resolved = isAbsolute(cwd) ? resolve(cwd) : resolve(absoluteAppRoot, cwd)\n const rel = relative(absoluteAppRoot, resolved)\n if (rel !== \"\" && (rel.startsWith(\"..\") || isAbsolute(rel))) {\n throw new Error(\n `driver '${driverId}': 'metadata.cli.cwd' (${cwd}) resolves to '${resolved}', outside the app root '${absoluteAppRoot}'.`,\n )\n }\n return resolved\n}\n\n/** Build a working {@link DriverHandle} from a parsed DRIVER.md, dispatching\n * on `kind`. Throws a plain `Error` (wrapped in `AppLoadError` by the\n * caller, which has the file path) on a `cli`/`http` manifest missing its\n * dispatch config. */\nfunction driverHandleFromManifest(manifest: DriverManifest, appRoot: string): DriverHandle {\n const fm = manifest.frontmatter\n const secretNames = requiredSecretNames(fm)\n\n if (fm.kind === \"cli\") {\n const cliMeta = (fm.metadata?.cli ?? {}) as Partial<CliDriverDefinition> & { cwd?: unknown }\n if (typeof cliMeta.bin !== \"string\" || cliMeta.bin.trim() === \"\") {\n throw new Error(\n \"kind:cli DRIVER.md requires a non-empty 'metadata.cli.bin' frontmatter field naming the binary.\",\n )\n }\n const handle = defineCliDriver({\n ...driverDefinitionFromManifest(manifest),\n bin: cliMeta.bin,\n binArgs: cliMeta.binArgs,\n output: cliMeta.output,\n tty: cliMeta.tty,\n sandbox: cliMeta.sandbox,\n cwd: resolveCliCwd(appRoot, fm.id, cliMeta.cwd),\n })\n return { ...handle, execute: wrapExecuteWithSecretCheck(fm.id, handle.execute, secretNames) }\n }\n\n if (fm.kind === \"http\") {\n const httpMeta = (fm.metadata?.http ?? {}) as Partial<HttpDriverDefinition>\n if (typeof httpMeta.baseUrl !== \"string\" || httpMeta.baseUrl.trim() === \"\") {\n throw new Error(\"kind:http DRIVER.md requires a non-empty 'metadata.http.baseUrl' frontmatter field.\")\n }\n const handle = defineHttpDriver({\n ...driverDefinitionFromManifest(manifest),\n baseUrl: httpMeta.baseUrl,\n defaultHeaders: httpMeta.defaultHeaders,\n defaultMethod: httpMeta.defaultMethod,\n streaming: httpMeta.streaming,\n })\n return { ...handle, execute: wrapExecuteWithSecretCheck(fm.id, handle.execute, secretNames) }\n }\n\n // mcp / sdk / builtin: load (so a malformed manifest still fails the app\n // load), but refuse at resolve/dispatch — every implements[] entry gets\n // an execute body that fails with a clear message instead of silently\n // no-oping or throwing an opaque \"no dispatch mechanism\" error.\n const execute: Record<string, ExecuteFn> = {}\n for (const entry of fm.implements) {\n const toolId = normalizeToolId(entry.tool)\n execute[toolId] = async () => {\n throw new Error(\n `driver '${fm.id}': kind '${fm.kind}' is not supported by this host — only 'cli' and 'http' drivers dispatch.`,\n )\n }\n }\n return driverFromManifest({ manifest, execute })\n}\n\nasync function loadDriverEntry(id: string, driverPath: string, appRoot: string): Promise<DriverHandle> {\n let source: string\n try {\n source = await readFile(driverPath, \"utf8\")\n } catch (err) {\n throw new AppLoadError(`driver '${id}': cannot read '${driverPath}': ${errMsg(err)}`)\n }\n try {\n return driverHandleFromManifest(parseDriverManifest(source), appRoot)\n } catch (err) {\n throw new AppLoadError(`driver '${id}' at '${driverPath}': ${errMsg(err)}`)\n }\n}\n\n/**\n * Scan `<dir>/.agentproto/tools/*` and `<dir>/.agentproto/drivers/*` for\n * TOOL.md / DRIVER.md bundles and load them into live handles. Used by\n * `loadAppHandle` (install-time validation, via `defineApp`) and reusable\n * directly by a host that needs an already-installed app's tools/drivers\n * without re-walking its agents/workflows (see `@agentproto/runtime`'s\n * workflow `compileWorkflow` seam).\n */\nexport async function loadAppBundledTools(\n dir: string,\n): Promise<{ tools: ToolHandle[]; drivers: DriverHandle[] }> {\n const toolsDir = join(dir, \".agentproto\", \"tools\")\n const driversDir = join(dir, \".agentproto\", \"drivers\")\n\n const tools: ToolHandle[] = []\n for (const id of await listBundleIds(toolsDir)) {\n tools.push(await loadToolEntry(id, join(toolsDir, id, \"TOOL.md\")))\n }\n\n const drivers: DriverHandle[] = []\n for (const id of await listBundleIds(driversDir)) {\n drivers.push(await loadDriverEntry(id, join(driversDir, id, \"DRIVER.md\"), dir))\n }\n\n return { tools, drivers }\n}\n","/**\n * `loadAppHandle(dir)` — read a root `APP.md` off disk into an `AppHandle`.\n *\n * Mirror of `@agentproto/workflow-loader`'s `loadWorkflowHandle`: this is\n * the host-side seam that touches the filesystem so the pure packages\n * (`@agentproto/agent`, `@agentproto/workflow`, `@agentproto/workspace`)\n * don't have to.\n *\n * `<dir>/.agentproto/APP.md` lists every agent + workflow the app bundles\n * as `{ id, path }` refs (relative to `dir`, the shape `emitApp` writes).\n * Each is loaded with its own package's manifest reader — `AGENT.md` via\n * `@agentproto/agent/manifest`, `WORKFLOW.md` via\n * `@agentproto/workflow-loader` (which itself resolves an `entry:` module\n * when present) — then the whole bundle is re-run through `defineApp` so\n * the attachment invariant (every agent/workflow ref resolves both ways)\n * re-validates exactly as it did at authoring time. A stale or hand-edited\n * APP.md that drifted from its AGENT.md/WORKFLOW.md refs fails the same\n * way a bad `defineApp({...})` call would.\n *\n * The app may also ship AIP-14 TOOL.md / AIP-30 DRIVER.md bundles under\n * `.agentproto/tools/<id>/TOOL.md` and `.agentproto/drivers/<id>/DRIVER.md`\n * — discovered by directory convention (see `loadAppBundledTools`), not\n * declared as APP.md frontmatter refs like agents/workflows are.\n *\n * Frontmatter validation here is deliberately minimal, and that is now an\n * AIP-53 conformance decision, not an accident of app having \"no AIP yet\":\n * AIP-53 (Draft) freezes the loader contract at the checks below — schema\n * MUST be exactly `app/v1`, `agents`/`workflows` MUST be `{ id, path }`\n * ref arrays, every ref MUST resolve, and the bundle MUST re-run through\n * `defineApp` — and it does NOT require rejecting unknown frontmatter\n * keys. Staying permissive past the frozen checks lets a future frontmatter\n * key (e.g. a later WP's addition) round-trip through this loader without\n * hosts that haven't upgraded rejecting the whole app; tightening beyond\n * the spec would break that forward compatibility for no conformance gain.\n */\n\nimport { readFile } from \"node:fs/promises\"\nimport { dirname, isAbsolute, join } from \"node:path\"\nimport matter from \"gray-matter\"\nimport { agentFromManifest, parseAgentManifest } from \"@agentproto/agent/manifest\"\nimport { loadWorkflowHandle } from \"@agentproto/workflow-loader\"\nimport { parseWorkspaceManifest, workspaceFromManifest } from \"@agentproto/workspace/manifest\"\nimport type {\n AgentEntry,\n AppArtifactDecl,\n AppBoundariesDefinition,\n AppDataDefinition,\n AppDefinition,\n AppDevDefinition,\n AppHandle,\n AppUiBuildConfig,\n AppUiDefinition,\n} from \"./types.js\"\nimport { defineApp } from \"./define-app.js\"\nimport { AppLoadError } from \"./errors.js\"\nimport { loadAppBundledTools } from \"./load-app-tools.js\"\nimport { normalizeManifestFields } from \"./manifest-fields.js\"\n\nexport { AppLoadError }\n\ninterface AppRef {\n readonly id: string\n readonly path: string\n}\n\ninterface AppFrontmatterUi {\n readonly path: string\n readonly title?: string\n readonly description?: string\n readonly tools?: readonly string[]\n readonly port?: number\n readonly csp?: {\n readonly connectDomains?: readonly string[]\n readonly resourceDomains?: readonly string[]\n readonly frameDomains?: readonly string[]\n }\n readonly build?: AppUiBuildConfig\n /**\n * Namespaced vendor extension metadata. Passed through to `defineApp`\n * UNFILTERED (not just `openai`) so its namespace check — `ui.extensions`\n * accepts ONLY `openai` — actually runs against a hand-authored APP.md's\n * sibling keys too, not just the TS-authoring path.\n */\n readonly extensions?: { readonly [key: string]: unknown }\n}\n\ninterface AppFrontmatterArtifact {\n readonly path: string\n readonly title?: string\n readonly description?: string\n}\n\ninterface AppFrontmatterSkill {\n readonly path: string\n readonly title?: string\n readonly description?: string\n}\n\ninterface AppFrontmatter {\n readonly schema: string\n readonly id?: string\n readonly name?: string\n readonly version?: string\n readonly description?: string\n readonly agents: readonly AppRef[]\n readonly workflows: readonly AppRef[]\n readonly workspace?: string\n readonly requires?: AppDefinition[\"requires\"]\n readonly placement?: AppDefinition[\"placement\"]\n readonly exposes?: AppDefinition[\"exposes\"]\n readonly accepts?: AppDefinition[\"accepts\"]\n readonly ui?: AppFrontmatterUi\n readonly artifact?: AppFrontmatterArtifact\n readonly skill?: AppFrontmatterSkill\n readonly artifacts?: readonly AppArtifactDecl[]\n readonly dev?: AppDevDefinition\n readonly data?: AppDataDefinition\n readonly externalReadRoots?: readonly string[]\n readonly boundaries?: AppBoundariesDefinition\n readonly category?: string\n}\n\nfunction resolveRef(dir: string, path: string): string {\n return isAbsolute(path) ? path : join(dir, path)\n}\n\n/**\n * Resolve the UI ROOT directory an app's UI should be served from — the\n * same resolution `app_install`/`loadAppHandle` uses for `ui.path`, so\n * `app serve` and install agree on where the UI lives.\n *\n * Reads `<appDir>/.agentproto/APP.md` frontmatter: when a `ui.path` is\n * declared, the UI root is the directory CONTAINING that entry file (e.g.\n * `ui.path: ui/index.html` → `<appDir>/ui`); when `ui` is absent, returns\n * `undefined` and callers fall back to the legacy `<appDir>/.agentproto/ui/`.\n * Throws {@link AppLoadError} on a `ui` that isn't an object or whose `path`\n * isn't a non-empty string — the same shape `loadAppHandle` would reject.\n * Returns `undefined` (not a throw) when APP.md itself is unreadable, since\n * callers check APP.md existence separately.\n */\nexport async function resolveAppUIRoot(appDir: string): Promise<string | undefined> {\n const appMdPath = join(appDir, \".agentproto\", \"APP.md\")\n let source: string\n try {\n source = await readFile(appMdPath, \"utf8\")\n } catch {\n return undefined\n }\n const data = matter(source).data as Record<string, unknown>\n const ui = data.ui\n if (ui === undefined) return undefined\n if (typeof ui !== \"object\" || ui === null || Array.isArray(ui)) {\n throw new AppLoadError(`'${appMdPath}': frontmatter 'ui' must be an object.`)\n }\n const path = (ui as Record<string, unknown>).path\n if (typeof path !== \"string\" || path.trim() === \"\") {\n throw new AppLoadError(\n `'${appMdPath}': frontmatter 'ui.path' must be a non-empty string.`,\n )\n }\n return dirname(resolveRef(appDir, path))\n}\n\n/** Validated `ui.path` + `ui.build`, as returned by {@link peekAppUi}. */\nexport interface AppUiPeek {\n readonly path: string\n readonly build?: AppUiBuildConfig\n}\n\nfunction parseUiBuildFrontmatter(raw: unknown, appMdPath: string): AppUiBuildConfig | undefined {\n if (raw === undefined) return undefined\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw new AppLoadError(`'${appMdPath}': frontmatter 'ui.build' must be an object.`)\n }\n const command = (raw as Record<string, unknown>).command\n if (typeof command !== \"string\" || command.trim() === \"\") {\n throw new AppLoadError(`'${appMdPath}': frontmatter 'ui.build.command' must be a non-empty string.`)\n }\n const cwd = (raw as Record<string, unknown>).cwd\n if (cwd !== undefined && (typeof cwd !== \"string\" || cwd.trim() === \"\")) {\n throw new AppLoadError(`'${appMdPath}': frontmatter 'ui.build.cwd' must be a non-empty string.`)\n }\n const sources = (raw as Record<string, unknown>).sources\n if (\n sources !== undefined &&\n (!Array.isArray(sources) || !sources.every(s => typeof s === \"string\" && s.trim() !== \"\"))\n ) {\n throw new AppLoadError(\n `'${appMdPath}': frontmatter 'ui.build.sources' must be an array of non-empty strings.`,\n )\n }\n return {\n command,\n ...(cwd !== undefined ? { cwd: cwd as string } : {}),\n ...(sources !== undefined ? { sources: sources as string[] } : {}),\n }\n}\n\n/**\n * Peek `<appDir>/.agentproto/APP.md`'s `ui.path` + `ui.build` WITHOUT\n * reading the ui html itself.\n *\n * `loadAppHandle` reads `ui.path` eagerly and throws {@link AppLoadError}\n * when it's missing — exactly the case a declared `ui.build` exists to\n * recover from. A caller that wants to build the bundle before it's\n * expected to exist (the daemon's `app_install`, `app serve`, first UI\n * serve — see `@agentproto/runtime`'s `ensureAppUiBuilt`) resolves this\n * first, runs the build if declared, then calls `loadAppHandle` as usual.\n *\n * Returns `undefined` when APP.md is unreadable or declares no `ui` block\n * — same \"caller checks existence separately\" contract as\n * `resolveAppUIRoot`. Throws on a malformed `ui`/`ui.build` shape, same\n * validation `loadAppHandle` would eventually hit.\n */\nexport async function peekAppUi(appDir: string): Promise<AppUiPeek | undefined> {\n const appMdPath = join(appDir, \".agentproto\", \"APP.md\")\n let source: string\n try {\n source = await readFile(appMdPath, \"utf8\")\n } catch {\n return undefined\n }\n const data = matter(source).data as Record<string, unknown>\n const ui = data.ui\n if (ui === undefined) return undefined\n if (typeof ui !== \"object\" || ui === null || Array.isArray(ui)) {\n throw new AppLoadError(`'${appMdPath}': frontmatter 'ui' must be an object.`)\n }\n const path = (ui as Record<string, unknown>).path\n if (typeof path !== \"string\" || path.trim() === \"\") {\n throw new AppLoadError(\n `'${appMdPath}': frontmatter 'ui.path' must be a non-empty string.`,\n )\n }\n const build = parseUiBuildFrontmatter((ui as Record<string, unknown>).build, appMdPath)\n return { path: resolveRef(appDir, path), ...(build ? { build } : {}) }\n}\n\nfunction isRefArray(v: unknown): v is AppRef[] {\n return (\n Array.isArray(v) &&\n v.every(\n (e) =>\n typeof e === \"object\" &&\n e !== null &&\n typeof (e as { id?: unknown }).id === \"string\" &&\n typeof (e as { path?: unknown }).path === \"string\",\n )\n )\n}\n\n/** Minimal shape check — see the module doc for why this stays loose. */\nfunction parseAppFrontmatter(data: Record<string, unknown>, appPath: string): AppFrontmatter {\n if (data.schema !== \"app/v1\") {\n throw new AppLoadError(\n `'${appPath}': expected frontmatter 'schema: app/v1', got ${JSON.stringify(data.schema)}.`,\n )\n }\n if (!isRefArray(data.agents)) {\n throw new AppLoadError(`'${appPath}': frontmatter 'agents' must be an array of { id, path }.`)\n }\n if (!isRefArray(data.workflows)) {\n throw new AppLoadError(\n `'${appPath}': frontmatter 'workflows' must be an array of { id, path }.`,\n )\n }\n // placement / requires / exposes / accepts: shape, enum and \"exposed id is\n // declared\" checks, same rules `defineApp` re-applies.\n normalizeManifestFields(\n data,\n { agents: data.agents.map(a => a.id), workflows: data.workflows.map(w => w.id) },\n msg => new AppLoadError(`'${appPath}': frontmatter ${msg}`),\n )\n if (data.data !== undefined) {\n const d = data.data as { dir?: unknown } | null\n if (\n typeof d !== \"object\" ||\n d === null ||\n (d.dir !== undefined && (typeof d.dir !== \"string\" || d.dir.trim() === \"\"))\n ) {\n throw new AppLoadError(\n `'${appPath}': frontmatter 'data' must be an object whose optional 'dir' is a non-empty string.`,\n )\n }\n }\n if (data.externalReadRoots !== undefined) {\n if (\n !Array.isArray(data.externalReadRoots) ||\n !data.externalReadRoots.every((e) => typeof e === \"string\" && e.trim() !== \"\")\n ) {\n throw new AppLoadError(\n `'${appPath}': frontmatter 'externalReadRoots' must be an array of non-empty strings.`,\n )\n }\n }\n if (data.boundaries !== undefined) {\n const b = data.boundaries as { enforce?: unknown } | null\n if (\n typeof b !== \"object\" ||\n b === null ||\n Array.isArray(b) ||\n (b.enforce !== undefined && b.enforce !== \"required\" && b.enforce !== \"best-effort\")\n ) {\n throw new AppLoadError(\n `'${appPath}': frontmatter 'boundaries' must be an object whose optional 'enforce' is \"required\" or \"best-effort\".`,\n )\n }\n }\n if (data.category !== undefined && (typeof data.category !== \"string\" || data.category.trim() === \"\")) {\n throw new AppLoadError(`'${appPath}': frontmatter 'category' must be a non-empty string.`)\n }\n return data as unknown as AppFrontmatter\n}\n\nasync function loadAgentEntry(dir: string, ref: AppRef): Promise<AgentEntry> {\n const agentPath = resolveRef(dir, ref.path)\n let source: string\n try {\n source = await readFile(agentPath, \"utf8\")\n } catch (err) {\n throw new AppLoadError(\n `agent '${ref.id}': cannot read '${agentPath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n let body: string\n let manifest: ReturnType<typeof parseAgentManifest>\n try {\n manifest = parseAgentManifest(source)\n body = manifest.body.trim()\n } catch (err) {\n throw new AppLoadError(\n `agent '${ref.id}' at '${agentPath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n return { agent: agentFromManifest(manifest), ...(body ? { body } : {}) }\n}\n\nasync function loadWorkflowRef(dir: string, ref: AppRef) {\n const wfPath = resolveRef(dir, ref.path)\n try {\n return await loadWorkflowHandle(wfPath)\n } catch (err) {\n throw new AppLoadError(\n `workflow '${ref.id}' at '${wfPath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Load `<dir>/.agentproto/APP.md` and every AGENT.md/WORKFLOW.md (and, if\n * declared, `<dir>/WORKSPACE.md`) it references, then re-run `defineApp` on\n * the result. Throws {@link AppLoadError} naming the offending path on a\n * missing APP.md, a missing referenced file, or a frontmatter/schema\n * mismatch; throws `AppDefinitionError` (from `defineApp`) if the loaded\n * bundle fails the attachment invariant.\n */\nexport async function loadAppHandle(dir: string): Promise<AppHandle> {\n const appPath = join(dir, \".agentproto\", \"APP.md\")\n let source: string\n try {\n source = await readFile(appPath, \"utf8\")\n } catch (err) {\n throw new AppLoadError(\n `cannot read '${appPath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n const parsed = matter(source)\n const fm = parseAppFrontmatter(parsed.data, appPath)\n\n const agents: AgentEntry[] = []\n for (const ref of fm.agents) {\n agents.push(await loadAgentEntry(dir, ref))\n }\n\n const workflows = []\n for (const ref of fm.workflows) {\n workflows.push(await loadWorkflowRef(dir, ref))\n }\n\n // AIP-14/AIP-30 tool + driver bundles — not enumerated in APP.md\n // frontmatter like agents/workflows are; discovered by convention under\n // `.agentproto/tools/<id>/TOOL.md` and `.agentproto/drivers/<id>/DRIVER.md`.\n // No declared bundle location exists yet in AIP-53/14/30 (spec gap) — see\n // `loadAppBundledTools` for the loader and its error-handling contract\n // (a parse/read failure fails the whole app load, naming the file path;\n // an absent `tools`/`drivers` directory is not an error).\n const { tools, drivers } = await loadAppBundledTools(dir)\n\n let workspace\n if (fm.workspace) {\n const workspacePath = join(dir, \"WORKSPACE.md\")\n let workspaceSource: string\n try {\n workspaceSource = await readFile(workspacePath, \"utf8\")\n } catch (err) {\n throw new AppLoadError(\n `workspace '${fm.workspace}': cannot read '${workspacePath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n try {\n workspace = workspaceFromManifest(parseWorkspaceManifest(workspaceSource))\n } catch (err) {\n throw new AppLoadError(\n `workspace '${fm.workspace}' at '${workspacePath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n }\n\n let ui\n if (fm.ui) {\n const uiPath = resolveRef(dir, fm.ui.path)\n let html: string\n try {\n html = await readFile(uiPath, \"utf8\")\n } catch (err) {\n throw new AppLoadError(\n `ui: cannot read '${uiPath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n const build = parseUiBuildFrontmatter(fm.ui.build, appPath)\n ui = {\n html,\n ...(fm.ui.title !== undefined ? { title: fm.ui.title } : {}),\n ...(fm.ui.description !== undefined ? { description: fm.ui.description } : {}),\n ...(fm.ui.tools !== undefined ? { tools: fm.ui.tools } : {}),\n ...(fm.ui.port !== undefined ? { port: fm.ui.port } : {}),\n ...(fm.ui.csp !== undefined ? { csp: fm.ui.csp } : {}),\n ...(build !== undefined ? { build } : {}),\n // Pass through UNFILTERED — `defineApp`'s\n // `validateOpenAIExtensionsNamespace` rejects any sibling vendor key\n // (a typo, a future vendor block, hand-authored drift) with the same\n // diagnostic the TS-authoring path throws. Pre-filtering to `openai`\n // here would silently drop those instead of failing loudly.\n ...(fm.ui.extensions !== undefined\n ? { extensions: fm.ui.extensions as unknown as AppUiDefinition[\"extensions\"] }\n : {}),\n }\n }\n\n return defineApp({\n agents,\n workflows,\n tools,\n drivers,\n ...(workspace ? { workspace } : {}),\n ...(fm.id !== undefined ? { id: fm.id } : {}),\n ...(fm.name !== undefined ? { name: fm.name } : {}),\n ...(fm.version !== undefined ? { version: fm.version } : {}),\n ...(fm.description !== undefined ? { description: fm.description } : {}),\n ...(fm.requires !== undefined ? { requires: fm.requires } : {}),\n ...(fm.placement !== undefined ? { placement: fm.placement } : {}),\n ...(fm.exposes !== undefined ? { exposes: fm.exposes } : {}),\n ...(fm.accepts !== undefined ? { accepts: fm.accepts } : {}),\n ...(ui !== undefined ? { ui } : {}),\n ...(fm.artifact !== undefined\n ? { artifact: { path: resolveRef(dir, fm.artifact.path), ...(fm.artifact.title !== undefined ? { title: fm.artifact.title } : {}), ...(fm.artifact.description !== undefined ? { description: fm.artifact.description } : {}) } }\n : {}),\n ...(fm.skill !== undefined\n ? { skill: { path: resolveRef(dir, fm.skill.path), ...(fm.skill.title !== undefined ? { title: fm.skill.title } : {}), ...(fm.skill.description !== undefined ? { description: fm.skill.description } : {}) } }\n : {}),\n ...(fm.artifacts !== undefined ? { artifacts: fm.artifacts } : {}),\n ...(fm.dev !== undefined ? { dev: fm.dev } : {}),\n ...(fm.data !== undefined ? { data: fm.data } : {}),\n ...(fm.externalReadRoots !== undefined ? { externalReadRoots: fm.externalReadRoots } : {}),\n ...(fm.boundaries !== undefined ? { boundaries: fm.boundaries } : {}),\n ...(fm.category !== undefined ? { category: fm.category } : {}),\n })\n}\n","/**\n * `.agentapp` pack / unpack core (AIP-53 §\"The `.agentapp` package format\").\n *\n * PACK walks the app dir (skipping `node_modules/` and `.git/` at any\n * depth), applies the APP.md `package` include/exclude rules (plus\n * RELEASE_DEFAULT_EXCLUDE in release mode), stages ONLY the selected\n * files (rewriting APP.md without `ui.build` when stripping), writes a\n * `manifest.json` at the bundle root, and tars the staged CONTENTS\n * with system `tar`, so extraction yields `manifest.json` +\n * `.agentproto/` + loose files at the top level.\n *\n * UNPACK extracts to a fresh temp dir, reads `manifest.json`, validates\n * `format === \"agentapp/v1\"`, recomputes the aggregate SHA over the\n * listed files and compares it to `manifest.sha256`, then moves the\n * restored contents (WITHOUT `manifest.json` — it is a bundle\n * artifact, not part of the app) into the destination dir.\n *\n * The SHA is over file contents ONLY (excluding manifest.json), fed in the\n * manifest `files` order (pack already sorts them), accumulated into one\n * hasher so bundling-scale trees don't load into memory.\n *\n * Both entries throw {@link AgentAppPackError}; `code` lets a caller (the\n * CLI, the daemon's remote install) map failures without parsing messages.\n */\n\nimport { copyFile, cp, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from \"node:fs/promises\"\nimport { createHash } from \"node:crypto\"\nimport { basename, dirname, isAbsolute, join, posix, resolve } from \"node:path\"\nimport { tmpdir } from \"node:os\"\nimport { spawn } from \"node:child_process\"\n\nimport matter from \"gray-matter\"\n\nexport const AGENTAPP_FORMAT = \"agentapp/v1\" as const\nconst DEFAULT_VERSION = \"0.1.0\"\n\n/** Directory names skipped at any depth while walking/copying an app dir. */\nconst SKIP_DIR_NAMES = new Set([\"node_modules\", \".git\"])\n\n/** The manifest.json written at the bundle root (and validated on unpack). */\nexport interface AgentAppManifest {\n format: typeof AGENTAPP_FORMAT\n id: string\n name?: string\n version: string\n description?: string\n agents: string[]\n workflows: string[]\n ui?: string[]\n files: string[]\n fileCount: number\n totalSize: number\n sha256: string\n createdAt: string\n agentprotoVersion: string\n}\n\n/** A file discovered under the app dir, with its size for the manifest. */\nexport interface BundleFile {\n path: string\n size: number\n}\n\nexport type AgentAppPackErrorCode =\n | \"not-an-app\"\n | \"bundle-not-found\"\n | \"tar-failed\"\n | \"missing-manifest\"\n | \"malformed-manifest\"\n | \"unsupported-format\"\n | \"unsafe-path\"\n | \"digest-mismatch\"\n | \"invalid-package\"\n | \"missing-ui\"\n\nexport class AgentAppPackError extends Error {\n readonly code: AgentAppPackErrorCode\n constructor(code: AgentAppPackErrorCode, message: string) {\n super(message)\n this.name = \"AgentAppPackError\"\n this.code = code\n }\n}\n\n/** `.agentproto/APP.md` frontmatter, digested into bundle metadata. */\ninterface AppMeta {\n id: string\n name?: string\n version: string\n description?: string\n agents: string[]\n workflows: string[]\n ui?: string[]\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p)\n return true\n } catch {\n return false\n }\n}\n\n/** Derive a filesystem-safe id from a possibly scoped/odd app id. */\nexport function safeId(id: unknown): string {\n return String(id || \"app\").replace(/^@/, \"\").replace(/[^A-Za-z0-9._-]+/g, \"-\")\n}\n\n/** Narrow an unknown parsed JSON value to the manifest shape. */\nexport function isManifest(value: unknown): value is AgentAppManifest {\n if (typeof value !== \"object\" || value === null) return false\n const m = value as Record<string, unknown>\n return (\n typeof m.format === \"string\" &&\n typeof m.id === \"string\" &&\n typeof m.version === \"string\" &&\n Array.isArray(m.agents) &&\n Array.isArray(m.workflows) &&\n Array.isArray(m.files) &&\n typeof m.fileCount === \"number\" &&\n typeof m.totalSize === \"number\" &&\n typeof m.sha256 === \"string\"\n )\n}\n\n/**\n * Recursively collect every regular file under root as relative paths,\n * skipping any `node_modules/` or `.git/` directory at any depth — a `ui/`\n * source tree ships both, and bundling either would balloon the .agentapp\n * for no benefit (they're never part of the shipped app).\n */\nexport async function collectFiles(root: string): Promise<BundleFile[]> {\n const files: BundleFile[] = []\n async function walk(relDir: string): Promise<void> {\n const absDir = join(root, relDir)\n for (const entry of await readdir(absDir, { withFileTypes: true })) {\n if (entry.isDirectory() && SKIP_DIR_NAMES.has(entry.name)) continue\n const rel = relDir ? join(relDir, entry.name) : entry.name\n const abs = join(absDir, entry.name)\n if (entry.isDirectory()) {\n await walk(rel)\n } else if (entry.isFile()) {\n const st = await stat(abs)\n files.push({ path: rel, size: st.size })\n }\n }\n }\n await walk(\"\")\n return files\n}\n\n/** Aggregate sha256 over the concatenated bytes of the given files. */\nexport async function aggregateSha256(root: string, files: readonly string[]): Promise<string> {\n const hash = createHash(\"sha256\")\n for (const file of files) {\n hash.update(await readFile(join(root, file)))\n }\n return hash.digest(\"hex\")\n}\n\n/**\n * Run system `tar` with the given args, resolving the exit code (0 = ok).\n * Uses `spawn` + an exit handler so the awaited promise actually tracks\n * process completion cross-platform (BSD/macOS and GNU tar).\n */\nfunction runTar(args: string[], opts?: { cwd?: string }): Promise<number> {\n return new Promise((resolvePromise, reject) => {\n const child = spawn(\"tar\", args, { stdio: \"ignore\", cwd: opts?.cwd })\n child.once(\"error\", reject)\n child.once(\"exit\", (code) => resolvePromise(code ?? 0))\n })\n}\n\n/** Pull ids from an `[{id, path}]` (or bare-string) array. */\nfunction extractIds(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n const out: string[] = []\n for (const entry of value) {\n if (typeof entry === \"string\") {\n if (entry) out.push(entry)\n } else if (entry && typeof entry === \"object\") {\n const id = (entry as { id?: unknown }).id\n if (typeof id === \"string\" && id) out.push(id)\n }\n }\n return out\n}\n\n/** Basenames for a path/`{path}`/array-of-either frontmatter field. */\nfunction extractPaths(front: Record<string, unknown>, key: string): string[] | undefined {\n const value = front[key]\n if (value === undefined || value === null) return undefined\n const items = Array.isArray(value) ? value : [value]\n const out: string[] = []\n for (const item of items) {\n if (typeof item === \"string\") {\n if (item) out.push(basename(item))\n } else if (item && typeof item === \"object\") {\n const p = (item as { path?: unknown }).path\n if (typeof p === \"string\" && p) out.push(basename(p))\n }\n }\n return out.length > 0 ? out : undefined\n}\n\n/** Extract bundle metadata from APP.md frontmatter. */\nfunction extractMeta(front: Record<string, unknown>): AppMeta {\n const id =\n typeof front.id === \"string\" && front.id.length > 0\n ? front.id\n : typeof front.slug === \"string\" && front.slug.length > 0\n ? front.slug\n : \"app\"\n const version =\n typeof front.version === \"string\" && front.version.length > 0\n ? front.version\n : DEFAULT_VERSION\n const name = typeof front.name === \"string\" ? front.name : undefined\n const description = typeof front.description === \"string\" ? front.description : undefined\n const ui = extractPaths(front, \"ui\")\n\n return {\n id,\n ...(name !== undefined ? { name } : {}),\n version,\n ...(description !== undefined ? { description } : {}),\n agents: extractIds(front.agents),\n workflows: extractIds(front.workflows),\n ...(ui !== undefined ? { ui } : {}),\n }\n}\n\n/**\n * Release-mode default excludes: dev-only trees and artifacts that must never\n * ship in a published `.agentapp` (UI sources, docs, runtime data, scripts,\n * dev harnesses, tests, repo docs and tooling config, logs, source maps, env\n * files). Nothing the runtime reads: an installed app is its\n * `.agentproto/` tree plus the files its workflows import. APP.md\n * `package.exclude` ADDS to this list in release mode; it never removes\n * from it. `LICENSE` / `NOTICE` are deliberately NOT excluded.\n */\nexport const RELEASE_DEFAULT_EXCLUDE: readonly string[] = [\n \"ui/**\",\n \"docs/**\",\n \"data/**\",\n \"scripts/**\",\n // Root-level only: `**/dev/**` would also drop a shipped agent named\n // `dev` (`.agentproto/agents/dev/`); `ui/dev/` is covered by `ui/**`.\n // Same for `test/` and `tests/`.\n \"dev/**\",\n \"test/**\",\n \"tests/**\",\n // Test files and folders anywhere (a workflow's `foo.test.mjs` next to\n // its `entry.mjs`); these names are never a runtime import.\n \"**/__tests__/**\",\n \"**/*.test.*\",\n \"**/*.spec.*\",\n // Repo docs at the app root (the catalog entry carries the description).\n \"README.md\",\n \"CHANGELOG.md\",\n \"CONTRIBUTING.md\",\n // Repo and editor tooling.\n \".github/**\",\n \".vscode/**\",\n \".idea/**\",\n \".gitignore\",\n \".editorconfig\",\n \"tsconfig*.json\",\n \"vitest.config.*\",\n \"jest.config.*\",\n \"eslint.config.*\",\n \".eslintrc*\",\n \".prettierrc*\",\n \"**/*.log\",\n \"**/*.map\",\n \"**/.DS_Store\",\n \"**/.env\",\n \"**/.env.*\",\n]\n\n/** APP.md `package` block — what a `.agentapp` ships. All fields optional. */\nexport interface AppPackageRules {\n /** When set, only files matching one of these globs ship (APP.md and the\n * `ui.path` entry + its `assets/` are always kept). */\n include?: string[]\n /** Files matching any of these globs are dropped. */\n exclude?: string[]\n /** Remove `ui.build` from the packed APP.md. Default: true in release mode,\n * false otherwise. */\n stripBuild?: boolean\n}\n\n/**\n * Glob → RegExp over a `/`-separated relative path. `**` spans any number of\n * segments (including none when followed by `/`), `*` stays inside one\n * segment. No braces, no negation, no `?` — enough for package rules without\n * a glob dependency.\n */\nexport function globToRegExp(glob: string): RegExp {\n const g = glob.replace(/^\\.\\//, \"\")\n let re = \"\"\n for (let i = 0; i < g.length; i++) {\n const c = g[i]!\n if (c === \"*\") {\n if (g[i + 1] === \"*\") {\n i++\n if (g[i + 1] === \"/\") {\n i++\n re += \"(?:.*/)?\"\n } else {\n re += \".*\"\n }\n } else {\n re += \"[^/]*\"\n }\n } else if (\"\\\\^$+?.()|{}[]\".includes(c)) {\n re += \"\\\\\" + c\n } else {\n re += c\n }\n }\n return new RegExp(`^${re}$`)\n}\n\nfunction toPosix(p: string): string {\n return p.replace(/\\\\/g, \"/\")\n}\n\nfunction matchesAny(path: string, globs: readonly RegExp[]): boolean {\n const p = toPosix(path)\n return globs.some((re) => re.test(p))\n}\n\n/** Read + validate the APP.md `package` block. Throws `invalid-package`. */\nexport function readPackageRules(front: Record<string, unknown>): AppPackageRules {\n const raw = front.package\n if (raw === undefined || raw === null) return {}\n if (typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new AgentAppPackError(\"invalid-package\", \"APP.md `package` must be an object.\")\n }\n const r = raw as Record<string, unknown>\n const list = (key: \"include\" | \"exclude\"): string[] | undefined => {\n const v = r[key]\n if (v === undefined) return undefined\n if (!Array.isArray(v) || v.some((s) => typeof s !== \"string\" || s.trim() === \"\")) {\n throw new AgentAppPackError(\n \"invalid-package\",\n `APP.md \\`package.${key}\\` must be an array of non-empty glob strings.`,\n )\n }\n return v as string[]\n }\n if (r.stripBuild !== undefined && typeof r.stripBuild !== \"boolean\") {\n throw new AgentAppPackError(\"invalid-package\", \"APP.md `package.stripBuild` must be a boolean.\")\n }\n const include = list(\"include\")\n const exclude = list(\"exclude\")\n return {\n ...(include !== undefined ? { include } : {}),\n ...(exclude !== undefined ? { exclude } : {}),\n ...(typeof r.stripBuild === \"boolean\" ? { stripBuild: r.stripBuild } : {}),\n }\n}\n\n/** APP.md `ui.path` (string or `{path}`) as a posix path relative to the app\n * dir, or undefined when absent / absolute / escaping the app dir. */\nfunction uiRelPath(front: Record<string, unknown>): string | undefined {\n const ui = front.ui\n const raw =\n typeof ui === \"string\"\n ? ui\n : ui && typeof ui === \"object\" && !Array.isArray(ui) && typeof (ui as { path?: unknown }).path === \"string\"\n ? (ui as { path: string }).path\n : undefined\n if (raw === undefined || raw === \"\" || isAbsolute(raw)) return undefined\n const rel = posix.normalize(toPosix(raw)).replace(/^\\.\\//, \"\")\n if (rel.startsWith(\"../\") || rel === \"..\") return undefined\n return rel\n}\n\n/**\n * Package `appDir` (must hold `.agentproto/APP.md`) into a `.agentapp`.\n * Without `out`, the file is `<safeId>-<version>.agentapp` in the cwd.\n *\n * File selection: every file under `appDir` minus `node_modules/`/`.git/`,\n * then the APP.md `package` rules (`include` restricts, `exclude` drops). In\n * `release` mode {@link RELEASE_DEFAULT_EXCLUDE} is added to `exclude`, the\n * built `ui.path` must be in the bundle (`missing-ui` otherwise), and\n * `ui.build` is stripped from the packed APP.md (override with\n * `package.stripBuild`). `.agentproto/APP.md`, the `ui.path` entry and the\n * files under its sibling `assets/` dir always ship. Only the selected files\n * are staged, and the SHA covers the staged bytes (so a rewritten APP.md is\n * what gets hashed).\n */\nexport async function packApp(input: {\n appDir: string\n out?: string\n release?: boolean\n}): Promise<{ file: string; manifest: AgentAppManifest }> {\n const appDirAbs = resolve(input.appDir)\n const release = input.release === true\n\n const appMdPath = join(appDirAbs, \".agentproto\", \"APP.md\")\n if (!(await pathExists(appMdPath))) {\n throw new AgentAppPackError(\n \"not-an-app\",\n `${appDirAbs} is not an agentproto app (missing ${appMdPath}).`,\n )\n }\n\n const raw = await readFile(appMdPath, \"utf8\")\n const parsedAppMd = matter(raw)\n const front = parsedAppMd.data as Record<string, unknown>\n const meta = extractMeta(front)\n const rules = readPackageRules(front)\n\n const outAbs =\n input.out !== undefined\n ? resolve(input.out)\n : resolve(process.cwd(), `${safeId(meta.id)}-${meta.version}.agentapp`)\n await mkdir(dirname(outAbs), { recursive: true })\n\n const appMdRel = \".agentproto/APP.md\"\n const uiRel = uiRelPath(front)\n const uiAssetsPrefix = uiRel !== undefined ? `${posix.dirname(uiRel)}/assets/`.replace(/^\\.\\//, \"\") : undefined\n const includeRes = rules.include?.map(globToRegExp)\n const excludeRes = [...(release ? RELEASE_DEFAULT_EXCLUDE : []), ...(rules.exclude ?? [])].map(globToRegExp)\n const alwaysShip = (p: string): boolean =>\n p === appMdRel || p === uiRel || (uiAssetsPrefix !== undefined && p.startsWith(uiAssetsPrefix))\n\n const selected = (await collectFiles(appDirAbs))\n .filter((f) => f.path !== \"manifest.json\")\n .filter((f) => join(appDirAbs, f.path) !== outAbs)\n .filter((f) => {\n const p = toPosix(f.path)\n if (alwaysShip(p)) return true\n if (includeRes !== undefined && !matchesAny(p, includeRes)) return false\n return !matchesAny(p, excludeRes)\n })\n .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))\n\n if (release && uiRel !== undefined && !selected.some((f) => toPosix(f.path) === uiRel)) {\n throw new AgentAppPackError(\n \"missing-ui\",\n `ui.path \"${uiRel}\" does not exist in ${appDirAbs} — build the UI first ` +\n \"(`agentproto app build <appDir>`, or `agentproto app pack --release`, which runs `ui.build`).\",\n )\n }\n\n const stripBuild = rules.stripBuild ?? release\n\n // Stage ONLY the selected files, optionally rewrite APP.md, then hash and\n // tar what is actually staged — excluded files never reach the archive.\n const staging = await mkdtemp(join(tmpdir(), \"agentapp-\"))\n try {\n for (const f of selected) {\n const dest = join(staging, f.path)\n await mkdir(dirname(dest), { recursive: true })\n await copyFile(join(appDirAbs, f.path), dest)\n }\n\n if (stripBuild) {\n const ui = front.ui\n if (ui && typeof ui === \"object\" && !Array.isArray(ui) && \"build\" in ui) {\n // Clone: gray-matter caches parse results per input string, so the\n // cached `data` object must not be mutated.\n const data = structuredClone(front)\n delete (data.ui as Record<string, unknown>).build\n await writeFile(join(staging, appMdRel), matter.stringify(parsedAppMd.content, data), \"utf8\")\n }\n }\n\n const files: BundleFile[] = []\n for (const f of selected) {\n files.push({ path: f.path, size: (await stat(join(staging, f.path))).size })\n }\n const fileCount = files.length\n const totalSize = files.reduce((sum, f) => sum + f.size, 0)\n const sha256 = await aggregateSha256(\n staging,\n files.map((f) => f.path),\n )\n\n const manifest: AgentAppManifest = {\n format: AGENTAPP_FORMAT,\n id: meta.id,\n ...(meta.name !== undefined ? { name: meta.name } : {}),\n version: meta.version,\n ...(meta.description !== undefined ? { description: meta.description } : {}),\n agents: meta.agents,\n workflows: meta.workflows,\n ...(meta.ui !== undefined ? { ui: meta.ui } : {}),\n files: files.map((f) => f.path),\n fileCount,\n totalSize,\n sha256,\n createdAt: new Date().toISOString(),\n agentprotoVersion: \">=0.1.0\",\n }\n\n await writeFile(join(staging, \"manifest.json\"), JSON.stringify(manifest, null, 2) + \"\\n\", \"utf8\")\n // Offline-deterministic archive: pass the entry list explicitly (sorted) so\n // the archive order is reproducible without GNU-only `--sort=name`, which\n // BSD/macOS tar rejects. Dotfiles (`.agentproto`) are included by readdir.\n const entries = (await readdir(staging)).sort()\n const packCode = await runTar([\"-czf\", outAbs, ...entries], { cwd: staging })\n if (packCode !== 0) {\n throw new AgentAppPackError(\"tar-failed\", `tar failed with exit code ${packCode}`)\n }\n return { file: outAbs, manifest }\n } finally {\n await rm(staging, { recursive: true, force: true })\n }\n}\n\n/** A manifest `files` entry that could read or write outside the bundle root. */\nfunction isUnsafeBundlePath(p: string): boolean {\n if (p === \"\" || isAbsolute(p)) return true\n return p.split(/[\\\\/]/).includes(\"..\")\n}\n\n/**\n * Extract a `.agentapp`, verify format + aggregate SHA-256, and restore the\n * app folder (without `manifest.json`) into `dest`. Without `dest`, restores\n * into `<safeId>-<version>` in the cwd. A failed verification leaves `dest`\n * untouched (nothing is created).\n */\nexport async function unpackApp(input: {\n file: string\n dest?: string\n}): Promise<{ dir: string; manifest: AgentAppManifest }> {\n const bundleAbs = resolve(input.file)\n if (!(await pathExists(bundleAbs))) {\n throw new AgentAppPackError(\"bundle-not-found\", `bundle not found: ${bundleAbs}`)\n }\n\n const temp = await mkdtemp(join(tmpdir(), \"agentapp-\"))\n try {\n const unpackCode = await runTar([\"-xzf\", bundleAbs, \"-C\", temp])\n if (unpackCode !== 0) {\n throw new AgentAppPackError(\"tar-failed\", `tar failed with exit code ${unpackCode}`)\n }\n\n const manifestPath = join(temp, \"manifest.json\")\n if (!(await pathExists(manifestPath))) {\n throw new AgentAppPackError(\n \"missing-manifest\",\n `${bundleAbs} is not a valid .agentapp (missing manifest.json).`,\n )\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(await readFile(manifestPath, \"utf8\"))\n } catch {\n throw new AgentAppPackError(\"malformed-manifest\", `${bundleAbs} has a malformed manifest.json.`)\n }\n if (!isManifest(parsed)) {\n throw new AgentAppPackError(\"malformed-manifest\", `${bundleAbs} has a malformed manifest.json.`)\n }\n const manifest = parsed\n\n if (manifest.format !== AGENTAPP_FORMAT) {\n throw new AgentAppPackError(\n \"unsupported-format\",\n `unsupported bundle format '${manifest.format}' (expected ${AGENTAPP_FORMAT}).`,\n )\n }\n\n const unsafe = manifest.files.find((f) => typeof f !== \"string\" || isUnsafeBundlePath(f))\n if (unsafe !== undefined) {\n throw new AgentAppPackError(\n \"unsafe-path\",\n `manifest.json lists a path outside the bundle root: ${JSON.stringify(unsafe)}.`,\n )\n }\n\n const actual = await aggregateSha256(temp, manifest.files)\n if (actual !== manifest.sha256) {\n throw new AgentAppPackError(\n \"digest-mismatch\",\n `SHA-256 mismatch (expected ${manifest.sha256}, got ${actual}). Bundle is corrupted.`,\n )\n }\n\n const outDir =\n input.dest !== undefined\n ? resolve(input.dest)\n : resolve(process.cwd(), `${safeId(manifest.id)}-${manifest.version}`)\n // Drop the bundle artifact before moving the app contents over.\n await rm(manifestPath, { force: true })\n await mkdir(outDir, { recursive: true })\n await cp(temp, outDir, { recursive: true })\n\n return { dir: outDir, manifest }\n } finally {\n await rm(temp, { recursive: true, force: true })\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/refs.ts","../src/emit.ts","../src/version-range.ts","../src/manifest-fields.ts","../src/define-app.ts","../src/errors.ts","../src/load-app-tools.ts","../src/load-app.ts","../src/pack.ts"],"names":["workflowRefs","matter","isAbsolute","relative","join","readFile","readdir","resolve","mkdir","dirname","copyFile","writeFile","cp"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AASO,SAAS,OAAO,GAAA,EAAqB;AAC1C,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,EAAU,OAAO,GAAA;AACpC,EAAA,OAAO,GAAA,CAAI,OAAO,GAAA,CAAI,IAAA,IAAQ,KAAK,SAAA,CAAU,GAAA,CAAI,UAAU,GAAG,CAAA;AAChE;AAGO,SAAS,WAAW,EAAA,EAAoB;AAC7C,EAAA,MAAM,CAAA,GAAI,EAAA,CAAG,KAAA,CAAM,gBAAgB,CAAA;AACnC,EAAA,OAAO,CAAA,GAAI,CAAA,CAAE,CAAC,CAAA,GAAK,EAAA;AACrB;ACgDA,eAAsB,OAAA,CAAQ,KAAgB,GAAA,EAAkC;AAC9E,EAAA,IAAI,aAAA;AACJ,EAAA,IAAI,IAAI,SAAA,EAAW;AACjB,IAAA,MAAM,KAAA,CAAM,GAAA,EAAK,EAAE,SAAA,EAAW,MAAM,CAAA;AACpC,IAAA,aAAA,GAAgB,IAAA,CAAK,KAAK,cAAc,CAAA;AACxC,IAAA,MAAM,SAAA;AAAA,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A,GAAS,MAAM,eAAA,CAAgB,IAAA,EAAM,SAAS,KAAK,CAAA;AACzD,IAAA,IAAI,MAAA,KAAW,SAAS,MAAA,EAAQ;AAC9B,MAAA,MAAM,IAAI,iBAAA;AAAA,QACR,iBAAA;AAAA,QACA,CAAA,2BAAA,EAA8B,QAAA,CAAS,MAAM,CAAA,MAAA,EAAS,MAAM,CAAA,uBAAA;AAAA,OAC9D;AAAA,IACF;AAEA,IAAA,MAAM,MAAA,GACJ,MAAM,IAAA,KAAS,KAAA,CAAA,GACXE,QAAQ,KAAA,CAAM,IAAI,IAClBA,OAAAA,CAAQ,OAAA,CAAQ,KAAI,EAAG,CAAA,EAAG,OAAO,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA,EAAI,QAAA,CAAS,OAAO,CAAA,CAAE,CAAA;AAEzE,IAAA,MAAM,EAAA,CAAG,YAAA,EAAc,EAAE,KAAA,EAAO,MAAM,CAAA;AACtC,IAAA,MAAMC,KAAAA,CAAM,MAAA,EAAQ,EAAE,SAAA,EAAW,MAAM,CAAA;AACvC,IAAA,MAAMI,GAAG,IAAA,EAAM,MAAA,EAAQ,EAAE,SAAA,EAAW,MAAM,CAAA;AAE1C,IAAA,OAAO,EAAE,GAAA,EAAK,MAAA,EAAQ,QAAA,EAAS;AAAA,EACjC,CAAA,SAAE;AACA,IAAA,MAAM,GAAG,IAAA,EAAM,EAAE,WAAW,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAAA,EACjD;AACF","file":"index.mjs","sourcesContent":["/**\n * Ref-key extraction, shared with the same convention `buildMastraAgent`\n * uses (`packages/mastra/src/build-agent.ts` `refKey`). An AIP-27 ref is\n * a string shorthand or `{ ref | file | inline }`; the key is the string,\n * else `.ref`, else `.file`, else a stable JSON of the inline payload.\n */\n\nimport type { AnyRef } from \"@agentproto/agent\"\n\nexport function refKey(ref: AnyRef): string {\n if (typeof ref === \"string\") return ref\n return ref.ref ?? ref.file ?? JSON.stringify(ref.inline ?? ref)\n}\n\n/** `@agentik/writer` → `writer`; bare ids untouched. */\nexport function stripOwner(id: string): string {\n const m = id.match(/^@[^/]+\\/(.+)$/)\n return m ? m[1]! : id\n}\n","/**\n * `emitApp(app, dir)` — write an app's agents + workflows to disk under an\n * agentproto-owned base, so the manifests don't squat the shared root\n * `.agents/` convention:\n *\n * <dir>/WORKSPACE.md (when the app has a\n * workspace — AIP-34 root\n * manifest; owner = tenant)\n * <dir>/.agentproto/agents/<id>/AGENT.md (one per agent)\n * <dir>/.agentproto/workflows/<wf.id>/WORKFLOW.md (shared — a workflow may\n * be run by several agents)\n * <dir>/.agentproto/APP.md (root index — always\n * written, so a future\n * `app_install` can\n * discover the bundle)\n *\n * The \"tenant\" isn't a `tenants/<t>/…` path segment — it's the `owner` of\n * the AIP-34 WORKSPACE.md (guild / user / org), and local storage is its\n * AIP-35 `storage` block. So there is no bespoke tenant folder to invent.\n *\n * All manifests are plain markdown: frontmatter = the validated handle (or,\n * for APP.md, the identity + a manifest of `{ id, path }` refs to every\n * agent/workflow it bundles), body = the agent's `body` (its system prompt),\n * the workflow description, or the app description. Because a\n * `defineWorkflow` handle is pure data, the WORKFLOW.md needs no `entry:`\n * module — the manifest *is* the workflow, so `loadWorkflowHandle` returns\n * it directly with nothing to reconcile against.\n *\n * `emitApp` stays dependency-light on purpose (no Mastra import) — that\n * split lets a host write/discover an app without paying for the Mastra\n * build path.\n */\n\nimport { copyFile, cp, mkdir, writeFile } from \"node:fs/promises\"\nimport { join, relative } from \"node:path\"\nimport matter from \"gray-matter\"\nimport type { WorkflowHandle } from \"@agentproto/workflow\"\nimport type { WorkspaceHandle } from \"@agentproto/workspace\"\nimport type { AgentEntry, AppAccepts, AppArtifactDecl, AppArtifactSurface, AppBoundariesDefinition, AppDataDefinition, AppDevDefinition, AppExposes, AppPlacement, AppRequirement, AppRequirements, AppSkillSurface, AppUiDefinition, EmittedApp } from \"./types.js\"\nimport { stripOwner } from \"./refs.js\"\n\ninterface EmitInput {\n readonly agents: readonly AgentEntry[]\n readonly workflows: readonly WorkflowHandle[]\n readonly workspace?: WorkspaceHandle\n readonly id?: string\n readonly name?: string\n readonly version?: string\n readonly description?: string\n readonly requires?: readonly string[]\n readonly requirements?: AppRequirements\n readonly appRequirements?: readonly AppRequirement[]\n readonly placement?: AppPlacement\n readonly exposes?: AppExposes\n readonly accepts?: AppAccepts\n readonly ui?: AppUiDefinition\n readonly artifact?: AppArtifactSurface\n readonly skill?: AppSkillSurface\n readonly artifacts?: readonly AppArtifactDecl[]\n readonly dev?: AppDevDefinition\n readonly data?: AppDataDefinition\n readonly externalReadRoots?: readonly string[]\n readonly boundaries?: AppBoundariesDefinition\n readonly category?: string\n}\n\nexport async function emitApp(app: EmitInput, dir: string): Promise<EmittedApp> {\n let workspacePath: string | undefined\n if (app.workspace) {\n await mkdir(dir, { recursive: true })\n workspacePath = join(dir, \"WORKSPACE.md\")\n await writeFile(\n workspacePath,\n toManifest(app.workspace, app.workspace.description ?? app.workspace.name),\n \"utf8\",\n )\n }\n\n const agentPaths: Record<string, string> = {}\n for (const { agent, body } of app.agents) {\n const agentDir = join(dir, \".agentproto\", \"agents\", stripOwner(agent.id))\n await mkdir(agentDir, { recursive: true })\n const agentPath = join(agentDir, \"AGENT.md\")\n await writeFile(agentPath, toManifest(agent, body ?? \"\"), \"utf8\")\n agentPaths[agent.id] = agentPath\n }\n\n let uiPath: string | undefined\n let uiFrontmatter: Record<string, unknown> | undefined\n if (app.ui) {\n const uiDir = join(dir, \".agentproto\", \"ui\")\n await mkdir(uiDir, { recursive: true })\n uiPath = join(uiDir, \"index.html\")\n await writeFile(uiPath, app.ui.html, \"utf8\")\n uiFrontmatter = {\n path: relative(dir, uiPath),\n ...(app.ui.title !== undefined ? { title: app.ui.title } : {}),\n ...(app.ui.description !== undefined ? { description: app.ui.description } : {}),\n ...(app.ui.tools !== undefined ? { tools: app.ui.tools } : {}),\n ...(app.ui.port !== undefined ? { port: app.ui.port } : {}),\n ...(app.ui.csp !== undefined ? { csp: app.ui.csp } : {}),\n ...(app.ui.build !== undefined ? { build: app.ui.build } : {}),\n ...(app.ui.extensions !== undefined ? { extensions: app.ui.extensions } : {}),\n }\n }\n\n let artifactPath: string | undefined\n let artifactFrontmatter: Record<string, unknown> | undefined\n if (app.artifact) {\n const artifactDir = join(dir, \".agentproto\", \"artifact\")\n await mkdir(artifactDir, { recursive: true })\n artifactPath = join(artifactDir, \"index.html\")\n await copyFile(app.artifact.path, artifactPath)\n artifactFrontmatter = {\n path: relative(dir, artifactPath),\n ...(app.artifact.title !== undefined ? { title: app.artifact.title } : {}),\n ...(app.artifact.description !== undefined ? { description: app.artifact.description } : {}),\n }\n }\n\n let skillPath: string | undefined\n let skillFrontmatter: Record<string, unknown> | undefined\n if (app.skill) {\n skillPath = join(dir, \".agentproto\", \"skill\")\n await mkdir(skillPath, { recursive: true })\n await cp(app.skill.path, skillPath, { recursive: true })\n skillFrontmatter = {\n path: relative(dir, skillPath),\n ...(app.skill.title !== undefined ? { title: app.skill.title } : {}),\n ...(app.skill.description !== undefined ? { description: app.skill.description } : {}),\n }\n }\n\n const workflowPaths: string[] = []\n const workflowRefs: { id: string; path: string }[] = []\n for (const wf of app.workflows) {\n const wfDir = join(dir, \".agentproto\", \"workflows\", wf.id)\n await mkdir(wfDir, { recursive: true })\n const wfPath = join(wfDir, \"WORKFLOW.md\")\n await writeFile(wfPath, toManifest(wf, wf.description ?? \"\"), \"utf8\")\n workflowPaths.push(wfPath)\n workflowRefs.push({ id: wf.id, path: relative(dir, wfPath) })\n }\n\n await mkdir(join(dir, \".agentproto\"), { recursive: true })\n const appPath = join(dir, \".agentproto\", \"APP.md\")\n const agentRefs = app.agents.map(({ agent }) => ({\n id: agent.id,\n path: relative(dir, agentPaths[agent.id]!),\n }))\n const appFrontmatter: Record<string, unknown> = {\n schema: \"app/v1\",\n ...(app.id !== undefined ? { id: app.id } : {}),\n ...(app.name !== undefined ? { name: app.name } : {}),\n version: app.version ?? \"0.1.0\",\n ...(app.description !== undefined ? { description: app.description } : {}),\n agents: agentRefs,\n workflows: workflowRefs,\n ...(app.workspace ? { workspace: app.workspace.id } : {}),\n ...requiresFrontmatter(app),\n ...(app.placement !== undefined && app.placement !== \"any\" ? { placement: app.placement } : {}),\n ...(app.exposes && (app.exposes.agents.length > 0 || app.exposes.workflows.length > 0)\n ? { exposes: { agents: app.exposes.agents, workflows: app.exposes.workflows } }\n : {}),\n ...(app.accepts?.tasks ? { accepts: { tasks: true } } : {}),\n ...(uiFrontmatter !== undefined ? { ui: uiFrontmatter } : {}),\n ...(artifactFrontmatter !== undefined ? { artifact: artifactFrontmatter } : {}),\n ...(skillFrontmatter !== undefined ? { skill: skillFrontmatter } : {}),\n ...(app.artifacts !== undefined ? { artifacts: app.artifacts } : {}),\n ...(app.dev !== undefined ? { dev: app.dev } : {}),\n ...(app.data !== undefined ? { data: app.data } : {}),\n ...(app.externalReadRoots !== undefined ? { externalReadRoots: app.externalReadRoots } : {}),\n ...(app.boundaries !== undefined ? { boundaries: app.boundaries } : {}),\n ...(app.category !== undefined ? { category: app.category } : {}),\n }\n await writeFile(appPath, toManifest(appFrontmatter, app.description ?? \"\"), \"utf8\")\n\n return {\n agentPaths,\n workflowPaths,\n appPath,\n ...(workspacePath ? { workspacePath } : {}),\n ...(uiPath ? { uiPath } : {}),\n ...(artifactPath ? { artifactPath } : {}),\n ...(skillPath ? { skillPath } : {}),\n }\n}\n\n/** Legacy flat array while only bare app ids are declared; object form once\n * any host requirement (browser/fs/gpu/secrets) OR any per-dependency detail\n * (a version range / workflow allowlist) is set. Defaults are omitted.\n * `apps` entries carrying no extra fields emit as bare ids (byte-stable with\n * pre-object-form APP.md files). */\nfunction requiresFrontmatter(app: EmitInput): Record<string, unknown> {\n const r = app.requirements\n const apps = appsFrontmatter(app)\n const hasAppDetail = (app.appRequirements ?? []).some(\n e => e.version !== undefined || (e.workflows !== undefined && e.workflows.length > 0),\n )\n if (r && (r.browser || r.fs || r.gpu || r.secrets.length > 0)) {\n return {\n requires: { browser: r.browser, fs: r.fs, gpu: r.gpu, secrets: r.secrets, apps },\n }\n }\n if (hasAppDetail) {\n return { requires: { apps } }\n }\n return app.requires !== undefined ? { requires: app.requires } : {}\n}\n\nfunction appsFrontmatter(app: EmitInput): unknown[] {\n const entries = app.appRequirements ?? app.requires ?? []\n return entries.map(e => {\n if (typeof e === \"string\") return e\n if (e.version === undefined && (e.workflows === undefined || e.workflows.length === 0)) return e.id\n return e\n })\n}\n\nfunction toManifest(handle: object, body: string): string {\n const data: Record<string, unknown> = JSON.parse(JSON.stringify(handle))\n return matter.stringify(`\\n${body}\\n`, data)\n}\n","/**\n * Tiny pure semver-range checker for `requires.apps[].version` — the only\n * version constraint the app→app call mechanism supports. Deliberately small:\n * an exact version, a caret (`^1`, `^1.2`, `^1.2.3`; npm semantics: it pins\n * the leftmost non-zero component, so `^0.2.3` stays on the 0.2 line), or a\n * tilde on the major[.minor] (`~1`, `~1.2`, `~1.2.3`). No dependency on a\n * semver package — the surface is three comparison shapes, not a grammar.\n *\n * Versions are `major.minor.patch` with an optional prerelease/build suffix\n * (the APP.md `version` pattern); the suffix is ignored for comparison, so\n * `1.2.3-rc1` satisfies `^1` exactly as `1.2.3` would.\n */\n\nconst VERSION_RE = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:[-+][\\w.\\-]+)?$/\n\ntype VersionTuple = readonly [number, number, number]\n\nexport type VersionRange =\n | { readonly kind: \"exact\"; readonly version: VersionTuple }\n | { readonly kind: \"caret\"; readonly version: VersionTuple }\n /** `minorGiven` distinguishes `~1` (any minor of that major) from\n * `~1.2` / `~1.2.3` (that minor line only). */\n | { readonly kind: \"tilde\"; readonly version: VersionTuple; readonly minorGiven: boolean }\n\nfunction parseVersion(v: string): VersionTuple {\n const m = VERSION_RE.exec(v)\n if (!m) {\n throw new Error(`invalid version \"${v}\" — expected major.minor.patch (e.g. \"1.2.3\").`)\n }\n return [Number(m[1]), Number(m[2]), Number(m[3])]\n}\n\nfunction compare(a: VersionTuple, b: VersionTuple): number {\n return a[0] - b[0] || a[1] - b[1] || a[2] - b[2]\n}\n\n/** Parse a supported range shape. Throws on anything else — callers with\n * user-authored input wrap this for a field-prefixed diagnostic. */\nexport function parseVersionRange(range: string): VersionRange {\n let m = /^\\^(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?$/.exec(range)\n if (m !== null) {\n return {\n kind: \"caret\",\n version: [Number(m[1]), m[2] !== undefined ? Number(m[2]) : 0, m[3] !== undefined ? Number(m[3]) : 0],\n }\n }\n m = /^~(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?$/.exec(range)\n if (m !== null) {\n return {\n kind: \"tilde\",\n version: [Number(m[1]), m[2] !== undefined ? Number(m[2]) : 0, m[3] !== undefined ? Number(m[3]) : 0],\n minorGiven: m[2] !== undefined,\n }\n }\n if (VERSION_RE.test(range)) return { kind: \"exact\", version: parseVersion(range) }\n throw new Error(\n `invalid version range \"${range}\" — expected an exact version (\"1.2.3\"), ` +\n `a caret (\"^1\", \"^1.2\", \"^1.2.3\"), or a tilde (\"~1\", \"~1.2\", \"~1.2.3\").`,\n )\n}\n\n/** True when `version` satisfies `range`. Throws on a malformed version or\n * range — both are validated at manifest-parse time, so reaching this with\n * bad input is a programming error, not a user one. */\nexport function versionSatisfies(version: string, range: string): boolean {\n const v = parseVersion(version)\n const r = parseVersionRange(range)\n if (r.kind === \"exact\") return compare(v, r.version) === 0\n if (compare(v, r.version) < 0) return false\n if (r.kind === \"caret\") {\n if (r.version[0] > 0) return v[0] === r.version[0]\n if (r.version[1] > 0) return v[0] === 0 && v[1] === r.version[1]\n return v[0] === 0 && v[1] === 0 && v[2] === r.version[2]\n }\n return v[0] === r.version[0] && (!r.minorGiven || v[1] === r.version[1])\n}\n","/**\n * Validation + defaulting for the APP.md placement/requires/exposes/accepts\n * keys. Shared by `defineApp` (throws `AppDefinitionError`) and\n * `loadAppHandle` (throws `AppLoadError`) through the `fail` factory, so a\n * hand-edited APP.md and a bad `defineApp({...})` call get the same diagnostic.\n */\n\nimport type { AppAccepts, AppExposes, AppPlacement, AppRequirement, AppRequirements } from \"./types.js\"\nimport { parseVersionRange } from \"./version-range.js\"\n\nexport const APP_PLACEMENTS: readonly AppPlacement[] = [\"local\", \"box\", \"any\", \"split\"]\n\nexport interface ManifestFieldsInput {\n readonly placement?: unknown\n readonly requires?: unknown\n readonly exposes?: unknown\n readonly accepts?: unknown\n}\n\nexport interface DeclaredIds {\n readonly agents: readonly string[]\n readonly workflows: readonly string[]\n}\n\nexport interface NormalizedManifestFields {\n readonly placement: AppPlacement\n /** Flat app-id list; undefined when `requires` was absent (or an object with no `apps`). */\n readonly requires: readonly string[] | undefined\n readonly requirements: AppRequirements\n /** Every `requires.apps` entry in normalized object form (bare ids become\n * `{ id }`); empty when no app dependency was declared. */\n readonly appRequirements: readonly AppRequirement[]\n readonly exposes: AppExposes\n readonly accepts: AppAccepts\n}\n\ntype Fail = (message: string) => Error\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\nfunction stringList(v: unknown, key: string, fail: Fail): readonly string[] {\n if (v === undefined) return []\n if (!Array.isArray(v) || !v.every(e => typeof e === \"string\" && e.trim() !== \"\")) {\n throw fail(`'${key}' must be an array of non-empty strings.`)\n }\n return [...v] as string[]\n}\n\nfunction bool(v: unknown, key: string, fail: Fail): boolean {\n if (v === undefined) return false\n if (typeof v !== \"boolean\") throw fail(`'${key}' must be a boolean.`)\n return v\n}\n\n/** Parse one `requires.apps` entry — a bare id or an\n * `{ id, version?, workflows? }` object. Shared by the array element check\n * and the object form's `apps` list so both accept exactly the same shape. */\nfunction appRequirementEntry(entry: unknown, key: string, fail: Fail): AppRequirement {\n if (typeof entry === \"string\") {\n if (entry.trim() === \"\") throw fail(`'${key}' entries must be non-empty strings or objects.`)\n return { id: entry }\n }\n if (!isRecord(entry)) {\n throw fail(`'${key}' entries must be non-empty strings or objects, got ${JSON.stringify(entry)}.`)\n }\n const id = entry.id\n if (typeof id !== \"string\" || id.trim() === \"\") {\n throw fail(`'${key}.id' must be a non-empty string.`)\n }\n const version = entry.version\n if (version !== undefined) {\n if (typeof version !== \"string\" || version.trim() === \"\") {\n throw fail(`'${key}.version' must be a non-empty string.`)\n }\n try {\n parseVersionRange(version)\n } catch (err) {\n throw fail(`'${key}.version' ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n const workflows = entry.workflows\n if (workflows !== undefined) {\n if (!Array.isArray(workflows) || !workflows.every(w => typeof w === \"string\" && w.trim() !== \"\")) {\n throw fail(`'${key}.workflows' must be an array of non-empty strings.`)\n }\n }\n const extra = Object.keys(entry).filter(k => k !== \"id\" && k !== \"version\" && k !== \"workflows\")\n if (extra.length > 0) {\n throw fail(`'${key}.${extra[0]}' is not a supported requires.apps entry field (expected id, version, workflows).`)\n }\n return {\n id,\n ...(version !== undefined ? { version } : {}),\n ...(workflows !== undefined ? { workflows: [...workflows] as string[] } : {}),\n }\n}\n\nfunction appRequirementList(v: unknown, key: string, fail: Fail): readonly AppRequirement[] {\n if (v === undefined) return []\n if (!Array.isArray(v)) {\n throw fail(`'${key}' must be an array of non-empty strings or { id, version?, workflows? } objects.`)\n }\n return v.map((e, i) => appRequirementEntry(e, `${key}[${i}]`, fail))\n}\n\nexport function normalizeManifestFields(\n input: ManifestFieldsInput,\n declared: DeclaredIds,\n fail: Fail,\n): NormalizedManifestFields {\n let placement: AppPlacement = \"any\"\n if (input.placement !== undefined) {\n if (typeof input.placement !== \"string\" || !APP_PLACEMENTS.includes(input.placement as AppPlacement)) {\n throw fail(\n `'placement' must be one of ${APP_PLACEMENTS.map(p => `\"${p}\"`).join(\", \")}, got ${JSON.stringify(input.placement)}.`,\n )\n }\n placement = input.placement as AppPlacement\n }\n\n let requires: readonly string[] | undefined\n let requirements: AppRequirements = { browser: false, fs: false, gpu: false, secrets: [], apps: [] }\n let appRequirements: readonly AppRequirement[] = []\n const r = input.requires\n if (r !== undefined) {\n if (Array.isArray(r)) {\n if (!r.every(e => typeof e === \"string\")) {\n throw fail(\"'requires' must be an array of strings or an object { browser, fs, gpu, secrets, apps }.\")\n }\n requires = [...r] as string[]\n requirements = { ...requirements, apps: requires }\n appRequirements = appRequirementList(r, \"requires\", fail)\n } else if (isRecord(r)) {\n const apps = appRequirementList(r.apps, \"requires.apps\", fail)\n requirements = {\n browser: bool(r.browser, \"requires.browser\", fail),\n fs: bool(r.fs, \"requires.fs\", fail),\n gpu: bool(r.gpu, \"requires.gpu\", fail),\n secrets: stringList(r.secrets, \"requires.secrets\", fail),\n apps: apps.map(e => e.id),\n }\n appRequirements = apps\n if (apps.length > 0) requires = apps.map(e => e.id)\n } else {\n throw fail(\"'requires' must be an array of strings or an object { browser, fs, gpu, secrets, apps }.\")\n }\n }\n\n let exposes: AppExposes = { agents: [], workflows: [] }\n if (input.exposes !== undefined) {\n if (!isRecord(input.exposes)) throw fail(\"'exposes' must be an object { agents, workflows }.\")\n const agents = stringList(input.exposes.agents, \"exposes.agents\", fail)\n const workflows = stringList(input.exposes.workflows, \"exposes.workflows\", fail)\n for (const id of agents) {\n if (!declared.agents.includes(id)) {\n throw fail(\n `'exposes.agents' names '${id}' but the app declares no such agent. Declared: [${declared.agents.join(\", \") || \"none\"}].`,\n )\n }\n }\n for (const id of workflows) {\n if (!declared.workflows.includes(id)) {\n throw fail(\n `'exposes.workflows' names '${id}' but the app declares no such workflow. Declared: [${declared.workflows.join(\", \") || \"none\"}].`,\n )\n }\n }\n exposes = { agents, workflows }\n }\n\n let accepts: AppAccepts = { tasks: false }\n if (input.accepts !== undefined) {\n if (!isRecord(input.accepts)) throw fail(\"'accepts' must be an object { tasks }.\")\n accepts = { tasks: bool(input.accepts.tasks, \"accepts.tasks\", fail) }\n }\n\n return { placement, requires, requirements, appRequirements, exposes, accepts }\n}\n","/**\n * `defineApp({ agents, workflows, attach })` — bundle one or more AIP-42\n * agents, the AIP-15 workflows they run, and any other AIP artifacts into\n * one cross-linked, frozen handle.\n *\n * The only new invariant app-kit adds is *attachment*: the agents and the\n * bundled workflows must reference each other. Everything else (field\n * validation) already ran when the caller built the handles with\n * `defineAgent` / `defineWorkflow`, so `defineApp` validates the coupling,\n * not the fields.\n *\n * - agent ids are unique within the app.\n * - every `agent.workflows[]` ref MUST resolve to a bundled workflow id.\n * - every bundled workflow MUST be referenced by at least one agent.\n *\n * A dangling ref (an agent points at a workflow the app didn't bundle) or\n * an orphan (a bundled workflow no agent lists) throws — that is what \"an\n * agent attached to its workflows\" means, made checkable.\n */\n\nimport { isAbsolute } from \"node:path\"\nimport { defineWorkspace } from \"@agentproto/workspace\"\nimport type { AgentHandle, AnyRef } from \"@agentproto/agent\"\nimport type { BuildMastraAgentResult } from \"@agentproto/mastra\"\nimport type { WorkflowHandle } from \"@agentproto/workflow\"\nimport type { WorkspaceHandle } from \"@agentproto/workspace\"\nimport type {\n AgentEntry,\n AppDefinition,\n AppHandle,\n AppRequirement,\n DoctypeHandle,\n OpenAIAppUiExtension,\n OpenAIEntrypoint,\n OpenAIIcon,\n ToMastraAgentOptions,\n WorkspaceInput,\n} from \"./types.js\"\nimport { refKey } from \"./refs.js\"\nimport { emitApp } from \"./emit.js\"\nimport { normalizeManifestFields } from \"./manifest-fields.js\"\n\nexport class AppDefinitionError extends Error {\n constructor(message: string) {\n super(`defineApp (app-kit): ${message}`)\n this.name = \"AppDefinitionError\"\n }\n}\n\nexport function defineApp(def: AppDefinition): AppHandle {\n if (def.id !== undefined && def.id.trim() === \"\") {\n throw new AppDefinitionError(\"`id` must be non-empty when present.\")\n }\n if (def.ui !== undefined && (typeof def.ui.html !== \"string\" || def.ui.html.trim() === \"\")) {\n throw new AppDefinitionError(\"`ui.html` must be a non-empty string when `ui` is present.\")\n }\n if ((def.agents === undefined || def.agents.length === 0) && def.ui === undefined) {\n throw new AppDefinitionError(\n \"an app needs at least one agent, or a `ui` block for a UI-only app — got neither.\",\n )\n }\n if (def.dev !== undefined && (!Array.isArray(def.dev.launch) || def.dev.launch.length === 0)) {\n throw new AppDefinitionError(\"`dev.launch` must be a non-empty array when `dev` is present.\")\n }\n if (def.data !== undefined && def.data.dir !== undefined && (typeof def.data.dir !== \"string\" || def.data.dir.trim() === \"\")) {\n throw new AppDefinitionError(\"`data.dir` must be a non-empty string when present.\")\n }\nif (def.artifact !== undefined && (typeof def.artifact.path !== \"string\" || def.artifact.path.trim() === \"\")) {\n throw new AppDefinitionError(\"`artifact.path` must be a non-empty string when `artifact` is present.\")\n }\n // AIP-53 rule 7: `artifact.path` / `skill.path` MUST be absolute —\n // `emit` copies from them at write time and a relative path has no\n // defined base to resolve against.\n if (def.artifact !== undefined && !isAbsolute(def.artifact.path)) {\n throw new AppDefinitionError(\n `\\`artifact.path\\` must be an absolute filesystem path, got '${def.artifact.path}' — a relative path has no defined base to resolve against (AIP-53 rule 7).`,\n )\n }\n if (def.skill !== undefined && (typeof def.skill.path !== \"string\" || def.skill.path.trim() === \"\")) {\n throw new AppDefinitionError(\"`skill.path` must be a non-empty string when `skill` is present.\")\n }\n if (def.skill !== undefined && !isAbsolute(def.skill.path)) {\n throw new AppDefinitionError(\n `\\`skill.path\\` must be an absolute filesystem path, got '${def.skill.path}' — a relative path has no defined base to resolve against (AIP-53 rule 7).`,\n )\n }\n if (def.category !== undefined && def.category.trim() === \"\") {\n throw new AppDefinitionError(\"`category` must be a non-empty string when present.\")\n }\n\n const agents = (def.agents ?? []).map(normalizeEntry)\n const workflows = def.workflows ?? []\n const tools = def.tools ?? []\n const drivers = def.drivers ?? []\n const attachments = def.attach ?? []\n const workspace = def.workspace ? toWorkspaceHandle(def.workspace) : undefined\n const id = def.id\n const name = def.name\n const version = def.version ?? (id ? \"0.1.0\" : undefined)\n const description = def.description\n const fields = normalizeManifestFields(\n { placement: def.placement, requires: def.requires, exposes: def.exposes, accepts: def.accepts },\n { agents: agents.map(e => e.agent.id), workflows: workflows.map(w => w.id) },\n msg => new AppDefinitionError(msg),\n )\n const requires = fields.requires ? Object.freeze([...fields.requires]) : undefined\n const requirements = Object.freeze({\n ...fields.requirements,\n secrets: Object.freeze([...fields.requirements.secrets]),\n apps: Object.freeze([...fields.requirements.apps]),\n })\n const appRequirements = Object.freeze(\n fields.appRequirements.map(e => Object.freeze({ ...e, ...(e.workflows !== undefined ? { workflows: Object.freeze([...e.workflows]) } : {}) })),\n )\n const placement = fields.placement\n const exposes = Object.freeze({\n agents: Object.freeze([...fields.exposes.agents]),\n workflows: Object.freeze([...fields.exposes.workflows]),\n })\n const accepts = Object.freeze({ ...fields.accepts })\n const uiExtensions =\n def.ui === undefined || def.ui.extensions === undefined\n ? undefined\n : (Object.freeze({\n openai: freezeDeep(\n normalizeOpenAIUiExtension(\n validateOpenAIExtensionsNamespace(def.ui.extensions),\n def.ui.tools,\n msg => new AppDefinitionError(msg),\n ),\n ),\n }) as { readonly openai?: OpenAIAppUiExtension })\n const ui = def.ui\n ? Object.freeze({\n ...def.ui,\n ...(uiExtensions !== undefined ? { extensions: uiExtensions } : {}),\n })\n : undefined\n const artifact = def.artifact ? Object.freeze({ ...def.artifact }) : undefined\n const skill = def.skill ? Object.freeze({ ...def.skill }) : undefined\n const artifacts = def.artifacts ? Object.freeze(def.artifacts.map(a => Object.freeze({ ...a }))) : undefined\n const dev = def.dev\n ? Object.freeze({ launch: Object.freeze(def.dev.launch.map(l => Object.freeze({ ...l }))) })\n : undefined\n const externalReadRoots = def.externalReadRoots ? Object.freeze([...def.externalReadRoots]) : undefined\n const data = def.data ? Object.freeze({ ...def.data }) : undefined\n const boundaries = def.boundaries ? Object.freeze({ ...def.boundaries }) : undefined\n const category = def.category\n\n validateAttachment(agents, workflows)\n validateUniqueIds(tools, \"tool\")\n validateUniqueIds(drivers, \"driver\")\n\n const frozenAgents = Object.freeze(agents.map((e) => Object.freeze({ ...e })))\n const frozenWorkflows = Object.freeze([...workflows])\n const frozenTools = Object.freeze([...tools])\n const frozenDrivers = Object.freeze([...drivers])\n const frozenAttachments = Object.freeze([...attachments])\n\n const handle: AppHandle = {\n agents: frozenAgents,\n workflows: frozenWorkflows,\n tools: frozenTools,\n drivers: frozenDrivers,\n attachments: frozenAttachments,\n ...(workspace ? { workspace } : {}),\n ...(id !== undefined ? { id } : {}),\n ...(name !== undefined ? { name } : {}),\n ...(version !== undefined ? { version } : {}),\n ...(description !== undefined ? { description } : {}),\n ...(requires !== undefined ? { requires } : {}),\n requirements,\n appRequirements,\n placement,\n exposes,\n accepts,\n ...(ui !== undefined ? { ui } : {}),\n ...(artifact !== undefined ? { artifact } : {}),\n ...(skill !== undefined ? { skill } : {}),\n ...(artifacts !== undefined ? { artifacts } : {}),\n ...(dev !== undefined ? { dev } : {}),\n ...(data !== undefined ? { data } : {}),\n ...(externalReadRoots !== undefined ? { externalReadRoots } : {}),\n ...(boundaries !== undefined ? { boundaries } : {}),\n ...(category !== undefined ? { category } : {}),\n\n async toMastraAgents(opts: ToMastraAgentOptions, only?: readonly string[]) {\n const targets = only ? selectAgents(frozenAgents, only) : frozenAgents\n const out: Record<string, BuildMastraAgentResult> = {}\n for (const entry of targets) {\n out[entry.agent.id] = await buildOne(entry, opts)\n }\n return out\n },\n\n pick(ids: readonly string[]) {\n return selectAgents(frozenAgents, ids)\n },\n\n async toMastraAgent(opts: ToMastraAgentOptions) {\n if (frozenAgents.length !== 1) {\n throw new AppDefinitionError(\n `toMastraAgent requires exactly one agent (app has ${frozenAgents.length}); use toMastraAgents.`,\n )\n }\n return buildOne(frozenAgents[0]!, opts)\n },\n\n emit(dir: string) {\n return emitApp(\n {\n agents: frozenAgents,\n workflows: frozenWorkflows,\n ...(workspace ? { workspace } : {}),\n ...(id !== undefined ? { id } : {}),\n ...(name !== undefined ? { name } : {}),\n ...(version !== undefined ? { version } : {}),\n ...(description !== undefined ? { description } : {}),\n ...(requires !== undefined ? { requires } : {}),\n requirements,\n appRequirements,\n placement,\n exposes,\n accepts,\n ...(ui !== undefined ? { ui } : {}),\n ...(artifact !== undefined ? { artifact } : {}),\n ...(skill !== undefined ? { skill } : {}),\n ...(artifacts !== undefined ? { artifacts } : {}),\n ...(dev !== undefined ? { dev } : {}),\n ...(data !== undefined ? { data } : {}),\n ...(externalReadRoots !== undefined ? { externalReadRoots } : {}),\n ...(boundaries !== undefined ? { boundaries } : {}),\n ...(category !== undefined ? { category } : {}),\n },\n dir,\n )\n },\n }\n\n return Object.freeze(handle)\n}\n\n/**\n * Normalize the `workspace` input to an AIP-34 `WorkspaceHandle`. A built\n * handle (already run through `defineWorkspace`) carries `schema:\n * \"workspace/v1\"` and passes straight through; a `WorkspaceShorthand` is\n * completed with a local-fs storage default and a `0.1.0` version, then\n * validated by `defineWorkspace` — so a malformed shorthand fails with the\n * same AIP-34 diagnostic as a malformed WORKSPACE.md.\n */\nfunction toWorkspaceHandle(input: WorkspaceInput): WorkspaceHandle {\n if (\"schema\" in input) return input\n return defineWorkspace({\n schema: \"workspace/v1\",\n version: input.version ?? \"0.1.0\",\n id: input.id,\n name: input.name,\n owner: input.owner,\n storage: input.storage ?? { inline: { provider: \"local-fs\", config: {} } },\n ...(input.description ? { description: input.description } : {}),\n })\n}\n\n/**\n * Resolve `ids` to their app entries, preserving the caller's order. Throws\n * `AppDefinitionError` on any id the app doesn't bundle — a hand-picked list\n * that names a missing agent is a bug, not a silent no-op.\n */\nfunction selectAgents(\n agents: readonly AgentEntry[],\n ids: readonly string[],\n): readonly AgentEntry[] {\n const byId = new Map(agents.map((e) => [e.agent.id, e]))\n return ids.map((id) => {\n const entry = byId.get(id)\n if (!entry) {\n throw new AppDefinitionError(\n `agent '${id}' is not in this app. Bundled: [${[...byId.keys()].join(\", \")}].`,\n )\n }\n return entry\n })\n}\n\nasync function buildOne(entry: AgentEntry, opts: ToMastraAgentOptions): Promise<BuildMastraAgentResult> {\n // Dynamic import, not a static top-level one: `@agentproto/mastra` pulls in\n // `@mastra/core` (a documented peer dependency — see index.ts), which a\n // bundler would otherwise inline into ANY host that merely calls\n // `defineApp()` without ever calling `toMastraAgent(s)` (e.g. a UI-only app\n // consumer). Loading it lazily, only from the one place it's actually used,\n // keeps `defineApp()`/the rest of this module free of that cost.\n const { buildMastraAgent } = await import(\"@agentproto/mastra\")\n // `entry.body` (the AGENT.md body) wins as instructions; an explicit\n // `opts.body` still overrides, matching buildMastraAgent's contract.\n return buildMastraAgent(entry.agent, { body: entry.body, ...opts })\n}\n\nfunction normalizeEntry(input: AgentEntry | AgentHandle): AgentEntry {\n // An AgentEntry has an `.agent`; a bare AgentHandle has `.id`/`.schema`.\n if (\"agent\" in input) return input\n return { agent: input }\n}\n\n/**\n * The attachment invariant across all agents: bundled workflow ids and\n * the union of every agent's `workflows[]` refs must be the same set.\n * External/registry workflow refs are out of scope for an app bundle —\n * if an agent lists it, the app must ship it.\n */\nfunction validateAttachment(\n agents: readonly AgentEntry[],\n workflows: readonly WorkflowHandle[],\n): void {\n const seenAgentIds = new Set<string>()\n for (const { agent } of agents) {\n if (seenAgentIds.has(agent.id)) {\n throw new AppDefinitionError(`duplicate agent id '${agent.id}' in the bundle.`)\n }\n seenAgentIds.add(agent.id)\n }\n\n const bundledIds = new Set<string>()\n for (const wf of workflows) {\n if (bundledIds.has(wf.id)) {\n throw new AppDefinitionError(`duplicate workflow id '${wf.id}' in the bundle.`)\n }\n bundledIds.add(wf.id)\n }\n\n const referenced = new Set<string>()\n for (const { agent } of agents) {\n for (const ref of workflowRefs(agent)) {\n const key = refKey(ref)\n referenced.add(key)\n if (!bundledIds.has(key)) {\n throw new AppDefinitionError(\n `agent '${agent.id}' references workflow '${key}' but the app does not bundle it. ` +\n `Bundled: [${[...bundledIds].join(\", \") || \"none\"}].`,\n )\n }\n }\n }\n\n for (const id of bundledIds) {\n if (!referenced.has(id)) {\n throw new AppDefinitionError(\n `workflow '${id}' is bundled but no agent lists it in workflows[]. ` +\n `Add { ref: \"${id}\" } to an agent, or drop the workflow.`,\n )\n }\n }\n}\n\nfunction workflowRefs(agent: AgentHandle): readonly AnyRef[] {\n return agent.workflows ?? []\n}\n\n/** Duplicate-id guard for `tools`/`drivers` — mirrors the agent/workflow id\n * uniqueness `validateAttachment` already enforces. */\nfunction validateUniqueIds(items: readonly { id: string }[], kind: string): void {\n const seen = new Set()\n for (const item of items) {\n if (seen.has(item.id)) {\n throw new AppDefinitionError(`duplicate ${kind} id '${item.id}' in the bundle.`)\n }\n seen.add(item.id)\n }\n}\n\n/**\n * `ui.extensions` accepts ONLY the `openai` namespace (plan I8). Any other\n * vendor block is rejected with the exact field path rather than silently\n * carried and half-advertised downstream. Returns the `openai` value.\n */\nfunction validateOpenAIExtensionsNamespace(raw: unknown): unknown {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw new AppDefinitionError(\"`ui.extensions` must be an object.\")\n }\n for (const key of Object.keys(raw as Record<string, unknown>)) {\n if (key !== \"openai\") {\n throw new AppDefinitionError(\n `\\`ui.extensions.${key}\\` is not supported — \\`extensions\\` accepts only \\`openai\\` (v1).`,\n )\n }\n }\n return (raw as Record<string, unknown>).openai\n}\n\nconst OPENAI_EXTENSION_KEYS = new Set([\"entrypoints\", \"icons\", \"display\", \"mentions\"])\n/** Cut in v1: forms/elicitation+MRTR, plugin settings, resource writes,\n * raw local-file opening, plugin onboarding manifest, deep links. Any of\n * these keys (or anything unknown) fails with the exact field path. */\nconst OPENAI_CUT_KEY_MESSAGE =\n \"is not a supported OpenAI extension field in v1 (cut would be silently half-advertised)\"\n\nconst DOT_EXTENSION_RE = /^\\.[a-z0-9][a-z0-9._+-]{0,31}$/\nconst OPENAI_MODES = [\"inline\", \"fullscreen\"] as const\n\n/**\n * The single `ui.extensions.openai` validator/normalizer, shared by TS\n * authoring (`defineApp`) and manifest loading (`loadAppHandle` re-runs\n * through `defineApp`), so there is no hand-maintained duplicate. Normalizes\n * file entrypoint extensions to lowercase; validates every shape/range rule\n * with the exact `ui.extensions.openai.*` field path.\n */\nexport function normalizeOpenAIUiExtension(\n raw: unknown,\n tools: readonly string[] | undefined,\n fail: (message: string) => Error,\n): OpenAIAppUiExtension | undefined {\n if (raw === undefined) return undefined\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw fail(\"`ui.extensions.openai` must be an object.\")\n }\n for (const key of Object.keys(raw)) {\n if (!OPENAI_EXTENSION_KEYS.has(key)) {\n throw fail(`\\`ui.extensions.openai.${key}\\` ${OPENAI_CUT_KEY_MESSAGE}.`)\n }\n }\n\n const entrypoints = normalizeOpenAIEntrypoints((raw as Record<string, unknown>).entrypoints, fail)\n const icons = normalizeOpenAIIcons((raw as Record<string, unknown>).icons, fail)\n const display = normalizeOpenAIDisplay((raw as Record<string, unknown>).display, fail)\n const mentions = normalizeOpenAIMentions((raw as Record<string, unknown>).mentions, tools, fail)\n\n return {\n ...(entrypoints !== undefined ? { entrypoints } : {}),\n ...(icons !== undefined ? { icons } : {}),\n ...(display !== undefined ? { display } : {}),\n ...(mentions !== undefined ? { mentions } : {}),\n }\n}\n\nfunction normalizeOpenAIEntrypoints(\n raw: unknown,\n fail: (message: string) => Error,\n): readonly OpenAIEntrypoint[] | undefined {\n if (raw === undefined) return undefined\n if (!Array.isArray(raw)) {\n throw fail(\"`ui.extensions.openai.entrypoints` must be an array.\")\n }\n if (raw.length < 1 || raw.length > 3) {\n throw fail(\n `\\`ui.extensions.openai.entrypoints\\` must contain 1..3 entries, got ${raw.length}.`,\n )\n }\n const seenTypes = new Set<string>()\n const out: OpenAIEntrypoint[] = []\n for (let i = 0; i < raw.length; i++) {\n const path = `ui.extensions.openai.entrypoints[${i}]`\n const ep = raw[i]\n if (typeof ep !== \"object\" || ep === null || Array.isArray(ep)) {\n throw fail(`\\`${path}\\` must be an object.`)\n }\n const keys = Object.keys(ep as Record<string, unknown>)\n const invalidKeys = keys.filter(k => k !== \"type\" && k !== \"extensions\")\n if (invalidKeys.length > 0) {\n throw fail(\n `\\`${path}.${invalidKeys[0]}\\` is not a supported \\`${(ep as { type?: unknown }).type}\\` entrypoint field.`,\n )\n }\n const type = (ep as Record<string, unknown>).type\n if (type !== \"global\" && type !== \"thread\" && type !== \"file\") {\n throw fail(`\\`${path}.type\\` must be \"global\", \"thread\" or \"file\", got ${JSON.stringify(type)}.`)\n }\n if (seenTypes.has(type)) {\n throw fail(`\\`ui.extensions.openai.entrypoints\\` declares \\`${type}\\` more than once.`)\n }\n seenTypes.add(type)\n if (type === \"file\") {\n out.push({ type, extensions: normalizeDotExtensions((ep as Record<string, unknown>).extensions, path, fail) })\n } else {\n out.push({ type })\n }\n }\n return out\n}\n\nfunction normalizeDotExtensions(\n raw: unknown,\n path: string,\n fail: (message: string) => Error,\n): readonly `.${string}`[] {\n if (!Array.isArray(raw)) {\n throw fail(`\\`${path}.extensions\\` must be an array of dot-prefixed strings.`)\n }\n if (raw.length < 1 || raw.length > 32) {\n throw fail(`\\`${path}.extensions\\` must contain 1..32 entries, got ${raw.length}.`)\n }\n const seen = new Set<string>()\n const out: `.${string}`[] = []\n for (let i = 0; i < raw.length; i++) {\n const ext = raw[i]\n if (typeof ext !== \"string\" || ext.trim() === \"\") {\n throw fail(`\\`${path}.extensions[${i}]\\` must be a non-empty string.`)\n }\n const normalized = ext.toLowerCase()\n if (seen.has(normalized)) {\n throw fail(`\\`${path}.extensions\\` declares '${normalized}' more than once.`)\n }\n seen.add(normalized)\n if (!DOT_EXTENSION_RE.test(normalized)) {\n throw fail(\n `\\`${path}.extensions[${i}]\\` ('${ext}') must be a dot-prefixed lowercase suffix matching /^\\\\.[a-z0-9][a-z0-9._+-]{0,31}$/, e.g. '.md'.`,\n )\n }\n out.push(normalized as `.${string}`)\n }\n return out\n}\n\nfunction normalizeOpenAIIcons(\n raw: unknown,\n fail: (message: string) => Error,\n): readonly OpenAIIcon[] | undefined {\n if (raw === undefined) return undefined\n if (!Array.isArray(raw)) throw fail(\"`ui.extensions.openai.icons` must be an array.\")\n if (raw.length < 1) {\n throw fail(\"`ui.extensions.openai.icons` must contain at least one icon when present.\")\n }\n return raw.map((icon, i) => {\n const path = `ui.extensions.openai.icons[${i}]`\n if (typeof icon !== \"object\" || icon === null || Array.isArray(icon)) {\n throw fail(`\\`${path}\\` must be an object.`)\n }\n const keys = Object.keys(icon as Record<string, unknown>)\n for (const key of keys) {\n if (key !== \"src\" && key !== \"mimeType\" && key !== \"sizes\" && key !== \"theme\") {\n throw fail(`\\`${path}.${key}\\` is not a supported icon field.`)\n }\n }\n const src = (icon as Record<string, unknown>).src\n if (typeof src !== \"string\" || src.trim() === \"\") {\n throw fail(`\\`${path}.src\\` must be a non-empty string.`)\n }\n if (!(ICON_SRC_HTTPS_RE.test(src) || hasValidIconSrcDataUrl(src))) {\n throw fail(\n `\\`${path}.src\\` must be an HTTPS URL or a 'data:image/…;base64,…' URL (inline SVG data allowed), got '${src.slice(0, 64)}'.`,\n )\n }\n const mimeType = (icon as Record<string, unknown>).mimeType\n if (mimeType !== undefined && (typeof mimeType !== \"string\" || mimeType.trim() === \"\")) {\n throw fail(`\\`${path}.mimeType\\` must be a non-empty string when present.`)\n }\n const sizes = (icon as Record<string, unknown>).sizes\n if (\n sizes !== undefined &&\n (!Array.isArray(sizes) || (sizes as unknown[]).length === 0 ||\n !(sizes as unknown[]).every((s) => typeof s === \"string\" && s.trim() !== \"\"))\n ) {\n throw fail(`\\`${path}.sizes\\` must be an array of non-empty strings when present.`)\n }\n const theme = (icon as Record<string, unknown>).theme\n if (theme !== undefined && theme !== \"light\" && theme !== \"dark\") {\n throw fail(`\\`${path}.theme\\` must be \"light\" or \"dark\" when present, got ${JSON.stringify(theme)}.`)\n }\n return {\n src,\n ...(mimeType !== undefined ? { mimeType: mimeType as string } : {}),\n ...(sizes !== undefined ? { sizes: Object.freeze([...(sizes as string[])]) } : {}),\n ...(theme !== undefined ? { theme: theme as \"light\" | \"dark\" } : {}),\n }\n })\n}\n\nconst ICON_SRC_HTTPS_RE = /^https:\\/\\/\\S+$/\n\nfunction hasValidIconSrcDataUrl(src: string): boolean {\n const comma = src.indexOf(\",\")\n if (comma < 0) return false\n const header = src.slice(0, comma)\n const payload = src.slice(comma + 1)\n if (!/^data:image\\/[a-z0-9.+-]+(?:;charset=[\\w-]+)?(?:;base64|;utf8)?$/i.test(header)) return false\n if (/;base64$/i.test(header)) return /^[A-Za-z0-9+/=\\r\\n]+$/.test(payload)\n return payload.trim() !== \"\"\n}\n\nfunction normalizeOpenAIDisplay(\n raw: unknown,\n fail: (message: string) => Error,\n):\n | { readonly availableModes?: readonly (\"inline\" | \"fullscreen\")[]\n readonly preferredMode?: \"inline\" | \"fullscreen\" }\n | undefined {\n if (raw === undefined) return undefined\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw fail(\"`ui.extensions.openai.display` must be an object.\")\n }\n const availableModes = (raw as Record<string, unknown>).availableModes\n if (availableModes !== undefined) {\n if (!Array.isArray(availableModes) || availableModes.length === 0) {\n throw fail(\"`ui.extensions.openai.display.availableModes` must be a non-empty array when present.\")\n }\n const seen = new Set<string>()\n for (const mode of availableModes) {\n if (mode !== \"inline\" && mode !== \"fullscreen\") {\n throw fail(\n `\\`ui.extensions.openai.display.availableModes\\` supports only \"inline\" and \"fullscreen\", got ${JSON.stringify(mode)}.`,\n )\n }\n if (seen.has(mode)) {\n throw fail(`\\`ui.extensions.openai.display.availableModes\\` declares '${mode}' more than once.`)\n }\n seen.add(mode)\n }\n }\n const preferredMode = (raw as Record<string, unknown>).preferredMode\n if (\n preferredMode !== undefined &&\n !(OPENAI_MODES as readonly unknown[]).includes(preferredMode)\n ) {\n throw fail(\n `\\`ui.extensions.openai.display.preferredMode\\` must be \"inline\" or \"fullscreen\", got ${JSON.stringify(preferredMode)}.`,\n )\n }\n if (\n availableModes !== undefined &&\n preferredMode !== undefined &&\n !availableModes.includes(preferredMode as \"inline\" | \"fullscreen\")\n ) {\n throw fail(\n `\\`ui.extensions.openai.display.preferredMode\\` ('${preferredMode}') must occur in \\`ui.extensions.openai.display.availableModes\\` when both are declared.`,\n )\n }\n return {\n ...(availableModes !== undefined\n ? { availableModes: Object.freeze([...(availableModes as (\"inline\" | \"fullscreen\")[])]) }\n : {}),\n ...(preferredMode !== undefined ? { preferredMode: preferredMode as \"inline\" | \"fullscreen\" } : {}),\n }\n}\n\nfunction normalizeOpenAIMentions(\n raw: unknown,\n tools: readonly string[] | undefined,\n fail: (message: string) => Error,\n):\n | { readonly searchTool: string }\n | undefined {\n if (raw === undefined) return undefined\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw fail(\"`ui.extensions.openai.mentions` must be an object.\")\n }\n for (const key of Object.keys(raw)) {\n if (key !== \"searchTool\") {\n throw fail(`\\`ui.extensions.openai.mentions.${key}\\` is not a supported mentions field.`)\n }\n }\n const searchTool = (raw as Record<string, unknown>).searchTool\n if (typeof searchTool !== \"string\" || searchTool.trim() === \"\") {\n throw fail(\"`ui.extensions.openai.mentions.searchTool` must be a non-empty string.\")\n }\n if (tools === undefined || !tools.includes(searchTool)) {\n throw fail(\n `\\`ui.extensions.openai.mentions.searchTool\\` '${searchTool}' must be declared in this same ui block's \\`tools\\`${tools ? ` (${tools.join(\", \")})` : \" — the ui declares none\"}.`,\n )\n }\n return { searchTool }\n}\n\n/** Deep-freeze the normalized OpenAI extension tree — same immutability\n * discipline the rest of app-kit applies to top-level handle fields. */\nfunction freezeDeep(value: unknown): unknown {\n if (Array.isArray(value)) return Object.freeze(value.map(freezeDeep))\n if (typeof value === \"object\" && value !== null) {\n const out: Record<string, unknown> = {}\n for (const [key, v] of Object.entries(value)) {\n out[key] = freezeDeep(v)\n }\n return Object.freeze(out)\n }\n return value\n}\n\nexport type { DoctypeHandle }\n","/** Thrown by `loadAppHandle` and its helpers (`loadAppBundledTools`, …) on\n * any disk/parse/validation failure while reading an app bundle off disk. */\nexport class AppLoadError extends Error {\n constructor(message: string) {\n super(`loadAppHandle: ${message}`)\n this.name = \"AppLoadError\"\n }\n}\n","/**\n * Loader for an app's bundled AIP-14 TOOL.md contracts and AIP-30 DRIVER.md\n * implementations — the deterministic-step half of WORKFLOW.md `tool` steps\n * (yt-dlp, an STT HTTP call, a PDF render, …), as opposed to `agent` steps.\n *\n * Neither AIP-53 (app, still Draft with no scaffolded spec) nor AIP-14/30\n * declare a bundle location for these, so this is a convention this loader\n * defines: `<dir>/.agentproto/tools/<id>/TOOL.md` and\n * `<dir>/.agentproto/drivers/<id>/DRIVER.md`, one manifest per `<id>`\n * subdirectory, discovered by listing — not declared as APP.md frontmatter\n * refs like `agents`/`workflows` are. An absent `tools`/`drivers` directory\n * is not an error (most apps have neither); a subdirectory that exists but\n * fails to parse, or is missing its TOOL.md/DRIVER.md, fails the whole load\n * — `loadAppHandle` never silently drops a broken tool/driver bundle.\n *\n * Only `kind: cli` and `kind: http` drivers dispatch (the two\n * `@agentproto/driver-cli` / `@agentproto/driver-http` sugars this package\n * already depends on). Any other `kind` (`mcp`, `sdk`, `builtin`) still\n * loads — a malformed manifest still fails the app load — but its execute\n * body refuses clearly instead of silently no-oping or crashing on a\n * dispatch mechanism this host doesn't implement yet.\n *\n * A `kind: cli` driver's subprocess `cwd` defaults to the app root (`dir`,\n * the directory containing `.agentproto/`) rather than the host process's\n * own cwd — relative paths in an app-bundled cli driver (DRIVER.md argv,\n * `--out-dir`-style flags, …) resolve against the app root. A DRIVER.md can\n * override this with `metadata.cli.cwd`; a relative value there is itself\n * resolved against the app root, and a value that escapes the app root\n * (`../..`) is a load error, not a silent escape.\n */\n\nimport { readdir, readFile } from \"node:fs/promises\"\nimport type { Dirent } from \"node:fs\"\nimport { isAbsolute, join, relative, resolve } from \"node:path\"\nimport {\n parseToolManifest,\n toolFromManifestOnly,\n type ToolHandle,\n} from \"@agentproto/tool\"\nimport {\n driverFromManifest,\n driverDefinitionFromManifest,\n parseDriverManifest,\n type DriverManifest,\n} from \"@agentproto/driver/manifest\"\nimport { normalizeToolId, type DriverHandle, type ExecuteFn } from \"@agentproto/driver\"\nimport { defineCliDriver, type CliDriverDefinition } from \"@agentproto/driver-cli\"\nimport { defineHttpDriver, type HttpDriverDefinition } from \"@agentproto/driver-http\"\nimport { AppLoadError } from \"./errors.js\"\n\n/** List `<id>` subdirectory names under `base`, sorted. Missing `base` (the\n * common case — most apps ship neither tools nor drivers) is not an error. */\nasync function listBundleIds(base: string): Promise<string[]> {\n let entries: Dirent[]\n try {\n entries = await readdir(base, { withFileTypes: true })\n } catch {\n return []\n }\n return entries\n .filter((e) => e.isDirectory())\n .map((e) => e.name)\n .sort()\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\nasync function loadToolEntry(id: string, toolPath: string): Promise<ToolHandle> {\n let source: string\n try {\n source = await readFile(toolPath, \"utf8\")\n } catch (err) {\n throw new AppLoadError(`tool '${id}': cannot read '${toolPath}': ${errMsg(err)}`)\n }\n try {\n return toolFromManifestOnly(parseToolManifest(source))\n } catch (err) {\n throw new AppLoadError(`tool '${id}' at '${toolPath}': ${errMsg(err)}`)\n }\n}\n\n/** Env var names DRIVER.md declares as required secrets — `auth.state.env`,\n * the existing AIP-30 field for \"env var names this provider's auth needs\".\n * Loosely typed at the manifest layer (`auth: z.unknown()`), so this reads\n * defensively rather than trusting a shape. */\nfunction requiredSecretNames(fm: DriverManifest[\"frontmatter\"]): readonly string[] {\n const auth = fm.auth as { state?: { env?: unknown } } | undefined\n const env = auth?.state?.env\n return Array.isArray(env) ? env.filter((e): e is string => typeof e === \"string\") : []\n}\n\n/**\n * Wrap every execute body so a declared-but-unresolved secret fails the\n * STEP with a clear `driver-error` naming the secret — never at app\n * install (secrets are resolved lazily, only when the tool actually\n * dispatches). Resolved values are merged into `driverCtx.secrets` ahead of\n * whatever the caller already put there (a workflow tool step's compiled\n * `secrets` is empty today — see BRIEF-D — so this is the only source for\n * an app-bundled driver), letting `${secrets.X}` templating in\n * `defineCliDriver`/`defineHttpDriver` resolve as authors expect.\n */\nfunction wrapExecuteWithSecretCheck(\n driverId: string,\n execute: Record<string, ExecuteFn>,\n secretNames: readonly string[],\n): Record<string, ExecuteFn> {\n if (secretNames.length === 0) return execute\n const wrapped: Record<string, ExecuteFn> = {}\n for (const [toolId, fn] of Object.entries(execute)) {\n wrapped[toolId] = async (args) => {\n const resolved: Record<string, string> = {}\n for (const name of secretNames) {\n const value = process.env[name]\n if (!value) {\n throw new Error(\n `driver '${driverId}': missing required secret '${name}' (declared in DRIVER.md 'auth.state.env').`,\n )\n }\n resolved[name] = value\n }\n const priorSecrets = (args.driverCtx as { secrets?: Record<string, string> }).secrets ?? {}\n return fn({ ...args, driverCtx: { ...args.driverCtx, secrets: { ...resolved, ...priorSecrets } } })\n }\n }\n return wrapped\n}\n\n/**\n * Resolve a kind:cli DRIVER.md's working directory. Relative paths in an\n * app-bundled cli driver resolve against the app root (the dir containing\n * `.agentproto/`) — not the daemon's own cwd, which is what `runSubprocess`\n * fell back to before this existed and is almost never what a DRIVER.md\n * author means (see `@agentproto/driver-cli`'s README). Defaults to the app\n * root itself when `metadata.cli.cwd` is unset; an explicit value — relative\n * or absolute — that resolves outside the app root is a load error rather\n * than silently escaping the bundle.\n */\nfunction resolveCliCwd(appRoot: string, driverId: string, cwd: unknown): string {\n const absoluteAppRoot = resolve(appRoot)\n if (cwd === undefined) return absoluteAppRoot\n if (typeof cwd !== \"string\" || cwd.trim() === \"\") {\n throw new Error(`driver '${driverId}': 'metadata.cli.cwd' must be a non-empty string.`)\n }\n const resolved = isAbsolute(cwd) ? resolve(cwd) : resolve(absoluteAppRoot, cwd)\n const rel = relative(absoluteAppRoot, resolved)\n if (rel !== \"\" && (rel.startsWith(\"..\") || isAbsolute(rel))) {\n throw new Error(\n `driver '${driverId}': 'metadata.cli.cwd' (${cwd}) resolves to '${resolved}', outside the app root '${absoluteAppRoot}'.`,\n )\n }\n return resolved\n}\n\n/** Build a working {@link DriverHandle} from a parsed DRIVER.md, dispatching\n * on `kind`. Throws a plain `Error` (wrapped in `AppLoadError` by the\n * caller, which has the file path) on a `cli`/`http` manifest missing its\n * dispatch config. */\nfunction driverHandleFromManifest(manifest: DriverManifest, appRoot: string): DriverHandle {\n const fm = manifest.frontmatter\n const secretNames = requiredSecretNames(fm)\n\n if (fm.kind === \"cli\") {\n const cliMeta = (fm.metadata?.cli ?? {}) as Partial<CliDriverDefinition> & { cwd?: unknown }\n if (typeof cliMeta.bin !== \"string\" || cliMeta.bin.trim() === \"\") {\n throw new Error(\n \"kind:cli DRIVER.md requires a non-empty 'metadata.cli.bin' frontmatter field naming the binary.\",\n )\n }\n const handle = defineCliDriver({\n ...driverDefinitionFromManifest(manifest),\n bin: cliMeta.bin,\n binArgs: cliMeta.binArgs,\n output: cliMeta.output,\n tty: cliMeta.tty,\n sandbox: cliMeta.sandbox,\n cwd: resolveCliCwd(appRoot, fm.id, cliMeta.cwd),\n })\n return { ...handle, execute: wrapExecuteWithSecretCheck(fm.id, handle.execute, secretNames) }\n }\n\n if (fm.kind === \"http\") {\n const httpMeta = (fm.metadata?.http ?? {}) as Partial<HttpDriverDefinition>\n if (typeof httpMeta.baseUrl !== \"string\" || httpMeta.baseUrl.trim() === \"\") {\n throw new Error(\"kind:http DRIVER.md requires a non-empty 'metadata.http.baseUrl' frontmatter field.\")\n }\n const handle = defineHttpDriver({\n ...driverDefinitionFromManifest(manifest),\n baseUrl: httpMeta.baseUrl,\n defaultHeaders: httpMeta.defaultHeaders,\n defaultMethod: httpMeta.defaultMethod,\n streaming: httpMeta.streaming,\n })\n return { ...handle, execute: wrapExecuteWithSecretCheck(fm.id, handle.execute, secretNames) }\n }\n\n // mcp / sdk / builtin: load (so a malformed manifest still fails the app\n // load), but refuse at resolve/dispatch — every implements[] entry gets\n // an execute body that fails with a clear message instead of silently\n // no-oping or throwing an opaque \"no dispatch mechanism\" error.\n const execute: Record<string, ExecuteFn> = {}\n for (const entry of fm.implements) {\n const toolId = normalizeToolId(entry.tool)\n execute[toolId] = async () => {\n throw new Error(\n `driver '${fm.id}': kind '${fm.kind}' is not supported by this host — only 'cli' and 'http' drivers dispatch.`,\n )\n }\n }\n return driverFromManifest({ manifest, execute })\n}\n\nasync function loadDriverEntry(id: string, driverPath: string, appRoot: string): Promise<DriverHandle> {\n let source: string\n try {\n source = await readFile(driverPath, \"utf8\")\n } catch (err) {\n throw new AppLoadError(`driver '${id}': cannot read '${driverPath}': ${errMsg(err)}`)\n }\n try {\n return driverHandleFromManifest(parseDriverManifest(source), appRoot)\n } catch (err) {\n throw new AppLoadError(`driver '${id}' at '${driverPath}': ${errMsg(err)}`)\n }\n}\n\n/**\n * Scan `<dir>/.agentproto/tools/*` and `<dir>/.agentproto/drivers/*` for\n * TOOL.md / DRIVER.md bundles and load them into live handles. Used by\n * `loadAppHandle` (install-time validation, via `defineApp`) and reusable\n * directly by a host that needs an already-installed app's tools/drivers\n * without re-walking its agents/workflows (see `@agentproto/runtime`'s\n * workflow `compileWorkflow` seam).\n */\nexport async function loadAppBundledTools(\n dir: string,\n): Promise<{ tools: ToolHandle[]; drivers: DriverHandle[] }> {\n const toolsDir = join(dir, \".agentproto\", \"tools\")\n const driversDir = join(dir, \".agentproto\", \"drivers\")\n\n const tools: ToolHandle[] = []\n for (const id of await listBundleIds(toolsDir)) {\n tools.push(await loadToolEntry(id, join(toolsDir, id, \"TOOL.md\")))\n }\n\n const drivers: DriverHandle[] = []\n for (const id of await listBundleIds(driversDir)) {\n drivers.push(await loadDriverEntry(id, join(driversDir, id, \"DRIVER.md\"), dir))\n }\n\n return { tools, drivers }\n}\n","/**\n * `loadAppHandle(dir)` — read a root `APP.md` off disk into an `AppHandle`.\n *\n * Mirror of `@agentproto/workflow-loader`'s `loadWorkflowHandle`: this is\n * the host-side seam that touches the filesystem so the pure packages\n * (`@agentproto/agent`, `@agentproto/workflow`, `@agentproto/workspace`)\n * don't have to.\n *\n * `<dir>/.agentproto/APP.md` lists every agent + workflow the app bundles\n * as `{ id, path }` refs (relative to `dir`, the shape `emitApp` writes).\n * Each is loaded with its own package's manifest reader — `AGENT.md` via\n * `@agentproto/agent/manifest`, `WORKFLOW.md` via\n * `@agentproto/workflow-loader` (which itself resolves an `entry:` module\n * when present) — then the whole bundle is re-run through `defineApp` so\n * the attachment invariant (every agent/workflow ref resolves both ways)\n * re-validates exactly as it did at authoring time. A stale or hand-edited\n * APP.md that drifted from its AGENT.md/WORKFLOW.md refs fails the same\n * way a bad `defineApp({...})` call would.\n *\n * The app may also ship AIP-14 TOOL.md / AIP-30 DRIVER.md bundles under\n * `.agentproto/tools/<id>/TOOL.md` and `.agentproto/drivers/<id>/DRIVER.md`\n * — discovered by directory convention (see `loadAppBundledTools`), not\n * declared as APP.md frontmatter refs like agents/workflows are.\n *\n * Frontmatter validation here is deliberately minimal, and that is now an\n * AIP-53 conformance decision, not an accident of app having \"no AIP yet\":\n * AIP-53 (Draft) freezes the loader contract at the checks below — schema\n * MUST be exactly `app/v1`, `agents`/`workflows` MUST be `{ id, path }`\n * ref arrays, every ref MUST resolve, and the bundle MUST re-run through\n * `defineApp` — and it does NOT require rejecting unknown frontmatter\n * keys. Staying permissive past the frozen checks lets a future frontmatter\n * key (e.g. a later WP's addition) round-trip through this loader without\n * hosts that haven't upgraded rejecting the whole app; tightening beyond\n * the spec would break that forward compatibility for no conformance gain.\n */\n\nimport { readFile } from \"node:fs/promises\"\nimport { dirname, isAbsolute, join } from \"node:path\"\nimport matter from \"gray-matter\"\nimport { agentFromManifest, parseAgentManifest } from \"@agentproto/agent/manifest\"\nimport { loadWorkflowHandle } from \"@agentproto/workflow-loader\"\nimport { parseWorkspaceManifest, workspaceFromManifest } from \"@agentproto/workspace/manifest\"\nimport type {\n AgentEntry,\n AppArtifactDecl,\n AppBoundariesDefinition,\n AppDataDefinition,\n AppDefinition,\n AppDevDefinition,\n AppHandle,\n AppUiBuildConfig,\n AppUiDefinition,\n} from \"./types.js\"\nimport { defineApp } from \"./define-app.js\"\nimport { AppLoadError } from \"./errors.js\"\nimport { loadAppBundledTools } from \"./load-app-tools.js\"\nimport { normalizeManifestFields } from \"./manifest-fields.js\"\n\nexport { AppLoadError }\n\ninterface AppRef {\n readonly id: string\n readonly path: string\n}\n\ninterface AppFrontmatterUi {\n readonly path: string\n readonly title?: string\n readonly description?: string\n readonly tools?: readonly string[]\n readonly port?: number\n readonly csp?: {\n readonly connectDomains?: readonly string[]\n readonly resourceDomains?: readonly string[]\n readonly frameDomains?: readonly string[]\n }\n readonly build?: AppUiBuildConfig\n /**\n * Namespaced vendor extension metadata. Passed through to `defineApp`\n * UNFILTERED (not just `openai`) so its namespace check — `ui.extensions`\n * accepts ONLY `openai` — actually runs against a hand-authored APP.md's\n * sibling keys too, not just the TS-authoring path.\n */\n readonly extensions?: { readonly [key: string]: unknown }\n}\n\ninterface AppFrontmatterArtifact {\n readonly path: string\n readonly title?: string\n readonly description?: string\n}\n\ninterface AppFrontmatterSkill {\n readonly path: string\n readonly title?: string\n readonly description?: string\n}\n\ninterface AppFrontmatter {\n readonly schema: string\n readonly id?: string\n readonly name?: string\n readonly version?: string\n readonly description?: string\n readonly agents: readonly AppRef[]\n readonly workflows: readonly AppRef[]\n readonly workspace?: string\n readonly requires?: AppDefinition[\"requires\"]\n readonly placement?: AppDefinition[\"placement\"]\n readonly exposes?: AppDefinition[\"exposes\"]\n readonly accepts?: AppDefinition[\"accepts\"]\n readonly ui?: AppFrontmatterUi\n readonly artifact?: AppFrontmatterArtifact\n readonly skill?: AppFrontmatterSkill\n readonly artifacts?: readonly AppArtifactDecl[]\n readonly dev?: AppDevDefinition\n readonly data?: AppDataDefinition\n readonly externalReadRoots?: readonly string[]\n readonly boundaries?: AppBoundariesDefinition\n readonly category?: string\n}\n\nfunction resolveRef(dir: string, path: string): string {\n return isAbsolute(path) ? path : join(dir, path)\n}\n\n/**\n * Resolve the UI ROOT directory an app's UI should be served from — the\n * same resolution `app_install`/`loadAppHandle` uses for `ui.path`, so\n * `app serve` and install agree on where the UI lives.\n *\n * Reads `<appDir>/.agentproto/APP.md` frontmatter: when a `ui.path` is\n * declared, the UI root is the directory CONTAINING that entry file (e.g.\n * `ui.path: ui/index.html` → `<appDir>/ui`); when `ui` is absent, returns\n * `undefined` and callers fall back to the legacy `<appDir>/.agentproto/ui/`.\n * Throws {@link AppLoadError} on a `ui` that isn't an object or whose `path`\n * isn't a non-empty string — the same shape `loadAppHandle` would reject.\n * Returns `undefined` (not a throw) when APP.md itself is unreadable, since\n * callers check APP.md existence separately.\n */\nexport async function resolveAppUIRoot(appDir: string): Promise<string | undefined> {\n const appMdPath = join(appDir, \".agentproto\", \"APP.md\")\n let source: string\n try {\n source = await readFile(appMdPath, \"utf8\")\n } catch {\n return undefined\n }\n const data = matter(source).data as Record<string, unknown>\n const ui = data.ui\n if (ui === undefined) return undefined\n if (typeof ui !== \"object\" || ui === null || Array.isArray(ui)) {\n throw new AppLoadError(`'${appMdPath}': frontmatter 'ui' must be an object.`)\n }\n const path = (ui as Record<string, unknown>).path\n if (typeof path !== \"string\" || path.trim() === \"\") {\n throw new AppLoadError(\n `'${appMdPath}': frontmatter 'ui.path' must be a non-empty string.`,\n )\n }\n return dirname(resolveRef(appDir, path))\n}\n\n/** Validated `ui.path` + `ui.build`, as returned by {@link peekAppUi}. */\nexport interface AppUiPeek {\n readonly path: string\n readonly build?: AppUiBuildConfig\n}\n\nfunction parseUiBuildFrontmatter(raw: unknown, appMdPath: string): AppUiBuildConfig | undefined {\n if (raw === undefined) return undefined\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw new AppLoadError(`'${appMdPath}': frontmatter 'ui.build' must be an object.`)\n }\n const command = (raw as Record<string, unknown>).command\n if (typeof command !== \"string\" || command.trim() === \"\") {\n throw new AppLoadError(`'${appMdPath}': frontmatter 'ui.build.command' must be a non-empty string.`)\n }\n const cwd = (raw as Record<string, unknown>).cwd\n if (cwd !== undefined && (typeof cwd !== \"string\" || cwd.trim() === \"\")) {\n throw new AppLoadError(`'${appMdPath}': frontmatter 'ui.build.cwd' must be a non-empty string.`)\n }\n const sources = (raw as Record<string, unknown>).sources\n if (\n sources !== undefined &&\n (!Array.isArray(sources) || !sources.every(s => typeof s === \"string\" && s.trim() !== \"\"))\n ) {\n throw new AppLoadError(\n `'${appMdPath}': frontmatter 'ui.build.sources' must be an array of non-empty strings.`,\n )\n }\n return {\n command,\n ...(cwd !== undefined ? { cwd: cwd as string } : {}),\n ...(sources !== undefined ? { sources: sources as string[] } : {}),\n }\n}\n\n/**\n * Peek `<appDir>/.agentproto/APP.md`'s `ui.path` + `ui.build` WITHOUT\n * reading the ui html itself.\n *\n * `loadAppHandle` reads `ui.path` eagerly and throws {@link AppLoadError}\n * when it's missing — exactly the case a declared `ui.build` exists to\n * recover from. A caller that wants to build the bundle before it's\n * expected to exist (the daemon's `app_install`, `app serve`, first UI\n * serve — see `@agentproto/runtime`'s `ensureAppUiBuilt`) resolves this\n * first, runs the build if declared, then calls `loadAppHandle` as usual.\n *\n * Returns `undefined` when APP.md is unreadable or declares no `ui` block\n * — same \"caller checks existence separately\" contract as\n * `resolveAppUIRoot`. Throws on a malformed `ui`/`ui.build` shape, same\n * validation `loadAppHandle` would eventually hit.\n */\nexport async function peekAppUi(appDir: string): Promise<AppUiPeek | undefined> {\n const appMdPath = join(appDir, \".agentproto\", \"APP.md\")\n let source: string\n try {\n source = await readFile(appMdPath, \"utf8\")\n } catch {\n return undefined\n }\n const data = matter(source).data as Record<string, unknown>\n const ui = data.ui\n if (ui === undefined) return undefined\n if (typeof ui !== \"object\" || ui === null || Array.isArray(ui)) {\n throw new AppLoadError(`'${appMdPath}': frontmatter 'ui' must be an object.`)\n }\n const path = (ui as Record<string, unknown>).path\n if (typeof path !== \"string\" || path.trim() === \"\") {\n throw new AppLoadError(\n `'${appMdPath}': frontmatter 'ui.path' must be a non-empty string.`,\n )\n }\n const build = parseUiBuildFrontmatter((ui as Record<string, unknown>).build, appMdPath)\n return { path: resolveRef(appDir, path), ...(build ? { build } : {}) }\n}\n\nfunction isRefArray(v: unknown): v is AppRef[] {\n return (\n Array.isArray(v) &&\n v.every(\n (e) =>\n typeof e === \"object\" &&\n e !== null &&\n typeof (e as { id?: unknown }).id === \"string\" &&\n typeof (e as { path?: unknown }).path === \"string\",\n )\n )\n}\n\n/** Minimal shape check — see the module doc for why this stays loose. */\nfunction parseAppFrontmatter(data: Record<string, unknown>, appPath: string): AppFrontmatter {\n if (data.schema !== \"app/v1\") {\n throw new AppLoadError(\n `'${appPath}': expected frontmatter 'schema: app/v1', got ${JSON.stringify(data.schema)}.`,\n )\n }\n if (!isRefArray(data.agents)) {\n throw new AppLoadError(`'${appPath}': frontmatter 'agents' must be an array of { id, path }.`)\n }\n if (!isRefArray(data.workflows)) {\n throw new AppLoadError(\n `'${appPath}': frontmatter 'workflows' must be an array of { id, path }.`,\n )\n }\n // placement / requires / exposes / accepts: shape, enum and \"exposed id is\n // declared\" checks, same rules `defineApp` re-applies.\n normalizeManifestFields(\n data,\n { agents: data.agents.map(a => a.id), workflows: data.workflows.map(w => w.id) },\n msg => new AppLoadError(`'${appPath}': frontmatter ${msg}`),\n )\n if (data.data !== undefined) {\n const d = data.data as { dir?: unknown } | null\n if (\n typeof d !== \"object\" ||\n d === null ||\n (d.dir !== undefined && (typeof d.dir !== \"string\" || d.dir.trim() === \"\"))\n ) {\n throw new AppLoadError(\n `'${appPath}': frontmatter 'data' must be an object whose optional 'dir' is a non-empty string.`,\n )\n }\n }\n if (data.externalReadRoots !== undefined) {\n if (\n !Array.isArray(data.externalReadRoots) ||\n !data.externalReadRoots.every((e) => typeof e === \"string\" && e.trim() !== \"\")\n ) {\n throw new AppLoadError(\n `'${appPath}': frontmatter 'externalReadRoots' must be an array of non-empty strings.`,\n )\n }\n }\n if (data.boundaries !== undefined) {\n const b = data.boundaries as { enforce?: unknown } | null\n if (\n typeof b !== \"object\" ||\n b === null ||\n Array.isArray(b) ||\n (b.enforce !== undefined && b.enforce !== \"required\" && b.enforce !== \"best-effort\")\n ) {\n throw new AppLoadError(\n `'${appPath}': frontmatter 'boundaries' must be an object whose optional 'enforce' is \"required\" or \"best-effort\".`,\n )\n }\n }\n if (data.category !== undefined && (typeof data.category !== \"string\" || data.category.trim() === \"\")) {\n throw new AppLoadError(`'${appPath}': frontmatter 'category' must be a non-empty string.`)\n }\n return data as unknown as AppFrontmatter\n}\n\nasync function loadAgentEntry(dir: string, ref: AppRef): Promise<AgentEntry> {\n const agentPath = resolveRef(dir, ref.path)\n let source: string\n try {\n source = await readFile(agentPath, \"utf8\")\n } catch (err) {\n throw new AppLoadError(\n `agent '${ref.id}': cannot read '${agentPath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n let body: string\n let manifest: ReturnType<typeof parseAgentManifest>\n try {\n manifest = parseAgentManifest(source)\n body = manifest.body.trim()\n } catch (err) {\n throw new AppLoadError(\n `agent '${ref.id}' at '${agentPath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n return { agent: agentFromManifest(manifest), ...(body ? { body } : {}) }\n}\n\nasync function loadWorkflowRef(dir: string, ref: AppRef) {\n const wfPath = resolveRef(dir, ref.path)\n try {\n return await loadWorkflowHandle(wfPath)\n } catch (err) {\n throw new AppLoadError(\n `workflow '${ref.id}' at '${wfPath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Load `<dir>/.agentproto/APP.md` and every AGENT.md/WORKFLOW.md (and, if\n * declared, `<dir>/WORKSPACE.md`) it references, then re-run `defineApp` on\n * the result. Throws {@link AppLoadError} naming the offending path on a\n * missing APP.md, a missing referenced file, or a frontmatter/schema\n * mismatch; throws `AppDefinitionError` (from `defineApp`) if the loaded\n * bundle fails the attachment invariant.\n */\nexport async function loadAppHandle(dir: string): Promise<AppHandle> {\n const appPath = join(dir, \".agentproto\", \"APP.md\")\n let source: string\n try {\n source = await readFile(appPath, \"utf8\")\n } catch (err) {\n throw new AppLoadError(\n `cannot read '${appPath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n const parsed = matter(source)\n const fm = parseAppFrontmatter(parsed.data, appPath)\n\n const agents: AgentEntry[] = []\n for (const ref of fm.agents) {\n agents.push(await loadAgentEntry(dir, ref))\n }\n\n const workflows = []\n for (const ref of fm.workflows) {\n workflows.push(await loadWorkflowRef(dir, ref))\n }\n\n // AIP-14/AIP-30 tool + driver bundles — not enumerated in APP.md\n // frontmatter like agents/workflows are; discovered by convention under\n // `.agentproto/tools/<id>/TOOL.md` and `.agentproto/drivers/<id>/DRIVER.md`.\n // No declared bundle location exists yet in AIP-53/14/30 (spec gap) — see\n // `loadAppBundledTools` for the loader and its error-handling contract\n // (a parse/read failure fails the whole app load, naming the file path;\n // an absent `tools`/`drivers` directory is not an error).\n const { tools, drivers } = await loadAppBundledTools(dir)\n\n let workspace\n if (fm.workspace) {\n const workspacePath = join(dir, \"WORKSPACE.md\")\n let workspaceSource: string\n try {\n workspaceSource = await readFile(workspacePath, \"utf8\")\n } catch (err) {\n throw new AppLoadError(\n `workspace '${fm.workspace}': cannot read '${workspacePath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n try {\n workspace = workspaceFromManifest(parseWorkspaceManifest(workspaceSource))\n } catch (err) {\n throw new AppLoadError(\n `workspace '${fm.workspace}' at '${workspacePath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n }\n\n let ui\n if (fm.ui) {\n const uiPath = resolveRef(dir, fm.ui.path)\n let html: string\n try {\n html = await readFile(uiPath, \"utf8\")\n } catch (err) {\n throw new AppLoadError(\n `ui: cannot read '${uiPath}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n const build = parseUiBuildFrontmatter(fm.ui.build, appPath)\n ui = {\n html,\n ...(fm.ui.title !== undefined ? { title: fm.ui.title } : {}),\n ...(fm.ui.description !== undefined ? { description: fm.ui.description } : {}),\n ...(fm.ui.tools !== undefined ? { tools: fm.ui.tools } : {}),\n ...(fm.ui.port !== undefined ? { port: fm.ui.port } : {}),\n ...(fm.ui.csp !== undefined ? { csp: fm.ui.csp } : {}),\n ...(build !== undefined ? { build } : {}),\n // Pass through UNFILTERED — `defineApp`'s\n // `validateOpenAIExtensionsNamespace` rejects any sibling vendor key\n // (a typo, a future vendor block, hand-authored drift) with the same\n // diagnostic the TS-authoring path throws. Pre-filtering to `openai`\n // here would silently drop those instead of failing loudly.\n ...(fm.ui.extensions !== undefined\n ? { extensions: fm.ui.extensions as unknown as AppUiDefinition[\"extensions\"] }\n : {}),\n }\n }\n\n return defineApp({\n agents,\n workflows,\n tools,\n drivers,\n ...(workspace ? { workspace } : {}),\n ...(fm.id !== undefined ? { id: fm.id } : {}),\n ...(fm.name !== undefined ? { name: fm.name } : {}),\n ...(fm.version !== undefined ? { version: fm.version } : {}),\n ...(fm.description !== undefined ? { description: fm.description } : {}),\n ...(fm.requires !== undefined ? { requires: fm.requires } : {}),\n ...(fm.placement !== undefined ? { placement: fm.placement } : {}),\n ...(fm.exposes !== undefined ? { exposes: fm.exposes } : {}),\n ...(fm.accepts !== undefined ? { accepts: fm.accepts } : {}),\n ...(ui !== undefined ? { ui } : {}),\n ...(fm.artifact !== undefined\n ? { artifact: { path: resolveRef(dir, fm.artifact.path), ...(fm.artifact.title !== undefined ? { title: fm.artifact.title } : {}), ...(fm.artifact.description !== undefined ? { description: fm.artifact.description } : {}) } }\n : {}),\n ...(fm.skill !== undefined\n ? { skill: { path: resolveRef(dir, fm.skill.path), ...(fm.skill.title !== undefined ? { title: fm.skill.title } : {}), ...(fm.skill.description !== undefined ? { description: fm.skill.description } : {}) } }\n : {}),\n ...(fm.artifacts !== undefined ? { artifacts: fm.artifacts } : {}),\n ...(fm.dev !== undefined ? { dev: fm.dev } : {}),\n ...(fm.data !== undefined ? { data: fm.data } : {}),\n ...(fm.externalReadRoots !== undefined ? { externalReadRoots: fm.externalReadRoots } : {}),\n ...(fm.boundaries !== undefined ? { boundaries: fm.boundaries } : {}),\n ...(fm.category !== undefined ? { category: fm.category } : {}),\n })\n}\n","/**\n * `.agentapp` pack / unpack core (AIP-53 §\"The `.agentapp` package format\").\n *\n * PACK walks the app dir (skipping `node_modules/` and `.git/` at any\n * depth), applies the APP.md `package` include/exclude rules (plus\n * RELEASE_DEFAULT_EXCLUDE in release mode), stages ONLY the selected\n * files (rewriting APP.md without `ui.build` when stripping), writes a\n * `manifest.json` at the bundle root, and tars the staged CONTENTS\n * with system `tar`, so extraction yields `manifest.json` +\n * `.agentproto/` + loose files at the top level.\n *\n * UNPACK extracts to a fresh temp dir, reads `manifest.json`, validates\n * `format === \"agentapp/v1\"`, recomputes the aggregate SHA over the\n * listed files and compares it to `manifest.sha256`, then moves the\n * restored contents (WITHOUT `manifest.json` — it is a bundle\n * artifact, not part of the app) into the destination dir.\n *\n * The SHA is over file contents ONLY (excluding manifest.json), fed in the\n * manifest `files` order (pack already sorts them), accumulated into one\n * hasher so bundling-scale trees don't load into memory.\n *\n * Both entries throw {@link AgentAppPackError}; `code` lets a caller (the\n * CLI, the daemon's remote install) map failures without parsing messages.\n */\n\nimport { copyFile, cp, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from \"node:fs/promises\"\nimport { createHash } from \"node:crypto\"\nimport { basename, dirname, isAbsolute, join, posix, resolve } from \"node:path\"\nimport { tmpdir } from \"node:os\"\nimport { spawn } from \"node:child_process\"\n\nimport matter from \"gray-matter\"\n\nexport const AGENTAPP_FORMAT = \"agentapp/v1\" as const\nconst DEFAULT_VERSION = \"0.1.0\"\n\n/** Directory names skipped at any depth while walking/copying an app dir. */\nconst SKIP_DIR_NAMES = new Set([\"node_modules\", \".git\"])\n\n/** The manifest.json written at the bundle root (and validated on unpack). */\nexport interface AgentAppManifest {\n format: typeof AGENTAPP_FORMAT\n id: string\n name?: string\n version: string\n description?: string\n agents: string[]\n workflows: string[]\n ui?: string[]\n files: string[]\n fileCount: number\n totalSize: number\n sha256: string\n createdAt: string\n agentprotoVersion: string\n}\n\n/** A file discovered under the app dir, with its size for the manifest. */\nexport interface BundleFile {\n path: string\n size: number\n}\n\nexport type AgentAppPackErrorCode =\n | \"not-an-app\"\n | \"bundle-not-found\"\n | \"tar-failed\"\n | \"missing-manifest\"\n | \"malformed-manifest\"\n | \"unsupported-format\"\n | \"unsafe-path\"\n | \"digest-mismatch\"\n | \"invalid-package\"\n | \"missing-ui\"\n\nexport class AgentAppPackError extends Error {\n readonly code: AgentAppPackErrorCode\n constructor(code: AgentAppPackErrorCode, message: string) {\n super(message)\n this.name = \"AgentAppPackError\"\n this.code = code\n }\n}\n\n/** `.agentproto/APP.md` frontmatter, digested into bundle metadata. */\ninterface AppMeta {\n id: string\n name?: string\n version: string\n description?: string\n agents: string[]\n workflows: string[]\n ui?: string[]\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p)\n return true\n } catch {\n return false\n }\n}\n\n/** Derive a filesystem-safe id from a possibly scoped/odd app id. */\nexport function safeId(id: unknown): string {\n return String(id || \"app\").replace(/^@/, \"\").replace(/[^A-Za-z0-9._-]+/g, \"-\")\n}\n\n/** Narrow an unknown parsed JSON value to the manifest shape. */\nexport function isManifest(value: unknown): value is AgentAppManifest {\n if (typeof value !== \"object\" || value === null) return false\n const m = value as Record<string, unknown>\n return (\n typeof m.format === \"string\" &&\n typeof m.id === \"string\" &&\n typeof m.version === \"string\" &&\n Array.isArray(m.agents) &&\n Array.isArray(m.workflows) &&\n Array.isArray(m.files) &&\n typeof m.fileCount === \"number\" &&\n typeof m.totalSize === \"number\" &&\n typeof m.sha256 === \"string\"\n )\n}\n\n/**\n * Recursively collect every regular file under root as relative paths,\n * skipping any `node_modules/` or `.git/` directory at any depth — a `ui/`\n * source tree ships both, and bundling either would balloon the .agentapp\n * for no benefit (they're never part of the shipped app).\n */\nexport async function collectFiles(root: string): Promise<BundleFile[]> {\n const files: BundleFile[] = []\n async function walk(relDir: string): Promise<void> {\n const absDir = join(root, relDir)\n for (const entry of await readdir(absDir, { withFileTypes: true })) {\n if (entry.isDirectory() && SKIP_DIR_NAMES.has(entry.name)) continue\n const rel = relDir ? join(relDir, entry.name) : entry.name\n const abs = join(absDir, entry.name)\n if (entry.isDirectory()) {\n await walk(rel)\n } else if (entry.isFile()) {\n const st = await stat(abs)\n files.push({ path: rel, size: st.size })\n }\n }\n }\n await walk(\"\")\n return files\n}\n\n/** Aggregate sha256 over the concatenated bytes of the given files. */\nexport async function aggregateSha256(root: string, files: readonly string[]): Promise<string> {\n const hash = createHash(\"sha256\")\n for (const file of files) {\n hash.update(await readFile(join(root, file)))\n }\n return hash.digest(\"hex\")\n}\n\n/**\n * Run system `tar` with the given args, resolving the exit code (0 = ok).\n * Uses `spawn` + an exit handler so the awaited promise actually tracks\n * process completion cross-platform (BSD/macOS and GNU tar).\n */\nfunction runTar(args: string[], opts?: { cwd?: string }): Promise<number> {\n return new Promise((resolvePromise, reject) => {\n const child = spawn(\"tar\", args, { stdio: \"ignore\", cwd: opts?.cwd })\n child.once(\"error\", reject)\n child.once(\"exit\", (code) => resolvePromise(code ?? 0))\n })\n}\n\n/** Pull ids from an `[{id, path}]` (or bare-string) array. */\nfunction extractIds(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n const out: string[] = []\n for (const entry of value) {\n if (typeof entry === \"string\") {\n if (entry) out.push(entry)\n } else if (entry && typeof entry === \"object\") {\n const id = (entry as { id?: unknown }).id\n if (typeof id === \"string\" && id) out.push(id)\n }\n }\n return out\n}\n\n/** Basenames for a path/`{path}`/array-of-either frontmatter field. */\nfunction extractPaths(front: Record<string, unknown>, key: string): string[] | undefined {\n const value = front[key]\n if (value === undefined || value === null) return undefined\n const items = Array.isArray(value) ? value : [value]\n const out: string[] = []\n for (const item of items) {\n if (typeof item === \"string\") {\n if (item) out.push(basename(item))\n } else if (item && typeof item === \"object\") {\n const p = (item as { path?: unknown }).path\n if (typeof p === \"string\" && p) out.push(basename(p))\n }\n }\n return out.length > 0 ? out : undefined\n}\n\n/** Extract bundle metadata from APP.md frontmatter. */\nfunction extractMeta(front: Record<string, unknown>): AppMeta {\n const id =\n typeof front.id === \"string\" && front.id.length > 0\n ? front.id\n : typeof front.slug === \"string\" && front.slug.length > 0\n ? front.slug\n : \"app\"\n const version =\n typeof front.version === \"string\" && front.version.length > 0\n ? front.version\n : DEFAULT_VERSION\n const name = typeof front.name === \"string\" ? front.name : undefined\n const description = typeof front.description === \"string\" ? front.description : undefined\n const ui = extractPaths(front, \"ui\")\n\n return {\n id,\n ...(name !== undefined ? { name } : {}),\n version,\n ...(description !== undefined ? { description } : {}),\n agents: extractIds(front.agents),\n workflows: extractIds(front.workflows),\n ...(ui !== undefined ? { ui } : {}),\n }\n}\n\n/**\n * Release-mode default excludes: dev-only trees and artifacts that must never\n * ship in a published `.agentapp` (UI sources, docs, runtime data, scripts,\n * dev harnesses, tests, repo docs and tooling config, logs, source maps, env\n * files). Nothing the runtime reads: an installed app is its\n * `.agentproto/` tree plus the files its workflows import. APP.md\n * `package.exclude` ADDS to this list in release mode; it never removes\n * from it. `LICENSE` / `NOTICE` are deliberately NOT excluded.\n */\nexport const RELEASE_DEFAULT_EXCLUDE: readonly string[] = [\n \"ui/**\",\n \"docs/**\",\n \"data/**\",\n \"scripts/**\",\n // Store listing sources (APP.md `store:`): published next to the catalog\n // entry, never needed by an installed app.\n \"store/**\",\n // Root-level only: `**/dev/**` would also drop a shipped agent named\n // `dev` (`.agentproto/agents/dev/`); `ui/dev/` is covered by `ui/**`.\n // Same for `test/` and `tests/`.\n \"dev/**\",\n \"test/**\",\n \"tests/**\",\n // Test files and folders anywhere (a workflow's `foo.test.mjs` next to\n // its `entry.mjs`); these names are never a runtime import.\n \"**/__tests__/**\",\n \"**/*.test.*\",\n \"**/*.spec.*\",\n // Repo docs at the app root (the catalog entry carries the description).\n \"README.md\",\n \"CHANGELOG.md\",\n \"CONTRIBUTING.md\",\n // Repo and editor tooling.\n \".github/**\",\n \".vscode/**\",\n \".idea/**\",\n \".gitignore\",\n \".editorconfig\",\n \"tsconfig*.json\",\n \"vitest.config.*\",\n \"jest.config.*\",\n \"eslint.config.*\",\n \".eslintrc*\",\n \".prettierrc*\",\n \"**/*.log\",\n \"**/*.map\",\n \"**/.DS_Store\",\n \"**/.env\",\n \"**/.env.*\",\n]\n\n/** APP.md `package` block — what a `.agentapp` ships. All fields optional. */\nexport interface AppPackageRules {\n /** When set, only files matching one of these globs ship (APP.md and the\n * `ui.path` entry + its `assets/` are always kept). */\n include?: string[]\n /** Files matching any of these globs are dropped. */\n exclude?: string[]\n /** Remove `ui.build` from the packed APP.md. Default: true in release mode,\n * false otherwise. */\n stripBuild?: boolean\n}\n\n/**\n * Glob → RegExp over a `/`-separated relative path. `**` spans any number of\n * segments (including none when followed by `/`), `*` stays inside one\n * segment. No braces, no negation, no `?` — enough for package rules without\n * a glob dependency.\n */\nexport function globToRegExp(glob: string): RegExp {\n const g = glob.replace(/^\\.\\//, \"\")\n let re = \"\"\n for (let i = 0; i < g.length; i++) {\n const c = g[i]!\n if (c === \"*\") {\n if (g[i + 1] === \"*\") {\n i++\n if (g[i + 1] === \"/\") {\n i++\n re += \"(?:.*/)?\"\n } else {\n re += \".*\"\n }\n } else {\n re += \"[^/]*\"\n }\n } else if (\"\\\\^$+?.()|{}[]\".includes(c)) {\n re += \"\\\\\" + c\n } else {\n re += c\n }\n }\n return new RegExp(`^${re}$`)\n}\n\nfunction toPosix(p: string): string {\n return p.replace(/\\\\/g, \"/\")\n}\n\nfunction matchesAny(path: string, globs: readonly RegExp[]): boolean {\n const p = toPosix(path)\n return globs.some((re) => re.test(p))\n}\n\n/** Read + validate the APP.md `package` block. Throws `invalid-package`. */\nexport function readPackageRules(front: Record<string, unknown>): AppPackageRules {\n const raw = front.package\n if (raw === undefined || raw === null) return {}\n if (typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new AgentAppPackError(\"invalid-package\", \"APP.md `package` must be an object.\")\n }\n const r = raw as Record<string, unknown>\n const list = (key: \"include\" | \"exclude\"): string[] | undefined => {\n const v = r[key]\n if (v === undefined) return undefined\n if (!Array.isArray(v) || v.some((s) => typeof s !== \"string\" || s.trim() === \"\")) {\n throw new AgentAppPackError(\n \"invalid-package\",\n `APP.md \\`package.${key}\\` must be an array of non-empty glob strings.`,\n )\n }\n return v as string[]\n }\n if (r.stripBuild !== undefined && typeof r.stripBuild !== \"boolean\") {\n throw new AgentAppPackError(\"invalid-package\", \"APP.md `package.stripBuild` must be a boolean.\")\n }\n const include = list(\"include\")\n const exclude = list(\"exclude\")\n return {\n ...(include !== undefined ? { include } : {}),\n ...(exclude !== undefined ? { exclude } : {}),\n ...(typeof r.stripBuild === \"boolean\" ? { stripBuild: r.stripBuild } : {}),\n }\n}\n\n/** APP.md `ui.path` (string or `{path}`) as a posix path relative to the app\n * dir, or undefined when absent / absolute / escaping the app dir. */\nfunction uiRelPath(front: Record<string, unknown>): string | undefined {\n const ui = front.ui\n const raw =\n typeof ui === \"string\"\n ? ui\n : ui && typeof ui === \"object\" && !Array.isArray(ui) && typeof (ui as { path?: unknown }).path === \"string\"\n ? (ui as { path: string }).path\n : undefined\n if (raw === undefined || raw === \"\" || isAbsolute(raw)) return undefined\n const rel = posix.normalize(toPosix(raw)).replace(/^\\.\\//, \"\")\n if (rel.startsWith(\"../\") || rel === \"..\") return undefined\n return rel\n}\n\n/**\n * Package `appDir` (must hold `.agentproto/APP.md`) into a `.agentapp`.\n * Without `out`, the file is `<safeId>-<version>.agentapp` in the cwd.\n *\n * File selection: every file under `appDir` minus `node_modules/`/`.git/`,\n * then the APP.md `package` rules (`include` restricts, `exclude` drops). In\n * `release` mode {@link RELEASE_DEFAULT_EXCLUDE} is added to `exclude`, the\n * built `ui.path` must be in the bundle (`missing-ui` otherwise), and\n * `ui.build` is stripped from the packed APP.md (override with\n * `package.stripBuild`). `.agentproto/APP.md`, the `ui.path` entry and the\n * files under its sibling `assets/` dir always ship. Only the selected files\n * are staged, and the SHA covers the staged bytes (so a rewritten APP.md is\n * what gets hashed).\n */\nexport async function packApp(input: {\n appDir: string\n out?: string\n release?: boolean\n}): Promise<{ file: string; manifest: AgentAppManifest }> {\n const appDirAbs = resolve(input.appDir)\n const release = input.release === true\n\n const appMdPath = join(appDirAbs, \".agentproto\", \"APP.md\")\n if (!(await pathExists(appMdPath))) {\n throw new AgentAppPackError(\n \"not-an-app\",\n `${appDirAbs} is not an agentproto app (missing ${appMdPath}).`,\n )\n }\n\n const raw = await readFile(appMdPath, \"utf8\")\n const parsedAppMd = matter(raw)\n const front = parsedAppMd.data as Record<string, unknown>\n const meta = extractMeta(front)\n const rules = readPackageRules(front)\n\n const outAbs =\n input.out !== undefined\n ? resolve(input.out)\n : resolve(process.cwd(), `${safeId(meta.id)}-${meta.version}.agentapp`)\n await mkdir(dirname(outAbs), { recursive: true })\n\n const appMdRel = \".agentproto/APP.md\"\n const uiRel = uiRelPath(front)\n const uiAssetsPrefix = uiRel !== undefined ? `${posix.dirname(uiRel)}/assets/`.replace(/^\\.\\//, \"\") : undefined\n const includeRes = rules.include?.map(globToRegExp)\n const excludeRes = [...(release ? RELEASE_DEFAULT_EXCLUDE : []), ...(rules.exclude ?? [])].map(globToRegExp)\n const alwaysShip = (p: string): boolean =>\n p === appMdRel || p === uiRel || (uiAssetsPrefix !== undefined && p.startsWith(uiAssetsPrefix))\n\n const selected = (await collectFiles(appDirAbs))\n .filter((f) => f.path !== \"manifest.json\")\n .filter((f) => join(appDirAbs, f.path) !== outAbs)\n .filter((f) => {\n const p = toPosix(f.path)\n if (alwaysShip(p)) return true\n if (includeRes !== undefined && !matchesAny(p, includeRes)) return false\n return !matchesAny(p, excludeRes)\n })\n .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))\n\n if (release && uiRel !== undefined && !selected.some((f) => toPosix(f.path) === uiRel)) {\n throw new AgentAppPackError(\n \"missing-ui\",\n `ui.path \"${uiRel}\" does not exist in ${appDirAbs} — build the UI first ` +\n \"(`agentproto app build <appDir>`, or `agentproto app pack --release`, which runs `ui.build`).\",\n )\n }\n\n const stripBuild = rules.stripBuild ?? release\n\n // Stage ONLY the selected files, optionally rewrite APP.md, then hash and\n // tar what is actually staged — excluded files never reach the archive.\n const staging = await mkdtemp(join(tmpdir(), \"agentapp-\"))\n try {\n for (const f of selected) {\n const dest = join(staging, f.path)\n await mkdir(dirname(dest), { recursive: true })\n await copyFile(join(appDirAbs, f.path), dest)\n }\n\n if (stripBuild) {\n const ui = front.ui\n if (ui && typeof ui === \"object\" && !Array.isArray(ui) && \"build\" in ui) {\n // Clone: gray-matter caches parse results per input string, so the\n // cached `data` object must not be mutated.\n const data = structuredClone(front)\n delete (data.ui as Record<string, unknown>).build\n await writeFile(join(staging, appMdRel), matter.stringify(parsedAppMd.content, data), \"utf8\")\n }\n }\n\n const files: BundleFile[] = []\n for (const f of selected) {\n files.push({ path: f.path, size: (await stat(join(staging, f.path))).size })\n }\n const fileCount = files.length\n const totalSize = files.reduce((sum, f) => sum + f.size, 0)\n const sha256 = await aggregateSha256(\n staging,\n files.map((f) => f.path),\n )\n\n const manifest: AgentAppManifest = {\n format: AGENTAPP_FORMAT,\n id: meta.id,\n ...(meta.name !== undefined ? { name: meta.name } : {}),\n version: meta.version,\n ...(meta.description !== undefined ? { description: meta.description } : {}),\n agents: meta.agents,\n workflows: meta.workflows,\n ...(meta.ui !== undefined ? { ui: meta.ui } : {}),\n files: files.map((f) => f.path),\n fileCount,\n totalSize,\n sha256,\n createdAt: new Date().toISOString(),\n agentprotoVersion: \">=0.1.0\",\n }\n\n await writeFile(join(staging, \"manifest.json\"), JSON.stringify(manifest, null, 2) + \"\\n\", \"utf8\")\n // Offline-deterministic archive: pass the entry list explicitly (sorted) so\n // the archive order is reproducible without GNU-only `--sort=name`, which\n // BSD/macOS tar rejects. Dotfiles (`.agentproto`) are included by readdir.\n const entries = (await readdir(staging)).sort()\n const packCode = await runTar([\"-czf\", outAbs, ...entries], { cwd: staging })\n if (packCode !== 0) {\n throw new AgentAppPackError(\"tar-failed\", `tar failed with exit code ${packCode}`)\n }\n return { file: outAbs, manifest }\n } finally {\n await rm(staging, { recursive: true, force: true })\n }\n}\n\n/** A manifest `files` entry that could read or write outside the bundle root. */\nfunction isUnsafeBundlePath(p: string): boolean {\n if (p === \"\" || isAbsolute(p)) return true\n return p.split(/[\\\\/]/).includes(\"..\")\n}\n\n/**\n * Extract a `.agentapp`, verify format + aggregate SHA-256, and restore the\n * app folder (without `manifest.json`) into `dest`. Without `dest`, restores\n * into `<safeId>-<version>` in the cwd. A failed verification leaves `dest`\n * untouched (nothing is created).\n */\nexport async function unpackApp(input: {\n file: string\n dest?: string\n}): Promise<{ dir: string; manifest: AgentAppManifest }> {\n const bundleAbs = resolve(input.file)\n if (!(await pathExists(bundleAbs))) {\n throw new AgentAppPackError(\"bundle-not-found\", `bundle not found: ${bundleAbs}`)\n }\n\n const temp = await mkdtemp(join(tmpdir(), \"agentapp-\"))\n try {\n const unpackCode = await runTar([\"-xzf\", bundleAbs, \"-C\", temp])\n if (unpackCode !== 0) {\n throw new AgentAppPackError(\"tar-failed\", `tar failed with exit code ${unpackCode}`)\n }\n\n const manifestPath = join(temp, \"manifest.json\")\n if (!(await pathExists(manifestPath))) {\n throw new AgentAppPackError(\n \"missing-manifest\",\n `${bundleAbs} is not a valid .agentapp (missing manifest.json).`,\n )\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(await readFile(manifestPath, \"utf8\"))\n } catch {\n throw new AgentAppPackError(\"malformed-manifest\", `${bundleAbs} has a malformed manifest.json.`)\n }\n if (!isManifest(parsed)) {\n throw new AgentAppPackError(\"malformed-manifest\", `${bundleAbs} has a malformed manifest.json.`)\n }\n const manifest = parsed\n\n if (manifest.format !== AGENTAPP_FORMAT) {\n throw new AgentAppPackError(\n \"unsupported-format\",\n `unsupported bundle format '${manifest.format}' (expected ${AGENTAPP_FORMAT}).`,\n )\n }\n\n const unsafe = manifest.files.find((f) => typeof f !== \"string\" || isUnsafeBundlePath(f))\n if (unsafe !== undefined) {\n throw new AgentAppPackError(\n \"unsafe-path\",\n `manifest.json lists a path outside the bundle root: ${JSON.stringify(unsafe)}.`,\n )\n }\n\n const actual = await aggregateSha256(temp, manifest.files)\n if (actual !== manifest.sha256) {\n throw new AgentAppPackError(\n \"digest-mismatch\",\n `SHA-256 mismatch (expected ${manifest.sha256}, got ${actual}). Bundle is corrupted.`,\n )\n }\n\n const outDir =\n input.dest !== undefined\n ? resolve(input.dest)\n : resolve(process.cwd(), `${safeId(manifest.id)}-${manifest.version}`)\n // Drop the bundle artifact before moving the app contents over.\n await rm(manifestPath, { force: true })\n await mkdir(outDir, { recursive: true })\n await cp(temp, outDir, { recursive: true })\n\n return { dir: outDir, manifest }\n } finally {\n await rm(temp, { recursive: true, force: true })\n }\n}\n"]}
|
package/dist/pack.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pack.d.ts","sourceRoot":"","sources":["../src/pack.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAUH,eAAO,MAAM,eAAe,EAAG,aAAsB,CAAA;AAMrD,8EAA8E;AAC9E,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,OAAO,eAAe,CAAA;IAC9B,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,MAAM,CAAA;IACf,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,MAAM,EAAE,MAAM,EAAE,CAAA;IAChB,SAAS,EAAE,MAAM,EAAE,CAAA;IACnB,EAAE,CAAC,EAAE,MAAM,EAAE,CAAA;IACb,KAAK,EAAE,MAAM,EAAE,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;IACjB,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,EAAE,MAAM,CAAA;IACjB,iBAAiB,EAAE,MAAM,CAAA;CAC1B;AAED,2EAA2E;AAC3E,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;CACb;AAED,MAAM,MAAM,qBAAqB,GAC7B,YAAY,GACZ,kBAAkB,GAClB,YAAY,GACZ,kBAAkB,GAClB,oBAAoB,GACpB,oBAAoB,GACpB,aAAa,GACb,iBAAiB,GACjB,iBAAiB,GACjB,YAAY,CAAA;AAEhB,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,QAAQ,CAAC,IAAI,EAAE,qBAAqB,CAAA;gBACxB,IAAI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AAC,GAAG,eAAe,CA4BhF;AAkBD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,OAAO,CAAC,KAAK,EAAE;IACnC,MAAM,EAAE,MAAM,CAAA;IACd,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,OAAO,CAAC,EAAE,OAAO,CAAA;CAClB,GAAG,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,gBAAgB,CAAA;CAAE,CAAC,CAmHxD;AAQD;;;;;GAKG;AACH,wBAAsB,SAAS,CAAC,KAAK,EAAE;IACrC,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,CAAC,EAAE,MAAM,CAAA;CACd,GAAG,OAAO,CAAC;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,gBAAgB,CAAA;CAAE,CAAC,CAmEvD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentproto/app-kit",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.2",
|
|
4
4
|
"description": "@agentproto/app-kit — declare an agent (with its system prompt) and its workflows in one TypeScript module and import them anywhere. A thin umbrella over AIP-42 defineAgent + AIP-15 defineWorkflow: defineApp cross-links the two (every workflow agent-step must target the app's agent, every agent workflow ref must resolve), toMastraAgent turns the AGENT.md body into a real Mastra `instructions` field, and emit writes the .agents/<id>/AGENT.md + WORKFLOW.md(+entry) pair that runs through the agentproto-run lane unchanged.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentproto",
|
|
@@ -44,10 +44,10 @@
|
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"gray-matter": "^4.0.3",
|
|
46
46
|
"@agentproto/agent": "0.2.5",
|
|
47
|
-
"@agentproto/
|
|
47
|
+
"@agentproto/mastra": "0.2.16",
|
|
48
48
|
"@agentproto/driver-cli": "0.2.2",
|
|
49
49
|
"@agentproto/driver-http": "0.1.10",
|
|
50
|
-
"@agentproto/
|
|
50
|
+
"@agentproto/driver": "0.3.0",
|
|
51
51
|
"@agentproto/tool": "0.4.0",
|
|
52
52
|
"@agentproto/workflow": "0.7.1",
|
|
53
53
|
"@agentproto/workflow-loader": "0.2.5",
|