@open-mercato/cli 0.8.1-develop.7269.1.493e13f954 → 0.8.1-develop.7275.1.f772b944d4
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/.turbo/turbo-build.log +1 -1
- package/dist/agentic/guides/module-facts.json +140 -140
- package/dist/agentic/guides/module-facts.v2.json +140 -140
- package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
- package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
- package/dist/agentic/guides/modules/api_docs/index.md +1 -1
- package/dist/agentic/guides/modules/api_keys/index.md +1 -1
- package/dist/agentic/guides/modules/attachments/index.md +1 -1
- package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
- package/dist/agentic/guides/modules/auth/index.md +1 -1
- package/dist/agentic/guides/modules/business_rules/index.md +1 -1
- package/dist/agentic/guides/modules/catalog/index.md +1 -1
- package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
- package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
- package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
- package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
- package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
- package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
- package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
- package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
- package/dist/agentic/guides/modules/checkout/index.md +1 -1
- package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
- package/dist/agentic/guides/modules/configs/index.md +1 -1
- package/dist/agentic/guides/modules/content/index.md +1 -1
- package/dist/agentic/guides/modules/currencies/index.md +1 -1
- package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
- package/dist/agentic/guides/modules/customers/index.md +1 -1
- package/dist/agentic/guides/modules/dashboards/index.md +1 -1
- package/dist/agentic/guides/modules/data_sync/index.md +1 -1
- package/dist/agentic/guides/modules/design_system/index.md +1 -1
- package/dist/agentic/guides/modules/devices/index.md +1 -1
- package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
- package/dist/agentic/guides/modules/directory/index.md +1 -1
- package/dist/agentic/guides/modules/documents/index.md +1 -1
- package/dist/agentic/guides/modules/entities/index.md +1 -1
- package/dist/agentic/guides/modules/eudr/index.md +1 -1
- package/dist/agentic/guides/modules/events/index.md +1 -1
- package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
- package/dist/agentic/guides/modules/generators/index.md +1 -1
- package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
- package/dist/agentic/guides/modules/integrations/index.md +1 -1
- package/dist/agentic/guides/modules/messages/index.md +1 -1
- package/dist/agentic/guides/modules/notifications/index.md +1 -1
- package/dist/agentic/guides/modules/onboarding/index.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
- package/dist/agentic/guides/modules/perspectives/index.md +1 -1
- package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
- package/dist/agentic/guides/modules/planner/index.md +1 -1
- package/dist/agentic/guides/modules/portal/index.md +1 -1
- package/dist/agentic/guides/modules/progress/index.md +1 -1
- package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
- package/dist/agentic/guides/modules/query_index/index.md +1 -1
- package/dist/agentic/guides/modules/record_locks/index.md +1 -1
- package/dist/agentic/guides/modules/resources/index.md +1 -1
- package/dist/agentic/guides/modules/sales/index.md +1 -1
- package/dist/agentic/guides/modules/scheduler/index.md +1 -1
- package/dist/agentic/guides/modules/search/index.md +1 -1
- package/dist/agentic/guides/modules/security/index.md +1 -1
- package/dist/agentic/guides/modules/seeds/index.md +1 -1
- package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
- package/dist/agentic/guides/modules/sso/index.md +1 -1
- package/dist/agentic/guides/modules/staff/index.md +1 -1
- package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
- package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
- package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
- package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
- package/dist/agentic/guides/modules/tillio/index.md +1 -1
- package/dist/agentic/guides/modules/translations/index.md +1 -1
- package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
- package/dist/agentic/guides/modules/webhooks/index.md +1 -1
- package/dist/agentic/guides/modules/wms/index.md +1 -1
- package/dist/agentic/guides/modules/workflows/index.md +1 -1
- package/dist/agentic/guides/reference-module-facts.json +1 -1
- package/dist/agentic/guides/upstream/manifest.json +1 -1
- package/dist/lib/generators/extensions/agent-files.js +18 -5
- package/dist/lib/generators/extensions/agent-files.js.map +2 -2
- package/package.json +6 -6
- package/src/lib/generators/__tests__/agent-files-extension.test.ts +19 -1
- package/src/lib/generators/extensions/agent-files.ts +31 -5
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
# workflows — module facts (generated, do not edit)
|
|
2
|
-
<!-- generated from @open-mercato/core 0.8.1-develop.
|
|
2
|
+
<!-- generated from @open-mercato/core 0.8.1-develop.7275.1.f772b944d4; core 0.8.1-develop.7275.1.f772b944d4 — R1 staleness stamp -->
|
|
3
3
|
Source root: node_modules/@open-mercato/core/src/modules/workflows
|
|
4
4
|
|
|
5
5
|
## Sections
|
|
@@ -1185,7 +1185,7 @@
|
|
|
1185
1185
|
"facts": {
|
|
1186
1186
|
"title": "Example Module",
|
|
1187
1187
|
"description": "Demonstrates pages, APIs, entities and DI.",
|
|
1188
|
-
"coreVersion": "0.8.1-develop.
|
|
1188
|
+
"coreVersion": "0.8.1-develop.7275.1.f772b944d4",
|
|
1189
1189
|
"sourcePackage": null,
|
|
1190
1190
|
"sourceVersion": null,
|
|
1191
1191
|
"sourceRoot": "src/modules/example",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 1,
|
|
3
|
-
"generator": "@open-mercato/cli@0.8.1-develop.
|
|
3
|
+
"generator": "@open-mercato/cli@0.8.1-develop.7275.1.f772b944d4",
|
|
4
4
|
"files": {
|
|
5
5
|
"AGENTS.md": "9fdaca247f55c64f5966cc103265cfb03233e0532f58f14aff538ae18aa3555d",
|
|
6
6
|
"BACKWARD_COMPATIBILITY.md": "7f7d93266be9dbf1a1e154df6d40efd6de4ffeea3a2d7b2822f3081d6395c272"
|
|
@@ -517,6 +517,7 @@ function resolveAgentFilesTargets(resolver, fallbackRepoRoot) {
|
|
|
517
517
|
if (resolver && !resolver.isMonorepo()) {
|
|
518
518
|
const appDir = resolver.getAppDir();
|
|
519
519
|
return {
|
|
520
|
+
layout: "standalone",
|
|
520
521
|
manifestPath: path.join(resolver.getOutputDir(), "file-agents.generated.ts"),
|
|
521
522
|
dockerAgentsDir: path.join(appDir, "docker", "opencode", "agents"),
|
|
522
523
|
dockerSkillsDir: path.join(appDir, "docker", "opencode", "skills")
|
|
@@ -525,6 +526,7 @@ function resolveAgentFilesTargets(resolver, fallbackRepoRoot) {
|
|
|
525
526
|
const repoRoot = resolver?.getRootDir() ?? fallbackRepoRoot;
|
|
526
527
|
if (!repoRoot) return null;
|
|
527
528
|
return {
|
|
529
|
+
layout: "monorepo",
|
|
528
530
|
manifestPath: path.join(
|
|
529
531
|
repoRoot,
|
|
530
532
|
"packages",
|
|
@@ -670,8 +672,19 @@ ${indent} ],`);
|
|
|
670
672
|
`${indent}},`
|
|
671
673
|
].join("\n");
|
|
672
674
|
}
|
|
673
|
-
|
|
675
|
+
const MANIFEST_TYPE_IMPORTS = {
|
|
676
|
+
monorepo: {
|
|
677
|
+
outcomeSchema: "../lib/sdk/outcomeSchema",
|
|
678
|
+
tokensTypes: "../lib/tokens/types"
|
|
679
|
+
},
|
|
680
|
+
standalone: {
|
|
681
|
+
outcomeSchema: "@open-mercato/enterprise/modules/agent_orchestrator/lib/sdk/outcomeSchema",
|
|
682
|
+
tokensTypes: "@open-mercato/enterprise/modules/agent_orchestrator/lib/tokens/types"
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
function renderManifest(agents, options = { layout: "monorepo" }) {
|
|
674
686
|
const descriptors = agents.map((agent) => renderDescriptor(agent, " ")).join("\n");
|
|
687
|
+
const typeImports = MANIFEST_TYPE_IMPORTS[options.layout];
|
|
675
688
|
return `// AUTO-GENERATED by mercato generate registry \u2014 DO NOT EDIT BY HAND.
|
|
676
689
|
//
|
|
677
690
|
// Committed, generator-owned manifest of file-defined (OpenCode) agents,
|
|
@@ -682,8 +695,8 @@ function renderManifest(agents) {
|
|
|
682
695
|
// \`compileOutcome\` at load time and registers it with \`runtime:'opencode'\`.
|
|
683
696
|
//
|
|
684
697
|
// Regenerate with \`yarn generate\`.
|
|
685
|
-
import type { JsonSchemaNode, OutcomeKind } from '
|
|
686
|
-
import type { AgentTokenUsage, FileAgentFile } from '
|
|
698
|
+
import type { JsonSchemaNode, OutcomeKind } from '${typeImports.outcomeSchema}'
|
|
699
|
+
import type { AgentTokenUsage, FileAgentFile } from '${typeImports.tokensTypes}'
|
|
687
700
|
|
|
688
701
|
export type FileAgentScript = {
|
|
689
702
|
name: string
|
|
@@ -878,9 +891,9 @@ function createAgentFilesExtension(resolver) {
|
|
|
878
891
|
if (!sawOrchestratorModule && sorted.length === 0) {
|
|
879
892
|
return /* @__PURE__ */ new Map();
|
|
880
893
|
}
|
|
881
|
-
const { manifestPath, dockerAgentsDir, dockerSkillsDir } = targets;
|
|
894
|
+
const { layout, manifestPath, dockerAgentsDir, dockerSkillsDir } = targets;
|
|
882
895
|
fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
|
|
883
|
-
fs.writeFileSync(manifestPath, renderManifest(sorted), "utf8");
|
|
896
|
+
fs.writeFileSync(manifestPath, renderManifest(sorted, { layout }), "utf8");
|
|
884
897
|
fs.mkdirSync(dockerAgentsDir, { recursive: true });
|
|
885
898
|
const desiredFiles = /* @__PURE__ */ new Map();
|
|
886
899
|
for (const agent of sorted) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/lib/generators/extensions/agent-files.ts"],
|
|
4
|
-
"sourcesContent": ["import fs from 'node:fs'\nimport path from 'node:path'\nimport { countTokens } from '@open-mercato/shared/lib/ai/token-count'\nimport type { GeneratorExtension, ModuleScanContext } from '../extension'\nimport { resolveStandaloneSourceMirrorBase } from '../scanner'\n\n/**\n * The slice of `PackageResolver` this extension needs. Kept structural (rather\n * than importing the full interface) so the extension stays testable with a\n * literal and carries no dependency on the resolver module.\n */\nexport type AgentFilesResolver = {\n isMonorepo(): boolean\n getRootDir(): string\n getAppDir(): string\n getOutputDir(): string\n}\n\n/**\n * Generator extension for the `agents/<id>/` file-defined-agent convention\n * (AGENT.md + OUTCOME.md). For every enabled module it scans the module's\n * `agents/` tree, validates each agent dir, and emits two artifacts as a\n * deterministic fs side effect from `generateOutput()`:\n *\n * 1. The committed, git-tracked registry manifest\n * `packages/enterprise/src/modules/agent_orchestrator/generated/file-agents.generated.ts`\n * (raw JSON-Schema, recompiled to Zod at load by `ensureAgentsLoaded`).\n * 2. OpenCode agent `.md` files under `docker/opencode/agents/` (container\n * delivery: dev bind-mount, prod Dockerfile COPY).\n *\n * Both targets live OUTSIDE the app `.mercato/generated/` dir, so they are\n * written directly (not via the Map<filename,content> return, which targets the\n * app generated dir). `generateOutput()` therefore returns an empty Map.\n *\n * Generation FAILS (throws) on any malformed AGENT.md/OUTCOME.md/SKILL.md,\n * naming the offending dir (spec \u00A79). The CLI does not depend on\n * `@open-mercato/core`, so the small AGENT.md/OUTCOME.md/SKILL.md parsers are\n * reimplemented here; they MUST stay in sync with\n * `lib/sdk/{agentMarkdown,skillMarkdown,defineFileAgent}.ts`.\n *\n * Phase 3 also emits NATIVE OpenCode skill files under `docker/opencode/skills/`\n * (frontmatter `name` sanitized to `^[a-z0-9]+(-[a-z0-9]+)*$`, `description`\n * required, body = skill instructions) and unions skill-contributed read-only\n * tools into the agent allowlist (manifest + docker agent-file `tools` block).\n */\n\n/** One sandboxed script carried as plain data (Phase 5). */\ntype DiscoveredScript = {\n name: string\n source: string\n}\n\ntype DiscoveredSkill = {\n /** Skill id: frontmatter `id` or, when absent, the skill dir name. */\n id: string\n description: string\n instructions: string\n template?: string\n examples: string[]\n tools: string[]\n /** Sandboxed helper scripts (`scripts/*.ts`), Phase 5. */\n scripts: DiscoveredScript[]\n /** OpenCode native skill name (sanitized to ^[a-z0-9]+(-[a-z0-9]+)*$). */\n openCodeSkillName: string\n}\n\ntype DiscoveredAgent = {\n moduleId: string\n dir: string\n id: string\n label: string\n description: string\n instructions: string\n resultKind: 'research' | 'proposal' | 'artifact'\n /** Absent for `kind: artifact`, whose result envelope is fixed. */\n outcomeSchema?: Record<string, unknown>\n /** OUTCOME.md prose after the JSON-Schema fence \u2014 injected into the agent prompt. */\n outcomeProse: string\n /** Effective allowlist: AGENT.md tools \u222A skill-contributed read-only tools. */\n tools: string[]\n skills: string[]\n subAgents: string[]\n openCodeAgentName: string\n /** Resolved agent-local skill content (Phase 3). */\n skillsContent: DiscoveredSkill[]\n /**\n * Resolved sub-agents under `sub-agents/<subid>/` (Phase 4). Each is a full\n * file agent, constrained to research + non-delegating. Empty for a\n * sub-agent itself (depth cap = 1) and for primaries with no sub-agents.\n */\n subAgentsContent: DiscoveredAgent[]\n /** `'primary'` (default) or `'subagent'` for a discovered sub-agent. */\n mode: 'primary' | 'subagent'\n maxSteps?: number\n provider?: string\n model?: string\n /** Optional `SAMPLE.json` example input for the Playground \"Insert sample\" button. */\n sampleInput?: unknown\n /** Optional `FACTS.json` declarations driving the Caseload facts panel. */\n facts?: DiscoveredFact[]\n /** Baked token-usage breakdown of the agent's construction files (Phase: token accounting). */\n tokenUsage: FileAgentTokenUsage\n /** Baked raw content of every construction file, for the read-only Files tab (#12 files). */\n sourceFiles: FileAgentSourceFile[]\n}\n\n/**\n * Raw definition file baked into the manifest so the Files tab reads agent source\n * without runtime fs access. MIRRORS `FileAgentFile` in\n * `packages/enterprise/.../lib/tokens/types.ts` \u2014 the CLI cannot import the\n * enterprise package, so the shape is reimplemented here and MUST stay in sync.\n */\ntype FileAgentSourceFile = {\n path: string\n content: string\n tokens: number\n inContext: boolean\n}\n\n/**\n * Token-usage shape MIRRORED from\n * `packages/enterprise/src/modules/agent_orchestrator/lib/tokens/types.ts`. The\n * CLI cannot import `@open-mercato/enterprise`, so both the type and the walker\n * below are reimplemented here and MUST stay in sync \u2014 a parity test in the\n * enterprise module (`agent-token-usage.test.ts`) guards the numbers.\n */\ntype TokenizedFile = { path: string; tokens: number }\ntype SkillTokenUsage = { id: string; tokens: number; files: TokenizedFile[] }\ntype ToolTokenUsage = { name: string; path: string; tokens: number }\ntype SubAgentTokenUsage = { id: string; tokens: number }\ntype FileAgentTokenUsage = {\n total: number\n self: number\n agent: number\n outcome: number\n skills: SkillTokenUsage[]\n tools: ToolTokenUsage[]\n subAgents: SubAgentTokenUsage[]\n}\n\ntype DiscoveredFact = {\n label: string\n source: 'input' | 'payload' | 'output'\n path: string\n format?: 'text' | 'number' | 'boolean' | 'percent'\n}\n\nconst FRONTMATTER_RE = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n?([\\s\\S]*)$/\nconst JSON_FENCE_RE = /```json\\s*\\n([\\s\\S]*?)\\n```/\nconst LIST_KEYS = ['tools', 'skills', 'subAgents'] as const\n\nfunction stripQuotes(value: string): string {\n return value.trim().replace(/^['\"]/, '').replace(/['\"]$/, '').trim()\n}\n\nfunction parseInlineList(rawValue: string): string[] {\n return rawValue\n .replace(/^\\[/, '')\n .replace(/\\]$/, '')\n .split(',')\n .map((entry) => stripQuotes(entry))\n .filter(Boolean)\n}\n\ntype AgentFrontmatter = {\n id?: string\n label?: string\n description?: string\n provider?: string\n model?: string\n tools: string[]\n skills: string[]\n subAgents: string[]\n maxSteps?: number\n instructions: string\n}\n\nfunction parseAgentMarkdown(raw: string): AgentFrontmatter | null {\n const match = FRONTMATTER_RE.exec(raw)\n if (!match) return null\n const [, frontmatterBlock, body] = match\n const meta: AgentFrontmatter = { tools: [], skills: [], subAgents: [], instructions: body.trim() }\n const lines = frontmatterBlock.split('\\n')\n let index = 0\n while (index < lines.length) {\n const line = lines[index]\n if (!line.trim()) {\n index += 1\n continue\n }\n const lineMatch = /^([A-Za-z0-9_]+):\\s*(.*)$/.exec(line)\n if (!lineMatch) {\n index += 1\n continue\n }\n const key = lineMatch[1]\n const rawValue = lineMatch[2].trim()\n if ((LIST_KEYS as readonly string[]).includes(key)) {\n const listKey = key as (typeof LIST_KEYS)[number]\n if (rawValue.startsWith('[')) {\n meta[listKey] = parseInlineList(rawValue)\n index += 1\n continue\n }\n const items: string[] = []\n index += 1\n while (index < lines.length && /^\\s*-\\s+/.test(lines[index])) {\n items.push(stripQuotes(lines[index].replace(/^\\s*-\\s+/, '')))\n index += 1\n }\n meta[listKey] = items.filter(Boolean)\n continue\n }\n if (key === 'maxSteps') {\n const parsed = Number.parseInt(stripQuotes(rawValue), 10)\n if (!Number.isNaN(parsed)) meta.maxSteps = parsed\n index += 1\n continue\n }\n if (key === 'id' || key === 'label' || key === 'description' || key === 'provider' || key === 'model') {\n meta[key] = stripQuotes(rawValue)\n }\n index += 1\n }\n if (!meta.id || !meta.label || !meta.description) return null\n return meta\n}\n\nfunction parseOutcomeKind(frontmatterBlock: string): 'research' | 'proposal' | 'artifact' | null {\n for (const line of frontmatterBlock.split('\\n')) {\n const match = /^kind:\\s*(.*)$/.exec(line.trim())\n if (!match) continue\n const value = stripQuotes(match[1])\n if (value === 'research' || value === 'proposal' || value === 'artifact') return value\n return null\n }\n return null\n}\n\nfunction parseOutcomeMarkdown(\n raw: string,\n): {\n kind: 'research' | 'proposal' | 'artifact'\n schema?: Record<string, unknown>\n prose: string\n} | null {\n const frontmatterMatch = FRONTMATTER_RE.exec(raw)\n if (!frontmatterMatch) return null\n const [, frontmatterBlock, body] = frontmatterMatch\n const kind = parseOutcomeKind(frontmatterBlock)\n if (!kind) return null\n const fenceMatch = JSON_FENCE_RE.exec(body)\n // An artifact agent declares no schema \u2014 its envelope is the fixed file list \u2014\n // so its whole OUTCOME.md is guidance.\n if (!fenceMatch) {\n return kind === 'artifact' ? { kind, prose: body.trim() } : null\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(fenceMatch[1])\n } catch {\n return null\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null\n const prose = body.slice(fenceMatch.index + fenceMatch[0].length).trim()\n return { kind, schema: parsed as Record<string, unknown>, prose }\n}\n\n// Keep in sync with `agent_orchestrator/lib/sdk/outcomeSchema.ts` (the CLI cannot\n// import @open-mercato/core). Mirrors `jsonSchemaToZod`'s supported subset so a\n// schema that parses as JSON but could NOT compile to Zod fails generation LOUDLY\n// here, instead of parsing fine and being silently dropped at load time (M2).\nconst OUTCOME_UNSUPPORTED_KEYWORDS = [\n 'oneOf', 'anyOf', 'allOf', 'not', '$ref', 'format', 'patternProperties', 'pattern',\n 'additionalItems', 'propertyNames', 'if', 'then', 'else',\n] as const\nconst OUTCOME_SUPPORTED_TYPES = ['object', 'array', 'string', 'number', 'integer', 'boolean']\n\n/** Throw (failing `yarn generate`) when an OUTCOME schema node is outside the supported subset. */\nfunction assertOutcomeSchemaSupported(node: unknown, where: string, path = '$'): void {\n if (typeof node !== 'object' || node === null || Array.isArray(node)) {\n throw new Error(`[internal] malformed OUTCOME.md at ${where}: schema node at ${path} must be an object`)\n }\n const schema = node as Record<string, unknown>\n for (const keyword of OUTCOME_UNSUPPORTED_KEYWORDS) {\n if (keyword in schema) {\n throw new Error(`[internal] malformed OUTCOME.md at ${where}: unsupported keyword \"${keyword}\" at ${path}`)\n }\n }\n if ('const' in schema) return\n const type = schema.type\n if (typeof type !== 'string' || !OUTCOME_SUPPORTED_TYPES.includes(type)) {\n throw new Error(`[internal] malformed OUTCOME.md at ${where}: missing/unsupported \"type\" at ${path}`)\n }\n if (type === 'object' && schema.properties != null) {\n if (typeof schema.properties !== 'object' || schema.properties === null || Array.isArray(schema.properties)) {\n throw new Error(`[internal] malformed OUTCOME.md at ${where}: \"properties\" at ${path} must be an object`)\n }\n for (const [key, child] of Object.entries(schema.properties as Record<string, unknown>)) {\n assertOutcomeSchemaSupported(child, where, `${path}.${key}`)\n }\n }\n if (type === 'array') {\n if (schema.items == null) {\n throw new Error(`[internal] malformed OUTCOME.md at ${where}: array at ${path} requires \"items\"`)\n }\n assertOutcomeSchemaSupported(schema.items, where, `${path}[]`)\n }\n}\n\nfunction sanitizeAgentName(id: string): string {\n return id.replace(/[^a-z0-9_-]/gi, '_')\n}\n\n/**\n * Read the optional `agents/<id>/SAMPLE.json` example input emitted into the\n * manifest for the Playground \"Insert sample\" button. Pure JSON (no markdown),\n * so a missing file is fine; a malformed one fails generation LOUDLY (naming the\n * dir) rather than being silently dropped. Must stay in sync with\n * `lib/sdk/defineFileAgent.ts` `loadSampleInput`.\n */\nfunction discoverSampleInput(dir: string): unknown {\n const samplePath = path.join(dir, 'SAMPLE.json')\n if (!fs.existsSync(samplePath)) return undefined\n try {\n return JSON.parse(fs.readFileSync(samplePath, 'utf8'))\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new Error(`[internal] malformed SAMPLE.json at ${dir}: ${detail}`)\n }\n}\n\nconst FACT_SOURCES = ['input', 'payload', 'output'] as const\nconst FACT_FORMATS = ['text', 'number', 'boolean', 'percent'] as const\n\n/**\n * Read the optional `agents/<id>/FACTS.json` declarations that drive the\n * Caseload decision panel's facts grid (label + dot-path into the run input,\n * proposal payload, or run output). Accepts `{ \"facts\": [...] }` or a bare\n * array. A missing file is fine; a malformed one fails generation LOUDLY\n * (naming the dir). Must stay in sync with `lib/sdk/defineFileAgent.ts`\n * `loadFacts`.\n */\nfunction discoverFacts(dir: string): DiscoveredFact[] | undefined {\n const factsPath = path.join(dir, 'FACTS.json')\n if (!fs.existsSync(factsPath)) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(fs.readFileSync(factsPath, 'utf8'))\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new Error(`[internal] malformed FACTS.json at ${dir}: ${detail}`)\n }\n const entries = Array.isArray(parsed)\n ? parsed\n : parsed && typeof parsed === 'object' && Array.isArray((parsed as { facts?: unknown }).facts)\n ? ((parsed as { facts: unknown[] }).facts)\n : null\n if (!entries) {\n throw new Error(`[internal] malformed FACTS.json at ${dir}: expected an array or { \"facts\": [...] }`)\n }\n return entries.map((entry, index) => {\n const fact = entry as Partial<DiscoveredFact> | null\n if (\n !fact ||\n typeof fact.label !== 'string' ||\n !fact.label.trim() ||\n typeof fact.path !== 'string' ||\n !fact.path.trim() ||\n !FACT_SOURCES.includes(fact.source as (typeof FACT_SOURCES)[number])\n ) {\n throw new Error(\n `[internal] malformed FACTS.json at ${dir}: entry ${index} needs label (string), source (${FACT_SOURCES.join('|')}), path (string)`,\n )\n }\n if (fact.format !== undefined && !FACT_FORMATS.includes(fact.format as (typeof FACT_FORMATS)[number])) {\n throw new Error(\n `[internal] malformed FACTS.json at ${dir}: entry ${index} format must be one of ${FACT_FORMATS.join('|')}`,\n )\n }\n return {\n label: fact.label.trim(),\n source: fact.source as DiscoveredFact['source'],\n path: fact.path.trim(),\n ...(fact.format !== undefined ? { format: fact.format as DiscoveredFact['format'] } : {}),\n }\n })\n}\n\n/**\n * Sanitize a skill id into an OpenCode native skill `name`, which must match\n * `^[a-z0-9]+(-[a-z0-9]+)*$`: lowercase, underscores/dots/spaces \u2192 hyphens,\n * any other char \u2192 hyphen, collapse runs, trim leading/trailing hyphens. Must\n * stay in sync with the loader's interpretation of skill ids.\n */\nfunction sanitizeSkillName(id: string): string {\n const name = id\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+/, '')\n .replace(/-+$/, '')\n return name || 'skill'\n}\n\ntype SkillFrontmatter = {\n id?: string\n label?: string\n description?: string\n tools: string[]\n}\n\n/**\n * Parse an agent-local SKILL.md frontmatter (in sync with\n * `lib/sdk/skillMarkdown.ts`). Agent-local skills may omit `moduleId` and `id`\n * (the dir name is then authoritative); only a parseable frontmatter block is\n * required. Returns null when there is no frontmatter block.\n */\nfunction parseSkillMarkdown(raw: string): { meta: SkillFrontmatter; body: string } | null {\n const match = FRONTMATTER_RE.exec(raw)\n if (!match) return null\n const [, frontmatterBlock, body] = match\n const meta: SkillFrontmatter = { tools: [] }\n const lines = frontmatterBlock.split('\\n')\n let index = 0\n while (index < lines.length) {\n const line = lines[index]\n if (!line.trim()) {\n index += 1\n continue\n }\n const lineMatch = /^([A-Za-z0-9_]+):\\s*(.*)$/.exec(line)\n if (!lineMatch) {\n index += 1\n continue\n }\n const key = lineMatch[1]\n const rawValue = lineMatch[2].trim()\n if (key === 'tools') {\n if (rawValue.startsWith('[')) {\n meta.tools = parseInlineList(rawValue)\n index += 1\n continue\n }\n const items: string[] = []\n index += 1\n while (index < lines.length && /^\\s*-\\s+/.test(lines[index])) {\n items.push(stripQuotes(lines[index].replace(/^\\s*-\\s+/, '')))\n index += 1\n }\n meta.tools = items.filter(Boolean)\n continue\n }\n if (key === 'id' || key === 'label' || key === 'description') {\n meta[key] = stripQuotes(rawValue)\n }\n index += 1\n }\n return { meta, body: body.trim() }\n}\n\nfunction listExampleBodies(skillDir: string): string[] {\n const examplesDir = path.join(skillDir, 'examples')\n if (!fs.existsSync(examplesDir) || !fs.statSync(examplesDir).isDirectory()) return []\n return fs\n .readdirSync(examplesDir)\n .filter((name) => name.endsWith('.md'))\n .sort((a, b) => a.localeCompare(b))\n .map((name) => fs.readFileSync(path.join(examplesDir, name), 'utf8').trim())\n .filter(Boolean)\n}\n\n/**\n * Basic parse validation of a script source (Phase 5). The script runs in the\n * `isolated-vm` sandbox server-side (never copied to the container), so we only\n * cheaply assert it defines a `run` function \u2014 a missing `run` would fail at\n * runtime, so we fail generation early naming the file. We do NOT execute it.\n */\nfunction validateScriptSource(file: string, source: string): void {\n const definesRun = /(^|\\b)(async\\s+)?function\\s+run\\b/.test(source) || /\\brun\\s*=/.test(source)\n if (!definesRun) {\n throw new Error(\n `[internal] malformed agent script at ${file}: must define a \\`run(args)\\` function`,\n )\n }\n}\n\n/**\n * Read sandboxed scripts from a `scripts/` dir (`*.ts` / `*.js`), Phase 5. Each\n * file's basename (no extension) is the script name; the raw source is carried\n * as plain data. Validates each parses (basic). Ordered by filename.\n */\nfunction listScripts(scriptsDir: string): DiscoveredScript[] {\n if (!fs.existsSync(scriptsDir) || !fs.statSync(scriptsDir).isDirectory()) return []\n const scripts: DiscoveredScript[] = []\n for (const name of fs\n .readdirSync(scriptsDir)\n .filter((entry) => entry.endsWith('.ts') || entry.endsWith('.js'))\n .sort((a, b) => a.localeCompare(b))) {\n const file = path.join(scriptsDir, name)\n const source = fs.readFileSync(file, 'utf8')\n validateScriptSource(file, source)\n scripts.push({ name: name.replace(/\\.(ts|js)$/, ''), source })\n }\n return scripts\n}\n\n/** Synthetic skill id under which an agent's LOCAL sandboxed tool files register. */\nconst AGENT_TOOLS_SKILL_ID = '__agent_tools__'\nconst TOOL_REF_RE = /^\\s*\\/\\/\\s*@ref:?\\s+(\\S+)/\n\n/**\n * Discover `agents/<id>/tools/*.ts` local tool files (Phase 5). Reference-form\n * files (first line `// @ref <defineAiTool id>`) contribute the id to `refs`\n * (unioned into the allowlist, flows through the central ACL + propose-only\n * gate). Any other file is a LOCAL sandboxed tool: carried as a script run via\n * `run_skill_script` under the synthetic `__agent_tools__` skill. Must stay in\n * sync with `lib/sdk/defineFileAgent.ts` `loadToolFiles`.\n */\nfunction discoverToolFiles(agentDir: string): { refs: string[]; scripts: DiscoveredScript[] } {\n const toolsBase = path.join(agentDir, 'tools')\n if (!fs.existsSync(toolsBase) || !fs.statSync(toolsBase).isDirectory()) {\n return { refs: [], scripts: [] }\n }\n const refs: string[] = []\n const scripts: DiscoveredScript[] = []\n for (const name of fs\n .readdirSync(toolsBase)\n .filter((entry) => entry.endsWith('.ts') || entry.endsWith('.js'))\n .sort((a, b) => a.localeCompare(b))) {\n const file = path.join(toolsBase, name)\n const source = fs.readFileSync(file, 'utf8')\n const firstLine = source.split('\\n', 1)[0] ?? ''\n const refMatch = TOOL_REF_RE.exec(firstLine)\n if (refMatch) {\n refs.push(refMatch[1])\n continue\n }\n validateScriptSource(file, source)\n scripts.push({ name: name.replace(/\\.(ts|js)$/, ''), source })\n }\n return { refs, scripts }\n}\n\n/**\n * Discover the agent's referenced skills under `agents/<id>/skills/<skill_id>/`.\n * For each id in AGENT.md `skills:` we look up the matching dir (by frontmatter\n * id or dir name). FAILS generation when a referenced SKILL.md is malformed\n * (present dir but unparseable frontmatter). A referenced id with no dir is\n * skipped (the loader warns identically at runtime).\n */\nfunction discoverAgentSkills(agentDir: string, skillIds: string[]): DiscoveredSkill[] {\n if (skillIds.length === 0) return []\n const skillsBase = path.join(agentDir, 'skills')\n if (!fs.existsSync(skillsBase) || !fs.statSync(skillsBase).isDirectory()) return []\n\n const bySkillId = new Map<string, DiscoveredSkill>()\n for (const entry of fs.readdirSync(skillsBase, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue\n const skillDir = path.join(skillsBase, entry.name)\n const skillPath = path.join(skillDir, 'SKILL.md')\n if (!fs.existsSync(skillPath)) continue\n const parsed = parseSkillMarkdown(fs.readFileSync(skillPath, 'utf8'))\n if (!parsed) {\n throw new Error(`[internal] malformed SKILL.md at ${skillDir}: missing frontmatter block`)\n }\n const id = parsed.meta.id || entry.name\n const templatePath = path.join(skillDir, 'TEMPLATE.md')\n const template = fs.existsSync(templatePath)\n ? fs.readFileSync(templatePath, 'utf8').trim() || undefined\n : undefined\n bySkillId.set(id, {\n id,\n description: parsed.meta.description ?? '',\n instructions: parsed.body,\n template,\n examples: listExampleBodies(skillDir),\n tools: parsed.meta.tools,\n scripts: listScripts(path.join(skillDir, 'scripts')),\n openCodeSkillName: sanitizeSkillName(id),\n })\n }\n\n const resolved: DiscoveredSkill[] = []\n for (const skillId of skillIds) {\n const skill = bySkillId.get(skillId)\n if (skill) resolved.push(skill)\n }\n return resolved\n}\n\n/**\n * Discover and validate the sub-agents under `agents/<id>/sub-agents/<subid>/`\n * (Phase 4). Each is a full file agent (AGENT.md + OUTCOME.md) constrained to:\n * 1. OUTCOME `kind: research` (sub-agents inform; only the primary proposes);\n * 2. NO `subAgents` of its own (depth cap = 1).\n * FAILS generation (throws, naming the dir) on a malformed sub-agent OR a\n * constraint violation \u2014 in sync with `lib/sdk/defineFileAgent.ts` `loadSubAgentDir`.\n */\nfunction discoverSubAgents(agentDir: string): DiscoveredAgent[] {\n const base = path.join(agentDir, 'sub-agents')\n if (!fs.existsSync(base) || !fs.statSync(base).isDirectory()) return []\n const subAgents: DiscoveredAgent[] = []\n for (const entry of fs.readdirSync(base, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.name === '__tests__') continue\n const dir = path.join(base, entry.name)\n const agentMdPath = path.join(dir, 'AGENT.md')\n const outcomePath = path.join(dir, 'OUTCOME.md')\n if (!fs.existsSync(agentMdPath) || !fs.existsSync(outcomePath)) {\n throw new Error(\n `[internal] malformed sub-agent at ${dir}: both AGENT.md and OUTCOME.md are required`,\n )\n }\n const agent = parseAgentMarkdown(fs.readFileSync(agentMdPath, 'utf8'))\n if (!agent) {\n throw new Error(`[internal] malformed AGENT.md at ${dir}: missing id/label/description`)\n }\n const outcome = parseOutcomeMarkdown(fs.readFileSync(outcomePath, 'utf8'))\n if (!outcome) {\n throw new Error(`[internal] malformed OUTCOME.md at ${dir}: missing kind or JSON-Schema block`)\n }\n if (outcome.schema) assertOutcomeSchemaSupported(outcome.schema, dir)\n if (outcome.kind !== 'research') {\n throw new Error(\n `[internal] sub-agent at ${dir} must be research (kind: research); only the primary proposes`,\n )\n }\n if (agent.subAgents.length > 0) {\n throw new Error(\n `[internal] sub-agent at ${dir} may not declare subAgents (depth cap = 1); sub-agents may not delegate further`,\n )\n }\n const skillsContent = discoverAgentSkills(dir, agent.skills)\n const skillTools = skillsContent.flatMap((skill) => skill.tools)\n const toolFiles = discoverToolFiles(dir)\n const effectiveSkillsContent =\n toolFiles.scripts.length > 0\n ? [\n ...skillsContent,\n {\n id: AGENT_TOOLS_SKILL_ID,\n description: '',\n instructions: '',\n examples: [],\n tools: [],\n scripts: toolFiles.scripts,\n openCodeSkillName: sanitizeSkillName(AGENT_TOOLS_SKILL_ID),\n },\n ]\n : skillsContent\n const effectiveTools = Array.from(\n new Set([...agent.tools, ...skillTools, ...toolFiles.refs]),\n )\n subAgents.push({\n moduleId: '',\n dir,\n id: agent.id!,\n label: agent.label!,\n description: agent.description!,\n instructions: agent.instructions,\n resultKind: outcome.kind,\n outcomeSchema: outcome.schema,\n outcomeProse: outcome.prose,\n tools: effectiveTools,\n skills: agent.skills,\n subAgents: [],\n openCodeAgentName: sanitizeAgentName(agent.id!),\n skillsContent: effectiveSkillsContent,\n subAgentsContent: [],\n mode: 'subagent',\n maxSteps: agent.maxSteps,\n provider: agent.provider,\n model: agent.model,\n sampleInput: discoverSampleInput(dir),\n facts: discoverFacts(dir),\n tokenUsage: discoverAgentTokenUsage(dir),\n sourceFiles: collectAgentFiles(dir),\n })\n }\n return subAgents\n}\n\n// --- Token accounting (MIRRORS lib/tokens/computeAgentTokenUsage.ts) ---\n\nconst TOKEN_TOOL_EXTENSIONS = ['.ts', '.js']\n\n/**\n * MIRRORS `toPosixRelativePath` in lib/tokens/computeAgentTokenUsage.ts.\n *\n * These relative paths are baked into `file-agents.generated.ts` and split into\n * a folder tree in the browser, so they must be `/`-separated whatever machine\n * ran `yarn generate`. `path.join` answers with the native separator, which on\n * Windows baked backslashes into the artifact and flattened the Files tab.\n */\nfunction toPosixRelativePath(relativePath: string): string {\n return relativePath.split(path.sep).join('/')\n}\n\nfunction tokenCountFile(agentDir: string, relativePath: string): TokenizedFile | null {\n const absolute = path.join(agentDir, relativePath)\n if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) return null\n return { path: toPosixRelativePath(relativePath), tokens: countTokens(fs.readFileSync(absolute, 'utf8')) }\n}\n\nfunction tokenListFiles(dir: string, extensions?: string[]): string[] {\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return []\n return fs\n .readdirSync(dir, { withFileTypes: true })\n .filter((entry) => entry.isFile())\n .map((entry) => entry.name)\n .filter((name) => !extensions || extensions.includes(path.extname(name)))\n .sort((a, b) => a.localeCompare(b))\n}\n\nfunction tokenListDirs(dir: string): string[] {\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return []\n return fs\n .readdirSync(dir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && entry.name !== '__tests__')\n .map((entry) => entry.name)\n .sort((a, b) => a.localeCompare(b))\n}\n\nfunction tokenComputeSkills(agentDir: string): SkillTokenUsage[] {\n return tokenListDirs(path.join(agentDir, 'skills')).map((skillId) => {\n const skillRel = path.join('skills', skillId)\n const files: TokenizedFile[] = []\n for (const name of ['SKILL.md', 'TEMPLATE.md']) {\n const file = tokenCountFile(agentDir, path.join(skillRel, name))\n if (file) files.push(file)\n }\n for (const subdir of ['examples', 'scripts']) {\n for (const name of tokenListFiles(path.join(agentDir, skillRel, subdir))) {\n const file = tokenCountFile(agentDir, path.join(skillRel, subdir, name))\n if (file) files.push(file)\n }\n }\n return { id: skillId, tokens: files.reduce((sum, f) => sum + f.tokens, 0), files }\n })\n}\n\nfunction tokenComputeTools(agentDir: string): ToolTokenUsage[] {\n return tokenListFiles(path.join(agentDir, 'tools'), TOKEN_TOOL_EXTENSIONS).map((name) => {\n const rel = path.join('tools', name)\n return {\n name: name.replace(/\\.[^.]+$/, ''),\n path: toPosixRelativePath(rel),\n tokens: countTokens(fs.readFileSync(path.join(agentDir, rel), 'utf8')),\n }\n })\n}\n\nfunction discoverAgentTokenUsage(agentDir: string, depth = 0): FileAgentTokenUsage {\n const agent = tokenCountFile(agentDir, 'AGENT.md')?.tokens ?? 0\n const outcome = tokenCountFile(agentDir, 'OUTCOME.md')?.tokens ?? 0\n const skills = tokenComputeSkills(agentDir)\n const tools = tokenComputeTools(agentDir)\n\n const subAgents: SubAgentTokenUsage[] = []\n if (depth === 0) {\n for (const subId of tokenListDirs(path.join(agentDir, 'sub-agents'))) {\n const nested = discoverAgentTokenUsage(path.join(agentDir, 'sub-agents', subId), depth + 1)\n subAgents.push({ id: subId, tokens: nested.total })\n }\n }\n\n const self =\n agent +\n outcome +\n skills.reduce((sum, s) => sum + s.tokens, 0) +\n tools.reduce((sum, t) => sum + t.tokens, 0)\n const total = self + subAgents.reduce((sum, s) => sum + s.tokens, 0)\n\n return { total, self, agent, outcome, skills, tools, subAgents }\n}\n\n// --- Raw source-file collection (feeds the read-only Files tab, #12 files) ---\n\n/** Files present at the agent root but NOT part of the constructed prompt. */\nconst AGENT_AUX_FILES = ['SAMPLE.json', 'FACTS.json']\n\n/**\n * Walks every construction file of a file-defined agent and returns its raw\n * content + `o200k_base` token count, paths relative to the agent root. Recurses\n * `sub-agents/<id>/` once (depth cap = 1, matching `discoverAgentTokenUsage`),\n * prefixing nested paths with `sub-agents/<id>/`. The `inContext` sum of a tree\n * equals `discoverAgentTokenUsage(...).total`, so the Files tab and the baked\n * token estimate stay consistent.\n */\nfunction collectAgentFiles(agentDir: string, prefix = '', depth = 0): FileAgentSourceFile[] {\n const files: FileAgentSourceFile[] = []\n const add = (relativePath: string, inContext: boolean): void => {\n const absolute = path.join(agentDir, relativePath)\n if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) return\n const content = fs.readFileSync(absolute, 'utf8')\n files.push({ path: toPosixRelativePath(path.join(prefix, relativePath)), content, tokens: countTokens(content), inContext })\n }\n add('AGENT.md', true)\n add('OUTCOME.md', true)\n for (const name of AGENT_AUX_FILES) add(name, false)\n for (const skillId of tokenListDirs(path.join(agentDir, 'skills'))) {\n const skillRel = path.join('skills', skillId)\n for (const name of ['SKILL.md', 'TEMPLATE.md']) add(path.join(skillRel, name), true)\n for (const subdir of ['examples', 'scripts']) {\n for (const name of tokenListFiles(path.join(agentDir, skillRel, subdir))) {\n add(path.join(skillRel, subdir, name), true)\n }\n }\n }\n for (const name of tokenListFiles(path.join(agentDir, 'tools'), TOKEN_TOOL_EXTENSIONS)) {\n add(path.join('tools', name), true)\n }\n if (depth === 0) {\n for (const subId of tokenListDirs(path.join(agentDir, 'sub-agents'))) {\n files.push(\n ...collectAgentFiles(\n path.join(agentDir, 'sub-agents', subId),\n path.join(prefix, 'sub-agents', subId),\n depth + 1,\n ),\n )\n }\n }\n return files\n}\n\nfunction renderOpenCodeSkillFile(skill: DiscoveredSkill): string {\n const frontmatter = [\n '---',\n `name: ${skill.openCodeSkillName}`,\n `description: ${JSON.stringify(skill.description)}`,\n '---',\n ]\n return `${frontmatter.join('\\n')}\\n${skill.instructions.trim()}\\n`\n}\n\n/** Walk up from a known in-repo path until a dir containing both `docker` and `packages` is found. */\nfunction findRepoRoot(start: string): string | null {\n let current = path.resolve(start)\n for (let depth = 0; depth < 40; depth += 1) {\n if (\n fs.existsSync(path.join(current, 'docker', 'opencode')) &&\n fs.existsSync(path.join(current, 'packages'))\n ) {\n return current\n }\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n return null\n}\n\n/**\n * Where this extension's three artifacts land. The two layouts differ because a\n * standalone app has no `packages/` tree to host the manifest: the enterprise\n * module lives under `node_modules/`, which `yarn install` rewrites.\n *\n * | Artifact | Monorepo | Standalone |\n * |-----------|------------------------------------------------------------|-------------------------------------------|\n * | manifest | `packages/enterprise/src/modules/agent_orchestrator/generated/` | `<app>/.mercato/generated/` |\n * | agents/ | `<repo>/docker/opencode/agents/` | `<app>/docker/opencode/agents/` |\n * | skills/ | `<repo>/docker/opencode/skills/` | `<app>/docker/opencode/skills/` |\n *\n * The standalone manifest sits in the generated output dir that\n * `findGeneratedFile()` already probes (`generated-registry-loader.ts` resolves\n * `<cwd>/.mercato/generated/<file>` for exactly this case), so the runtime\n * loader reaches it with no new resolution logic. It is regenerated on every\n * `yarn generate`, which both `scripts/dev.mjs` setup and\n * `docker/scripts/init-or-migrate.sh` run before the app boots.\n */\ntype AgentFilesTargets = {\n manifestPath: string\n dockerAgentsDir: string\n dockerSkillsDir: string\n}\n\nfunction resolveAgentFilesTargets(\n resolver: AgentFilesResolver | undefined,\n fallbackRepoRoot: string | null,\n): AgentFilesTargets | null {\n if (resolver && !resolver.isMonorepo()) {\n const appDir = resolver.getAppDir()\n return {\n manifestPath: path.join(resolver.getOutputDir(), 'file-agents.generated.ts'),\n dockerAgentsDir: path.join(appDir, 'docker', 'opencode', 'agents'),\n dockerSkillsDir: path.join(appDir, 'docker', 'opencode', 'skills'),\n }\n }\n // Monorepo. Prefer the resolver's root, falling back to the walk-up probe so\n // unit tests that construct the extension without a resolver keep working.\n const repoRoot = resolver?.getRootDir() ?? fallbackRepoRoot\n if (!repoRoot) return null\n return {\n manifestPath: path.join(\n repoRoot,\n 'packages',\n 'enterprise',\n 'src',\n 'modules',\n 'agent_orchestrator',\n 'generated',\n 'file-agents.generated.ts',\n ),\n dockerAgentsDir: path.join(repoRoot, 'docker', 'opencode', 'agents'),\n dockerSkillsDir: path.join(repoRoot, 'docker', 'opencode', 'skills'),\n }\n}\n\nfunction listAgentDirs(agentsBase: string): string[] {\n if (!fs.existsSync(agentsBase)) return []\n return fs\n .readdirSync(agentsBase, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && entry.name !== '__tests__')\n .map((entry) => path.join(agentsBase, entry.name))\n}\n\nfunction renderToolPermissionLine(toolName: string): string {\n return ` ${JSON.stringify(toolName)}: true`\n}\n\nconst ORCHESTRATOR_MODULE_ID = 'agent_orchestrator'\n// OpenCode names every MCP tool `<serverKey>_<toolName with dots\u2192underscores>`\n// (verified against the running image). Keep in sync with\n// `lib/sdk/defineFileAgent.ts`.\nconst OPENCODE_MCP_SERVER_KEY = 'open-mercato'\nconst CORE_FILE_AGENT_TOOL_IDS = [\n 'agent_orchestrator.submit_outcome',\n 'agent_orchestrator.load_skill',\n 'agent_orchestrator.run_skill_script',\n]\n/**\n * MCP tool a file-agent orchestrator uses to run a sub-agent SERVER-SIDE. We\n * route delegation through this tool instead of OpenCode's built-in `task` tool:\n * `task` spawns each sub-agent in a fresh session that never receives the run's\n * `_sessionToken`, so the sub-agent's MCP calls fail with `no_active_run`. The\n * delegate tool runs the sub-agent via `agentRuntime.run`, which mints its own\n * per-run session token + correlation, so sub-agent tool calls authenticate.\n */\nconst DELEGATE_AGENT_TOOL_ID = 'agent_orchestrator.delegate_agent'\nfunction toOpenCodeMcpToolId(omToolId: string): string {\n return `${OPENCODE_MCP_SERVER_KEY}_${omToolId.replace(/\\./g, '_')}`\n}\n\n/**\n * Render an OpenCode agent .md file. Must stay in sync with\n * `lib/sdk/defineFileAgent.ts` `renderOpenCodeAgentFile`. The built-in OpenCode\n * `task` tool is NEVER granted (`permission.task: deny` for every agent): it\n * spawns each sub-agent in a fresh session that does not inherit the run's\n * `_sessionToken`, so the sub-agent's MCP calls fail with `no_active_run`.\n * Instead, a primary that declares sub-agents is granted the\n * `agent_orchestrator.delegate_agent` MCP tool (runs each sub-agent server-side\n * under its own minted session token) and gains a \"Sub-agents\" prompt section\n * nudging parallel fan-out through that tool. Sub-agent files (`mode: subagent`)\n * get neither the delegate tool nor `task` (depth cap = 1).\n */\nfunction renderOpenCodeAgentFile(agent: DiscoveredAgent): string {\n const subAgentIds =\n agent.mode === 'primary' ? agent.subAgentsContent.map((sub) => sub.id) : []\n const hasSubAgents = subAgentIds.length > 0\n const omMcpToolIds = Array.from(\n new Set([\n ...agent.tools,\n ...CORE_FILE_AGENT_TOOL_IDS,\n ...(hasSubAgents ? [DELEGATE_AGENT_TOOL_ID] : []),\n ]),\n )\n const allowedTools = omMcpToolIds.map(toOpenCodeMcpToolId)\n const modelLine =\n agent.provider && agent.model\n ? `model: ${agent.provider}/${agent.model}`\n : agent.model\n ? `model: ${agent.model}`\n : null\n const frontmatterLines = [\n '---',\n `description: ${JSON.stringify(agent.description)}`,\n ...(modelLine ? [modelLine] : []),\n `mode: ${agent.mode}`,\n 'tools:',\n ' \"*\": false',\n ...allowedTools.map(renderToolPermissionLine),\n 'permission:',\n ' write: deny',\n ' edit: deny',\n ' bash: deny',\n ' task: deny',\n '---',\n ]\n const terminalInstruction =\n `Finish by calling the \\`${toOpenCodeMcpToolId('agent_orchestrator.submit_outcome')}\\` tool with a value matching the outcome contract (pass it as the \\`outcome\\` argument). You MUST call the tool \u2014 do not answer in prose or emit the result as a code block.`\n const delegateToolName = toOpenCodeMcpToolId(DELEGATE_AGENT_TOOL_ID)\n const subAgentSection = hasSubAgents\n ? `## Sub-agents\\nDelegate a sub-task by calling the \\`${delegateToolName}\\` tool with \\`{ agentId: \"<sub-agent id>\", input: <sub-task input object> }\\`. Issue multiple \\`${delegateToolName}\\` calls in the SAME step to fan out in parallel, then combine their results before submitting your outcome. Available sub-agents: ${subAgentIds.join(', ')}.`\n : null\n // Inject the OUTCOME contract so the agent SEES the exact shape it must submit\n // (otherwise it guesses and learns the shape only from validation errors). Keep\n // in sync with lib/sdk/defineFileAgent.ts renderOutcomeSection.\n const outcomeTarget = agent.resultKind === 'proposal' ? 'the `proposal` object' : 'the `data` object'\n const outcomeSection =\n agent.resultKind === 'artifact'\n ? [\n '## Outcome contract',\n \"Write the files you produce into the run's `out/` directory, then pass this shape as the `outcome` argument of the submit_outcome tool:\",\n '',\n '```json',\n JSON.stringify(\n {\n artifacts: [\n { fileName: 'report.pdf', mimeType: 'application/pdf', caption: 'What this file is' },\n ],\n summary: 'One sentence about what you produced.',\n },\n null,\n 2,\n ),\n '```',\n ...(agent.outcomeProse ? ['', agent.outcomeProse] : []),\n ].join('\\n')\n : [\n '## Outcome contract',\n `Your result MUST match this JSON Schema (${outcomeTarget}). Pass it as the \\`outcome\\` argument of the submit_outcome tool, as a JSON object (not a string):`,\n '',\n '```json',\n JSON.stringify(agent.outcomeSchema, null, 2),\n '```',\n ...(agent.outcomeProse ? ['', agent.outcomeProse] : []),\n ].join('\\n')\n const body = [\n agent.instructions.trim(),\n ...(subAgentSection ? [subAgentSection] : []),\n outcomeSection,\n terminalInstruction,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n return `${frontmatterLines.join('\\n')}\\n${body}\\n`\n}\n\n/**\n * Render one agent descriptor as a key-per-line object literal at `indent`.\n * Used for both top-level agents and nested sub-agents (Phase 4). A primary that\n * declares sub-agents emits them as a nested `subAgentDescriptors` array so\n * `ensureAgentsLoaded` can register each sub-agent too (research, individually\n * runnable file agents). A nested sub-agent carries no `subAgentDescriptors`\n * (depth cap = 1).\n */\nfunction renderDescriptor(agent: DiscoveredAgent, indent: string): string {\n const optional: string[] = []\n if (agent.subAgentsContent.length > 0) {\n const nested = agent.subAgentsContent\n .map((sub) => renderDescriptor(sub, `${indent} `))\n .join('\\n')\n optional.push(`${indent} subAgentDescriptors: [\\n${nested}\\n${indent} ],`)\n }\n if (agent.maxSteps != null) optional.push(`${indent} maxSteps: ${agent.maxSteps},`)\n if (agent.provider != null) optional.push(`${indent} provider: ${JSON.stringify(agent.provider)},`)\n if (agent.model != null) optional.push(`${indent} model: ${JSON.stringify(agent.model)},`)\n if (agent.sampleInput !== undefined) {\n optional.push(`${indent} sampleInput: ${JSON.stringify(agent.sampleInput)},`)\n }\n if (agent.facts !== undefined) {\n optional.push(`${indent} facts: ${JSON.stringify(agent.facts)},`)\n }\n const skillsContent = agent.skillsContent.map((skill) => ({\n id: skill.id,\n instructions: skill.instructions,\n ...(skill.template != null ? { template: skill.template } : {}),\n examples: skill.examples,\n tools: skill.tools,\n ...(skill.scripts.length > 0 ? { scripts: skill.scripts } : {}),\n }))\n return [\n `${indent}{`,\n `${indent} id: ${JSON.stringify(agent.id)},`,\n `${indent} moduleId: ${JSON.stringify(agent.moduleId)},`,\n `${indent} label: ${JSON.stringify(agent.label)},`,\n `${indent} description: ${JSON.stringify(agent.description)},`,\n `${indent} instructions: ${JSON.stringify(agent.instructions)},`,\n `${indent} resultKind: ${JSON.stringify(agent.resultKind)},`,\n ...(agent.outcomeSchema ? [`${indent} outcomeSchema: ${JSON.stringify(agent.outcomeSchema)},`] : []),\n `${indent} tools: ${JSON.stringify(agent.tools)},`,\n `${indent} skills: ${JSON.stringify(agent.skills)},`,\n `${indent} subAgents: ${JSON.stringify(agent.subAgents)},`,\n `${indent} openCodeAgentName: ${JSON.stringify(agent.openCodeAgentName)},`,\n `${indent} skillsContent: ${JSON.stringify(skillsContent)},`,\n `${indent} tokenUsage: ${JSON.stringify(agent.tokenUsage)},`,\n `${indent} sourceFiles: ${JSON.stringify(agent.sourceFiles)},`,\n ...optional,\n `${indent}},`,\n ].join('\\n')\n}\n\nfunction renderManifest(agents: DiscoveredAgent[]): string {\n const descriptors = agents.map((agent) => renderDescriptor(agent, ' ')).join('\\n')\n\n return `// AUTO-GENERATED by mercato generate registry \u2014 DO NOT EDIT BY HAND.\n//\n// Committed, generator-owned manifest of file-defined (OpenCode) agents,\n// discovered from \\`agents/<id>/\\` directories across every enabled module. It\n// stores PLAIN data (raw JSON-Schema, not a Zod instance) so this file is pure\n// data and travels with the repo (survives \\`yarn clean-generated\\`).\n// \\`ensureAgentsLoaded()\\` recompiles each \\`outcomeSchema\\` to Zod via\n// \\`compileOutcome\\` at load time and registers it with \\`runtime:'opencode'\\`.\n//\n// Regenerate with \\`yarn generate\\`.\nimport type { JsonSchemaNode, OutcomeKind } from '../lib/sdk/outcomeSchema'\nimport type { AgentTokenUsage, FileAgentFile } from '../lib/tokens/types'\n\nexport type FileAgentScript = {\n name: string\n source: string\n}\n\nexport type FileAgentSkillContent = {\n id: string\n instructions: string\n template?: string\n examples: string[]\n tools: string[]\n /**\n * Sandboxed helper scripts (Phase 5). Carried as plain source; run server-side\n * in the Code Mode \\`isolated-vm\\` sandbox via the \\`run_skill_script\\` MCP tool.\n * Never copied to the OpenCode container. The synthetic skill id\n * \\`__agent_tools__\\` carries an agent's LOCAL \\`tools/*.ts\\` sources.\n */\n scripts?: FileAgentScript[]\n}\n\nexport type FileAgentFact = {\n /** Human label shown in the Caseload facts grid. */\n label: string\n /** Where to resolve the value: run input, proposal payload, or run output. */\n source: 'input' | 'payload' | 'output'\n /** Dot-path into the source (array indexes allowed), e.g. \"actions.0.payload.amount\". */\n path: string\n format?: 'text' | 'number' | 'boolean' | 'percent'\n}\n\nexport type FileAgentDescriptor = {\n id: string\n moduleId: string\n label: string\n description: string\n instructions: string\n resultKind: OutcomeKind\n outcomeSchema?: JsonSchemaNode\n tools: string[]\n skills: string[]\n subAgents: string[]\n openCodeAgentName: string\n skillsContent?: FileAgentSkillContent[]\n /**\n * Baked token-usage estimate of the agent's construction files (AGENT.md,\n * OUTCOME.md, skills, tools, sub-agents), counted with the shared\n * \\`o200k_base\\` tokenizer. Surfaced on the Agent detail page and the\n * \\`agent_orchestrator token-usage\\` CLI. An estimate, not an exact count.\n */\n tokenUsage?: AgentTokenUsage\n /**\n * Baked raw content of every construction file (AGENT.md, OUTCOME.md, skills,\n * tools, sub-agents, and auxiliary SAMPLE.json/FACTS.json), for the read-only\n * Files tab. Each carries its \\`o200k_base\\` token count; paths are relative to\n * the agent root (sub-agent files prefixed \\`sub-agents/<id>/\\`). Baked so the\n * runtime never reads agent dirs from disk.\n */\n sourceFiles?: FileAgentFile[]\n /**\n * Nested descriptors for this agent's sub-agents (Phase 4). Each is an\n * research-kind, non-delegating file agent registered individually (depth cap =\n * 1). Absent for agents without sub-agents and for sub-agents themselves.\n */\n subAgentDescriptors?: FileAgentDescriptor[]\n maxSteps?: number\n provider?: string\n model?: string\n /**\n * Optional example \\`input\\` for the Playground \"Insert sample\" button, read\n * from \\`agents/<id>/SAMPLE.json\\`. Any JSON value the agent accepts as input.\n */\n sampleInput?: unknown\n /**\n * Optional fact declarations for the Caseload decision panel, read from\n * \\`agents/<id>/FACTS.json\\`. Each maps a labelled dot-path into the run\n * input / proposal payload / run output.\n */\n facts?: FileAgentFact[]\n}\n\nexport const fileAgentDescriptors: FileAgentDescriptor[] = [${\n descriptors ? `\\n${descriptors}\\n` : ''\n }]\n`\n}\n\nexport function createAgentFilesExtension(resolver?: AgentFilesResolver): GeneratorExtension {\n const discovered: DiscoveredAgent[] = []\n const seenIds = new Set<string>()\n let repoRoot: string | null = null\n let sawOrchestratorModule = false\n\n function scanAgentsTree(moduleId: string, baseDir: string): void {\n for (const dir of listAgentDirs(baseDir)) {\n const agentMdPath = path.join(dir, 'AGENT.md')\n const outcomePath = path.join(dir, 'OUTCOME.md')\n // Only treat a dir as an agent if at least one convention file exists.\n const hasAgentMd = fs.existsSync(agentMdPath)\n const hasOutcome = fs.existsSync(outcomePath)\n if (!hasAgentMd && !hasOutcome) continue\n if (!hasAgentMd || !hasOutcome) {\n throw new Error(\n `[internal] malformed file agent at ${dir}: both AGENT.md and OUTCOME.md are required`,\n )\n }\n const agent = parseAgentMarkdown(fs.readFileSync(agentMdPath, 'utf8'))\n if (!agent) {\n throw new Error(`[internal] malformed AGENT.md at ${dir}: missing id/label/description`)\n }\n const outcome = parseOutcomeMarkdown(fs.readFileSync(outcomePath, 'utf8'))\n if (!outcome) {\n throw new Error(`[internal] malformed OUTCOME.md at ${dir}: missing kind or JSON-Schema block`)\n }\n if (outcome.schema) assertOutcomeSchemaSupported(outcome.schema, dir)\n // The id is the registry/dup key AND the OpenCode `agent` message field \u2014\n // constrain it to a safe charset (module.entity-style: lowercase alnum + . _ -).\n if (!/^[a-z0-9][a-z0-9._-]*$/.test(agent.id!)) {\n throw new Error(\n `[internal] invalid agent id \"${agent.id}\" at ${dir}: use lowercase [a-z0-9._-] (e.g. \"module.agent\")`,\n )\n }\n if (seenIds.has(agent.id!)) {\n // Surface accidental collisions at generate time instead of silently\n // dropping the later agent (the registry would only skip it at load).\n console.warn(`[internal] duplicate file-agent id \"${agent.id}\" at ${dir}; keeping the first, skipping this one.`)\n continue\n }\n seenIds.add(agent.id!)\n // Phase 3: resolve agent-local skills and UNION their read-only tools into\n // the agent allowlist (deduped), matching the loader.\n const skillsContent = discoverAgentSkills(dir, agent.skills)\n const skillTools = skillsContent.flatMap((skill) => skill.tools)\n // Phase 5: local tool files \u2014 reference ids union into the allowlist; local\n // sandboxed tool sources register under the synthetic `__agent_tools__` skill.\n const toolFiles = discoverToolFiles(dir)\n const effectiveSkillsContent =\n toolFiles.scripts.length > 0\n ? [\n ...skillsContent,\n {\n id: AGENT_TOOLS_SKILL_ID,\n description: '',\n instructions: '',\n examples: [],\n tools: [],\n scripts: toolFiles.scripts,\n openCodeSkillName: sanitizeSkillName(AGENT_TOOLS_SKILL_ID),\n },\n ]\n : skillsContent\n const effectiveTools = Array.from(\n new Set([...agent.tools, ...skillTools, ...toolFiles.refs]),\n )\n // Phase 4: discover + validate sub-agents (throws on a malformed/proposal/\n // self-delegating sub-agent).\n const subAgentsContent = discoverSubAgents(dir)\n discovered.push({\n moduleId,\n dir,\n id: agent.id!,\n label: agent.label!,\n description: agent.description!,\n instructions: agent.instructions,\n resultKind: outcome.kind,\n outcomeSchema: outcome.schema,\n outcomeProse: outcome.prose,\n tools: effectiveTools,\n skills: agent.skills,\n subAgents: agent.subAgents,\n openCodeAgentName: sanitizeAgentName(agent.id!),\n skillsContent: effectiveSkillsContent,\n subAgentsContent,\n mode: 'primary',\n maxSteps: agent.maxSteps,\n provider: agent.provider,\n model: agent.model,\n sampleInput: discoverSampleInput(dir),\n facts: discoverFacts(dir),\n tokenUsage: discoverAgentTokenUsage(dir),\n sourceFiles: collectAgentFiles(dir),\n })\n }\n }\n\n return {\n id: 'registry.agent-files',\n outputFiles: [],\n scanModule(ctx: ModuleScanContext) {\n if (ctx.moduleId === ORCHESTRATOR_MODULE_ID) sawOrchestratorModule = true\n if (!repoRoot) {\n repoRoot = findRepoRoot(ctx.roots.pkgBase) ?? findRepoRoot(ctx.roots.appBase)\n }\n const pkgScanBase = resolveStandaloneSourceMirrorBase(ctx.roots.pkgBase) ?? ctx.roots.pkgBase\n scanAgentsTree(ctx.moduleId, path.join(pkgScanBase, 'agents'))\n scanAgentsTree(ctx.moduleId, path.join(ctx.roots.appBase, 'agents'))\n },\n generateOutput() {\n const sorted = [...discovered].sort((a, b) => a.id.localeCompare(b.id))\n\n const targets = resolveAgentFilesTargets(resolver, repoRoot)\n\n if (!targets) {\n // No layout resolved (e.g. an isolated unit test constructing the\n // extension without a resolver and without in-repo module roots). Skip\n // the fs side effect; the empty-Map return keeps the contract intact.\n // Stay silent only when there is nothing to emit \u2014 otherwise the run\n // would drop real agents without saying so (the pre-2026-09 behaviour).\n if (sawOrchestratorModule || sorted.length > 0) {\n console.warn(\n '[agent-files] Could not resolve an output root, so the file-agent manifest and ' +\n 'docker/opencode/{agents,skills} were NOT written. ' +\n `Discovered ${sorted.length} file agent(s). ` +\n 'In a standalone app this means the generator ran without a package resolver.',\n )\n }\n return new Map<string, string>()\n }\n\n if (!sawOrchestratorModule && sorted.length === 0) {\n // Neither the orchestrator (the manifest's only consumer) nor any agent\n // module is part of this run \u2014 the enterprise agents flag is off. The\n // committed manifest and `docker/opencode/**` files belong to modules\n // that are merely switched off, so pruning them here would delete\n // tracked artifacts on every `yarn generate`. Leave the tree untouched.\n return new Map<string, string>()\n }\n\n const { manifestPath, dockerAgentsDir, dockerSkillsDir } = targets\n fs.mkdirSync(path.dirname(manifestPath), { recursive: true })\n fs.writeFileSync(manifestPath, renderManifest(sorted), 'utf8')\n\n fs.mkdirSync(dockerAgentsDir, { recursive: true })\n const desiredFiles = new Map<string, string>()\n for (const agent of sorted) {\n desiredFiles.set(`${agent.openCodeAgentName}.md`, renderOpenCodeAgentFile(agent))\n // Phase 4: emit each sub-agent as its own `mode: subagent` file so\n // OpenCode can reach it via the primary's whitelisted `task` tool.\n for (const sub of agent.subAgentsContent) {\n desiredFiles.set(`${sub.openCodeAgentName}.md`, renderOpenCodeAgentFile(sub))\n }\n }\n // Idempotent: remove stale generated agent files, write the current set.\n for (const existing of fs.existsSync(dockerAgentsDir) ? fs.readdirSync(dockerAgentsDir) : []) {\n if (existing.endsWith('.md') && !desiredFiles.has(existing)) {\n fs.rmSync(path.join(dockerAgentsDir, existing))\n }\n }\n for (const [fileName, content] of desiredFiles) {\n fs.writeFileSync(path.join(dockerAgentsDir, fileName), content, 'utf8')\n }\n\n // Phase 3: emit NATIVE OpenCode skill files (one dir per skill name) under\n // `docker/opencode/skills/<sanitized-skill-name>/SKILL.md`. Idempotent:\n // remove stale skill dirs not in the current desired set. Sub-agents\n // (Phase 4) may carry their own skills too, so flatten them in.\n const allAgents = sorted.flatMap((agent) => [agent, ...agent.subAgentsContent])\n // The synthetic `__agent_tools__` skill only carries an agent's local\n // `tools/*.ts` sources (run via `run_skill_script`); it has no instructions\n // and MUST NOT be emitted as a native OpenCode skill (OpenCode requires a\n // non-empty `description`, and it is not a progressive-disclosure skill).\n const isNativeSkill = (skill: { id: string }): boolean => skill.id !== AGENT_TOOLS_SKILL_ID\n const desiredSkillNames = new Set<string>()\n for (const agent of allAgents) {\n for (const skill of agent.skillsContent) {\n if (isNativeSkill(skill)) desiredSkillNames.add(skill.openCodeSkillName)\n }\n }\n if (desiredSkillNames.size > 0) fs.mkdirSync(dockerSkillsDir, { recursive: true })\n if (fs.existsSync(dockerSkillsDir)) {\n for (const existing of fs.readdirSync(dockerSkillsDir, { withFileTypes: true })) {\n if (existing.isDirectory() && !desiredSkillNames.has(existing.name)) {\n fs.rmSync(path.join(dockerSkillsDir, existing.name), { recursive: true, force: true })\n }\n }\n }\n const renderedSkillNames = new Set<string>()\n for (const agent of allAgents) {\n for (const skill of agent.skillsContent) {\n if (!isNativeSkill(skill)) continue\n // A skill name may be shared across agents; the first rendering wins\n // (content is keyed by name, deterministic by sorted agent order).\n if (renderedSkillNames.has(skill.openCodeSkillName)) continue\n renderedSkillNames.add(skill.openCodeSkillName)\n const skillDir = path.join(dockerSkillsDir, skill.openCodeSkillName)\n fs.mkdirSync(skillDir, { recursive: true })\n fs.writeFileSync(path.join(skillDir, 'SKILL.md'), renderOpenCodeSkillFile(skill), 'utf8')\n }\n }\n\n return new Map<string, string>()\n },\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,mBAAmB;AAE5B,SAAS,yCAAyC;AA+IlD,MAAM,iBAAiB;AACvB,MAAM,gBAAgB;AACtB,MAAM,YAAY,CA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,CAAC;AAC1C,aAAG,cAAc,KAAK,KAAK,UAAU,UAAU,GAAG,wBAAwB,KAAK,GAAG,MAAM;AAAA,QAC1F;AAAA,MACF;AAEA,aAAO,oBAAI,IAAoB;AAAA,IACjC;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["import fs from 'node:fs'\nimport path from 'node:path'\nimport { countTokens } from '@open-mercato/shared/lib/ai/token-count'\nimport type { GeneratorExtension, ModuleScanContext } from '../extension'\nimport { resolveStandaloneSourceMirrorBase } from '../scanner'\n\n/**\n * The slice of `PackageResolver` this extension needs. Kept structural (rather\n * than importing the full interface) so the extension stays testable with a\n * literal and carries no dependency on the resolver module.\n */\nexport type AgentFilesResolver = {\n isMonorepo(): boolean\n getRootDir(): string\n getAppDir(): string\n getOutputDir(): string\n}\n\n/**\n * Generator extension for the `agents/<id>/` file-defined-agent convention\n * (AGENT.md + OUTCOME.md). For every enabled module it scans the module's\n * `agents/` tree, validates each agent dir, and emits two artifacts as a\n * deterministic fs side effect from `generateOutput()`:\n *\n * 1. The committed, git-tracked registry manifest\n * `packages/enterprise/src/modules/agent_orchestrator/generated/file-agents.generated.ts`\n * (raw JSON-Schema, recompiled to Zod at load by `ensureAgentsLoaded`).\n * 2. OpenCode agent `.md` files under `docker/opencode/agents/` (container\n * delivery: dev bind-mount, prod Dockerfile COPY).\n *\n * Both targets live OUTSIDE the app `.mercato/generated/` dir, so they are\n * written directly (not via the Map<filename,content> return, which targets the\n * app generated dir). `generateOutput()` therefore returns an empty Map.\n *\n * Generation FAILS (throws) on any malformed AGENT.md/OUTCOME.md/SKILL.md,\n * naming the offending dir (spec \u00A79). The CLI does not depend on\n * `@open-mercato/core`, so the small AGENT.md/OUTCOME.md/SKILL.md parsers are\n * reimplemented here; they MUST stay in sync with\n * `lib/sdk/{agentMarkdown,skillMarkdown,defineFileAgent}.ts`.\n *\n * Phase 3 also emits NATIVE OpenCode skill files under `docker/opencode/skills/`\n * (frontmatter `name` sanitized to `^[a-z0-9]+(-[a-z0-9]+)*$`, `description`\n * required, body = skill instructions) and unions skill-contributed read-only\n * tools into the agent allowlist (manifest + docker agent-file `tools` block).\n */\n\n/** One sandboxed script carried as plain data (Phase 5). */\ntype DiscoveredScript = {\n name: string\n source: string\n}\n\ntype DiscoveredSkill = {\n /** Skill id: frontmatter `id` or, when absent, the skill dir name. */\n id: string\n description: string\n instructions: string\n template?: string\n examples: string[]\n tools: string[]\n /** Sandboxed helper scripts (`scripts/*.ts`), Phase 5. */\n scripts: DiscoveredScript[]\n /** OpenCode native skill name (sanitized to ^[a-z0-9]+(-[a-z0-9]+)*$). */\n openCodeSkillName: string\n}\n\ntype DiscoveredAgent = {\n moduleId: string\n dir: string\n id: string\n label: string\n description: string\n instructions: string\n resultKind: 'research' | 'proposal' | 'artifact'\n /** Absent for `kind: artifact`, whose result envelope is fixed. */\n outcomeSchema?: Record<string, unknown>\n /** OUTCOME.md prose after the JSON-Schema fence \u2014 injected into the agent prompt. */\n outcomeProse: string\n /** Effective allowlist: AGENT.md tools \u222A skill-contributed read-only tools. */\n tools: string[]\n skills: string[]\n subAgents: string[]\n openCodeAgentName: string\n /** Resolved agent-local skill content (Phase 3). */\n skillsContent: DiscoveredSkill[]\n /**\n * Resolved sub-agents under `sub-agents/<subid>/` (Phase 4). Each is a full\n * file agent, constrained to research + non-delegating. Empty for a\n * sub-agent itself (depth cap = 1) and for primaries with no sub-agents.\n */\n subAgentsContent: DiscoveredAgent[]\n /** `'primary'` (default) or `'subagent'` for a discovered sub-agent. */\n mode: 'primary' | 'subagent'\n maxSteps?: number\n provider?: string\n model?: string\n /** Optional `SAMPLE.json` example input for the Playground \"Insert sample\" button. */\n sampleInput?: unknown\n /** Optional `FACTS.json` declarations driving the Caseload facts panel. */\n facts?: DiscoveredFact[]\n /** Baked token-usage breakdown of the agent's construction files (Phase: token accounting). */\n tokenUsage: FileAgentTokenUsage\n /** Baked raw content of every construction file, for the read-only Files tab (#12 files). */\n sourceFiles: FileAgentSourceFile[]\n}\n\n/**\n * Raw definition file baked into the manifest so the Files tab reads agent source\n * without runtime fs access. MIRRORS `FileAgentFile` in\n * `packages/enterprise/.../lib/tokens/types.ts` \u2014 the CLI cannot import the\n * enterprise package, so the shape is reimplemented here and MUST stay in sync.\n */\ntype FileAgentSourceFile = {\n path: string\n content: string\n tokens: number\n inContext: boolean\n}\n\n/**\n * Token-usage shape MIRRORED from\n * `packages/enterprise/src/modules/agent_orchestrator/lib/tokens/types.ts`. The\n * CLI cannot import `@open-mercato/enterprise`, so both the type and the walker\n * below are reimplemented here and MUST stay in sync \u2014 a parity test in the\n * enterprise module (`agent-token-usage.test.ts`) guards the numbers.\n */\ntype TokenizedFile = { path: string; tokens: number }\ntype SkillTokenUsage = { id: string; tokens: number; files: TokenizedFile[] }\ntype ToolTokenUsage = { name: string; path: string; tokens: number }\ntype SubAgentTokenUsage = { id: string; tokens: number }\ntype FileAgentTokenUsage = {\n total: number\n self: number\n agent: number\n outcome: number\n skills: SkillTokenUsage[]\n tools: ToolTokenUsage[]\n subAgents: SubAgentTokenUsage[]\n}\n\ntype DiscoveredFact = {\n label: string\n source: 'input' | 'payload' | 'output'\n path: string\n format?: 'text' | 'number' | 'boolean' | 'percent'\n}\n\nconst FRONTMATTER_RE = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n?([\\s\\S]*)$/\nconst JSON_FENCE_RE = /```json\\s*\\n([\\s\\S]*?)\\n```/\nconst LIST_KEYS = ['tools', 'skills', 'subAgents'] as const\n\nfunction stripQuotes(value: string): string {\n return value.trim().replace(/^['\"]/, '').replace(/['\"]$/, '').trim()\n}\n\nfunction parseInlineList(rawValue: string): string[] {\n return rawValue\n .replace(/^\\[/, '')\n .replace(/\\]$/, '')\n .split(',')\n .map((entry) => stripQuotes(entry))\n .filter(Boolean)\n}\n\ntype AgentFrontmatter = {\n id?: string\n label?: string\n description?: string\n provider?: string\n model?: string\n tools: string[]\n skills: string[]\n subAgents: string[]\n maxSteps?: number\n instructions: string\n}\n\nfunction parseAgentMarkdown(raw: string): AgentFrontmatter | null {\n const match = FRONTMATTER_RE.exec(raw)\n if (!match) return null\n const [, frontmatterBlock, body] = match\n const meta: AgentFrontmatter = { tools: [], skills: [], subAgents: [], instructions: body.trim() }\n const lines = frontmatterBlock.split('\\n')\n let index = 0\n while (index < lines.length) {\n const line = lines[index]\n if (!line.trim()) {\n index += 1\n continue\n }\n const lineMatch = /^([A-Za-z0-9_]+):\\s*(.*)$/.exec(line)\n if (!lineMatch) {\n index += 1\n continue\n }\n const key = lineMatch[1]\n const rawValue = lineMatch[2].trim()\n if ((LIST_KEYS as readonly string[]).includes(key)) {\n const listKey = key as (typeof LIST_KEYS)[number]\n if (rawValue.startsWith('[')) {\n meta[listKey] = parseInlineList(rawValue)\n index += 1\n continue\n }\n const items: string[] = []\n index += 1\n while (index < lines.length && /^\\s*-\\s+/.test(lines[index])) {\n items.push(stripQuotes(lines[index].replace(/^\\s*-\\s+/, '')))\n index += 1\n }\n meta[listKey] = items.filter(Boolean)\n continue\n }\n if (key === 'maxSteps') {\n const parsed = Number.parseInt(stripQuotes(rawValue), 10)\n if (!Number.isNaN(parsed)) meta.maxSteps = parsed\n index += 1\n continue\n }\n if (key === 'id' || key === 'label' || key === 'description' || key === 'provider' || key === 'model') {\n meta[key] = stripQuotes(rawValue)\n }\n index += 1\n }\n if (!meta.id || !meta.label || !meta.description) return null\n return meta\n}\n\nfunction parseOutcomeKind(frontmatterBlock: string): 'research' | 'proposal' | 'artifact' | null {\n for (const line of frontmatterBlock.split('\\n')) {\n const match = /^kind:\\s*(.*)$/.exec(line.trim())\n if (!match) continue\n const value = stripQuotes(match[1])\n if (value === 'research' || value === 'proposal' || value === 'artifact') return value\n return null\n }\n return null\n}\n\nfunction parseOutcomeMarkdown(\n raw: string,\n): {\n kind: 'research' | 'proposal' | 'artifact'\n schema?: Record<string, unknown>\n prose: string\n} | null {\n const frontmatterMatch = FRONTMATTER_RE.exec(raw)\n if (!frontmatterMatch) return null\n const [, frontmatterBlock, body] = frontmatterMatch\n const kind = parseOutcomeKind(frontmatterBlock)\n if (!kind) return null\n const fenceMatch = JSON_FENCE_RE.exec(body)\n // An artifact agent declares no schema \u2014 its envelope is the fixed file list \u2014\n // so its whole OUTCOME.md is guidance.\n if (!fenceMatch) {\n return kind === 'artifact' ? { kind, prose: body.trim() } : null\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(fenceMatch[1])\n } catch {\n return null\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null\n const prose = body.slice(fenceMatch.index + fenceMatch[0].length).trim()\n return { kind, schema: parsed as Record<string, unknown>, prose }\n}\n\n// Keep in sync with `agent_orchestrator/lib/sdk/outcomeSchema.ts` (the CLI cannot\n// import @open-mercato/core). Mirrors `jsonSchemaToZod`'s supported subset so a\n// schema that parses as JSON but could NOT compile to Zod fails generation LOUDLY\n// here, instead of parsing fine and being silently dropped at load time (M2).\nconst OUTCOME_UNSUPPORTED_KEYWORDS = [\n 'oneOf', 'anyOf', 'allOf', 'not', '$ref', 'format', 'patternProperties', 'pattern',\n 'additionalItems', 'propertyNames', 'if', 'then', 'else',\n] as const\nconst OUTCOME_SUPPORTED_TYPES = ['object', 'array', 'string', 'number', 'integer', 'boolean']\n\n/** Throw (failing `yarn generate`) when an OUTCOME schema node is outside the supported subset. */\nfunction assertOutcomeSchemaSupported(node: unknown, where: string, path = '$'): void {\n if (typeof node !== 'object' || node === null || Array.isArray(node)) {\n throw new Error(`[internal] malformed OUTCOME.md at ${where}: schema node at ${path} must be an object`)\n }\n const schema = node as Record<string, unknown>\n for (const keyword of OUTCOME_UNSUPPORTED_KEYWORDS) {\n if (keyword in schema) {\n throw new Error(`[internal] malformed OUTCOME.md at ${where}: unsupported keyword \"${keyword}\" at ${path}`)\n }\n }\n if ('const' in schema) return\n const type = schema.type\n if (typeof type !== 'string' || !OUTCOME_SUPPORTED_TYPES.includes(type)) {\n throw new Error(`[internal] malformed OUTCOME.md at ${where}: missing/unsupported \"type\" at ${path}`)\n }\n if (type === 'object' && schema.properties != null) {\n if (typeof schema.properties !== 'object' || schema.properties === null || Array.isArray(schema.properties)) {\n throw new Error(`[internal] malformed OUTCOME.md at ${where}: \"properties\" at ${path} must be an object`)\n }\n for (const [key, child] of Object.entries(schema.properties as Record<string, unknown>)) {\n assertOutcomeSchemaSupported(child, where, `${path}.${key}`)\n }\n }\n if (type === 'array') {\n if (schema.items == null) {\n throw new Error(`[internal] malformed OUTCOME.md at ${where}: array at ${path} requires \"items\"`)\n }\n assertOutcomeSchemaSupported(schema.items, where, `${path}[]`)\n }\n}\n\nfunction sanitizeAgentName(id: string): string {\n return id.replace(/[^a-z0-9_-]/gi, '_')\n}\n\n/**\n * Read the optional `agents/<id>/SAMPLE.json` example input emitted into the\n * manifest for the Playground \"Insert sample\" button. Pure JSON (no markdown),\n * so a missing file is fine; a malformed one fails generation LOUDLY (naming the\n * dir) rather than being silently dropped. Must stay in sync with\n * `lib/sdk/defineFileAgent.ts` `loadSampleInput`.\n */\nfunction discoverSampleInput(dir: string): unknown {\n const samplePath = path.join(dir, 'SAMPLE.json')\n if (!fs.existsSync(samplePath)) return undefined\n try {\n return JSON.parse(fs.readFileSync(samplePath, 'utf8'))\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new Error(`[internal] malformed SAMPLE.json at ${dir}: ${detail}`)\n }\n}\n\nconst FACT_SOURCES = ['input', 'payload', 'output'] as const\nconst FACT_FORMATS = ['text', 'number', 'boolean', 'percent'] as const\n\n/**\n * Read the optional `agents/<id>/FACTS.json` declarations that drive the\n * Caseload decision panel's facts grid (label + dot-path into the run input,\n * proposal payload, or run output). Accepts `{ \"facts\": [...] }` or a bare\n * array. A missing file is fine; a malformed one fails generation LOUDLY\n * (naming the dir). Must stay in sync with `lib/sdk/defineFileAgent.ts`\n * `loadFacts`.\n */\nfunction discoverFacts(dir: string): DiscoveredFact[] | undefined {\n const factsPath = path.join(dir, 'FACTS.json')\n if (!fs.existsSync(factsPath)) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(fs.readFileSync(factsPath, 'utf8'))\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new Error(`[internal] malformed FACTS.json at ${dir}: ${detail}`)\n }\n const entries = Array.isArray(parsed)\n ? parsed\n : parsed && typeof parsed === 'object' && Array.isArray((parsed as { facts?: unknown }).facts)\n ? ((parsed as { facts: unknown[] }).facts)\n : null\n if (!entries) {\n throw new Error(`[internal] malformed FACTS.json at ${dir}: expected an array or { \"facts\": [...] }`)\n }\n return entries.map((entry, index) => {\n const fact = entry as Partial<DiscoveredFact> | null\n if (\n !fact ||\n typeof fact.label !== 'string' ||\n !fact.label.trim() ||\n typeof fact.path !== 'string' ||\n !fact.path.trim() ||\n !FACT_SOURCES.includes(fact.source as (typeof FACT_SOURCES)[number])\n ) {\n throw new Error(\n `[internal] malformed FACTS.json at ${dir}: entry ${index} needs label (string), source (${FACT_SOURCES.join('|')}), path (string)`,\n )\n }\n if (fact.format !== undefined && !FACT_FORMATS.includes(fact.format as (typeof FACT_FORMATS)[number])) {\n throw new Error(\n `[internal] malformed FACTS.json at ${dir}: entry ${index} format must be one of ${FACT_FORMATS.join('|')}`,\n )\n }\n return {\n label: fact.label.trim(),\n source: fact.source as DiscoveredFact['source'],\n path: fact.path.trim(),\n ...(fact.format !== undefined ? { format: fact.format as DiscoveredFact['format'] } : {}),\n }\n })\n}\n\n/**\n * Sanitize a skill id into an OpenCode native skill `name`, which must match\n * `^[a-z0-9]+(-[a-z0-9]+)*$`: lowercase, underscores/dots/spaces \u2192 hyphens,\n * any other char \u2192 hyphen, collapse runs, trim leading/trailing hyphens. Must\n * stay in sync with the loader's interpretation of skill ids.\n */\nfunction sanitizeSkillName(id: string): string {\n const name = id\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+/, '')\n .replace(/-+$/, '')\n return name || 'skill'\n}\n\ntype SkillFrontmatter = {\n id?: string\n label?: string\n description?: string\n tools: string[]\n}\n\n/**\n * Parse an agent-local SKILL.md frontmatter (in sync with\n * `lib/sdk/skillMarkdown.ts`). Agent-local skills may omit `moduleId` and `id`\n * (the dir name is then authoritative); only a parseable frontmatter block is\n * required. Returns null when there is no frontmatter block.\n */\nfunction parseSkillMarkdown(raw: string): { meta: SkillFrontmatter; body: string } | null {\n const match = FRONTMATTER_RE.exec(raw)\n if (!match) return null\n const [, frontmatterBlock, body] = match\n const meta: SkillFrontmatter = { tools: [] }\n const lines = frontmatterBlock.split('\\n')\n let index = 0\n while (index < lines.length) {\n const line = lines[index]\n if (!line.trim()) {\n index += 1\n continue\n }\n const lineMatch = /^([A-Za-z0-9_]+):\\s*(.*)$/.exec(line)\n if (!lineMatch) {\n index += 1\n continue\n }\n const key = lineMatch[1]\n const rawValue = lineMatch[2].trim()\n if (key === 'tools') {\n if (rawValue.startsWith('[')) {\n meta.tools = parseInlineList(rawValue)\n index += 1\n continue\n }\n const items: string[] = []\n index += 1\n while (index < lines.length && /^\\s*-\\s+/.test(lines[index])) {\n items.push(stripQuotes(lines[index].replace(/^\\s*-\\s+/, '')))\n index += 1\n }\n meta.tools = items.filter(Boolean)\n continue\n }\n if (key === 'id' || key === 'label' || key === 'description') {\n meta[key] = stripQuotes(rawValue)\n }\n index += 1\n }\n return { meta, body: body.trim() }\n}\n\nfunction listExampleBodies(skillDir: string): string[] {\n const examplesDir = path.join(skillDir, 'examples')\n if (!fs.existsSync(examplesDir) || !fs.statSync(examplesDir).isDirectory()) return []\n return fs\n .readdirSync(examplesDir)\n .filter((name) => name.endsWith('.md'))\n .sort((a, b) => a.localeCompare(b))\n .map((name) => fs.readFileSync(path.join(examplesDir, name), 'utf8').trim())\n .filter(Boolean)\n}\n\n/**\n * Basic parse validation of a script source (Phase 5). The script runs in the\n * `isolated-vm` sandbox server-side (never copied to the container), so we only\n * cheaply assert it defines a `run` function \u2014 a missing `run` would fail at\n * runtime, so we fail generation early naming the file. We do NOT execute it.\n */\nfunction validateScriptSource(file: string, source: string): void {\n const definesRun = /(^|\\b)(async\\s+)?function\\s+run\\b/.test(source) || /\\brun\\s*=/.test(source)\n if (!definesRun) {\n throw new Error(\n `[internal] malformed agent script at ${file}: must define a \\`run(args)\\` function`,\n )\n }\n}\n\n/**\n * Read sandboxed scripts from a `scripts/` dir (`*.ts` / `*.js`), Phase 5. Each\n * file's basename (no extension) is the script name; the raw source is carried\n * as plain data. Validates each parses (basic). Ordered by filename.\n */\nfunction listScripts(scriptsDir: string): DiscoveredScript[] {\n if (!fs.existsSync(scriptsDir) || !fs.statSync(scriptsDir).isDirectory()) return []\n const scripts: DiscoveredScript[] = []\n for (const name of fs\n .readdirSync(scriptsDir)\n .filter((entry) => entry.endsWith('.ts') || entry.endsWith('.js'))\n .sort((a, b) => a.localeCompare(b))) {\n const file = path.join(scriptsDir, name)\n const source = fs.readFileSync(file, 'utf8')\n validateScriptSource(file, source)\n scripts.push({ name: name.replace(/\\.(ts|js)$/, ''), source })\n }\n return scripts\n}\n\n/** Synthetic skill id under which an agent's LOCAL sandboxed tool files register. */\nconst AGENT_TOOLS_SKILL_ID = '__agent_tools__'\nconst TOOL_REF_RE = /^\\s*\\/\\/\\s*@ref:?\\s+(\\S+)/\n\n/**\n * Discover `agents/<id>/tools/*.ts` local tool files (Phase 5). Reference-form\n * files (first line `// @ref <defineAiTool id>`) contribute the id to `refs`\n * (unioned into the allowlist, flows through the central ACL + propose-only\n * gate). Any other file is a LOCAL sandboxed tool: carried as a script run via\n * `run_skill_script` under the synthetic `__agent_tools__` skill. Must stay in\n * sync with `lib/sdk/defineFileAgent.ts` `loadToolFiles`.\n */\nfunction discoverToolFiles(agentDir: string): { refs: string[]; scripts: DiscoveredScript[] } {\n const toolsBase = path.join(agentDir, 'tools')\n if (!fs.existsSync(toolsBase) || !fs.statSync(toolsBase).isDirectory()) {\n return { refs: [], scripts: [] }\n }\n const refs: string[] = []\n const scripts: DiscoveredScript[] = []\n for (const name of fs\n .readdirSync(toolsBase)\n .filter((entry) => entry.endsWith('.ts') || entry.endsWith('.js'))\n .sort((a, b) => a.localeCompare(b))) {\n const file = path.join(toolsBase, name)\n const source = fs.readFileSync(file, 'utf8')\n const firstLine = source.split('\\n', 1)[0] ?? ''\n const refMatch = TOOL_REF_RE.exec(firstLine)\n if (refMatch) {\n refs.push(refMatch[1])\n continue\n }\n validateScriptSource(file, source)\n scripts.push({ name: name.replace(/\\.(ts|js)$/, ''), source })\n }\n return { refs, scripts }\n}\n\n/**\n * Discover the agent's referenced skills under `agents/<id>/skills/<skill_id>/`.\n * For each id in AGENT.md `skills:` we look up the matching dir (by frontmatter\n * id or dir name). FAILS generation when a referenced SKILL.md is malformed\n * (present dir but unparseable frontmatter). A referenced id with no dir is\n * skipped (the loader warns identically at runtime).\n */\nfunction discoverAgentSkills(agentDir: string, skillIds: string[]): DiscoveredSkill[] {\n if (skillIds.length === 0) return []\n const skillsBase = path.join(agentDir, 'skills')\n if (!fs.existsSync(skillsBase) || !fs.statSync(skillsBase).isDirectory()) return []\n\n const bySkillId = new Map<string, DiscoveredSkill>()\n for (const entry of fs.readdirSync(skillsBase, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue\n const skillDir = path.join(skillsBase, entry.name)\n const skillPath = path.join(skillDir, 'SKILL.md')\n if (!fs.existsSync(skillPath)) continue\n const parsed = parseSkillMarkdown(fs.readFileSync(skillPath, 'utf8'))\n if (!parsed) {\n throw new Error(`[internal] malformed SKILL.md at ${skillDir}: missing frontmatter block`)\n }\n const id = parsed.meta.id || entry.name\n const templatePath = path.join(skillDir, 'TEMPLATE.md')\n const template = fs.existsSync(templatePath)\n ? fs.readFileSync(templatePath, 'utf8').trim() || undefined\n : undefined\n bySkillId.set(id, {\n id,\n description: parsed.meta.description ?? '',\n instructions: parsed.body,\n template,\n examples: listExampleBodies(skillDir),\n tools: parsed.meta.tools,\n scripts: listScripts(path.join(skillDir, 'scripts')),\n openCodeSkillName: sanitizeSkillName(id),\n })\n }\n\n const resolved: DiscoveredSkill[] = []\n for (const skillId of skillIds) {\n const skill = bySkillId.get(skillId)\n if (skill) resolved.push(skill)\n }\n return resolved\n}\n\n/**\n * Discover and validate the sub-agents under `agents/<id>/sub-agents/<subid>/`\n * (Phase 4). Each is a full file agent (AGENT.md + OUTCOME.md) constrained to:\n * 1. OUTCOME `kind: research` (sub-agents inform; only the primary proposes);\n * 2. NO `subAgents` of its own (depth cap = 1).\n * FAILS generation (throws, naming the dir) on a malformed sub-agent OR a\n * constraint violation \u2014 in sync with `lib/sdk/defineFileAgent.ts` `loadSubAgentDir`.\n */\nfunction discoverSubAgents(agentDir: string): DiscoveredAgent[] {\n const base = path.join(agentDir, 'sub-agents')\n if (!fs.existsSync(base) || !fs.statSync(base).isDirectory()) return []\n const subAgents: DiscoveredAgent[] = []\n for (const entry of fs.readdirSync(base, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.name === '__tests__') continue\n const dir = path.join(base, entry.name)\n const agentMdPath = path.join(dir, 'AGENT.md')\n const outcomePath = path.join(dir, 'OUTCOME.md')\n if (!fs.existsSync(agentMdPath) || !fs.existsSync(outcomePath)) {\n throw new Error(\n `[internal] malformed sub-agent at ${dir}: both AGENT.md and OUTCOME.md are required`,\n )\n }\n const agent = parseAgentMarkdown(fs.readFileSync(agentMdPath, 'utf8'))\n if (!agent) {\n throw new Error(`[internal] malformed AGENT.md at ${dir}: missing id/label/description`)\n }\n const outcome = parseOutcomeMarkdown(fs.readFileSync(outcomePath, 'utf8'))\n if (!outcome) {\n throw new Error(`[internal] malformed OUTCOME.md at ${dir}: missing kind or JSON-Schema block`)\n }\n if (outcome.schema) assertOutcomeSchemaSupported(outcome.schema, dir)\n if (outcome.kind !== 'research') {\n throw new Error(\n `[internal] sub-agent at ${dir} must be research (kind: research); only the primary proposes`,\n )\n }\n if (agent.subAgents.length > 0) {\n throw new Error(\n `[internal] sub-agent at ${dir} may not declare subAgents (depth cap = 1); sub-agents may not delegate further`,\n )\n }\n const skillsContent = discoverAgentSkills(dir, agent.skills)\n const skillTools = skillsContent.flatMap((skill) => skill.tools)\n const toolFiles = discoverToolFiles(dir)\n const effectiveSkillsContent =\n toolFiles.scripts.length > 0\n ? [\n ...skillsContent,\n {\n id: AGENT_TOOLS_SKILL_ID,\n description: '',\n instructions: '',\n examples: [],\n tools: [],\n scripts: toolFiles.scripts,\n openCodeSkillName: sanitizeSkillName(AGENT_TOOLS_SKILL_ID),\n },\n ]\n : skillsContent\n const effectiveTools = Array.from(\n new Set([...agent.tools, ...skillTools, ...toolFiles.refs]),\n )\n subAgents.push({\n moduleId: '',\n dir,\n id: agent.id!,\n label: agent.label!,\n description: agent.description!,\n instructions: agent.instructions,\n resultKind: outcome.kind,\n outcomeSchema: outcome.schema,\n outcomeProse: outcome.prose,\n tools: effectiveTools,\n skills: agent.skills,\n subAgents: [],\n openCodeAgentName: sanitizeAgentName(agent.id!),\n skillsContent: effectiveSkillsContent,\n subAgentsContent: [],\n mode: 'subagent',\n maxSteps: agent.maxSteps,\n provider: agent.provider,\n model: agent.model,\n sampleInput: discoverSampleInput(dir),\n facts: discoverFacts(dir),\n tokenUsage: discoverAgentTokenUsage(dir),\n sourceFiles: collectAgentFiles(dir),\n })\n }\n return subAgents\n}\n\n// --- Token accounting (MIRRORS lib/tokens/computeAgentTokenUsage.ts) ---\n\nconst TOKEN_TOOL_EXTENSIONS = ['.ts', '.js']\n\n/**\n * MIRRORS `toPosixRelativePath` in lib/tokens/computeAgentTokenUsage.ts.\n *\n * These relative paths are baked into `file-agents.generated.ts` and split into\n * a folder tree in the browser, so they must be `/`-separated whatever machine\n * ran `yarn generate`. `path.join` answers with the native separator, which on\n * Windows baked backslashes into the artifact and flattened the Files tab.\n */\nfunction toPosixRelativePath(relativePath: string): string {\n return relativePath.split(path.sep).join('/')\n}\n\nfunction tokenCountFile(agentDir: string, relativePath: string): TokenizedFile | null {\n const absolute = path.join(agentDir, relativePath)\n if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) return null\n return { path: toPosixRelativePath(relativePath), tokens: countTokens(fs.readFileSync(absolute, 'utf8')) }\n}\n\nfunction tokenListFiles(dir: string, extensions?: string[]): string[] {\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return []\n return fs\n .readdirSync(dir, { withFileTypes: true })\n .filter((entry) => entry.isFile())\n .map((entry) => entry.name)\n .filter((name) => !extensions || extensions.includes(path.extname(name)))\n .sort((a, b) => a.localeCompare(b))\n}\n\nfunction tokenListDirs(dir: string): string[] {\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return []\n return fs\n .readdirSync(dir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && entry.name !== '__tests__')\n .map((entry) => entry.name)\n .sort((a, b) => a.localeCompare(b))\n}\n\nfunction tokenComputeSkills(agentDir: string): SkillTokenUsage[] {\n return tokenListDirs(path.join(agentDir, 'skills')).map((skillId) => {\n const skillRel = path.join('skills', skillId)\n const files: TokenizedFile[] = []\n for (const name of ['SKILL.md', 'TEMPLATE.md']) {\n const file = tokenCountFile(agentDir, path.join(skillRel, name))\n if (file) files.push(file)\n }\n for (const subdir of ['examples', 'scripts']) {\n for (const name of tokenListFiles(path.join(agentDir, skillRel, subdir))) {\n const file = tokenCountFile(agentDir, path.join(skillRel, subdir, name))\n if (file) files.push(file)\n }\n }\n return { id: skillId, tokens: files.reduce((sum, f) => sum + f.tokens, 0), files }\n })\n}\n\nfunction tokenComputeTools(agentDir: string): ToolTokenUsage[] {\n return tokenListFiles(path.join(agentDir, 'tools'), TOKEN_TOOL_EXTENSIONS).map((name) => {\n const rel = path.join('tools', name)\n return {\n name: name.replace(/\\.[^.]+$/, ''),\n path: toPosixRelativePath(rel),\n tokens: countTokens(fs.readFileSync(path.join(agentDir, rel), 'utf8')),\n }\n })\n}\n\nfunction discoverAgentTokenUsage(agentDir: string, depth = 0): FileAgentTokenUsage {\n const agent = tokenCountFile(agentDir, 'AGENT.md')?.tokens ?? 0\n const outcome = tokenCountFile(agentDir, 'OUTCOME.md')?.tokens ?? 0\n const skills = tokenComputeSkills(agentDir)\n const tools = tokenComputeTools(agentDir)\n\n const subAgents: SubAgentTokenUsage[] = []\n if (depth === 0) {\n for (const subId of tokenListDirs(path.join(agentDir, 'sub-agents'))) {\n const nested = discoverAgentTokenUsage(path.join(agentDir, 'sub-agents', subId), depth + 1)\n subAgents.push({ id: subId, tokens: nested.total })\n }\n }\n\n const self =\n agent +\n outcome +\n skills.reduce((sum, s) => sum + s.tokens, 0) +\n tools.reduce((sum, t) => sum + t.tokens, 0)\n const total = self + subAgents.reduce((sum, s) => sum + s.tokens, 0)\n\n return { total, self, agent, outcome, skills, tools, subAgents }\n}\n\n// --- Raw source-file collection (feeds the read-only Files tab, #12 files) ---\n\n/** Files present at the agent root but NOT part of the constructed prompt. */\nconst AGENT_AUX_FILES = ['SAMPLE.json', 'FACTS.json']\n\n/**\n * Walks every construction file of a file-defined agent and returns its raw\n * content + `o200k_base` token count, paths relative to the agent root. Recurses\n * `sub-agents/<id>/` once (depth cap = 1, matching `discoverAgentTokenUsage`),\n * prefixing nested paths with `sub-agents/<id>/`. The `inContext` sum of a tree\n * equals `discoverAgentTokenUsage(...).total`, so the Files tab and the baked\n * token estimate stay consistent.\n */\nfunction collectAgentFiles(agentDir: string, prefix = '', depth = 0): FileAgentSourceFile[] {\n const files: FileAgentSourceFile[] = []\n const add = (relativePath: string, inContext: boolean): void => {\n const absolute = path.join(agentDir, relativePath)\n if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) return\n const content = fs.readFileSync(absolute, 'utf8')\n files.push({ path: toPosixRelativePath(path.join(prefix, relativePath)), content, tokens: countTokens(content), inContext })\n }\n add('AGENT.md', true)\n add('OUTCOME.md', true)\n for (const name of AGENT_AUX_FILES) add(name, false)\n for (const skillId of tokenListDirs(path.join(agentDir, 'skills'))) {\n const skillRel = path.join('skills', skillId)\n for (const name of ['SKILL.md', 'TEMPLATE.md']) add(path.join(skillRel, name), true)\n for (const subdir of ['examples', 'scripts']) {\n for (const name of tokenListFiles(path.join(agentDir, skillRel, subdir))) {\n add(path.join(skillRel, subdir, name), true)\n }\n }\n }\n for (const name of tokenListFiles(path.join(agentDir, 'tools'), TOKEN_TOOL_EXTENSIONS)) {\n add(path.join('tools', name), true)\n }\n if (depth === 0) {\n for (const subId of tokenListDirs(path.join(agentDir, 'sub-agents'))) {\n files.push(\n ...collectAgentFiles(\n path.join(agentDir, 'sub-agents', subId),\n path.join(prefix, 'sub-agents', subId),\n depth + 1,\n ),\n )\n }\n }\n return files\n}\n\nfunction renderOpenCodeSkillFile(skill: DiscoveredSkill): string {\n const frontmatter = [\n '---',\n `name: ${skill.openCodeSkillName}`,\n `description: ${JSON.stringify(skill.description)}`,\n '---',\n ]\n return `${frontmatter.join('\\n')}\\n${skill.instructions.trim()}\\n`\n}\n\n/** Walk up from a known in-repo path until a dir containing both `docker` and `packages` is found. */\nfunction findRepoRoot(start: string): string | null {\n let current = path.resolve(start)\n for (let depth = 0; depth < 40; depth += 1) {\n if (\n fs.existsSync(path.join(current, 'docker', 'opencode')) &&\n fs.existsSync(path.join(current, 'packages'))\n ) {\n return current\n }\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n return null\n}\n\n/**\n * Where this extension's three artifacts land. The two layouts differ because a\n * standalone app has no `packages/` tree to host the manifest: the enterprise\n * module lives under `node_modules/`, which `yarn install` rewrites.\n *\n * | Artifact | Monorepo | Standalone |\n * |-----------|------------------------------------------------------------|-------------------------------------------|\n * | manifest | `packages/enterprise/src/modules/agent_orchestrator/generated/` | `<app>/.mercato/generated/` |\n * | agents/ | `<repo>/docker/opencode/agents/` | `<app>/docker/opencode/agents/` |\n * | skills/ | `<repo>/docker/opencode/skills/` | `<app>/docker/opencode/skills/` |\n *\n * The standalone manifest sits in the generated output dir that\n * `findGeneratedFile()` already probes (`generated-registry-loader.ts` resolves\n * `<cwd>/.mercato/generated/<file>` for exactly this case), so the runtime\n * loader reaches it with no new resolution logic. It is regenerated on every\n * `yarn generate`, which both `scripts/dev.mjs` setup and\n * `docker/scripts/init-or-migrate.sh` run before the app boots.\n */\ntype AgentFilesTargets = {\n layout: 'monorepo' | 'standalone'\n manifestPath: string\n dockerAgentsDir: string\n dockerSkillsDir: string\n}\n\nfunction resolveAgentFilesTargets(\n resolver: AgentFilesResolver | undefined,\n fallbackRepoRoot: string | null,\n): AgentFilesTargets | null {\n if (resolver && !resolver.isMonorepo()) {\n const appDir = resolver.getAppDir()\n return {\n layout: 'standalone',\n manifestPath: path.join(resolver.getOutputDir(), 'file-agents.generated.ts'),\n dockerAgentsDir: path.join(appDir, 'docker', 'opencode', 'agents'),\n dockerSkillsDir: path.join(appDir, 'docker', 'opencode', 'skills'),\n }\n }\n // Monorepo. Prefer the resolver's root, falling back to the walk-up probe so\n // unit tests that construct the extension without a resolver keep working.\n const repoRoot = resolver?.getRootDir() ?? fallbackRepoRoot\n if (!repoRoot) return null\n return {\n layout: 'monorepo',\n manifestPath: path.join(\n repoRoot,\n 'packages',\n 'enterprise',\n 'src',\n 'modules',\n 'agent_orchestrator',\n 'generated',\n 'file-agents.generated.ts',\n ),\n dockerAgentsDir: path.join(repoRoot, 'docker', 'opencode', 'agents'),\n dockerSkillsDir: path.join(repoRoot, 'docker', 'opencode', 'skills'),\n }\n}\n\nfunction listAgentDirs(agentsBase: string): string[] {\n if (!fs.existsSync(agentsBase)) return []\n return fs\n .readdirSync(agentsBase, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && entry.name !== '__tests__')\n .map((entry) => path.join(agentsBase, entry.name))\n}\n\nfunction renderToolPermissionLine(toolName: string): string {\n return ` ${JSON.stringify(toolName)}: true`\n}\n\nconst ORCHESTRATOR_MODULE_ID = 'agent_orchestrator'\n// OpenCode names every MCP tool `<serverKey>_<toolName with dots\u2192underscores>`\n// (verified against the running image). Keep in sync with\n// `lib/sdk/defineFileAgent.ts`.\nconst OPENCODE_MCP_SERVER_KEY = 'open-mercato'\nconst CORE_FILE_AGENT_TOOL_IDS = [\n 'agent_orchestrator.submit_outcome',\n 'agent_orchestrator.load_skill',\n 'agent_orchestrator.run_skill_script',\n]\n/**\n * MCP tool a file-agent orchestrator uses to run a sub-agent SERVER-SIDE. We\n * route delegation through this tool instead of OpenCode's built-in `task` tool:\n * `task` spawns each sub-agent in a fresh session that never receives the run's\n * `_sessionToken`, so the sub-agent's MCP calls fail with `no_active_run`. The\n * delegate tool runs the sub-agent via `agentRuntime.run`, which mints its own\n * per-run session token + correlation, so sub-agent tool calls authenticate.\n */\nconst DELEGATE_AGENT_TOOL_ID = 'agent_orchestrator.delegate_agent'\nfunction toOpenCodeMcpToolId(omToolId: string): string {\n return `${OPENCODE_MCP_SERVER_KEY}_${omToolId.replace(/\\./g, '_')}`\n}\n\n/**\n * Render an OpenCode agent .md file. Must stay in sync with\n * `lib/sdk/defineFileAgent.ts` `renderOpenCodeAgentFile`. The built-in OpenCode\n * `task` tool is NEVER granted (`permission.task: deny` for every agent): it\n * spawns each sub-agent in a fresh session that does not inherit the run's\n * `_sessionToken`, so the sub-agent's MCP calls fail with `no_active_run`.\n * Instead, a primary that declares sub-agents is granted the\n * `agent_orchestrator.delegate_agent` MCP tool (runs each sub-agent server-side\n * under its own minted session token) and gains a \"Sub-agents\" prompt section\n * nudging parallel fan-out through that tool. Sub-agent files (`mode: subagent`)\n * get neither the delegate tool nor `task` (depth cap = 1).\n */\nfunction renderOpenCodeAgentFile(agent: DiscoveredAgent): string {\n const subAgentIds =\n agent.mode === 'primary' ? agent.subAgentsContent.map((sub) => sub.id) : []\n const hasSubAgents = subAgentIds.length > 0\n const omMcpToolIds = Array.from(\n new Set([\n ...agent.tools,\n ...CORE_FILE_AGENT_TOOL_IDS,\n ...(hasSubAgents ? [DELEGATE_AGENT_TOOL_ID] : []),\n ]),\n )\n const allowedTools = omMcpToolIds.map(toOpenCodeMcpToolId)\n const modelLine =\n agent.provider && agent.model\n ? `model: ${agent.provider}/${agent.model}`\n : agent.model\n ? `model: ${agent.model}`\n : null\n const frontmatterLines = [\n '---',\n `description: ${JSON.stringify(agent.description)}`,\n ...(modelLine ? [modelLine] : []),\n `mode: ${agent.mode}`,\n 'tools:',\n ' \"*\": false',\n ...allowedTools.map(renderToolPermissionLine),\n 'permission:',\n ' write: deny',\n ' edit: deny',\n ' bash: deny',\n ' task: deny',\n '---',\n ]\n const terminalInstruction =\n `Finish by calling the \\`${toOpenCodeMcpToolId('agent_orchestrator.submit_outcome')}\\` tool with a value matching the outcome contract (pass it as the \\`outcome\\` argument). You MUST call the tool \u2014 do not answer in prose or emit the result as a code block.`\n const delegateToolName = toOpenCodeMcpToolId(DELEGATE_AGENT_TOOL_ID)\n const subAgentSection = hasSubAgents\n ? `## Sub-agents\\nDelegate a sub-task by calling the \\`${delegateToolName}\\` tool with \\`{ agentId: \"<sub-agent id>\", input: <sub-task input object> }\\`. Issue multiple \\`${delegateToolName}\\` calls in the SAME step to fan out in parallel, then combine their results before submitting your outcome. Available sub-agents: ${subAgentIds.join(', ')}.`\n : null\n // Inject the OUTCOME contract so the agent SEES the exact shape it must submit\n // (otherwise it guesses and learns the shape only from validation errors). Keep\n // in sync with lib/sdk/defineFileAgent.ts renderOutcomeSection.\n const outcomeTarget = agent.resultKind === 'proposal' ? 'the `proposal` object' : 'the `data` object'\n const outcomeSection =\n agent.resultKind === 'artifact'\n ? [\n '## Outcome contract',\n \"Write the files you produce into the run's `out/` directory, then pass this shape as the `outcome` argument of the submit_outcome tool:\",\n '',\n '```json',\n JSON.stringify(\n {\n artifacts: [\n { fileName: 'report.pdf', mimeType: 'application/pdf', caption: 'What this file is' },\n ],\n summary: 'One sentence about what you produced.',\n },\n null,\n 2,\n ),\n '```',\n ...(agent.outcomeProse ? ['', agent.outcomeProse] : []),\n ].join('\\n')\n : [\n '## Outcome contract',\n `Your result MUST match this JSON Schema (${outcomeTarget}). Pass it as the \\`outcome\\` argument of the submit_outcome tool, as a JSON object (not a string):`,\n '',\n '```json',\n JSON.stringify(agent.outcomeSchema, null, 2),\n '```',\n ...(agent.outcomeProse ? ['', agent.outcomeProse] : []),\n ].join('\\n')\n const body = [\n agent.instructions.trim(),\n ...(subAgentSection ? [subAgentSection] : []),\n outcomeSection,\n terminalInstruction,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n return `${frontmatterLines.join('\\n')}\\n${body}\\n`\n}\n\n/**\n * Render one agent descriptor as a key-per-line object literal at `indent`.\n * Used for both top-level agents and nested sub-agents (Phase 4). A primary that\n * declares sub-agents emits them as a nested `subAgentDescriptors` array so\n * `ensureAgentsLoaded` can register each sub-agent too (research, individually\n * runnable file agents). A nested sub-agent carries no `subAgentDescriptors`\n * (depth cap = 1).\n */\nfunction renderDescriptor(agent: DiscoveredAgent, indent: string): string {\n const optional: string[] = []\n if (agent.subAgentsContent.length > 0) {\n const nested = agent.subAgentsContent\n .map((sub) => renderDescriptor(sub, `${indent} `))\n .join('\\n')\n optional.push(`${indent} subAgentDescriptors: [\\n${nested}\\n${indent} ],`)\n }\n if (agent.maxSteps != null) optional.push(`${indent} maxSteps: ${agent.maxSteps},`)\n if (agent.provider != null) optional.push(`${indent} provider: ${JSON.stringify(agent.provider)},`)\n if (agent.model != null) optional.push(`${indent} model: ${JSON.stringify(agent.model)},`)\n if (agent.sampleInput !== undefined) {\n optional.push(`${indent} sampleInput: ${JSON.stringify(agent.sampleInput)},`)\n }\n if (agent.facts !== undefined) {\n optional.push(`${indent} facts: ${JSON.stringify(agent.facts)},`)\n }\n const skillsContent = agent.skillsContent.map((skill) => ({\n id: skill.id,\n instructions: skill.instructions,\n ...(skill.template != null ? { template: skill.template } : {}),\n examples: skill.examples,\n tools: skill.tools,\n ...(skill.scripts.length > 0 ? { scripts: skill.scripts } : {}),\n }))\n return [\n `${indent}{`,\n `${indent} id: ${JSON.stringify(agent.id)},`,\n `${indent} moduleId: ${JSON.stringify(agent.moduleId)},`,\n `${indent} label: ${JSON.stringify(agent.label)},`,\n `${indent} description: ${JSON.stringify(agent.description)},`,\n `${indent} instructions: ${JSON.stringify(agent.instructions)},`,\n `${indent} resultKind: ${JSON.stringify(agent.resultKind)},`,\n ...(agent.outcomeSchema ? [`${indent} outcomeSchema: ${JSON.stringify(agent.outcomeSchema)},`] : []),\n `${indent} tools: ${JSON.stringify(agent.tools)},`,\n `${indent} skills: ${JSON.stringify(agent.skills)},`,\n `${indent} subAgents: ${JSON.stringify(agent.subAgents)},`,\n `${indent} openCodeAgentName: ${JSON.stringify(agent.openCodeAgentName)},`,\n `${indent} skillsContent: ${JSON.stringify(skillsContent)},`,\n `${indent} tokenUsage: ${JSON.stringify(agent.tokenUsage)},`,\n `${indent} sourceFiles: ${JSON.stringify(agent.sourceFiles)},`,\n ...optional,\n `${indent}},`,\n ].join('\\n')\n}\n\n/**\n * Type-only import paths baked into `file-agents.generated.ts`.\n *\n * Monorepo: the manifest lives next to `lib/` under `agent_orchestrator/`, so\n * module-relative paths resolve. Standalone: the same file lands in\n * `<app>/.mercato/generated/`, where those relatives do not exist \u2014 use the\n * public `@open-mercato/enterprise/...` package exports instead (#6227 / #6236).\n */\nconst MANIFEST_TYPE_IMPORTS = {\n monorepo: {\n outcomeSchema: '../lib/sdk/outcomeSchema',\n tokensTypes: '../lib/tokens/types',\n },\n standalone: {\n outcomeSchema: '@open-mercato/enterprise/modules/agent_orchestrator/lib/sdk/outcomeSchema',\n tokensTypes: '@open-mercato/enterprise/modules/agent_orchestrator/lib/tokens/types',\n },\n} as const\n\nfunction renderManifest(\n agents: DiscoveredAgent[],\n options: { layout: 'monorepo' | 'standalone' } = { layout: 'monorepo' },\n): string {\n const descriptors = agents.map((agent) => renderDescriptor(agent, ' ')).join('\\n')\n const typeImports = MANIFEST_TYPE_IMPORTS[options.layout]\n\n return `// AUTO-GENERATED by mercato generate registry \u2014 DO NOT EDIT BY HAND.\n//\n// Committed, generator-owned manifest of file-defined (OpenCode) agents,\n// discovered from \\`agents/<id>/\\` directories across every enabled module. It\n// stores PLAIN data (raw JSON-Schema, not a Zod instance) so this file is pure\n// data and travels with the repo (survives \\`yarn clean-generated\\`).\n// \\`ensureAgentsLoaded()\\` recompiles each \\`outcomeSchema\\` to Zod via\n// \\`compileOutcome\\` at load time and registers it with \\`runtime:'opencode'\\`.\n//\n// Regenerate with \\`yarn generate\\`.\nimport type { JsonSchemaNode, OutcomeKind } from '${typeImports.outcomeSchema}'\nimport type { AgentTokenUsage, FileAgentFile } from '${typeImports.tokensTypes}'\n\nexport type FileAgentScript = {\n name: string\n source: string\n}\n\nexport type FileAgentSkillContent = {\n id: string\n instructions: string\n template?: string\n examples: string[]\n tools: string[]\n /**\n * Sandboxed helper scripts (Phase 5). Carried as plain source; run server-side\n * in the Code Mode \\`isolated-vm\\` sandbox via the \\`run_skill_script\\` MCP tool.\n * Never copied to the OpenCode container. The synthetic skill id\n * \\`__agent_tools__\\` carries an agent's LOCAL \\`tools/*.ts\\` sources.\n */\n scripts?: FileAgentScript[]\n}\n\nexport type FileAgentFact = {\n /** Human label shown in the Caseload facts grid. */\n label: string\n /** Where to resolve the value: run input, proposal payload, or run output. */\n source: 'input' | 'payload' | 'output'\n /** Dot-path into the source (array indexes allowed), e.g. \"actions.0.payload.amount\". */\n path: string\n format?: 'text' | 'number' | 'boolean' | 'percent'\n}\n\nexport type FileAgentDescriptor = {\n id: string\n moduleId: string\n label: string\n description: string\n instructions: string\n resultKind: OutcomeKind\n outcomeSchema?: JsonSchemaNode\n tools: string[]\n skills: string[]\n subAgents: string[]\n openCodeAgentName: string\n skillsContent?: FileAgentSkillContent[]\n /**\n * Baked token-usage estimate of the agent's construction files (AGENT.md,\n * OUTCOME.md, skills, tools, sub-agents), counted with the shared\n * \\`o200k_base\\` tokenizer. Surfaced on the Agent detail page and the\n * \\`agent_orchestrator token-usage\\` CLI. An estimate, not an exact count.\n */\n tokenUsage?: AgentTokenUsage\n /**\n * Baked raw content of every construction file (AGENT.md, OUTCOME.md, skills,\n * tools, sub-agents, and auxiliary SAMPLE.json/FACTS.json), for the read-only\n * Files tab. Each carries its \\`o200k_base\\` token count; paths are relative to\n * the agent root (sub-agent files prefixed \\`sub-agents/<id>/\\`). Baked so the\n * runtime never reads agent dirs from disk.\n */\n sourceFiles?: FileAgentFile[]\n /**\n * Nested descriptors for this agent's sub-agents (Phase 4). Each is an\n * research-kind, non-delegating file agent registered individually (depth cap =\n * 1). Absent for agents without sub-agents and for sub-agents themselves.\n */\n subAgentDescriptors?: FileAgentDescriptor[]\n maxSteps?: number\n provider?: string\n model?: string\n /**\n * Optional example \\`input\\` for the Playground \"Insert sample\" button, read\n * from \\`agents/<id>/SAMPLE.json\\`. Any JSON value the agent accepts as input.\n */\n sampleInput?: unknown\n /**\n * Optional fact declarations for the Caseload decision panel, read from\n * \\`agents/<id>/FACTS.json\\`. Each maps a labelled dot-path into the run\n * input / proposal payload / run output.\n */\n facts?: FileAgentFact[]\n}\n\nexport const fileAgentDescriptors: FileAgentDescriptor[] = [${\n descriptors ? `\\n${descriptors}\\n` : ''\n }]\n`\n}\n\nexport function createAgentFilesExtension(resolver?: AgentFilesResolver): GeneratorExtension {\n const discovered: DiscoveredAgent[] = []\n const seenIds = new Set<string>()\n let repoRoot: string | null = null\n let sawOrchestratorModule = false\n\n function scanAgentsTree(moduleId: string, baseDir: string): void {\n for (const dir of listAgentDirs(baseDir)) {\n const agentMdPath = path.join(dir, 'AGENT.md')\n const outcomePath = path.join(dir, 'OUTCOME.md')\n // Only treat a dir as an agent if at least one convention file exists.\n const hasAgentMd = fs.existsSync(agentMdPath)\n const hasOutcome = fs.existsSync(outcomePath)\n if (!hasAgentMd && !hasOutcome) continue\n if (!hasAgentMd || !hasOutcome) {\n throw new Error(\n `[internal] malformed file agent at ${dir}: both AGENT.md and OUTCOME.md are required`,\n )\n }\n const agent = parseAgentMarkdown(fs.readFileSync(agentMdPath, 'utf8'))\n if (!agent) {\n throw new Error(`[internal] malformed AGENT.md at ${dir}: missing id/label/description`)\n }\n const outcome = parseOutcomeMarkdown(fs.readFileSync(outcomePath, 'utf8'))\n if (!outcome) {\n throw new Error(`[internal] malformed OUTCOME.md at ${dir}: missing kind or JSON-Schema block`)\n }\n if (outcome.schema) assertOutcomeSchemaSupported(outcome.schema, dir)\n // The id is the registry/dup key AND the OpenCode `agent` message field \u2014\n // constrain it to a safe charset (module.entity-style: lowercase alnum + . _ -).\n if (!/^[a-z0-9][a-z0-9._-]*$/.test(agent.id!)) {\n throw new Error(\n `[internal] invalid agent id \"${agent.id}\" at ${dir}: use lowercase [a-z0-9._-] (e.g. \"module.agent\")`,\n )\n }\n if (seenIds.has(agent.id!)) {\n // Surface accidental collisions at generate time instead of silently\n // dropping the later agent (the registry would only skip it at load).\n console.warn(`[internal] duplicate file-agent id \"${agent.id}\" at ${dir}; keeping the first, skipping this one.`)\n continue\n }\n seenIds.add(agent.id!)\n // Phase 3: resolve agent-local skills and UNION their read-only tools into\n // the agent allowlist (deduped), matching the loader.\n const skillsContent = discoverAgentSkills(dir, agent.skills)\n const skillTools = skillsContent.flatMap((skill) => skill.tools)\n // Phase 5: local tool files \u2014 reference ids union into the allowlist; local\n // sandboxed tool sources register under the synthetic `__agent_tools__` skill.\n const toolFiles = discoverToolFiles(dir)\n const effectiveSkillsContent =\n toolFiles.scripts.length > 0\n ? [\n ...skillsContent,\n {\n id: AGENT_TOOLS_SKILL_ID,\n description: '',\n instructions: '',\n examples: [],\n tools: [],\n scripts: toolFiles.scripts,\n openCodeSkillName: sanitizeSkillName(AGENT_TOOLS_SKILL_ID),\n },\n ]\n : skillsContent\n const effectiveTools = Array.from(\n new Set([...agent.tools, ...skillTools, ...toolFiles.refs]),\n )\n // Phase 4: discover + validate sub-agents (throws on a malformed/proposal/\n // self-delegating sub-agent).\n const subAgentsContent = discoverSubAgents(dir)\n discovered.push({\n moduleId,\n dir,\n id: agent.id!,\n label: agent.label!,\n description: agent.description!,\n instructions: agent.instructions,\n resultKind: outcome.kind,\n outcomeSchema: outcome.schema,\n outcomeProse: outcome.prose,\n tools: effectiveTools,\n skills: agent.skills,\n subAgents: agent.subAgents,\n openCodeAgentName: sanitizeAgentName(agent.id!),\n skillsContent: effectiveSkillsContent,\n subAgentsContent,\n mode: 'primary',\n maxSteps: agent.maxSteps,\n provider: agent.provider,\n model: agent.model,\n sampleInput: discoverSampleInput(dir),\n facts: discoverFacts(dir),\n tokenUsage: discoverAgentTokenUsage(dir),\n sourceFiles: collectAgentFiles(dir),\n })\n }\n }\n\n return {\n id: 'registry.agent-files',\n outputFiles: [],\n scanModule(ctx: ModuleScanContext) {\n if (ctx.moduleId === ORCHESTRATOR_MODULE_ID) sawOrchestratorModule = true\n if (!repoRoot) {\n repoRoot = findRepoRoot(ctx.roots.pkgBase) ?? findRepoRoot(ctx.roots.appBase)\n }\n const pkgScanBase = resolveStandaloneSourceMirrorBase(ctx.roots.pkgBase) ?? ctx.roots.pkgBase\n scanAgentsTree(ctx.moduleId, path.join(pkgScanBase, 'agents'))\n scanAgentsTree(ctx.moduleId, path.join(ctx.roots.appBase, 'agents'))\n },\n generateOutput() {\n const sorted = [...discovered].sort((a, b) => a.id.localeCompare(b.id))\n\n const targets = resolveAgentFilesTargets(resolver, repoRoot)\n\n if (!targets) {\n // No layout resolved (e.g. an isolated unit test constructing the\n // extension without a resolver and without in-repo module roots). Skip\n // the fs side effect; the empty-Map return keeps the contract intact.\n // Stay silent only when there is nothing to emit \u2014 otherwise the run\n // would drop real agents without saying so (the pre-2026-09 behaviour).\n if (sawOrchestratorModule || sorted.length > 0) {\n console.warn(\n '[agent-files] Could not resolve an output root, so the file-agent manifest and ' +\n 'docker/opencode/{agents,skills} were NOT written. ' +\n `Discovered ${sorted.length} file agent(s). ` +\n 'In a standalone app this means the generator ran without a package resolver.',\n )\n }\n return new Map<string, string>()\n }\n\n if (!sawOrchestratorModule && sorted.length === 0) {\n // Neither the orchestrator (the manifest's only consumer) nor any agent\n // module is part of this run \u2014 the enterprise agents flag is off. The\n // committed manifest and `docker/opencode/**` files belong to modules\n // that are merely switched off, so pruning them here would delete\n // tracked artifacts on every `yarn generate`. Leave the tree untouched.\n return new Map<string, string>()\n }\n\n const { layout, manifestPath, dockerAgentsDir, dockerSkillsDir } = targets\n fs.mkdirSync(path.dirname(manifestPath), { recursive: true })\n fs.writeFileSync(manifestPath, renderManifest(sorted, { layout }), 'utf8')\n\n fs.mkdirSync(dockerAgentsDir, { recursive: true })\n const desiredFiles = new Map<string, string>()\n for (const agent of sorted) {\n desiredFiles.set(`${agent.openCodeAgentName}.md`, renderOpenCodeAgentFile(agent))\n // Phase 4: emit each sub-agent as its own `mode: subagent` file so\n // OpenCode can reach it via the primary's whitelisted `task` tool.\n for (const sub of agent.subAgentsContent) {\n desiredFiles.set(`${sub.openCodeAgentName}.md`, renderOpenCodeAgentFile(sub))\n }\n }\n // Idempotent: remove stale generated agent files, write the current set.\n for (const existing of fs.existsSync(dockerAgentsDir) ? fs.readdirSync(dockerAgentsDir) : []) {\n if (existing.endsWith('.md') && !desiredFiles.has(existing)) {\n fs.rmSync(path.join(dockerAgentsDir, existing))\n }\n }\n for (const [fileName, content] of desiredFiles) {\n fs.writeFileSync(path.join(dockerAgentsDir, fileName), content, 'utf8')\n }\n\n // Phase 3: emit NATIVE OpenCode skill files (one dir per skill name) under\n // `docker/opencode/skills/<sanitized-skill-name>/SKILL.md`. Idempotent:\n // remove stale skill dirs not in the current desired set. Sub-agents\n // (Phase 4) may carry their own skills too, so flatten them in.\n const allAgents = sorted.flatMap((agent) => [agent, ...agent.subAgentsContent])\n // The synthetic `__agent_tools__` skill only carries an agent's local\n // `tools/*.ts` sources (run via `run_skill_script`); it has no instructions\n // and MUST NOT be emitted as a native OpenCode skill (OpenCode requires a\n // non-empty `description`, and it is not a progressive-disclosure skill).\n const isNativeSkill = (skill: { id: string }): boolean => skill.id !== AGENT_TOOLS_SKILL_ID\n const desiredSkillNames = new Set<string>()\n for (const agent of allAgents) {\n for (const skill of agent.skillsContent) {\n if (isNativeSkill(skill)) desiredSkillNames.add(skill.openCodeSkillName)\n }\n }\n if (desiredSkillNames.size > 0) fs.mkdirSync(dockerSkillsDir, { recursive: true })\n if (fs.existsSync(dockerSkillsDir)) {\n for (const existing of fs.readdirSync(dockerSkillsDir, { withFileTypes: true })) {\n if (existing.isDirectory() && !desiredSkillNames.has(existing.name)) {\n fs.rmSync(path.join(dockerSkillsDir, existing.name), { recursive: true, force: true })\n }\n }\n }\n const renderedSkillNames = new Set<string>()\n for (const agent of allAgents) {\n for (const skill of agent.skillsContent) {\n if (!isNativeSkill(skill)) continue\n // A skill name may be shared across agents; the first rendering wins\n // (content is keyed by name, deterministic by sorted agent order).\n if (renderedSkillNames.has(skill.openCodeSkillName)) continue\n renderedSkillNames.add(skill.openCodeSkillName)\n const skillDir = path.join(dockerSkillsDir, skill.openCodeSkillName)\n fs.mkdirSync(skillDir, { recursive: true })\n fs.writeFileSync(path.join(skillDir, 'SKILL.md'), renderOpenCodeSkillFile(skill), 'utf8')\n }\n }\n\n return new Map<string, string>()\n },\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,mBAAmB;AAE5B,SAAS,yCAAyC;AA+IlD,MAAM,iBAAiB;AACvB,MAAM,gBAAgB;AACtB,MAAM,YAAY,CAAC,SAAS,UAAU,WAAW;AAEjD,SAAS,YAAY,OAAuB;AAC1C,SAAO,MAAM,KAAK,EAAE,QAAQ,SAAS,EAAE,EAAE,QAAQ,SAAS,EAAE,EAAE,KAAK;AACrE;AAEA,SAAS,gBAAgB,UAA4B;AACnD,SAAO,SACJ,QAAQ,OAAO,EAAE,EACjB,QAAQ,OAAO,EAAE,EACjB,MAAM,GAAG,EACT,IAAI,CAAC,UAAU,YAAY,KAAK,CAAC,EACjC,OAAO,OAAO;AACnB;AAeA,SAAS,mBAAmB,KAAsC;AAChE,QAAM,QAAQ,eAAe,KAAK,GAAG;AACrC,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,CAAC,EAAE,kBAAkB,IAAI,IAAI;AACnC,QAAM,OAAyB,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAC,GAAG,WAAW,CA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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/cli",
|
|
3
|
-
"version": "0.8.1-develop.
|
|
3
|
+
"version": "0.8.1-develop.7275.1.f772b944d4",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -60,9 +60,9 @@
|
|
|
60
60
|
"@mikro-orm/decorators": "^7.1.14",
|
|
61
61
|
"@mikro-orm/migrations": "^7.1.14",
|
|
62
62
|
"@mikro-orm/postgresql": "^7.1.14",
|
|
63
|
-
"@open-mercato/queue": "0.8.1-develop.
|
|
64
|
-
"@open-mercato/shared": "0.8.1-develop.
|
|
65
|
-
"@open-mercato/telemetry": "0.8.1-develop.
|
|
63
|
+
"@open-mercato/queue": "0.8.1-develop.7275.1.f772b944d4",
|
|
64
|
+
"@open-mercato/shared": "0.8.1-develop.7275.1.f772b944d4",
|
|
65
|
+
"@open-mercato/telemetry": "0.8.1-develop.7275.1.f772b944d4",
|
|
66
66
|
"cross-spawn": "^7.0.6",
|
|
67
67
|
"pg": "8.23.0",
|
|
68
68
|
"semver": "^7.8.5",
|
|
@@ -73,10 +73,10 @@
|
|
|
73
73
|
"typescript-js": "npm:typescript@6.0.3"
|
|
74
74
|
},
|
|
75
75
|
"peerDependencies": {
|
|
76
|
-
"@open-mercato/shared": "0.8.1-develop.
|
|
76
|
+
"@open-mercato/shared": "0.8.1-develop.7275.1.f772b944d4"
|
|
77
77
|
},
|
|
78
78
|
"devDependencies": {
|
|
79
|
-
"@open-mercato/shared": "0.8.1-develop.
|
|
79
|
+
"@open-mercato/shared": "0.8.1-develop.7275.1.f772b944d4",
|
|
80
80
|
"@types/jest": "^30.0.0",
|
|
81
81
|
"jest": "^30.4.2",
|
|
82
82
|
"ts-jest": "^29.4.12"
|
|
@@ -94,6 +94,13 @@ describe('createAgentFilesExtension', () => {
|
|
|
94
94
|
expect(manifest).toContain("id: \"deals.health_check\"")
|
|
95
95
|
expect(manifest).toContain("openCodeAgentName: \"deals_health_check\"")
|
|
96
96
|
expect(manifest).toContain('export const fileAgentDescriptors')
|
|
97
|
+
expect(manifest).toContain(
|
|
98
|
+
"import type { JsonSchemaNode, OutcomeKind } from '../lib/sdk/outcomeSchema'",
|
|
99
|
+
)
|
|
100
|
+
expect(manifest).toContain(
|
|
101
|
+
"import type { AgentTokenUsage, FileAgentFile } from '../lib/tokens/types'",
|
|
102
|
+
)
|
|
103
|
+
expect(manifest).not.toContain('@open-mercato/enterprise/modules/agent_orchestrator/lib/')
|
|
97
104
|
|
|
98
105
|
const dockerFile = path.join(repoRoot, 'docker/opencode/agents/deals_health_check.md')
|
|
99
106
|
expect(fs.existsSync(dockerFile)).toBe(true)
|
|
@@ -559,7 +566,18 @@ describe('createAgentFilesExtension', () => {
|
|
|
559
566
|
'file-agents.generated.ts',
|
|
560
567
|
)
|
|
561
568
|
expect(fs.existsSync(manifestPath)).toBe(true)
|
|
562
|
-
|
|
569
|
+
const manifest = fs.readFileSync(manifestPath, 'utf8')
|
|
570
|
+
expect(manifest).toContain('id: "deals.health_check"')
|
|
571
|
+
// Standalone layout: type imports must use the public package path — the
|
|
572
|
+
// monorepo-relative `../lib/...` form does not resolve from `.mercato/generated/`.
|
|
573
|
+
expect(manifest).toContain(
|
|
574
|
+
"import type { JsonSchemaNode, OutcomeKind } from '@open-mercato/enterprise/modules/agent_orchestrator/lib/sdk/outcomeSchema'",
|
|
575
|
+
)
|
|
576
|
+
expect(manifest).toContain(
|
|
577
|
+
"import type { AgentTokenUsage, FileAgentFile } from '@open-mercato/enterprise/modules/agent_orchestrator/lib/tokens/types'",
|
|
578
|
+
)
|
|
579
|
+
expect(manifest).not.toContain("from '../lib/sdk/outcomeSchema'")
|
|
580
|
+
expect(manifest).not.toContain("from '../lib/tokens/types'")
|
|
563
581
|
|
|
564
582
|
// It must NOT write into node_modules, which yarn install rewrites.
|
|
565
583
|
expect(
|